title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
TYP: fix incorrect mypy error in reshape.py | diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 7edd5af7c6870..d043e3ad53f9a 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -39,6 +39,7 @@
Index,
MultiIndex,
)
+from pandas.core.indexes.frozen import FrozenList
from pandas.core.series import Series
from pandas.core.sorting import (
compress_group_index,
@@ -316,15 +317,16 @@ def get_new_columns(self, value_columns: Index | None):
stride = len(self.removed_level) + self.lift
width = len(value_columns)
propagator = np.repeat(np.arange(width), stride)
+
+ new_levels: FrozenList | list[Index]
+
if isinstance(value_columns, MultiIndex):
new_levels = value_columns.levels + (self.removed_level_full,)
new_names = value_columns.names + (self.removed_name,)
new_codes = [lab.take(propagator) for lab in value_columns.codes]
else:
- # error: Incompatible types in assignment (expression has type "List[Any]",
- # variable has type "FrozenList")
- new_levels = [ # type: ignore[assignment]
+ new_levels = [
value_columns,
self.removed_level_full,
]
| xref #37715
````new_levels```` is not defined as a ````FrozenList```` within ````get_new_colums```` | https://api.github.com/repos/pandas-dev/pandas/pulls/45127 | 2021-12-30T15:00:39Z | 2021-12-31T15:00:19Z | 2021-12-31T15:00:19Z | 2021-12-31T15:15:16Z |
BUG: Operations with SparseArray return SA with wrong indices | diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 538d4e7e4a7aa..2a21498a5d1e4 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -1680,13 +1680,14 @@ def _cmp_method(self, other, op) -> SparseArray:
op_name = op.__name__.strip("_")
return _sparse_array_op(self, other, op, op_name)
else:
+ # scalar
with np.errstate(all="ignore"):
fill_value = op(self.fill_value, other)
- result = op(self.sp_values, other)
+ result = np.full(len(self), fill_value, dtype=np.bool_)
+ result[self.sp_index.indices] = op(self.sp_values, other)
return type(self)(
result,
- sparse_index=self.sp_index,
fill_value=fill_value,
dtype=np.bool_,
)
diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py
index 012fe61fdba05..3db1ee9faad78 100644
--- a/pandas/tests/arrays/sparse/test_arithmetics.py
+++ b/pandas/tests/arrays/sparse/test_arithmetics.py
@@ -32,6 +32,7 @@ class TestSparseArrayArithmetics:
_klass = SparseArray
def _assert(self, a, b):
+ # We have to use tm.assert_sp_array_equal. See GH #45126
tm.assert_numpy_array_equal(a, b)
def _check_numeric_ops(self, a, b, a_dense, b_dense, mix: bool, op):
diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py
index 2c3dcdeeaf8dc..0ebe03d9a1198 100644
--- a/pandas/tests/arrays/sparse/test_array.py
+++ b/pandas/tests/arrays/sparse/test_array.py
@@ -248,8 +248,8 @@ def test_scalar_with_index_infer_dtype(self, scalar, dtype):
assert arr.dtype == dtype
assert exp.dtype == dtype
- # GH 23122
def test_getitem_bool_sparse_array(self):
+ # GH 23122
spar_bool = SparseArray([False, True] * 5, dtype=np.bool8, fill_value=True)
exp = SparseArray([np.nan, 2, np.nan, 5, 6])
tm.assert_sp_array_equal(self.arr[spar_bool], exp)
@@ -266,6 +266,13 @@ def test_getitem_bool_sparse_array(self):
exp = SparseArray([np.nan, 3, 5])
tm.assert_sp_array_equal(res, exp)
+ def test_getitem_bool_sparse_array_as_comparison(self):
+ # GH 45110
+ arr = SparseArray([1, 2, 3, 4, np.nan, np.nan], fill_value=np.nan)
+ res = arr[arr > 2]
+ exp = SparseArray([3.0, 4.0], fill_value=np.nan)
+ tm.assert_sp_array_equal(res, exp)
+
def test_get_item(self):
assert np.isnan(self.arr[1])
diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py
index f7809dc2e4217..5611889a9368c 100644
--- a/pandas/tests/extension/test_sparse.py
+++ b/pandas/tests/extension/test_sparse.py
@@ -100,6 +100,11 @@ def data_for_grouping(request):
return SparseArray([1, 1, np.nan, np.nan, 2, 2, 1, 3], fill_value=request.param)
+@pytest.fixture(params=[0, np.nan])
+def data_for_compare(request):
+ return SparseArray([0, 0, np.nan, -2, -1, 4, 2, 3, 0, 0], fill_value=request.param)
+
+
class BaseSparseTests:
def _check_unsupported(self, data):
if data.dtype == SparseDtype(int, 0):
@@ -432,32 +437,45 @@ def _check_divmod_op(self, ser, op, other, exc=NotImplementedError):
super()._check_divmod_op(ser, op, other, exc=None)
-class TestComparisonOps(BaseSparseTests, base.BaseComparisonOpsTests):
- def _compare_other(self, s, data, comparison_op, other):
+class TestComparisonOps(BaseSparseTests):
+ def _compare_other(self, data_for_compare: SparseArray, comparison_op, other):
op = comparison_op
- # array
- result = pd.Series(op(data, other))
- # hard to test the fill value, since we don't know what expected
- # is in general.
- # Rely on tests in `tests/sparse` to validate that.
- assert isinstance(result.dtype, SparseDtype)
- assert result.dtype.subtype == np.dtype("bool")
-
- with np.errstate(all="ignore"):
- expected = pd.Series(
- SparseArray(
- op(np.asarray(data), np.asarray(other)),
- fill_value=result.values.fill_value,
- )
+ result = op(data_for_compare, other)
+ assert isinstance(result, SparseArray)
+ assert result.dtype.subtype == np.bool_
+
+ if isinstance(other, SparseArray):
+ fill_value = op(data_for_compare.fill_value, other.fill_value)
+ else:
+ fill_value = np.all(
+ op(np.asarray(data_for_compare.fill_value), np.asarray(other))
)
- tm.assert_series_equal(result, expected)
+ expected = SparseArray(
+ op(data_for_compare.to_dense(), np.asarray(other)),
+ fill_value=fill_value,
+ dtype=np.bool_,
+ )
+ tm.assert_sp_array_equal(result, expected)
- # series
- ser = pd.Series(data)
- result = op(ser, other)
- tm.assert_series_equal(result, expected)
+ def test_scalar(self, data_for_compare: SparseArray, comparison_op):
+ self._compare_other(data_for_compare, comparison_op, 0)
+ self._compare_other(data_for_compare, comparison_op, 1)
+ self._compare_other(data_for_compare, comparison_op, -1)
+ self._compare_other(data_for_compare, comparison_op, np.nan)
+
+ @pytest.mark.xfail(reason="Wrong indices")
+ def test_array(self, data_for_compare: SparseArray, comparison_op):
+ arr = np.linspace(-4, 5, 10)
+ self._compare_other(data_for_compare, comparison_op, arr)
+
+ @pytest.mark.xfail(reason="Wrong indices")
+ def test_sparse_array(self, data_for_compare: SparseArray, comparison_op):
+ arr = data_for_compare + 1
+ self._compare_other(data_for_compare, comparison_op, arr)
+ arr = data_for_compare * 2
+ self._compare_other(data_for_compare, comparison_op, arr)
class TestPrinting(BaseSparseTests, base.BasePrintingTests):
| - [ ] closes #44956, #45110
- [ ] tests added / passed
Two tests have failed but looks like the reason is not my changes
(Perhaps won't see in checks)
<details>
====================================================================== FAILURES =======================================================================
__________________________________________ TestChaining.test_detect_chained_assignment_warning_stacklevel[3] __________________________________________
self = <pandas.tests.indexing.test_chaining_and_caching.TestChaining object at 0x0000022FC3FBFB80>, rhs = 3
@pytest.mark.parametrize("rhs", [3, DataFrame({0: [1, 2, 3, 4]})])
def test_detect_chained_assignment_warning_stacklevel(self, rhs):
# GH#42570
df = DataFrame(np.arange(25).reshape(5, 5))
chained = df.loc[:3]
with option_context("chained_assignment", "warn"):
with tm.assert_produces_warning(com.SettingWithCopyWarning) as t:
chained[2] = rhs
> assert t[0].filename == __file__
E AssertionError: assert 'c:\\Users\\b...nd_caching.py' == 'C:\\Users\\b...nd_caching.py'
E - C:\Users\bdrum\Development\python\pandas\pandas\tests\indexing\test_chaining_and_caching.py
E ? ^
E + c:\Users\bdrum\Development\python\pandas\pandas\tests\indexing\test_chaining_and_caching.py
E ? ^
pandas\tests\indexing\test_chaining_and_caching.py:444: AssertionError
------------------------------------- generated xml file: C:\Users\bdrum\Development\python\pandas\test-data.xml --------------------------------------
================================================================ slowest 30 durations =================================================================
0.29s call pandas/tests/indexing/test_chaining_and_caching.py::TestChaining::test_detect_chained_assignment_warning_stacklevel[3]
(2 durations < 0.005s hidden. Use -vv to show these durations.)
=============================================================== short test summary info ===============================================================
FAILED pandas/tests/indexing/test_chaining_and_caching.py::TestChaining::test_detect_chained_assignment_warning_stacklevel[3] - AssertionError: asser...
========================================================== 1 failed, 31 deselected in 0.84s ===========================================================
</details>
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry already there
This is only part of solutiion in order to close regression. I will create separate issue that describes global SparseArray indices problem.
Current behavior as expected in #45110
~~~python
s = pd.arrays.SparseArray([1, 2, 3, 4, np.nan, np.nan], fill_value=np.nan)
s[s>2]
# [3.0, 4.0]
# Fill: nan
# IntIndex
# Indices: array([0, 1])
~~~
| https://api.github.com/repos/pandas-dev/pandas/pulls/45125 | 2021-12-30T13:03:30Z | 2022-01-08T21:00:54Z | 2022-01-08T21:00:54Z | 2022-01-09T06:30:10Z |
BUG: IntegerArray/FloatingArray ufunc with 'out' kwd | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 22d6ae94863a1..b6ae804aa27b3 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -939,6 +939,7 @@ ExtensionArray
- Bug in :func:`array` failing to preserve :class:`PandasArray` (:issue:`43887`)
- NumPy ufuncs ``np.abs``, ``np.positive``, ``np.negative`` now correctly preserve dtype when called on ExtensionArrays that implement ``__abs__, __pos__, __neg__``, respectively. In particular this is fixed for :class:`TimedeltaArray` (:issue:`43899`, :issue:`23316`)
- NumPy ufuncs ``np.minimum.reduce`` ``np.maximum.reduce``, ``np.add.reduce``, and ``np.prod.reduce`` now work correctly instead of raising ``NotImplementedError`` on :class:`Series` with ``IntegerDtype`` or ``FloatDtype`` (:issue:`43923`, :issue:`44793`)
+- NumPy ufuncs with ``out`` keyword are now supported by arrays with ``IntegerDtype`` and ``FloatingDtype`` (:issue:`??`)
- Avoid raising ``PerformanceWarning`` about fragmented DataFrame when using many columns with an extension dtype (:issue:`44098`)
- Bug in :class:`IntegerArray` and :class:`FloatingArray` construction incorrectly coercing mismatched NA values (e.g. ``np.timedelta64("NaT")``) to numeric NA (:issue:`44514`)
- Bug in :meth:`BooleanArray.__eq__` and :meth:`BooleanArray.__ne__` raising ``TypeError`` on comparison with an incompatible type (like a string). This caused :meth:`DataFrame.replace` to sometimes raise a ``TypeError`` if a nullable boolean column was included (:issue:`44499`)
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 782fad435c1c5..91415758bda3c 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -433,6 +433,12 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
if result is not NotImplemented:
return result
+ if "out" in kwargs:
+ # e.g. test_ufunc_with_out
+ return arraylike.dispatch_ufunc_with_out(
+ self, ufunc, method, *inputs, **kwargs
+ )
+
if method == "reduce":
result = arraylike.dispatch_reduction_ufunc(
self, ufunc, method, *inputs, **kwargs
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 8a3d892876b5c..4a673fcc6439a 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -92,14 +92,15 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> npt.NDArray[np.bool_]:
# GH#29553 prevent numpy deprecation warnings
pass
else:
- mask |= arr == x
+ new_mask = arr == x
+ if not isinstance(new_mask, np.ndarray):
+ # usually BooleanArray
+ new_mask = new_mask.to_numpy(dtype=bool, na_value=False)
+ mask |= new_mask
if na_mask.any():
mask |= isna(arr)
- if not isinstance(mask, np.ndarray):
- # e.g. if arr is IntegerArray, then mask is BooleanArray
- mask = mask.to_numpy(dtype=bool, na_value=False)
return mask
diff --git a/pandas/tests/arrays/masked_shared.py b/pandas/tests/arrays/masked_shared.py
index 091412e1ec686..454be70cf405b 100644
--- a/pandas/tests/arrays/masked_shared.py
+++ b/pandas/tests/arrays/masked_shared.py
@@ -1,6 +1,8 @@
"""
Tests shared by MaskedArray subclasses.
"""
+import numpy as np
+import pytest
import pandas as pd
import pandas._testing as tm
@@ -102,3 +104,35 @@ def test_compare_to_string(self, dtype):
expected = pd.Series([False, pd.NA], dtype="boolean")
self.assert_series_equal(result, expected)
+
+ def test_ufunc_with_out(self, dtype):
+ arr = pd.array([1, 2, 3], dtype=dtype)
+ arr2 = pd.array([1, 2, pd.NA], dtype=dtype)
+
+ mask = arr == arr
+ mask2 = arr2 == arr2
+
+ result = np.zeros(3, dtype=bool)
+ result |= mask
+ # If MaskedArray.__array_ufunc__ handled "out" appropriately,
+ # `result` should still be an ndarray.
+ assert isinstance(result, np.ndarray)
+ assert result.all()
+
+ # result |= mask worked because mask could be cast lossslessly to
+ # boolean ndarray. mask2 can't, so this raises
+ result = np.zeros(3, dtype=bool)
+ msg = "Specify an appropriate 'na_value' for this dtype"
+ with pytest.raises(ValueError, match=msg):
+ result |= mask2
+
+ # addition
+ res = np.add(arr, arr2)
+ expected = pd.array([2, 4, pd.NA], dtype=dtype)
+ tm.assert_extension_array_equal(res, expected)
+
+ # when passing out=arr, we will modify 'arr' inplace.
+ res = np.add(arr, arr2, out=arr)
+ assert res is arr
+ tm.assert_extension_array_equal(res, expected)
+ tm.assert_extension_array_equal(arr, expected)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45122 | 2021-12-30T02:23:20Z | 2021-12-31T16:37:07Z | 2021-12-31T16:37:07Z | 2021-12-31T19:01:47Z |
BUG: Series.__setitem__ failing to cast numeric values | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 22d6ae94863a1..65f4d7099e336 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -800,6 +800,7 @@ Indexing
- Bug in :meth:`IntervalIndex.get_indexer_non_unique` not handling targets of ``dtype`` 'object' with NaNs correctly (:issue:`44482`)
- Fixed regression where a single column ``np.matrix`` was no longer coerced to a 1d ``np.ndarray`` when added to a :class:`DataFrame` (:issue:`42376`)
- Bug in :meth:`Series.__getitem__` with a :class:`CategoricalIndex` of integers treating lists of integers as positional indexers, inconsistent with the behavior with a single scalar integer (:issue:`15470`, :issue:`14865`)
+- Bug in :meth:`Series.__setitem__` when setting floats or integers into integer-dtype series failing to upcast when necessary to retain precision (:issue:`45121`)
-
Missing
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 4f4eac828fd60..f18f1c760ca28 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -2209,6 +2209,12 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool:
# Anything other than integer we cannot hold
return False
elif dtype.itemsize < tipo.itemsize:
+ if is_integer(element):
+ # e.g. test_setitem_series_int8 if we have a python int 1
+ # tipo may be np.int32, despite the fact that it will fit
+ # in smaller int dtypes.
+ info = np.iinfo(dtype)
+ return info.min <= element <= info.max
return False
elif not isinstance(tipo, np.dtype):
# i.e. nullable IntegerDtype; we can put this into an ndarray
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 252534a0cb790..9b35d9ce39ec6 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -92,6 +92,7 @@
)
from pandas.core.dtypes.cast import (
+ can_hold_element,
construct_1d_arraylike_from_scalar,
construct_2d_arraylike_from_scalar,
find_common_type,
@@ -99,7 +100,6 @@
invalidate_string_dtypes,
maybe_box_native,
maybe_downcast_to_dtype,
- validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_platform_int,
@@ -3865,7 +3865,9 @@ def _set_value(
series = self._get_item_cache(col)
loc = self.index.get_loc(index)
- validate_numeric_casting(series.dtype, value)
+ if not can_hold_element(series._values, value):
+ # We'll go through loc and end up casting.
+ raise TypeError
series._mgr.setitem_inplace(loc, value)
# Note: trying to use series._set_value breaks tests in
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index d2b02a5fac0cb..f84d797b0deb6 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -69,7 +69,6 @@
find_common_type,
infer_dtype_from,
maybe_cast_pointwise_result,
- validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_int64,
@@ -5589,7 +5588,8 @@ def set_value(self, arr, key, value):
stacklevel=find_stack_level(),
)
loc = self._engine.get_loc(key)
- validate_numeric_casting(arr.dtype, value)
+ if not can_hold_element(arr, value):
+ raise ValueError
arr[loc] = value
_index_shared_docs[
diff --git a/pandas/core/series.py b/pandas/core/series.py
index fa1ac0fcfb82d..81b901b13a42b 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -62,10 +62,10 @@
)
from pandas.core.dtypes.cast import (
+ can_hold_element,
convert_dtypes,
maybe_box_native,
maybe_cast_pointwise_result,
- validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_platform_int,
@@ -1143,9 +1143,9 @@ def __setitem__(self, key, value) -> None:
def _set_with_engine(self, key, value) -> None:
loc = self.index.get_loc(key)
- # error: Argument 1 to "validate_numeric_casting" has incompatible type
- # "Union[dtype, ExtensionDtype]"; expected "dtype"
- validate_numeric_casting(self.dtype, value) # type: ignore[arg-type]
+ if not can_hold_element(self._values, value):
+ raise ValueError
+
# this is equivalent to self._values[key] = value
self._mgr.setitem_inplace(loc, value)
diff --git a/pandas/tests/dtypes/cast/test_can_hold_element.py b/pandas/tests/dtypes/cast/test_can_hold_element.py
index 3a486f795f23e..906123b1aee74 100644
--- a/pandas/tests/dtypes/cast/test_can_hold_element.py
+++ b/pandas/tests/dtypes/cast/test_can_hold_element.py
@@ -53,3 +53,18 @@ def test_can_hold_element_int_values_float_ndarray():
# integer but not losslessly castable to int64
element = np.array([3, 2 ** 65], dtype=np.float64)
assert not can_hold_element(arr, element)
+
+
+def test_can_hold_element_int8_int():
+ arr = np.array([], dtype=np.int8)
+
+ element = 2
+ assert can_hold_element(arr, element)
+ assert can_hold_element(arr, np.int8(element))
+ assert can_hold_element(arr, np.uint8(element))
+ assert can_hold_element(arr, np.int16(element))
+ assert can_hold_element(arr, np.uint16(element))
+ assert can_hold_element(arr, np.int32(element))
+ assert can_hold_element(arr, np.uint32(element))
+ assert can_hold_element(arr, np.int64(element))
+ assert can_hold_element(arr, np.uint64(element))
diff --git a/pandas/tests/frame/indexing/test_set_value.py b/pandas/tests/frame/indexing/test_set_value.py
index b8150c26aa6bb..7b68566bab225 100644
--- a/pandas/tests/frame/indexing/test_set_value.py
+++ b/pandas/tests/frame/indexing/test_set_value.py
@@ -1,5 +1,4 @@
import numpy as np
-import pytest
from pandas.core.dtypes.common import is_float_dtype
@@ -38,9 +37,9 @@ def test_set_value_resize(self, float_frame):
res._set_value("foobar", "baz", 5)
assert is_float_dtype(res["baz"])
assert isna(res["baz"].drop(["foobar"])).all()
- msg = "could not convert string to float: 'sam'"
- with pytest.raises(ValueError, match=msg):
- res._set_value("foobar", "baz", "sam")
+
+ res._set_value("foobar", "baz", "sam")
+ assert res.loc["foobar", "baz"] == "sam"
def test_set_value_with_index_dtype_change(self):
df_orig = DataFrame(np.random.randn(3, 3), index=range(3), columns=list("ABC"))
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 014f0f5933387..1ace46b0ca5c9 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -110,38 +110,26 @@ def test_setitem_series_object(self, val, exp_dtype):
"val,exp_dtype",
[(1, np.int64), (1.1, np.float64), (1 + 1j, np.complex128), (True, object)],
)
- def test_setitem_series_int64(self, val, exp_dtype, request):
+ def test_setitem_series_int64(self, val, exp_dtype):
obj = pd.Series([1, 2, 3, 4])
assert obj.dtype == np.int64
- if exp_dtype is np.float64:
- exp = pd.Series([1, 1, 3, 4])
- self._assert_setitem_series_conversion(obj, 1.1, exp, np.int64)
- mark = pytest.mark.xfail(reason="GH12747 The result must be float")
- request.node.add_marker(mark)
-
exp = pd.Series([1, val, 3, 4])
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)]
)
- def test_setitem_series_int8(self, val, exp_dtype, request):
+ def test_setitem_series_int8(self, val, exp_dtype):
obj = pd.Series([1, 2, 3, 4], dtype=np.int8)
assert obj.dtype == np.int8
- if exp_dtype is np.int16:
- exp = pd.Series([1, 0, 3, 4], dtype=np.int8)
- self._assert_setitem_series_conversion(obj, val, exp, np.int8)
- mark = pytest.mark.xfail(
- reason="BUG: it must be pd.Series([1, 1, 3, 4], dtype=np.int16"
- )
- request.node.add_marker(mark)
-
warn = None if exp_dtype is np.int8 else FutureWarning
msg = "Values are too large to be losslessly cast to int8"
with tm.assert_produces_warning(warn, match=msg):
exp = pd.Series([1, val, 3, 4], dtype=np.int8)
+
+ exp = pd.Series([1, val, 3, 4], dtype=exp_dtype)
self._assert_setitem_series_conversion(obj, val, exp, exp_dtype)
@pytest.mark.parametrize(
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
Two cases this fixes (both tested in test_coersion)
```
ser = pd.Series([1, 2, 3, 4])
ser[1] = 1.1
>>> ser[1]
1.1 # <- PR
1 # <- master; note that setting with loc or iloc *does* cast
ser2 = pd.Series([1, 2, 3, 4], dtype=np.int8)
ser2[1] = np.int16(512)
>>> ser2[1]
512 # <- PR; casts to int16
0 # <- master; still np.int8; note that setting with with loc or iloc *does* cast
```
Downside: can_hold_element is heavier-weight than validate_numeric_casting. | https://api.github.com/repos/pandas-dev/pandas/pulls/45121 | 2021-12-30T02:05:16Z | 2021-12-31T15:20:29Z | 2021-12-31T15:20:29Z | 2021-12-31T16:05:09Z |
CI: Migrate Python 3.10 testing to Posix GHA/Azure Pipelines | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index 86c25642f4b2a..135ca0703de8b 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -33,9 +33,11 @@ jobs:
[actions-38.yaml, "not slow and not clipboard", "", "", "", "", ""],
[actions-38.yaml, "slow", "", "", "", "", ""],
[actions-pypy-38.yaml, "not slow and not clipboard", "", "", "", "", "--max-worker-restart 0"],
- [actions-39-numpydev.yaml, "not slow and not network", "xsel", "", "", "deprecate", "-W error"],
[actions-39.yaml, "slow", "", "", "", "", ""],
- [actions-39.yaml, "not slow and not clipboard", "", "", "", "", ""]
+ [actions-39.yaml, "not slow and not clipboard", "", "", "", "", ""],
+ [actions-310-numpydev.yaml, "not slow and not network", "xclip", "", "", "deprecate", "-W error"],
+ [actions-310.yaml, "not slow and not clipboard", "", "", "", "", ""],
+ [actions-310.yaml, "slow", "", "", "", "", ""],
]
fail-fast: false
env:
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 37d8b8474d962..fa1eee2db6fc3 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -1,3 +1,11 @@
+# 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:
@@ -21,13 +29,14 @@ env:
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-310-dev
+ name: actions-311-dev
timeout-minutes: 80
concurrency:
@@ -43,7 +52,7 @@ jobs:
- name: Set up Python Dev Version
uses: actions/setup-python@v2
with:
- python-version: '3.10-dev'
+ python-version: '3.11-dev'
# TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- name: Install dependencies
diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml
index b7c36bb87353b..02a4a9ad44865 100644
--- a/ci/azure/posix.yml
+++ b/ci/azure/posix.yml
@@ -18,6 +18,26 @@ jobs:
CONDA_PY: "38"
PATTERN: "not slow"
PYTEST_TARGET: "pandas/tests/[i-z]*"
+ py39_macos_1:
+ ENV_FILE: ci/deps/azure-macos-39.yaml
+ CONDA_PY: "39"
+ PATTERN: "not slow"
+ PYTEST_TARGET: "pandas/tests/[a-h]*"
+ py39_macos_2:
+ ENV_FILE: ci/deps/azure-macos-39.yaml
+ CONDA_PY: "39"
+ PATTERN: "not slow"
+ PYTEST_TARGET: "pandas/tests/[i-z]*"
+ py310_macos_1:
+ ENV_FILE: ci/deps/azure-macos-310.yaml
+ CONDA_PY: "310"
+ PATTERN: "not slow"
+ PYTEST_TARGET: "pandas/tests/[a-h]*"
+ py310_macos_2:
+ ENV_FILE: ci/deps/azure-macos-310.yaml
+ CONDA_PY: "310"
+ PATTERN: "not slow"
+ PYTEST_TARGET: "pandas/tests/[i-z]*"
steps:
- script: echo '##vso[task.prependpath]$(HOME)/miniconda3/bin'
diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml
index 7f3efb5a4dbf3..7061a266f28c7 100644
--- a/ci/azure/windows.yml
+++ b/ci/azure/windows.yml
@@ -36,6 +36,20 @@ jobs:
PYTEST_WORKERS: 2 # GH-42236
PYTEST_TARGET: "pandas/tests/[i-z]*"
+ py310_1:
+ ENV_FILE: ci/deps/azure-windows-310.yaml
+ CONDA_PY: "310"
+ PATTERN: "not slow and not high_memory"
+ PYTEST_WORKERS: 2 # GH-42236
+ PYTEST_TARGET: "pandas/tests/[a-h]*"
+
+ py310_2:
+ ENV_FILE: ci/deps/azure-windows-310.yaml
+ CONDA_PY: "310"
+ PATTERN: "not slow and not high_memory"
+ PYTEST_WORKERS: 2 # GH-42236
+ PYTEST_TARGET: "pandas/tests/[i-z]*"
+
steps:
- powershell: |
Write-Host "##vso[task.prependpath]$env:CONDA\Scripts"
diff --git a/ci/deps/actions-39-numpydev.yaml b/ci/deps/actions-310-numpydev.yaml
similarity index 95%
rename from ci/deps/actions-39-numpydev.yaml
rename to ci/deps/actions-310-numpydev.yaml
index 4a6acf55e265f..3e32665d5433f 100644
--- a/ci/deps/actions-39-numpydev.yaml
+++ b/ci/deps/actions-310-numpydev.yaml
@@ -2,7 +2,7 @@ name: pandas-dev
channels:
- defaults
dependencies:
- - python=3.9
+ - python=3.10
# tools
- pytest>=6.0
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml
new file mode 100644
index 0000000000000..9829380620f86
--- /dev/null
+++ b/ci/deps/actions-310.yaml
@@ -0,0 +1,51 @@
+name: pandas-dev
+channels:
+ - conda-forge
+dependencies:
+ - python=3.9
+
+ # test dependencies
+ - cython=0.29.24
+ - pytest>=6.0
+ - pytest-cov
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
+ - psutil
+
+ # required dependencies
+ - python-dateutil
+ - numpy
+ - pytz
+
+ # optional dependencies
+ - beautifulsoup4
+ - blosc
+ - bottleneck
+ - fastparquet
+ - fsspec
+ - html5lib
+ - gcsfs
+ - jinja2
+ - lxml
+ - matplotlib
+ # TODO: uncomment after numba supports py310
+ #- numba
+ - numexpr
+ - openpyxl
+ - odfpy
+ - pandas-gbq
+ - psycopg2
+ - pymysql
+ - pytables
+ - pyarrow
+ - pyreadstat
+ - pyxlsb
+ - s3fs
+ - scipy
+ - sqlalchemy
+ - tabulate
+ - xarray
+ - xlrd
+ - xlsxwriter
+ - xlwt
+ - zstandard
diff --git a/ci/deps/azure-macos-310.yaml b/ci/deps/azure-macos-310.yaml
new file mode 100644
index 0000000000000..312fac8091db6
--- /dev/null
+++ b/ci/deps/azure-macos-310.yaml
@@ -0,0 +1,36 @@
+name: pandas-dev
+channels:
+ - defaults
+ - conda-forge
+dependencies:
+ - python=3.10
+
+ # tools
+ - cython>=0.29.24
+ - pytest>=6.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
+ - pytest-azurepipelines
+
+ # pandas dependencies
+ - beautifulsoup4
+ - bottleneck
+ - html5lib
+ - jinja2
+ - lxml
+ - matplotlib
+ - nomkl
+ - numexpr
+ - numpy
+ - openpyxl
+ - pyarrow
+ - pyreadstat
+ - pytables
+ - python-dateutil==2.8.1
+ - pytz
+ - pyxlsb
+ - xarray
+ - xlrd
+ - xlsxwriter
+ - xlwt
+ - zstandard
diff --git a/ci/deps/azure-macos-38.yaml b/ci/deps/azure-macos-38.yaml
index 472dc8754d13e..422aa86c57fc7 100644
--- a/ci/deps/azure-macos-38.yaml
+++ b/ci/deps/azure-macos-38.yaml
@@ -6,6 +6,7 @@ dependencies:
- python=3.8
# tools
+ - cython>=0.29.24
- pytest>=6.0
- pytest-xdist>=1.31
- hypothesis>=5.5.3
@@ -33,6 +34,3 @@ dependencies:
- xlsxwriter
- xlwt
- zstandard
- - pip
- - pip:
- - cython>=0.29.24
diff --git a/ci/deps/azure-macos-39.yaml b/ci/deps/azure-macos-39.yaml
new file mode 100644
index 0000000000000..a0860ef536953
--- /dev/null
+++ b/ci/deps/azure-macos-39.yaml
@@ -0,0 +1,36 @@
+name: pandas-dev
+channels:
+ - defaults
+ - conda-forge
+dependencies:
+ - python=3.9
+
+ # tools
+ - cython>=0.29.24
+ - pytest>=6.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
+ - pytest-azurepipelines
+
+ # pandas dependencies
+ - beautifulsoup4
+ - bottleneck
+ - html5lib
+ - jinja2
+ - lxml
+ - matplotlib=3.3.2
+ - nomkl
+ - numexpr
+ - numpy=1.21.3
+ - openpyxl
+ - pyarrow=1.0.1
+ - pyreadstat
+ - pytables
+ - python-dateutil==2.8.1
+ - pytz
+ - pyxlsb
+ - xarray
+ - xlrd
+ - xlsxwriter
+ - xlwt
+ - zstandard
diff --git a/ci/deps/azure-windows-310.yaml b/ci/deps/azure-windows-310.yaml
new file mode 100644
index 0000000000000..8e6f4deef6057
--- /dev/null
+++ b/ci/deps/azure-windows-310.yaml
@@ -0,0 +1,41 @@
+name: pandas-dev
+channels:
+ - conda-forge
+ - defaults
+dependencies:
+ - python=3.10
+
+ # tools
+ - cython>=0.29.24
+ - pytest>=6.0
+ - pytest-xdist>=1.31
+ - hypothesis>=5.5.3
+ - pytest-azurepipelines
+
+ # pandas dependencies
+ - beautifulsoup4
+ - bottleneck
+ - fsspec>=0.8.0
+ - gcsfs
+ - html5lib
+ - jinja2
+ - lxml
+ - matplotlib
+ # TODO: uncomment after numba supports py310
+ #- numba
+ - numexpr
+ - numpy
+ - openpyxl
+ - pyarrow
+ - pytables
+ - python-dateutil
+ - pytz
+ - s3fs>=0.4.2
+ - scipy
+ - sqlalchemy
+ - xlrd
+ - xlsxwriter
+ - xlwt
+ - pyreadstat
+ - pyxlsb
+ - zstandard
diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py
index 6c07366e402d6..ff247349ff4d5 100644
--- a/pandas/tests/plotting/frame/test_frame.py
+++ b/pandas/tests/plotting/frame/test_frame.py
@@ -682,7 +682,7 @@ def test_raise_error_on_datetime_time_data(self):
# GH 8113, datetime.time type is not supported by matplotlib in scatter
df = DataFrame(np.random.randn(10), columns=["a"])
df["dtime"] = date_range(start="2014-01-01", freq="h", periods=10).time
- msg = "must be a string or a number, not 'datetime.time'"
+ msg = "must be a string or a (real )?number, not 'datetime.time'"
with pytest.raises(TypeError, match=msg):
df.plot(kind="scatter", x="dtime", y="a")
| - [ ] closes #43890
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45120 | 2021-12-30T00:33:50Z | 2022-01-17T13:42:04Z | 2022-01-17T13:42:03Z | 2022-01-20T20:17:04Z |
Improving ambiguous doc string | diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx
index 9d3b80b321537..924a7ad9a0751 100644
--- a/pandas/_libs/reshape.pyx
+++ b/pandas/_libs/reshape.pyx
@@ -87,7 +87,7 @@ def explode(ndarray[object] values):
Parameters
----------
- values : object ndarray
+ values : ndarray[object]
Returns
-------
| null | https://api.github.com/repos/pandas-dev/pandas/pulls/45119 | 2021-12-30T00:23:16Z | 2021-12-30T01:13:23Z | 2021-12-30T01:13:23Z | 2021-12-30T01:13:28Z |
CI/TST: Set deadline=None for flaky hypothesis test | diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py
index 1b4fa9292c403..5071c816c313d 100644
--- a/pandas/tests/tseries/offsets/test_offsets_properties.py
+++ b/pandas/tests/tseries/offsets/test_offsets_properties.py
@@ -10,6 +10,7 @@
from hypothesis import (
assume,
given,
+ settings,
)
import pytest
import pytz
@@ -45,6 +46,7 @@ def test_on_offset_implementations(dt, offset):
@given(YQM_OFFSET)
+@settings(deadline=None) # GH 45118
def test_shift_across_dst(offset):
# GH#18319 check that 1) timezone is correctly normalized and
# 2) that hour is not incorrectly changed by this normalization
| xref: https://github.com/pandas-dev/pandas/runs/4662296945?check_suite_focus=true
| https://api.github.com/repos/pandas-dev/pandas/pulls/45118 | 2021-12-29T23:06:46Z | 2021-12-30T00:21:03Z | 2021-12-30T00:21:03Z | 2021-12-30T01:20:08Z |
REF: avoid object-casting in _get_codes_for_values | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index bc83c723fae4a..25b9a1212a1ef 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -298,7 +298,7 @@ def _get_values_for_rank(values: ArrayLike) -> np.ndarray:
return values
-def get_data_algo(values: ArrayLike):
+def _get_data_algo(values: ArrayLike):
values = _get_values_for_rank(values)
ndtype = _check_object_for_strings(values)
@@ -555,7 +555,7 @@ def factorize_array(
codes : ndarray[np.intp]
uniques : ndarray
"""
- hash_klass, values = get_data_algo(values)
+ hash_klass, values = _get_data_algo(values)
table = hash_klass(size_hint or len(values))
uniques, codes = table.factorize(
@@ -1747,7 +1747,7 @@ def safe_sort(
if sorter is None:
# mixed types
- hash_klass, values = get_data_algo(values)
+ hash_klass, values = _get_data_algo(values)
t = hash_klass(len(values))
t.map_locations(values)
sorter = ensure_platform_int(t.lookup(ordered))
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index acace9085e18e..0188fedbf7741 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -55,7 +55,6 @@
)
from pandas.core.dtypes.common import (
ensure_int64,
- ensure_object,
ensure_platform_int,
is_categorical_dtype,
is_datetime64_dtype,
@@ -93,7 +92,6 @@
import pandas.core.algorithms as algorithms
from pandas.core.algorithms import (
factorize,
- get_data_algo,
take_nd,
unique1d,
)
@@ -2749,8 +2747,6 @@ def _get_codes_for_values(values, categories: Index) -> np.ndarray:
If `values` is known to be a Categorical, use recode_for_categories instead.
"""
- dtype_equal = is_dtype_equal(values.dtype, categories.dtype)
-
if values.ndim > 1:
flat = values.ravel()
codes = _get_codes_for_values(flat, categories)
@@ -2762,30 +2758,9 @@ def _get_codes_for_values(values, categories: Index) -> np.ndarray:
# Categorical(array[Period, Period], categories=PeriodIndex(...))
cls = categories.dtype.construct_array_type()
values = maybe_cast_to_extension_array(cls, values)
- if not isinstance(values, cls):
- # exception raised in _from_sequence
- values = ensure_object(values)
- # error: Incompatible types in assignment (expression has type
- # "ndarray", variable has type "Index")
- categories = ensure_object(categories) # type: ignore[assignment]
- elif not dtype_equal:
- values = ensure_object(values)
- # error: Incompatible types in assignment (expression has type "ndarray",
- # variable has type "Index")
- categories = ensure_object(categories) # type: ignore[assignment]
-
- if isinstance(categories, ABCIndex):
- return coerce_indexer_dtype(categories.get_indexer_for(values), categories)
-
- # Only hit here when we've already coerced to object dtypee.
-
- hash_klass, vals = get_data_algo(values)
- # pandas/core/arrays/categorical.py:2661: error: Argument 1 to "get_data_algo" has
- # incompatible type "Index"; expected "Union[ExtensionArray, ndarray]" [arg-type]
- _, cats = get_data_algo(categories) # type: ignore[arg-type]
- t = hash_klass(len(cats))
- t.map_locations(cats)
- return coerce_indexer_dtype(t.lookup(vals), cats)
+
+ codes = categories.get_indexer_for(values)
+ return coerce_indexer_dtype(codes, categories)
def recode_for_categories(
diff --git a/pandas/tests/io/parser/dtypes/test_categorical.py b/pandas/tests/io/parser/dtypes/test_categorical.py
index 7e04dd570e812..3b8c520004f12 100644
--- a/pandas/tests/io/parser/dtypes/test_categorical.py
+++ b/pandas/tests/io/parser/dtypes/test_categorical.py
@@ -269,7 +269,6 @@ def test_categorical_coerces_timestamp(all_parsers):
tm.assert_frame_equal(result, expected)
-@xfail_pyarrow
def test_categorical_coerces_timedelta(all_parsers):
parser = all_parsers
dtype = {"b": CategoricalDtype(pd.to_timedelta(["1H", "2H", "3H"]))}
| Index.get_indexer_for ends up going through the same hashtable-based lookup anyway. We add a little constructor overhead, but avoid object-dtype casting in cases where the common-dtype is e.g. numeric. | https://api.github.com/repos/pandas-dev/pandas/pulls/45117 | 2021-12-29T22:56:06Z | 2021-12-30T15:53:26Z | 2021-12-30T15:53:26Z | 2021-12-30T15:54:25Z |
BUG: to_xml raising for pd.NA | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 22d6ae94863a1..3924191bebcfd 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -856,6 +856,7 @@ I/O
- Bug in :func:`to_csv` always coercing datetime columns with different formats to the same format (:issue:`21734`)
- :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` with ``compression`` set to ``'zip'`` no longer create a zip file containing a file ending with ".zip". Instead, they try to infer the inner file name more smartly. (:issue:`39465`)
- Bug in :func:`read_csv` where reading a mixed column of booleans and missing values to a float type results in the missing values becoming 1.0 rather than NaN (:issue:`42808`, :issue:`34120`)
+- Bug in :func:`to_xml` raising error for ``pd.NA`` with extension array dtype (:issue:`43903`)
- Bug in :func:`read_csv` when passing simultaneously a parser in ``date_parser`` and ``parse_dates=False``, the parsing was still called (:issue:`44366`)
- Bug in :func:`read_csv` not setting name of :class:`MultiIndex` columns correctly when ``index_col`` is not the first column (:issue:`38549`)
- Bug in :func:`read_csv` silently ignoring errors when failing to create a memory-mapped file (:issue:`44766`)
diff --git a/pandas/io/formats/xml.py b/pandas/io/formats/xml.py
index 8e05afaa06919..1b11bb12757bb 100644
--- a/pandas/io/formats/xml.py
+++ b/pandas/io/formats/xml.py
@@ -18,6 +18,7 @@
from pandas.util._decorators import doc
from pandas.core.dtypes.common import is_list_like
+from pandas.core.dtypes.missing import isna
from pandas.core.frame import DataFrame
from pandas.core.shared_docs import _shared_docs
@@ -571,9 +572,7 @@ def build_elems(self) -> None:
elem_name = f"{self.prefix_uri}{flat_col}"
try:
val = (
- None
- if self.d[col] in [None, ""] or self.d[col] != self.d[col]
- else str(self.d[col])
+ None if isna(self.d[col]) or self.d[col] == "" else str(self.d[col])
)
SubElement(self.elem_row, elem_name).text = val
except KeyError:
diff --git a/pandas/tests/io/xml/__init__.py b/pandas/tests/io/xml/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py
index e0c2b3794a00c..c8828c08dba44 100644
--- a/pandas/tests/io/xml/test_to_xml.py
+++ b/pandas/tests/io/xml/test_to_xml.py
@@ -12,6 +12,7 @@
import pandas.util._test_decorators as td
from pandas import (
+ NA,
DataFrame,
Index,
)
@@ -1307,15 +1308,25 @@ def test_filename_and_suffix_comp(parser, compression_only):
assert geom_xml == output.strip()
+@td.skip_if_no("lxml")
+def test_ea_dtypes(any_numeric_ea_dtype):
+ # GH#43903
+ expected = """<?xml version='1.0' encoding='utf-8'?>
+<data>
+ <row>
+ <index>0</index>
+ <a/>
+ </row>
+</data>"""
+ df = DataFrame({"a": [NA]}).astype(any_numeric_ea_dtype)
+ result = df.to_xml()
+ assert result.strip() == expected
+
+
def test_unsuported_compression(datapath, parser):
with pytest.raises(ValueError, match="Unrecognized compression type"):
with tm.ensure_clean() as path:
- # Argument "compression" to "to_xml" of "DataFrame" has incompatible type
- # "Literal['7z']"; expected "Union[Literal['infer'], Literal['gzip'],
- # Literal['bz2'], Literal['zip'], Literal['xz'], Dict[str, Any], None]"
- geom_df.to_xml(
- path, parser=parser, compression="7z" # type: ignore[arg-type]
- )
+ geom_df.to_xml(path, parser=parser, compression="7z")
# STORAGE OPTIONS
diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py
index 30ba95fd82bf2..b72111ec6cf1e 100644
--- a/pandas/tests/io/xml/test_xml.py
+++ b/pandas/tests/io/xml/test_xml.py
@@ -684,9 +684,7 @@ def test_names_option_wrong_type(datapath, parser):
filename = datapath("io", "data", "xml", "books.xml")
with pytest.raises(TypeError, match=("is not a valid type for names")):
- read_xml(
- filename, names="Col1, Col2, Col3", parser=parser # type: ignore[arg-type]
- )
+ read_xml(filename, names="Col1, Col2, Col3", parser=parser)
# ENCODING
@@ -1056,10 +1054,7 @@ def test_wrong_compression(parser, compression, compression_only):
def test_unsuported_compression(datapath, parser):
with pytest.raises(ValueError, match="Unrecognized compression type"):
with tm.ensure_clean() as path:
- # error: Argument "compression" to "read_xml" has incompatible type
- # "Literal['7z']"; expected "Union[Literal['infer'], Literal['gzip'],
- # Literal['bz2'], Literal['zip'], Literal['xz'], Dict[str, Any], None]"
- read_xml(path, parser=parser, compression="7z") # type: ignore[arg-type]
+ read_xml(path, parser=parser, compression="7z")
# STORAGE OPTIONS
| - [x] closes #43903
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45116 | 2021-12-29T22:20:17Z | 2021-12-30T14:10:52Z | 2021-12-30T14:10:51Z | 2021-12-30T14:13:33Z |
TST: More pytest.mark.parameterize | diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 8b677bde2f7e2..7cf2721621a03 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -775,16 +775,6 @@ def test_constructor_dict_of_generators(self):
tm.assert_frame_equal(result, expected)
def test_constructor_dict_multiindex(self):
- def check(result, expected):
- return tm.assert_frame_equal(
- result,
- expected,
- check_dtype=True,
- check_index_type=True,
- check_column_type=True,
- check_names=True,
- )
-
d = {
("a", "a"): {("i", "i"): 0, ("i", "j"): 1, ("j", "i"): 2},
("b", "a"): {("i", "i"): 6, ("i", "j"): 5, ("j", "i"): 4},
@@ -796,7 +786,10 @@ def check(result, expected):
[x[1] for x in _d], index=MultiIndex.from_tuples([x[0] for x in _d])
).T
expected.index = MultiIndex.from_tuples(expected.index)
- check(df, expected)
+ tm.assert_frame_equal(
+ df,
+ expected,
+ )
d["z"] = {"y": 123.0, ("i", "i"): 111, ("i", "j"): 111, ("j", "i"): 111}
_d.insert(0, ("z", d["z"]))
@@ -806,7 +799,7 @@ def check(result, expected):
expected.index = Index(expected.index, tupleize_cols=False)
df = DataFrame(d)
df = df.reindex(columns=expected.columns, index=expected.index)
- check(df, expected)
+ tm.assert_frame_equal(df, expected)
def test_constructor_dict_datetime64_index(self):
# GH 10160
@@ -2167,44 +2160,38 @@ def test_constructor_series_copy(self, float_frame):
assert not (series["A"] == 5).all()
- def test_constructor_with_nas(self):
+ @pytest.mark.parametrize(
+ "df",
+ [
+ DataFrame([[1, 2, 3], [4, 5, 6]], index=[1, np.nan]),
+ DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1.1, 2.2, np.nan]),
+ DataFrame([[0, 1, 2, 3], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan]),
+ DataFrame(
+ [[0.0, 1, 2, 3.0], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan]
+ ),
+ DataFrame([[0.0, 1, 2, 3.0], [4, 5, 6, 7]], columns=[np.nan, 1, 2, 2]),
+ ],
+ )
+ def test_constructor_with_nas(self, df):
# GH 5016
# na's in indices
+ # GH 21428 (non-unique columns)
- def check(df):
- for i in range(len(df.columns)):
- df.iloc[:, i]
-
- indexer = np.arange(len(df.columns))[isna(df.columns)]
-
- # No NaN found -> error
- if len(indexer) == 0:
- with pytest.raises(KeyError, match="^nan$"):
- df.loc[:, np.nan]
- # single nan should result in Series
- elif len(indexer) == 1:
- tm.assert_series_equal(df.iloc[:, indexer[0]], df.loc[:, np.nan])
- # multiple nans should result in DataFrame
- else:
- tm.assert_frame_equal(df.iloc[:, indexer], df.loc[:, np.nan])
-
- df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[1, np.nan])
- check(df)
-
- df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1.1, 2.2, np.nan])
- check(df)
-
- df = DataFrame([[0, 1, 2, 3], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan])
- check(df)
+ for i in range(len(df.columns)):
+ df.iloc[:, i]
- df = DataFrame(
- [[0.0, 1, 2, 3.0], [4, 5, 6, 7]], columns=[np.nan, 1.1, 2.2, np.nan]
- )
- check(df)
+ indexer = np.arange(len(df.columns))[isna(df.columns)]
- # GH 21428 (non-unique columns)
- df = DataFrame([[0.0, 1, 2, 3.0], [4, 5, 6, 7]], columns=[np.nan, 1, 2, 2])
- check(df)
+ # No NaN found -> error
+ if len(indexer) == 0:
+ with pytest.raises(KeyError, match="^nan$"):
+ df.loc[:, np.nan]
+ # single nan should result in Series
+ elif len(indexer) == 1:
+ tm.assert_series_equal(df.iloc[:, indexer[0]], df.loc[:, np.nan])
+ # multiple nans should result in DataFrame
+ else:
+ tm.assert_frame_equal(df.iloc[:, indexer], df.loc[:, np.nan])
def test_constructor_lists_to_object_dtype(self):
# from #1074
diff --git a/pandas/tests/groupby/test_libgroupby.py b/pandas/tests/groupby/test_libgroupby.py
index 06e3e4f2877d6..2a24448d24ce2 100644
--- a/pandas/tests/groupby/test_libgroupby.py
+++ b/pandas/tests/groupby/test_libgroupby.py
@@ -130,35 +130,32 @@ class TestGroupVarFloat32(GroupVarTestMixin):
rtol = 1e-2
-def test_group_ohlc():
- def _check(dtype):
- obj = np.array(np.random.randn(20), dtype=dtype)
+@pytest.mark.parametrize("dtype", ["float32", "float64"])
+def test_group_ohlc(dtype):
+ obj = np.array(np.random.randn(20), dtype=dtype)
- bins = np.array([6, 12, 20])
- out = np.zeros((3, 4), dtype)
- counts = np.zeros(len(out), dtype=np.int64)
- labels = ensure_platform_int(np.repeat(np.arange(3), np.diff(np.r_[0, bins])))
+ bins = np.array([6, 12, 20])
+ out = np.zeros((3, 4), dtype)
+ counts = np.zeros(len(out), dtype=np.int64)
+ labels = ensure_platform_int(np.repeat(np.arange(3), np.diff(np.r_[0, bins])))
- func = libgroupby.group_ohlc
- func(out, counts, obj[:, None], labels)
+ func = libgroupby.group_ohlc
+ func(out, counts, obj[:, None], labels)
- def _ohlc(group):
- if isna(group).all():
- return np.repeat(np.nan, 4)
- return [group[0], group.max(), group.min(), group[-1]]
+ def _ohlc(group):
+ if isna(group).all():
+ return np.repeat(np.nan, 4)
+ return [group[0], group.max(), group.min(), group[-1]]
- expected = np.array([_ohlc(obj[:6]), _ohlc(obj[6:12]), _ohlc(obj[12:])])
+ expected = np.array([_ohlc(obj[:6]), _ohlc(obj[6:12]), _ohlc(obj[12:])])
- tm.assert_almost_equal(out, expected)
- tm.assert_numpy_array_equal(counts, np.array([6, 6, 8], dtype=np.int64))
+ tm.assert_almost_equal(out, expected)
+ tm.assert_numpy_array_equal(counts, np.array([6, 6, 8], dtype=np.int64))
- obj[:6] = np.nan
- func(out, counts, obj[:, None], labels)
- expected[0] = np.nan
- tm.assert_almost_equal(out, expected)
-
- _check("float32")
- _check("float64")
+ obj[:6] = np.nan
+ func(out, counts, obj[:, None], labels)
+ expected[0] = np.nan
+ tm.assert_almost_equal(out, expected)
def _check_cython_group_transform_cumulative(pd_op, np_op, dtype):
diff --git a/pandas/tests/indexes/multi/test_duplicates.py b/pandas/tests/indexes/multi/test_duplicates.py
index ee517a667d832..6ec4d1fac8c8a 100644
--- a/pandas/tests/indexes/multi/test_duplicates.py
+++ b/pandas/tests/indexes/multi/test_duplicates.py
@@ -178,49 +178,44 @@ def test_has_duplicates_from_tuples():
assert not mi.has_duplicates
-def test_has_duplicates_overflow():
+@pytest.mark.parametrize("nlevels", [4, 8])
+@pytest.mark.parametrize("with_nulls", [True, False])
+def test_has_duplicates_overflow(nlevels, with_nulls):
# handle int64 overflow if possible
- def check(nlevels, with_nulls):
- codes = np.tile(np.arange(500), 2)
- level = np.arange(500)
+ # no overflow with 4
+ # overflow possible with 8
+ codes = np.tile(np.arange(500), 2)
+ level = np.arange(500)
- if with_nulls: # inject some null values
- codes[500] = -1 # common nan value
- codes = [codes.copy() for i in range(nlevels)]
- for i in range(nlevels):
- codes[i][500 + i - nlevels // 2] = -1
+ if with_nulls: # inject some null values
+ codes[500] = -1 # common nan value
+ codes = [codes.copy() for i in range(nlevels)]
+ for i in range(nlevels):
+ codes[i][500 + i - nlevels // 2] = -1
- codes += [np.array([-1, 1]).repeat(500)]
- else:
- codes = [codes] * nlevels + [np.arange(2).repeat(500)]
+ codes += [np.array([-1, 1]).repeat(500)]
+ else:
+ codes = [codes] * nlevels + [np.arange(2).repeat(500)]
- levels = [level] * nlevels + [[0, 1]]
+ levels = [level] * nlevels + [[0, 1]]
- # no dups
- mi = MultiIndex(levels=levels, codes=codes)
- assert not mi.has_duplicates
-
- # with a dup
- if with_nulls:
-
- def f(a):
- return np.insert(a, 1000, a[0])
+ # no dups
+ mi = MultiIndex(levels=levels, codes=codes)
+ assert not mi.has_duplicates
- codes = list(map(f, codes))
- mi = MultiIndex(levels=levels, codes=codes)
- else:
- values = mi.values.tolist()
- mi = MultiIndex.from_tuples(values + [values[0]])
+ # with a dup
+ if with_nulls:
- assert mi.has_duplicates
+ def f(a):
+ return np.insert(a, 1000, a[0])
- # no overflow
- check(4, False)
- check(4, True)
+ codes = list(map(f, codes))
+ mi = MultiIndex(levels=levels, codes=codes)
+ else:
+ values = mi.values.tolist()
+ mi = MultiIndex.from_tuples(values + [values[0]])
- # overflow possible
- check(8, False)
- check(8, True)
+ assert mi.has_duplicates
@pytest.mark.parametrize(
diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py
index e6dfe64df3864..5544b8112627b 100644
--- a/pandas/tests/io/pytables/test_append.py
+++ b/pandas/tests/io/pytables/test_append.py
@@ -670,14 +670,10 @@ def test_append_misc(setup_path):
result = store.select("df1")
tm.assert_frame_equal(result, df)
- # more chunksize in append tests
- def check(obj, comparator):
- for c in [10, 200, 1000]:
- with ensure_clean_store(setup_path, mode="w") as store:
- store.append("obj", obj, chunksize=c)
- result = store.select("obj")
- comparator(result, obj)
+@pytest.mark.parametrize("chunksize", [10, 200, 1000])
+def test_append_misc_chunksize(setup_path, chunksize):
+ # more chunksize in append tests
df = tm.makeDataFrame()
df["string"] = "foo"
df["float322"] = 1.0
@@ -685,8 +681,13 @@ def check(obj, comparator):
df["bool"] = df["float322"] > 0
df["time1"] = Timestamp("20130101")
df["time2"] = Timestamp("20130102")
- check(df, tm.assert_frame_equal)
+ with ensure_clean_store(setup_path, mode="w") as store:
+ store.append("obj", df, chunksize=chunksize)
+ result = store.select("obj")
+ tm.assert_frame_equal(result, df)
+
+def test_append_misc_empty_frame(setup_path):
# empty frame, GH4273
with ensure_clean_store(setup_path) as store:
diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py
index df0f7b0951b7d..027c3d0bd821c 100644
--- a/pandas/tests/io/pytables/test_file_handling.py
+++ b/pandas/tests/io/pytables/test_file_handling.py
@@ -29,71 +29,64 @@
pytestmark = pytest.mark.single
-def test_mode(setup_path):
+@pytest.mark.parametrize("mode", ["r", "r+", "a", "w"])
+def test_mode(setup_path, mode):
df = tm.makeTimeDataFrame()
+ msg = r"[\S]* does not exist"
+ with ensure_clean_path(setup_path) as path:
- def check(mode):
-
- msg = r"[\S]* does not exist"
- with ensure_clean_path(setup_path) as path:
-
- # constructor
- if mode in ["r", "r+"]:
- with pytest.raises(OSError, match=msg):
- HDFStore(path, mode=mode)
+ # constructor
+ if mode in ["r", "r+"]:
+ with pytest.raises(OSError, match=msg):
+ HDFStore(path, mode=mode)
- else:
- store = HDFStore(path, mode=mode)
- assert store._handle.mode == mode
- store.close()
+ else:
+ store = HDFStore(path, mode=mode)
+ assert store._handle.mode == mode
+ store.close()
- with ensure_clean_path(setup_path) as path:
+ with ensure_clean_path(setup_path) as path:
- # context
- if mode in ["r", "r+"]:
- with pytest.raises(OSError, match=msg):
- with HDFStore(path, mode=mode) as store:
- pass
- else:
+ # context
+ if mode in ["r", "r+"]:
+ with pytest.raises(OSError, match=msg):
with HDFStore(path, mode=mode) as store:
- assert store._handle.mode == mode
+ pass
+ else:
+ with HDFStore(path, mode=mode) as store:
+ assert store._handle.mode == mode
- with ensure_clean_path(setup_path) as path:
+ with ensure_clean_path(setup_path) as path:
- # conv write
- if mode in ["r", "r+"]:
- with pytest.raises(OSError, match=msg):
- df.to_hdf(path, "df", mode=mode)
- df.to_hdf(path, "df", mode="w")
- else:
+ # conv write
+ if mode in ["r", "r+"]:
+ with pytest.raises(OSError, match=msg):
df.to_hdf(path, "df", mode=mode)
-
- # conv read
- if mode in ["w"]:
- msg = (
- "mode w is not allowed while performing a read. "
- r"Allowed modes are r, r\+ and a."
- )
- with pytest.raises(ValueError, match=msg):
- read_hdf(path, "df", mode=mode)
- else:
- result = read_hdf(path, "df", mode=mode)
- tm.assert_frame_equal(result, df)
-
- def check_default_mode():
-
- # read_hdf uses default mode
- with ensure_clean_path(setup_path) as path:
df.to_hdf(path, "df", mode="w")
- result = read_hdf(path, "df")
+ else:
+ df.to_hdf(path, "df", mode=mode)
+
+ # conv read
+ if mode in ["w"]:
+ msg = (
+ "mode w is not allowed while performing a read. "
+ r"Allowed modes are r, r\+ and a."
+ )
+ with pytest.raises(ValueError, match=msg):
+ read_hdf(path, "df", mode=mode)
+ else:
+ result = read_hdf(path, "df", mode=mode)
tm.assert_frame_equal(result, df)
- check("r")
- check("r+")
- check("a")
- check("w")
- check_default_mode()
+
+def test_default_mode(setup_path):
+ # read_hdf uses default mode
+ df = tm.makeTimeDataFrame()
+ with ensure_clean_path(setup_path) as path:
+ df.to_hdf(path, "df", mode="w")
+ result = read_hdf(path, "df")
+ tm.assert_frame_equal(result, df)
def test_reopen_handle(setup_path):
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45115 | 2021-12-29T22:03:01Z | 2021-12-30T14:08:56Z | 2021-12-30T14:08:56Z | 2021-12-30T17:56:49Z |
TST: Parameterize test_rank.py | diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index 87af6152b8189..4820fcce6486b 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -94,64 +94,92 @@ def test_frame_in_list(self):
with pytest.raises(ValueError, match=msg):
df in [None]
- def test_comparison_invalid(self):
- def check(df, df2):
-
- for (x, y) in [(df, df2), (df2, df)]:
- # we expect the result to match Series comparisons for
- # == and !=, inequalities should raise
- result = x == y
- expected = DataFrame(
- {col: x[col] == y[col] for col in x.columns},
- index=x.index,
- columns=x.columns,
- )
- tm.assert_frame_equal(result, expected)
-
- result = x != y
- expected = DataFrame(
- {col: x[col] != y[col] for col in x.columns},
- index=x.index,
- columns=x.columns,
- )
- tm.assert_frame_equal(result, expected)
-
- msgs = [
- r"Invalid comparison between dtype=datetime64\[ns\] and ndarray",
- "invalid type promotion",
- (
- # npdev 1.20.0
- r"The DTypes <class 'numpy.dtype\[.*\]'> and "
- r"<class 'numpy.dtype\[.*\]'> do not have a common DType."
- ),
- ]
- msg = "|".join(msgs)
- with pytest.raises(TypeError, match=msg):
- x >= y
- with pytest.raises(TypeError, match=msg):
- x > y
- with pytest.raises(TypeError, match=msg):
- x < y
- with pytest.raises(TypeError, match=msg):
- x <= y
-
+ @pytest.mark.parametrize(
+ "arg, arg2",
+ [
+ [
+ {
+ "a": np.random.randint(10, size=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ {
+ "a": np.random.randint(10, size=10),
+ "b": np.random.randint(10, size=10),
+ },
+ ],
+ [
+ {
+ "a": np.random.randint(10, size=10),
+ "b": np.random.randint(10, size=10),
+ },
+ {
+ "a": np.random.randint(10, size=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ ],
+ [
+ {
+ "a": pd.date_range("20010101", periods=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ {
+ "a": np.random.randint(10, size=10),
+ "b": np.random.randint(10, size=10),
+ },
+ ],
+ [
+ {
+ "a": np.random.randint(10, size=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ {
+ "a": pd.date_range("20010101", periods=10),
+ "b": pd.date_range("20010101", periods=10),
+ },
+ ],
+ ],
+ )
+ def test_comparison_invalid(self, arg, arg2):
# GH4968
# invalid date/int comparisons
- df = DataFrame(np.random.randint(10, size=(10, 1)), columns=["a"])
- df["dates"] = pd.date_range("20010101", periods=len(df))
-
- df2 = df.copy()
- df2["dates"] = df["a"]
- check(df, df2)
+ x = DataFrame(arg)
+ y = DataFrame(arg2)
+ # we expect the result to match Series comparisons for
+ # == and !=, inequalities should raise
+ result = x == y
+ expected = DataFrame(
+ {col: x[col] == y[col] for col in x.columns},
+ index=x.index,
+ columns=x.columns,
+ )
+ tm.assert_frame_equal(result, expected)
- df = DataFrame(np.random.randint(10, size=(10, 2)), columns=["a", "b"])
- df2 = DataFrame(
- {
- "a": pd.date_range("20010101", periods=len(df)),
- "b": pd.date_range("20100101", periods=len(df)),
- }
+ result = x != y
+ expected = DataFrame(
+ {col: x[col] != y[col] for col in x.columns},
+ index=x.index,
+ columns=x.columns,
)
- check(df, df2)
+ tm.assert_frame_equal(result, expected)
+
+ msgs = [
+ r"Invalid comparison between dtype=datetime64\[ns\] and ndarray",
+ "invalid type promotion",
+ (
+ # npdev 1.20.0
+ r"The DTypes <class 'numpy.dtype\[.*\]'> and "
+ r"<class 'numpy.dtype\[.*\]'> do not have a common DType."
+ ),
+ ]
+ msg = "|".join(msgs)
+ with pytest.raises(TypeError, match=msg):
+ x >= y
+ with pytest.raises(TypeError, match=msg):
+ x > y
+ with pytest.raises(TypeError, match=msg):
+ x < y
+ with pytest.raises(TypeError, match=msg):
+ x <= y
def test_timestamp_compare(self):
# make sure we can compare Timestamps on the right AND left hand side
diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py
index 43b210a50dab2..d85b84bec55ac 100644
--- a/pandas/tests/series/methods/test_rank.py
+++ b/pandas/tests/series/methods/test_rank.py
@@ -1,7 +1,5 @@
-from itertools import (
- chain,
- product,
-)
+from itertools import chain
+import operator
import numpy as np
import pytest
@@ -22,17 +20,25 @@
from pandas.api.types import CategoricalDtype
-class TestSeriesRank:
- s = Series([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3])
+@pytest.fixture
+def ser():
+ return Series([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3])
+
+
+@pytest.fixture(
+ params=[
+ ["average", np.array([1.5, 5.5, 7.0, 3.5, np.nan, 3.5, 1.5, 8.0, np.nan, 5.5])],
+ ["min", np.array([1, 5, 7, 3, np.nan, 3, 1, 8, np.nan, 5])],
+ ["max", np.array([2, 6, 7, 4, np.nan, 4, 2, 8, np.nan, 6])],
+ ["first", np.array([1, 5, 7, 3, np.nan, 4, 2, 8, np.nan, 6])],
+ ["dense", np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3])],
+ ]
+)
+def results(request):
+ return request.param
- results = {
- "average": np.array([1.5, 5.5, 7.0, 3.5, np.nan, 3.5, 1.5, 8.0, np.nan, 5.5]),
- "min": np.array([1, 5, 7, 3, np.nan, 3, 1, 8, np.nan, 5]),
- "max": np.array([2, 6, 7, 4, np.nan, 4, 2, 8, np.nan, 6]),
- "first": np.array([1, 5, 7, 3, np.nan, 4, 2, 8, np.nan, 6]),
- "dense": np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]),
- }
+class TestSeriesRank:
@td.skip_if_no_scipy
def test_rank(self, datetime_series):
from scipy.stats import rankdata
@@ -216,61 +222,49 @@ def test_rank_signature(self):
with pytest.raises(ValueError, match=msg):
s.rank("average")
- def test_rank_tie_methods(self):
- s = self.s
-
- def _check(s, expected, method="average"):
- result = s.rank(method=method)
- tm.assert_series_equal(result, Series(expected))
-
- dtypes = [None, object]
- disabled = {(object, "first")}
- results = self.results
-
- for method, dtype in product(results, dtypes):
- if (dtype, method) in disabled:
- continue
- series = s if dtype is None else s.astype(dtype)
- _check(series, results[method], method=method)
+ @pytest.mark.parametrize("dtype", [None, object])
+ def test_rank_tie_methods(self, ser, results, dtype):
+ method, exp = results
+ ser = ser if dtype is None else ser.astype(dtype)
+ result = ser.rank(method=method)
+ tm.assert_series_equal(result, Series(exp))
@td.skip_if_no_scipy
@pytest.mark.parametrize("ascending", [True, False])
@pytest.mark.parametrize("method", ["average", "min", "max", "first", "dense"])
@pytest.mark.parametrize("na_option", ["top", "bottom", "keep"])
- def test_rank_tie_methods_on_infs_nans(self, method, na_option, ascending):
- dtypes = [
+ @pytest.mark.parametrize(
+ "dtype, na_value, pos_inf, neg_inf",
+ [
("object", None, Infinity(), NegInfinity()),
("float64", np.nan, np.inf, -np.inf),
- ]
+ ],
+ )
+ def test_rank_tie_methods_on_infs_nans(
+ self, method, na_option, ascending, dtype, na_value, pos_inf, neg_inf
+ ):
chunk = 3
- disabled = {("object", "first")}
-
- def _check(s, method, na_option, ascending):
- exp_ranks = {
- "average": ([2, 2, 2], [5, 5, 5], [8, 8, 8]),
- "min": ([1, 1, 1], [4, 4, 4], [7, 7, 7]),
- "max": ([3, 3, 3], [6, 6, 6], [9, 9, 9]),
- "first": ([1, 2, 3], [4, 5, 6], [7, 8, 9]),
- "dense": ([1, 1, 1], [2, 2, 2], [3, 3, 3]),
- }
- ranks = exp_ranks[method]
- if na_option == "top":
- order = [ranks[1], ranks[0], ranks[2]]
- elif na_option == "bottom":
- order = [ranks[0], ranks[2], ranks[1]]
- else:
- order = [ranks[0], [np.nan] * chunk, ranks[1]]
- expected = order if ascending else order[::-1]
- expected = list(chain.from_iterable(expected))
- result = s.rank(method=method, na_option=na_option, ascending=ascending)
- tm.assert_series_equal(result, Series(expected, dtype="float64"))
-
- for dtype, na_value, pos_inf, neg_inf in dtypes:
- in_arr = [neg_inf] * chunk + [na_value] * chunk + [pos_inf] * chunk
- iseries = Series(in_arr, dtype=dtype)
- if (dtype, method) in disabled:
- continue
- _check(iseries, method, na_option, ascending)
+
+ in_arr = [neg_inf] * chunk + [na_value] * chunk + [pos_inf] * chunk
+ iseries = Series(in_arr, dtype=dtype)
+ exp_ranks = {
+ "average": ([2, 2, 2], [5, 5, 5], [8, 8, 8]),
+ "min": ([1, 1, 1], [4, 4, 4], [7, 7, 7]),
+ "max": ([3, 3, 3], [6, 6, 6], [9, 9, 9]),
+ "first": ([1, 2, 3], [4, 5, 6], [7, 8, 9]),
+ "dense": ([1, 1, 1], [2, 2, 2], [3, 3, 3]),
+ }
+ ranks = exp_ranks[method]
+ if na_option == "top":
+ order = [ranks[1], ranks[0], ranks[2]]
+ elif na_option == "bottom":
+ order = [ranks[0], ranks[2], ranks[1]]
+ else:
+ order = [ranks[0], [np.nan] * chunk, ranks[1]]
+ expected = order if ascending else order[::-1]
+ expected = list(chain.from_iterable(expected))
+ result = iseries.rank(method=method, na_option=na_option, ascending=ascending)
+ tm.assert_series_equal(result, Series(expected, dtype="float64"))
def test_rank_desc_mix_nans_infs(self):
# GH 19538
@@ -281,7 +275,16 @@ def test_rank_desc_mix_nans_infs(self):
tm.assert_series_equal(result, exp)
@td.skip_if_no_scipy
- def test_rank_methods_series(self):
+ @pytest.mark.parametrize("method", ["average", "min", "max", "first", "dense"])
+ @pytest.mark.parametrize(
+ "op, value",
+ [
+ [operator.add, 0],
+ [operator.add, 1e6],
+ [operator.mul, 1e-6],
+ ],
+ )
+ def test_rank_methods_series(self, method, op, value):
from scipy.stats import rankdata
xs = np.random.randn(9)
@@ -289,19 +292,17 @@ def test_rank_methods_series(self):
np.random.shuffle(xs)
index = [chr(ord("a") + i) for i in range(len(xs))]
+ vals = op(xs, value)
+ ts = Series(vals, index=index)
+ result = ts.rank(method=method)
+ sprank = rankdata(vals, method if method != "first" else "ordinal")
+ expected = Series(sprank, index=index).astype("float64")
+ tm.assert_series_equal(result, expected)
- for vals in [xs, xs + 1e6, xs * 1e-6]:
- ts = Series(vals, index=index)
-
- for m in ["average", "min", "max", "first", "dense"]:
- result = ts.rank(method=m)
- sprank = rankdata(vals, m if m != "first" else "ordinal")
- expected = Series(sprank, index=index).astype("float64")
- tm.assert_series_equal(result, expected)
-
- def test_rank_dense_method(self):
- dtypes = ["O", "f8", "i8"]
- in_out = [
+ @pytest.mark.parametrize("dtype", ["O", "f8", "i8"])
+ @pytest.mark.parametrize(
+ "ser, exp",
+ [
([1], [1]),
([2], [1]),
([0], [1]),
@@ -310,43 +311,38 @@ def test_rank_dense_method(self):
([4, 2, 1], [3, 2, 1]),
([1, 1, 5, 5, 3], [1, 1, 3, 3, 2]),
([-5, -4, -3, -2, -1], [1, 2, 3, 4, 5]),
- ]
-
- for ser, exp in in_out:
- for dtype in dtypes:
- s = Series(ser).astype(dtype)
- result = s.rank(method="dense")
- expected = Series(exp).astype(result.dtype)
- tm.assert_series_equal(result, expected)
-
- def test_rank_descending(self):
- dtypes = ["O", "f8", "i8"]
-
- for dtype, method in product(dtypes, self.results):
- if "i" in dtype:
- s = self.s.dropna()
- else:
- s = self.s.astype(dtype)
-
- res = s.rank(ascending=False)
- expected = (s.max() - s).rank()
- tm.assert_series_equal(res, expected)
-
- if method == "first" and dtype == "O":
- continue
-
- expected = (s.max() - s).rank(method=method)
- res2 = s.rank(method=method, ascending=False)
- tm.assert_series_equal(res2, expected)
-
- def test_rank_int(self):
- s = self.s.dropna().astype("i8")
-
- for method, res in self.results.items():
- result = s.rank(method=method)
- expected = Series(res).dropna()
- expected.index = result.index
- tm.assert_series_equal(result, expected)
+ ],
+ )
+ def test_rank_dense_method(self, dtype, ser, exp):
+ s = Series(ser).astype(dtype)
+ result = s.rank(method="dense")
+ expected = Series(exp).astype(result.dtype)
+ tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["O", "f8", "i8"])
+ def test_rank_descending(self, ser, results, dtype):
+ method, _ = results
+ if "i" in dtype:
+ s = ser.dropna()
+ else:
+ s = ser.astype(dtype)
+
+ res = s.rank(ascending=False)
+ expected = (s.max() - s).rank()
+ tm.assert_series_equal(res, expected)
+
+ expected = (s.max() - s).rank(method=method)
+ res2 = s.rank(method=method, ascending=False)
+ tm.assert_series_equal(res2, expected)
+
+ def test_rank_int(self, ser, results):
+ method, exp = results
+ s = ser.dropna().astype("i8")
+
+ result = s.rank(method=method)
+ expected = Series(exp).dropna()
+ expected.index = result.index
+ tm.assert_series_equal(result, expected)
def test_rank_object_bug(self):
# GH 13445
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45114 | 2021-12-29T20:33:48Z | 2021-12-29T23:55:51Z | 2021-12-29T23:55:51Z | 2021-12-30T01:19:13Z |
REF: standardize __array_ufunc__ patterns | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index acace9085e18e..d6c1f37633477 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -85,7 +85,10 @@
notna,
)
-from pandas.core import ops
+from pandas.core import (
+ arraylike,
+ ops,
+)
from pandas.core.accessor import (
PandasDelegate,
delegate_names,
@@ -1516,6 +1519,14 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
if result is not NotImplemented:
return result
+ if method == "reduce":
+ # e.g. TestCategoricalAnalytics::test_min_max_ordered
+ result = arraylike.dispatch_reduction_ufunc(
+ self, ufunc, method, *inputs, **kwargs
+ )
+ if result is not NotImplemented:
+ return result
+
# for all other cases, raise for now (similarly as what happens in
# Series.__array_prepare__)
raise TypeError(
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index 579d77369d27c..ddb36f5ef01d0 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-import numbers
-
import numpy as np
from pandas._libs import lib
@@ -130,8 +128,6 @@ def dtype(self) -> PandasDtype:
def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
return np.asarray(self._ndarray, dtype=dtype)
- _HANDLED_TYPES = (np.ndarray, numbers.Number)
-
def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
# Lightly modified version of
# https://numpy.org/doc/stable/reference/generated/numpy.lib.mixins.NDArrayOperatorsMixin.html
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 538d4e7e4a7aa..c861abfc7920d 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -73,6 +73,7 @@
notna,
)
+from pandas.core import arraylike
import pandas.core.algorithms as algos
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import ExtensionArray
@@ -1415,7 +1416,9 @@ def any(self, axis=0, *args, **kwargs):
return values.any().item()
- def sum(self, axis: int = 0, min_count: int = 0, *args, **kwargs) -> Scalar:
+ def sum(
+ self, axis: int = 0, min_count: int = 0, skipna: bool = True, *args, **kwargs
+ ) -> Scalar:
"""
Sum of non-NA/null values
@@ -1437,6 +1440,11 @@ def sum(self, axis: int = 0, min_count: int = 0, *args, **kwargs) -> Scalar:
nv.validate_sum(args, kwargs)
valid_vals = self._valid_sp_values
sp_sum = valid_vals.sum()
+ has_na = self.sp_index.ngaps > 0 and not self._null_fill_value
+
+ if has_na and not skipna:
+ return na_value_for_dtype(self.dtype.subtype, compat=False)
+
if self._null_fill_value:
if check_below_min_count(valid_vals.shape, None, min_count):
return na_value_for_dtype(self.dtype.subtype, compat=False)
@@ -1589,6 +1597,21 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
if result is not NotImplemented:
return result
+ if "out" in kwargs:
+ # e.g. tests.arrays.sparse.test_arithmetics.test_ndarray_inplace
+ res = arraylike.dispatch_ufunc_with_out(
+ self, ufunc, method, *inputs, **kwargs
+ )
+ return res
+
+ if method == "reduce":
+ result = arraylike.dispatch_reduction_ufunc(
+ self, ufunc, method, *inputs, **kwargs
+ )
+ if result is not NotImplemented:
+ # e.g. tests.series.test_ufunc.TestNumpyReductions
+ return result
+
if len(inputs) == 1:
# No alignment necessary.
sp_values = getattr(ufunc, method)(self.sp_values, **kwargs)
@@ -1611,7 +1634,8 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
sp_values, self.sp_index, SparseDtype(sp_values.dtype, fill_value)
)
- result = getattr(ufunc, method)(*(np.asarray(x) for x in inputs), **kwargs)
+ new_inputs = tuple(np.asarray(x) for x in inputs)
+ result = getattr(ufunc, method)(*new_inputs, **kwargs)
if out:
if len(out) == 1:
out = out[0]
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index d5b1292435f04..d2b02a5fac0cb 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -878,6 +878,12 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str_t, *inputs, **kwargs):
if result is not NotImplemented:
return result
+ if "out" in kwargs:
+ # e.g. test_dti_isub_tdi
+ return arraylike.dispatch_ufunc_with_out(
+ self, ufunc, method, *inputs, **kwargs
+ )
+
if method == "reduce":
result = arraylike.dispatch_reduction_ufunc(
self, ufunc, method, *inputs, **kwargs
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 6ddf63c03e4f1..e76b558f4c669 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -2107,7 +2107,7 @@ def test_dti_isub_tdi(self, tz_naive_fixture):
np.subtract(out, tdi, out=out)
tm.assert_datetime_array_equal(out, expected._data)
- msg = "cannot subtract .* from a TimedeltaArray"
+ msg = "cannot subtract a datelike from a TimedeltaArray"
with pytest.raises(TypeError, match=msg):
tdi -= dti
@@ -2116,11 +2116,9 @@ def test_dti_isub_tdi(self, tz_naive_fixture):
result -= tdi.values
tm.assert_index_equal(result, expected)
- msg = "cannot subtract DatetimeArray from ndarray"
with pytest.raises(TypeError, match=msg):
tdi.values -= dti
- msg = "cannot subtract a datelike from a TimedeltaArray"
with pytest.raises(TypeError, match=msg):
tdi._values -= dti
diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py
index 17384f3136a5a..59bb34f4f4c3e 100644
--- a/pandas/tests/arrays/categorical/test_analytics.py
+++ b/pandas/tests/arrays/categorical/test_analytics.py
@@ -29,20 +29,32 @@ def test_min_max_not_ordered_raises(self, aggregation):
with pytest.raises(TypeError, match=msg):
agg_func()
- def test_min_max_ordered(self):
+ ufunc = np.minimum if aggregation == "min" else np.maximum
+ with pytest.raises(TypeError, match=msg):
+ ufunc.reduce(cat)
+
+ def test_min_max_ordered(self, index_or_series_or_array):
cat = Categorical(["a", "b", "c", "d"], ordered=True)
- _min = cat.min()
- _max = cat.max()
+ obj = index_or_series_or_array(cat)
+ _min = obj.min()
+ _max = obj.max()
assert _min == "a"
assert _max == "d"
+ assert np.minimum.reduce(obj) == "a"
+ assert np.maximum.reduce(obj) == "d"
+ # TODO: raises if we pass axis=0 (on Index and Categorical, not Series)
+
cat = Categorical(
["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True
)
- _min = cat.min()
- _max = cat.max()
+ obj = index_or_series_or_array(cat)
+ _min = obj.min()
+ _max = obj.max()
assert _min == "d"
assert _max == "a"
+ assert np.minimum.reduce(obj) == "d"
+ assert np.maximum.reduce(obj) == "a"
@pytest.mark.parametrize(
"categories,expected",
diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py
index e58e26fafdc1b..1dbafb2dbb648 100644
--- a/pandas/tests/extension/decimal/array.py
+++ b/pandas/tests/extension/decimal/array.py
@@ -25,6 +25,7 @@
is_list_like,
is_scalar,
)
+from pandas.core import arraylike
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import (
ExtensionArray,
@@ -121,6 +122,13 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
inputs = tuple(x._data if isinstance(x, DecimalArray) else x for x in inputs)
result = getattr(ufunc, method)(*inputs, **kwargs)
+ if method == "reduce":
+ result = arraylike.dispatch_reduction_ufunc(
+ self, ufunc, method, *inputs, **kwargs
+ )
+ if result is not NotImplemented:
+ return result
+
def reconstruct(x):
if isinstance(x, (decimal.Decimal, numbers.Number)):
return x
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
The idea here is to get all of our `__array_ufunc__` implementations to use all of the helpers, at which point we can just combine them all into one helper. | https://api.github.com/repos/pandas-dev/pandas/pulls/45113 | 2021-12-29T19:05:50Z | 2021-12-30T00:16:55Z | 2021-12-30T00:16:55Z | 2021-12-30T00:18:55Z |
TST: Mock unstack and pivot_table test for PerformanceWarning | diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 7efe4b08895bc..eecae31bec914 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -18,6 +18,7 @@
date_range,
)
import pandas._testing as tm
+from pandas.core.reshape import reshape as reshape_lib
class TestDataFrameReshape:
@@ -1826,19 +1827,26 @@ def test_unstack_unobserved_keys(self):
tm.assert_frame_equal(recons, df)
@pytest.mark.slow
- def test_unstack_number_of_levels_larger_than_int32(self):
+ def test_unstack_number_of_levels_larger_than_int32(self, monkeypatch):
# GH#20601
# GH 26314: Change ValueError to PerformanceWarning
- df = DataFrame(
- 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):
- try:
- df.unstack()
- except MemoryError:
- # Just checking the warning
- return
+
+ class MockUnstacker(reshape_lib._Unstacker):
+ def __init__(self, *args, **kwargs):
+ # __init__ will raise the warning
+ super().__init__(*args, **kwargs)
+ raise Exception("Don't compute final result.")
+
+ 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)],
+ )
+ msg = "The following operation may generate"
+ with tm.assert_produces_warning(PerformanceWarning, match=msg):
+ with pytest.raises(Exception, match="Don't compute final result."):
+ df.unstack()
def test_stack_order_with_unsorted_levels(self):
# GH#16323
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index aa7af4548a770..a023adfb509a0 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -23,6 +23,7 @@
)
import pandas._testing as tm
from pandas.api.types import CategoricalDtype as CDT
+from pandas.core.reshape import reshape as reshape_lib
from pandas.core.reshape.pivot import pivot_table
@@ -1991,22 +1992,27 @@ def test_pivot_string_func_vs_func(self, f, f_numpy):
tm.assert_frame_equal(result, expected)
@pytest.mark.slow
- def test_pivot_number_of_levels_larger_than_int32(self):
+ def test_pivot_number_of_levels_larger_than_int32(self, monkeypatch):
# GH 20601
# GH 26314: Change ValueError to PerformanceWarning
- df = DataFrame(
- {"ind1": np.arange(2 ** 16), "ind2": np.arange(2 ** 16), "count": 0}
- )
+ class MockUnstacker(reshape_lib._Unstacker):
+ def __init__(self, *args, **kwargs):
+ # __init__ will raise the warning
+ super().__init__(*args, **kwargs)
+ raise Exception("Don't compute final result.")
+
+ 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}
+ )
- msg = "The following operation may generate"
- with tm.assert_produces_warning(PerformanceWarning, match=msg):
- try:
- df.pivot_table(
- index="ind1", columns="ind2", values="count", aggfunc="count"
- )
- except MemoryError:
- # Just checking the warning
- return
+ msg = "The following operation may generate"
+ with tm.assert_produces_warning(PerformanceWarning, match=msg):
+ with pytest.raises(Exception, match="Don't compute final result."):
+ df.pivot_table(
+ index="ind1", columns="ind2", values="count", aggfunc="count"
+ )
def test_pivot_table_aggfunc_dropna(self, dropna):
# GH 22159
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
xref https://github.com/pandas-dev/pandas/pull/45084#issuecomment-1002708717
Makes these tests run quicker locally.
| https://api.github.com/repos/pandas-dev/pandas/pulls/45112 | 2021-12-29T18:49:00Z | 2021-12-29T19:55:07Z | 2021-12-29T19:55:07Z | 2021-12-30T10:57:23Z |
Typ excel writer _base | diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
index 3a84a75be838f..634688d65e117 100644
--- a/.github/workflows/code-checks.yml
+++ b/.github/workflows/code-checks.yml
@@ -74,7 +74,7 @@ jobs:
- name: Install pyright
# note: keep version in sync with .pre-commit-config.yaml
- run: npm install -g pyright@1.1.200
+ run: npm install -g pyright@1.1.202
- name: Build Pandas
id: build
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 19a8a127fa1a5..e3c9be941498f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -78,7 +78,7 @@ repos:
types: [python]
stages: [manual]
# note: keep version in sync with .github/workflows/ci.yml
- additional_dependencies: ['pyright@1.1.200']
+ additional_dependencies: ['pyright@1.1.202']
- repo: local
hooks:
- id: flake8-rst
diff --git a/pandas/_typing.py b/pandas/_typing.py
index eb5bb30238893..159d57fb27c89 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -84,6 +84,7 @@
DatetimeLikeScalar = Union["Period", "Timestamp", "Timedelta"]
PandasScalar = Union["Period", "Timestamp", "Timedelta", "Interval"]
Scalar = Union[PythonScalar, PandasScalar]
+IntStrT = TypeVar("IntStrT", int, str)
# timestamp and timedelta convertible types
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 2ff3360d0b808..b490244f7f396 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -8,8 +8,16 @@
from typing import (
IO,
Any,
+ Callable,
+ Hashable,
+ Iterable,
+ List,
+ Literal,
Mapping,
+ Sequence,
+ Union,
cast,
+ overload,
)
import warnings
import zipfile
@@ -20,6 +28,7 @@
from pandas._typing import (
DtypeArg,
FilePath,
+ IntStrT,
ReadBuffer,
StorageOptions,
WriteExcelBuffer,
@@ -342,37 +351,105 @@
)
+@overload
+def read_excel(
+ io,
+ # sheet name is str or int -> DataFrame
+ sheet_name: str | int,
+ header: int | Sequence[int] | None = ...,
+ names=...,
+ index_col: int | Sequence[int] | None = ...,
+ usecols=...,
+ squeeze: bool | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = ...,
+ converters=...,
+ true_values: Iterable[Hashable] | None = ...,
+ false_values: Iterable[Hashable] | None = ...,
+ skiprows: Sequence[int] | int | Callable[[int], object] | None = ...,
+ nrows: int | None = ...,
+ na_values=...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ parse_dates=...,
+ date_parser=...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ comment: str | None = ...,
+ skipfooter: int = ...,
+ convert_float: bool | None = ...,
+ mangle_dupe_cols: bool = ...,
+ storage_options: StorageOptions = ...,
+) -> DataFrame:
+ ...
+
+
+@overload
+def read_excel(
+ io,
+ # sheet name is list or None -> dict[IntStrT, DataFrame]
+ sheet_name: list[IntStrT] | None,
+ header: int | Sequence[int] | None = ...,
+ names=...,
+ index_col: int | Sequence[int] | None = ...,
+ usecols=...,
+ squeeze: bool | None = ...,
+ dtype: DtypeArg | None = ...,
+ engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = ...,
+ converters=...,
+ true_values: Iterable[Hashable] | None = ...,
+ false_values: Iterable[Hashable] | None = ...,
+ skiprows: Sequence[int] | int | Callable[[int], object] | None = ...,
+ nrows: int | None = ...,
+ na_values=...,
+ keep_default_na: bool = ...,
+ na_filter: bool = ...,
+ verbose: bool = ...,
+ parse_dates=...,
+ date_parser=...,
+ thousands: str | None = ...,
+ decimal: str = ...,
+ comment: str | None = ...,
+ skipfooter: int = ...,
+ convert_float: bool | None = ...,
+ mangle_dupe_cols: bool = ...,
+ storage_options: StorageOptions = ...,
+) -> dict[IntStrT, DataFrame]:
+ ...
+
+
@deprecate_nonkeyword_arguments(allowed_args=["io", "sheet_name"], version="2.0")
@Appender(_read_excel_doc)
def read_excel(
io,
- sheet_name=0,
- header=0,
+ sheet_name: str | int | list[IntStrT] | None = 0,
+ header: int | Sequence[int] | None = 0,
names=None,
- index_col=None,
+ index_col: int | Sequence[int] | None = None,
usecols=None,
- squeeze=None,
+ squeeze: bool | None = None,
dtype: DtypeArg | None = None,
- engine=None,
+ engine: Literal["xlrd", "openpyxl", "odf", "pyxlsb"] | None = None,
converters=None,
- true_values=None,
- false_values=None,
- skiprows=None,
- nrows=None,
+ true_values: Iterable[Hashable] | None = None,
+ false_values: Iterable[Hashable] | None = None,
+ skiprows: Sequence[int] | int | Callable[[int], object] | None = None,
+ nrows: int | None = None,
na_values=None,
- keep_default_na=True,
- na_filter=True,
- verbose=False,
+ keep_default_na: bool = True,
+ na_filter: bool = True,
+ verbose: bool = False,
parse_dates=False,
date_parser=None,
- thousands=None,
- decimal=".",
- comment=None,
- skipfooter=0,
- convert_float=None,
- mangle_dupe_cols=True,
+ thousands: str | None = None,
+ decimal: str = ".",
+ comment: str | None = None,
+ skipfooter: int = 0,
+ convert_float: bool | None = None,
+ mangle_dupe_cols: bool = True,
storage_options: StorageOptions = None,
-):
+) -> DataFrame | dict[IntStrT, DataFrame]:
should_close = False
if not isinstance(io, ExcelFile):
@@ -466,19 +543,19 @@ def close(self):
@property
@abc.abstractmethod
- def sheet_names(self):
+ def sheet_names(self) -> list[str]:
pass
@abc.abstractmethod
- def get_sheet_by_name(self, name):
+ def get_sheet_by_name(self, name: str):
pass
@abc.abstractmethod
- def get_sheet_by_index(self, index):
+ def get_sheet_by_index(self, index: int):
pass
@abc.abstractmethod
- def get_sheet_data(self, sheet, convert_float):
+ def get_sheet_data(self, sheet, convert_float: bool):
pass
def raise_if_bad_sheet_by_index(self, index: int) -> None:
@@ -494,27 +571,27 @@ def raise_if_bad_sheet_by_name(self, name: str) -> None:
def parse(
self,
- sheet_name=0,
- header=0,
+ sheet_name: str | int | list[int] | list[str] | None = 0,
+ header: int | Sequence[int] | None = 0,
names=None,
- index_col=None,
+ index_col: int | Sequence[int] | None = None,
usecols=None,
- squeeze=None,
+ squeeze: bool | None = None,
dtype: DtypeArg | None = None,
- true_values=None,
- false_values=None,
- skiprows=None,
- nrows=None,
+ true_values: Iterable[Hashable] | None = None,
+ false_values: Iterable[Hashable] | None = None,
+ skiprows: Sequence[int] | int | Callable[[int], object] | None = None,
+ nrows: int | None = None,
na_values=None,
- verbose=False,
+ verbose: bool = False,
parse_dates=False,
date_parser=None,
- thousands=None,
- decimal=".",
- comment=None,
- skipfooter=0,
- convert_float=None,
- mangle_dupe_cols=True,
+ thousands: str | None = None,
+ decimal: str = ".",
+ comment: str | None = None,
+ skipfooter: int = 0,
+ convert_float: bool | None = None,
+ mangle_dupe_cols: bool = True,
**kwds,
):
@@ -532,17 +609,20 @@ def parse(
ret_dict = False
# Keep sheetname to maintain backwards compatibility.
+ sheets: list[int] | list[str]
if isinstance(sheet_name, list):
sheets = sheet_name
ret_dict = True
elif sheet_name is None:
sheets = self.sheet_names
ret_dict = True
+ elif isinstance(sheet_name, str):
+ sheets = [sheet_name]
else:
sheets = [sheet_name]
# handle same-type duplicates.
- sheets = list(dict.fromkeys(sheets).keys())
+ sheets = cast(Union[List[int], List[str]], list(dict.fromkeys(sheets).keys()))
output = {}
@@ -565,17 +645,28 @@ def parse(
output[asheetname] = DataFrame()
continue
- if is_list_like(header) and len(header) == 1:
- header = header[0]
+ is_list_header = False
+ is_len_one_list_header = False
+ if is_list_like(header):
+ assert isinstance(header, Sequence)
+ is_list_header = True
+ if len(header) == 1:
+ is_len_one_list_header = True
+
+ if is_len_one_list_header:
+ header = cast(Sequence[int], header)[0]
# forward fill and pull out names for MultiIndex column
header_names = None
if header is not None and is_list_like(header):
+ assert isinstance(header, Sequence)
+
header_names = []
control_row = [True] * len(data[0])
for row in header:
if is_integer(skiprows):
+ assert isinstance(skiprows, int)
row += skiprows
data[row], control_row = fill_mi_header(data[row], control_row)
@@ -587,14 +678,14 @@ def parse(
# If there is a MultiIndex header and an index then there is also
# a row containing just the index name(s)
has_index_names = (
- is_list_like(header) and len(header) > 1 and index_col is not None
+ is_list_header and not is_len_one_list_header and index_col is not None
)
if is_list_like(index_col):
# Forward fill values for MultiIndex index.
if header is None:
offset = 0
- elif not is_list_like(header):
+ elif isinstance(header, int):
offset = 1 + header
else:
offset = 1 + max(header)
@@ -608,6 +699,8 @@ def parse(
# Check if we have an empty dataset
# before trying to collect data.
if offset < len(data):
+ assert isinstance(index_col, Sequence)
+
for col in index_col:
last = data[offset][col]
@@ -875,12 +968,12 @@ class ExcelWriter(metaclass=abc.ABCMeta):
def __new__(
cls,
path: FilePath | WriteExcelBuffer | ExcelWriter,
- engine=None,
- date_format=None,
- datetime_format=None,
+ engine: str | None = None,
+ date_format: str | None = None,
+ datetime_format: str | None = None,
mode: str = "w",
storage_options: StorageOptions = None,
- if_sheet_exists: str | None = None,
+ if_sheet_exists: Literal["error", "new", "replace", "overlay"] | None = None,
engine_kwargs: dict | None = None,
**kwargs,
):
@@ -928,6 +1021,8 @@ def __new__(
stacklevel=find_stack_level(),
)
+ # for mypy
+ assert engine is not None
cls = get_writer(engine)
return object.__new__(cls)
@@ -937,7 +1032,7 @@ def __new__(
@property
@abc.abstractmethod
- def supported_extensions(self):
+ def supported_extensions(self) -> tuple[str, ...] | list[str]:
"""Extensions that writer engine supports."""
pass
@@ -949,8 +1044,13 @@ def engine(self) -> str:
@abc.abstractmethod
def write_cells(
- self, cells, sheet_name=None, startrow=0, startcol=0, freeze_panes=None
- ):
+ self,
+ cells,
+ sheet_name: str | None = None,
+ startrow: int = 0,
+ startcol: int = 0,
+ freeze_panes: tuple[int, int] | None = None,
+ ) -> None:
"""
Write given formatted cells into Excel an excel sheet
@@ -968,7 +1068,7 @@ def write_cells(
pass
@abc.abstractmethod
- def save(self):
+ def save(self) -> None:
"""
Save workbook to disk.
"""
@@ -977,9 +1077,9 @@ def save(self):
def __init__(
self,
path: FilePath | WriteExcelBuffer | ExcelWriter,
- engine=None,
- date_format=None,
- datetime_format=None,
+ engine: str | None = None,
+ date_format: str | None = None,
+ datetime_format: str | None = None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: str | None = None,
@@ -1034,14 +1134,14 @@ def __init__(
def __fspath__(self):
return getattr(self.handles.handle, "name", "")
- def _get_sheet_name(self, sheet_name):
+ def _get_sheet_name(self, sheet_name: str | None) -> str:
if sheet_name is None:
sheet_name = self.cur_sheet
if sheet_name is None: # pragma: no cover
raise ValueError("Must pass explicit sheet_name or set cur_sheet property")
return sheet_name
- def _value_with_fmt(self, val):
+ def _value_with_fmt(self, val) -> tuple[object, str | None]:
"""
Convert numpy types to Python types for the Excel writers.
@@ -1076,7 +1176,7 @@ def _value_with_fmt(self, val):
return val, fmt
@classmethod
- def check_extension(cls, ext: str):
+ def check_extension(cls, ext: str) -> Literal[True]:
"""
checks that path's extension against the Writer's supported
extensions. If it isn't supported, raises UnsupportedFiletypeError.
@@ -1100,11 +1200,10 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
self.close()
- def close(self):
+ def close(self) -> None:
"""synonym for save, to make it more file-like"""
- content = self.save()
+ self.save()
self.handles.close()
- return content
XLS_SIGNATURES = (
@@ -1243,7 +1342,10 @@ class ExcelFile:
}
def __init__(
- self, path_or_buffer, engine=None, storage_options: StorageOptions = None
+ self,
+ path_or_buffer,
+ engine: str | None = None,
+ storage_options: StorageOptions = None,
):
if engine is not None and engine not in self._engines:
raise ValueError(f"Unknown engine: {engine}")
@@ -1310,6 +1412,7 @@ def __init__(
stacklevel=stacklevel,
)
+ assert engine is not None
self.engine = engine
self.storage_options = storage_options
@@ -1320,27 +1423,27 @@ def __fspath__(self):
def parse(
self,
- sheet_name=0,
- header=0,
+ sheet_name: str | int | list[int] | list[str] | None = 0,
+ header: int | Sequence[int] | None = 0,
names=None,
- index_col=None,
+ index_col: int | Sequence[int] | None = None,
usecols=None,
- squeeze=None,
+ squeeze: bool | None = None,
converters=None,
- true_values=None,
- false_values=None,
- skiprows=None,
- nrows=None,
+ true_values: Iterable[Hashable] | None = None,
+ false_values: Iterable[Hashable] | None = None,
+ skiprows: Sequence[int] | int | Callable[[int], object] | None = None,
+ nrows: int | None = None,
na_values=None,
parse_dates=False,
date_parser=None,
- thousands=None,
- comment=None,
- skipfooter=0,
- convert_float=None,
- mangle_dupe_cols=True,
+ thousands: str | None = None,
+ comment: str | None = None,
+ skipfooter: int = 0,
+ convert_float: bool | None = None,
+ mangle_dupe_cols: bool = True,
**kwds,
- ):
+ ) -> DataFrame | dict[str, DataFrame] | dict[int, DataFrame]:
"""
Parse specified sheet(s) into a DataFrame.
@@ -1383,7 +1486,7 @@ def book(self):
def sheet_names(self):
return self._reader.sheet_names
- def close(self):
+ def close(self) -> None:
"""close io if necessary"""
self._reader.close()
diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py
index add95c58cd809..d4fe3683c907e 100644
--- a/pandas/io/excel/_odswriter.py
+++ b/pandas/io/excel/_odswriter.py
@@ -140,7 +140,7 @@ def _make_table_cell_attributes(self, cell) -> dict[str, int | str]:
attributes["numbercolumnsspanned"] = cell.mergeend
return attributes
- def _make_table_cell(self, cell) -> tuple[str, Any]:
+ def _make_table_cell(self, cell) -> tuple[object, Any]:
"""Convert cell data to an OpenDocument spreadsheet cell
Parameters
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
If this is ok, I will type the other classes too
| https://api.github.com/repos/pandas-dev/pandas/pulls/45111 | 2021-12-29T14:53:41Z | 2021-12-30T17:43:44Z | 2021-12-30T17:43:44Z | 2022-01-28T10:26:18Z |
ENH: Use flags.allows_duplicate_labels to define default insert behavior | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2a92d8b4964f1..bb2ee995c0e93 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4375,7 +4375,7 @@ def insert(
loc: int,
column: Hashable,
value: Scalar | AnyArrayLike,
- allow_duplicates: bool = False,
+ allow_duplicates: bool | None = None,
) -> None:
"""
Insert column into DataFrame at specified location.
@@ -4422,7 +4422,9 @@ def insert(
0 NaN 100 1 99 3
1 5.0 100 2 99 4
"""
- if allow_duplicates and not self.flags.allows_duplicate_labels:
+ if allow_duplicates is None:
+ allow_duplicates = self.flags.allows_duplicate_labels
+ elif allow_duplicates and not self.flags.allows_duplicate_labels:
raise ValueError(
"Cannot specify 'allow_duplicates=True' when "
"'self.flags.allows_duplicate_labels' is False."
diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py
index f67ecf601f838..2347a6e836932 100644
--- a/pandas/tests/frame/indexing/test_insert.py
+++ b/pandas/tests/frame/indexing/test_insert.py
@@ -16,6 +16,7 @@
class TestDataFrameInsert:
+ @pytest.mark.xfail(reason="Allow duplicate columns")
def test_insert(self):
df = DataFrame(
np.random.randn(5, 3), index=np.arange(5), columns=["c", "b", "a"]
diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py
index a707bbb377f24..ae2aefe34952a 100644
--- a/pandas/tests/frame/methods/test_reset_index.py
+++ b/pandas/tests/frame/methods/test_reset_index.py
@@ -328,12 +328,15 @@ def test_reset_index_multiindex_nan(self):
"2012-12-31",
],
)
- def test_reset_index_with_datetimeindex_cols(self, name):
+ def test_reset_index_with_datetimeindex_cols(self, name, request):
# GH#5818
warn = None
if isinstance(name, Timestamp) and name.tz is not None:
# _deprecate_mismatched_indexing
warn = FutureWarning
+ request.node.add_marker(
+ pytest.mark.xfail(reason="Duplicate labels allowed")
+ )
df = DataFrame(
[[1, 2], [3, 4]],
@@ -370,13 +373,14 @@ def test_reset_index_range(self):
)
tm.assert_frame_equal(result, expected)
- def test_reset_index_multiindex_columns(self):
+ def test_reset_index_multiindex_columns(self, request):
levels = [["A", ""], ["B", "b"]]
df = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels))
result = df[["B"]].rename_axis("A").reset_index()
tm.assert_frame_equal(result, df)
# GH#16120: already existing column
+ request.node.add_marker(pytest.mark.xfail(reason="Duplicate labels allowed"))
msg = r"cannot insert \('A', ''\), already exists"
with pytest.raises(ValueError, match=msg):
df.rename_axis("A").reset_index()
diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py
index d010426bee53e..7de1a61e7a0e4 100644
--- a/pandas/tests/frame/test_nonunique_indexes.py
+++ b/pandas/tests/frame/test_nonunique_indexes.py
@@ -38,6 +38,7 @@ def test_setattr_columns_vs_construct_with_columns_datetimeindx(self):
expected = DataFrame([[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=idx)
check(df, expected)
+ @pytest.mark.xfail(reason="Allow duplicate columns")
def test_insert_with_duplicate_columns(self):
# insert
df = DataFrame(
diff --git a/pandas/tests/groupby/test_frame_value_counts.py b/pandas/tests/groupby/test_frame_value_counts.py
index 79ef46db8e95e..ac9bad7991512 100644
--- a/pandas/tests/groupby/test_frame_value_counts.py
+++ b/pandas/tests/groupby/test_frame_value_counts.py
@@ -413,7 +413,7 @@ def test_mixed_groupings(normalize, expected_label, expected_values):
],
)
@pytest.mark.parametrize("as_index", [False, True])
-def test_column_name_clashes(test, expected_names, as_index):
+def test_column_name_clashes(test, expected_names, as_index, request):
df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6], "d": [7, 8], "e": [9, 10]})
if test == "repeat":
df.columns = list("abbde")
@@ -431,6 +431,7 @@ def test_column_name_clashes(test, expected_names, as_index):
)
tm.assert_series_equal(result, expected)
else:
+ request.node.add_marker(pytest.mark.xfail(reason="Duplicate labels allowed"))
with pytest.raises(ValueError, match="cannot insert"):
df.groupby(["a", [0, 1], "d"], as_index=as_index).value_counts()
diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py
index 8e7b31bcf8bca..10dce72b91934 100644
--- a/pandas/tests/io/pytables/test_put.py
+++ b/pandas/tests/io/pytables/test_put.py
@@ -302,6 +302,7 @@ def test_column_multiindex(setup_path):
)
+@pytest.mark.xfail(reason="Duplicate labels allowed")
def test_store_multiindex(setup_path):
# validate multi-index names
| - [x] closes #44410
- [ ] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
Alternative to #44755 to resolve #44410 and #44992 following @jreback's review requests.
The default for DataFrame.insert is now to use the flag, which defaults to allow duplicate column labels.
Comments please @rhshadrach, @phofl, @jbrockmendel
Some tests no longer raise and I have xfailed all of these these for the time being.
This is Draft and I have changed #44755 to Draft until there is agreement! | https://api.github.com/repos/pandas-dev/pandas/pulls/45109 | 2021-12-29T12:13:10Z | 2022-01-19T14:32:36Z | null | 2022-01-30T22:46:02Z |
BUG: Fix nanosecond timedeltas | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 2c77b87f8efb6..ec61b22eab318 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -714,6 +714,8 @@ Timedelta
^^^^^^^^^
- Bug in division of all-``NaT`` :class:`TimeDeltaIndex`, :class:`Series` or :class:`DataFrame` column with object-dtype arraylike of numbers failing to infer the result as timedelta64-dtype (:issue:`39750`)
- Bug in floor division of ``timedelta64[ns]`` data with a scalar returning garbage values (:issue:`44466`)
+- Bug in :class:`Timedelta` now properly taking into account any nanoseconds contribution of any kwarg (:issue:`43764`)
+-
Timezones
^^^^^^^^^
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 2ac635ad4fb9c..a908eefd41768 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -180,7 +180,7 @@ cpdef int64_t delta_to_nanoseconds(delta) except? -1:
if PyDelta_Check(delta):
try:
return (
- delta.days * 24 * 60 * 60 * 1_000_000
+ delta.days * 24 * 3600 * 1_000_000
+ delta.seconds * 1_000_000
+ delta.microseconds
) * 1000
@@ -1257,6 +1257,9 @@ class Timedelta(_Timedelta):
truncated to nanoseconds.
"""
+ _req_any_kwargs_new = {"weeks", "days", "hours", "minutes", "seconds",
+ "milliseconds", "microseconds", "nanoseconds"}
+
def __new__(cls, object value=_no_input, unit=None, **kwargs):
cdef _Timedelta td_base
@@ -1267,12 +1270,7 @@ class Timedelta(_Timedelta):
"(days,seconds....)")
kwargs = {key: _to_py_int_float(kwargs[key]) for key in kwargs}
-
- nano = convert_to_timedelta64(kwargs.pop('nanoseconds', 0), 'ns')
- try:
- value = nano + convert_to_timedelta64(timedelta(**kwargs),
- 'ns')
- except TypeError as e:
+ if not cls._req_any_kwargs_new.intersection(kwargs):
raise ValueError(
"cannot construct a Timedelta from the passed arguments, "
"allowed keywords are "
@@ -1280,6 +1278,27 @@ class Timedelta(_Timedelta):
"milliseconds, microseconds, nanoseconds]"
)
+ # GH43764, convert any input to nanoseconds first and then
+ # create the timestamp. This ensures that any potential
+ # nanosecond contributions from kwargs parsed as floats
+ # are taken into consideration.
+ seconds = int((
+ (
+ (kwargs.get('days', 0) + kwargs.get('weeks', 0) * 7) * 24
+ + kwargs.get('hours', 0)
+ ) * 3600
+ + kwargs.get('minutes', 0) * 60
+ + kwargs.get('seconds', 0)
+ ) * 1_000_000_000
+ )
+
+ value = np.timedelta64(
+ int(kwargs.get('nanoseconds', 0))
+ + int(kwargs.get('microseconds', 0) * 1_000)
+ + int(kwargs.get('milliseconds', 0) * 1_000_000)
+ + seconds
+ )
+
if unit in {'Y', 'y', 'M'}:
raise ValueError(
"Units 'M', 'Y', and 'y' are no longer supported, as they do not "
diff --git a/pandas/tests/tslibs/test_timedeltas.py b/pandas/tests/tslibs/test_timedeltas.py
index 25450bd64a298..c72d279580cca 100644
--- a/pandas/tests/tslibs/test_timedeltas.py
+++ b/pandas/tests/tslibs/test_timedeltas.py
@@ -15,6 +15,15 @@
(np.timedelta64(14, "D"), 14 * 24 * 3600 * 1e9),
(Timedelta(minutes=-7), -7 * 60 * 1e9),
(Timedelta(minutes=-7).to_pytimedelta(), -7 * 60 * 1e9),
+ (Timedelta(seconds=1234e-9), 1234), # GH43764, GH40946
+ (
+ Timedelta(seconds=1e-9, milliseconds=1e-5, microseconds=1e-1),
+ 111,
+ ), # GH43764
+ (
+ Timedelta(days=1, seconds=1e-9, milliseconds=1e-5, microseconds=1e-1),
+ 24 * 3600e9 + 111,
+ ), # GH43764
(offsets.Nano(125), 125),
(1, 1),
(np.int64(2), 2),
| - [x] closes #43764
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
Fixes the construction of `Timedelta` objects with any nanosecond contribution. | https://api.github.com/repos/pandas-dev/pandas/pulls/45108 | 2021-12-29T10:15:58Z | 2021-12-31T20:56:56Z | 2021-12-31T20:56:56Z | 2022-01-06T15:56:57Z |
TST: More pytest.mark.parameterize | diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py
index db63bba4d4eaf..527ae3ce37d1e 100644
--- a/pandas/tests/arrays/sparse/test_libsparse.py
+++ b/pandas/tests/arrays/sparse/test_libsparse.py
@@ -393,26 +393,27 @@ def test_lookup_array(self):
exp = np.array([-1, -1, 1, -1], dtype=np.int32)
tm.assert_numpy_array_equal(res, exp)
- def test_lookup_basics(self):
- def _check(index):
- assert index.lookup(0) == -1
- assert index.lookup(5) == 0
- assert index.lookup(7) == 2
- assert index.lookup(8) == -1
- assert index.lookup(9) == -1
- assert index.lookup(10) == -1
- assert index.lookup(11) == -1
- assert index.lookup(12) == 3
- assert index.lookup(17) == 8
- assert index.lookup(18) == -1
-
+ @pytest.mark.parametrize(
+ "idx, expected",
+ [
+ [0, -1],
+ [5, 0],
+ [7, 2],
+ [8, -1],
+ [9, -1],
+ [10, -1],
+ [11, -1],
+ [12, 3],
+ [17, 8],
+ [18, -1],
+ ],
+ )
+ def test_lookup_basics(self, idx, expected):
bindex = BlockIndex(20, [5, 12], [3, 6])
- iindex = bindex.to_int_index()
+ assert bindex.lookup(idx) == expected
- _check(bindex)
- _check(iindex)
-
- # corner cases
+ iindex = bindex.to_int_index()
+ assert iindex.lookup(idx) == expected
class TestBlockIndex:
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 4b3ddbc6c193c..7efe4b08895bc 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -1421,50 +1421,57 @@ def test_stack(self, multiindex_year_month_day_dataframe_random_data):
# stack with negative number
result = ymd.unstack(0).stack(-2)
expected = ymd.unstack(0).stack(0)
+ tm.assert_equal(result, expected)
+ @pytest.mark.parametrize(
+ "idx, columns, exp_idx",
+ [
+ [
+ list("abab"),
+ ["1st", "2nd", "3rd"],
+ MultiIndex(
+ levels=[["a", "b"], ["1st", "2nd", "3rd"]],
+ codes=[
+ np.tile(np.arange(2).repeat(3), 2),
+ np.tile(np.arange(3), 4),
+ ],
+ ),
+ ],
+ [
+ list("abab"),
+ ["1st", "2nd", "1st"],
+ MultiIndex(
+ levels=[["a", "b"], ["1st", "2nd"]],
+ codes=[np.tile(np.arange(2).repeat(3), 2), np.tile([0, 1, 0], 4)],
+ ),
+ ],
+ [
+ MultiIndex.from_tuples((("a", 2), ("b", 1), ("a", 1), ("b", 2))),
+ ["1st", "2nd", "1st"],
+ MultiIndex(
+ levels=[["a", "b"], [1, 2], ["1st", "2nd"]],
+ codes=[
+ np.tile(np.arange(2).repeat(3), 2),
+ np.repeat([1, 0, 1], [3, 6, 3]),
+ np.tile([0, 1, 0], 4),
+ ],
+ ),
+ ],
+ ],
+ )
+ def test_stack_duplicate_index(self, idx, columns, exp_idx):
# GH10417
- def check(left, right):
- tm.assert_series_equal(left, right)
- assert left.index.is_unique is False
- li, ri = left.index, right.index
- tm.assert_index_equal(li, ri)
-
df = DataFrame(
np.arange(12).reshape(4, 3),
- index=list("abab"),
- columns=["1st", "2nd", "3rd"],
+ index=idx,
+ columns=columns,
)
-
- mi = MultiIndex(
- levels=[["a", "b"], ["1st", "2nd", "3rd"]],
- codes=[np.tile(np.arange(2).repeat(3), 2), np.tile(np.arange(3), 4)],
- )
-
- left, right = df.stack(), Series(np.arange(12), index=mi)
- check(left, right)
-
- df.columns = ["1st", "2nd", "1st"]
- mi = MultiIndex(
- levels=[["a", "b"], ["1st", "2nd"]],
- codes=[np.tile(np.arange(2).repeat(3), 2), np.tile([0, 1, 0], 4)],
- )
-
- left, right = df.stack(), Series(np.arange(12), index=mi)
- check(left, right)
-
- tpls = ("a", 2), ("b", 1), ("a", 1), ("b", 2)
- df.index = MultiIndex.from_tuples(tpls)
- mi = MultiIndex(
- levels=[["a", "b"], [1, 2], ["1st", "2nd"]],
- codes=[
- np.tile(np.arange(2).repeat(3), 2),
- np.repeat([1, 0, 1], [3, 6, 3]),
- np.tile([0, 1, 0], 4),
- ],
- )
-
- left, right = df.stack(), Series(np.arange(12), index=mi)
- check(left, right)
+ result = df.stack()
+ expected = Series(np.arange(12), index=exp_idx)
+ tm.assert_series_equal(result, expected)
+ assert result.index.is_unique is False
+ li, ri = result.index, expected.index
+ tm.assert_index_equal(li, ri)
def test_unstack_odd_failure(self):
data = """day,time,smoker,sum,len
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index ef313b2840107..a5ba684a37edf 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -254,14 +254,18 @@ def test_constructor(self):
int32block = create_block("i4", [0])
assert int32block.dtype == np.int32
- def test_pickle(self):
- def _check(blk):
- assert_block_equal(tm.round_trip_pickle(blk), blk)
-
- _check(self.fblock)
- _check(self.cblock)
- _check(self.oblock)
- _check(self.bool_block)
+ @pytest.mark.parametrize(
+ "typ, data",
+ [
+ ["float", [0, 2, 4]],
+ ["complex", [7]],
+ ["object", [1, 3]],
+ ["bool", [5]],
+ ],
+ )
+ def test_pickle(self, typ, data):
+ blk = create_block(typ, data)
+ assert_block_equal(tm.round_trip_pickle(blk), blk)
def test_mgr_locs(self):
assert isinstance(self.fblock.mgr_locs, BlockPlacement)
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index fe6914e6ef4f5..bf0a10fa702a5 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -175,29 +175,32 @@ def test_eng_float_formatter(self, float_frame):
repr(df)
tm.reset_display_options()
- def test_show_null_counts(self):
+ @pytest.mark.parametrize(
+ "row, columns, show_counts, result",
+ [
+ [20, 20, None, True],
+ [20, 20, True, True],
+ [20, 20, False, False],
+ [5, 5, None, False],
+ [5, 5, True, False],
+ [5, 5, False, False],
+ ],
+ )
+ def test_show_counts(self, row, columns, show_counts, result):
df = DataFrame(1, columns=range(10), index=range(10))
df.iloc[1, 1] = np.nan
- def check(show_counts, result):
- buf = StringIO()
- df.info(buf=buf, show_counts=show_counts)
- assert ("non-null" in buf.getvalue()) is result
-
with option_context(
- "display.max_info_rows", 20, "display.max_info_columns", 20
+ "display.max_info_rows", row, "display.max_info_columns", columns
):
- check(None, True)
- check(True, True)
- check(False, False)
-
- with option_context("display.max_info_rows", 5, "display.max_info_columns", 5):
- check(None, False)
- check(True, False)
- check(False, False)
+ with StringIO() as buf:
+ df.info(buf=buf, show_counts=show_counts)
+ assert ("non-null" in buf.getvalue()) is result
+ def test_show_null_counts_deprecation(self):
# GH37999
+ df = DataFrame(1, columns=range(10), index=range(10))
with tm.assert_produces_warning(
FutureWarning, match="null_counts is deprecated.+"
):
diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py
index 41addc5023436..8e7b31bcf8bca 100644
--- a/pandas/tests/io/pytables/test_put.py
+++ b/pandas/tests/io/pytables/test_put.py
@@ -219,37 +219,35 @@ def test_put_mixed_type(setup_path):
tm.assert_frame_equal(expected, df)
-def test_store_index_types(setup_path):
+@pytest.mark.parametrize(
+ "format, index",
+ [
+ ["table", tm.makeFloatIndex],
+ ["table", tm.makeStringIndex],
+ ["table", tm.makeIntIndex],
+ ["table", tm.makeDateIndex],
+ ["fixed", tm.makeFloatIndex],
+ ["fixed", tm.makeStringIndex],
+ ["fixed", tm.makeIntIndex],
+ ["fixed", tm.makeDateIndex],
+ ["table", tm.makePeriodIndex], # GH#7796
+ ["fixed", tm.makePeriodIndex],
+ ["table", tm.makeUnicodeIndex],
+ ["fixed", tm.makeUnicodeIndex],
+ ],
+)
+def test_store_index_types(setup_path, format, index):
# GH5386
# test storing various index types
with ensure_clean_store(setup_path) as store:
- def check(format, index):
- df = DataFrame(np.random.randn(10, 2), columns=list("AB"))
- df.index = index(len(df))
-
- _maybe_remove(store, "df")
- store.put("df", df, format=format)
- tm.assert_frame_equal(df, store["df"])
-
- for index in [
- tm.makeFloatIndex,
- tm.makeStringIndex,
- tm.makeIntIndex,
- tm.makeDateIndex,
- ]:
+ df = DataFrame(np.random.randn(10, 2), columns=list("AB"))
+ df.index = index(len(df))
- check("table", index)
- check("fixed", index)
-
- check("fixed", tm.makePeriodIndex)
- check("table", tm.makePeriodIndex) # GH#7796
-
- # unicode
- index = tm.makeUnicodeIndex
- check("table", index)
- check("fixed", index)
+ _maybe_remove(store, "df")
+ store.put("df", df, format=format)
+ tm.assert_frame_equal(df, store["df"])
def test_column_multiindex(setup_path):
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45106 | 2021-12-29T04:18:41Z | 2021-12-29T14:22:25Z | 2021-12-29T14:22:25Z | 2021-12-29T18:52:56Z |
DEPR: downcast kwd in fillna | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c02749320e991..924c085e66507 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5207,7 +5207,7 @@ def fillna(
axis: Axis | None = None,
inplace: bool = False,
limit=None,
- downcast=None,
+ downcast=lib.no_default,
) -> DataFrame | None:
return super().fillna(
value=value,
@@ -10862,7 +10862,7 @@ def ffill(
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
- downcast=None,
+ downcast=lib.no_default,
) -> DataFrame | None:
return super().ffill(axis, inplace, limit, downcast)
@@ -10872,7 +10872,7 @@ def bfill(
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
- downcast=None,
+ downcast=lib.no_default,
) -> DataFrame | None:
return super().bfill(axis, inplace, limit, downcast)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index de40ad36a7d02..8de961f719e1b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6258,7 +6258,7 @@ def fillna(
axis=None,
inplace: bool_t = False,
limit=None,
- downcast=None,
+ downcast=lib.no_default,
) -> NDFrameT | None:
"""
Fill NA/NaN values using the specified method.
@@ -6293,6 +6293,8 @@ def fillna(
or the string 'infer' which will try to downcast to an appropriate
equal type (e.g. float64 to int64 if possible).
+ .. deprecated:: 1.4.0
+
Returns
-------
{klass} or None
@@ -6372,6 +6374,17 @@ def fillna(
inplace = validate_bool_kwarg(inplace, "inplace")
value, method = validate_fillna_kwargs(value, method)
+ if downcast is not lib.no_default:
+ warnings.warn(
+ f"{type(self).__name__}.fillna 'downcast' keyword is deprecated "
+ "and will be removed in a future version.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ pass
+ else:
+ downcast = None
+
self._consolidate_inplace()
# set the default here, so functions examining the signaure
@@ -6435,7 +6448,11 @@ def fillna(
for k, v in value.items():
if k not in result:
continue
- downcast_k = downcast if not is_dict else downcast.get(k)
+ downcast_k = (
+ downcast if not is_dict else downcast.get(k, lib.no_default)
+ )
+ if downcast_k is None:
+ downcast_k = lib.no_default
result[k] = result[k].fillna(v, limit=limit, downcast=downcast_k)
return result if not inplace else None
@@ -6468,7 +6485,7 @@ def ffill(
axis: None | Axis = None,
inplace: bool_t = False,
limit: None | int = None,
- downcast=None,
+ downcast=lib.no_default,
) -> NDFrameT | None:
"""
Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``.
@@ -6490,7 +6507,7 @@ def bfill(
axis: None | Axis = None,
inplace: bool_t = False,
limit: None | int = None,
- downcast=None,
+ downcast=lib.no_default,
) -> NDFrameT | None:
"""
Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``.
@@ -9008,6 +9025,7 @@ def _where(
# make sure we are boolean
fill_value = bool(inplace)
cond = cond.fillna(fill_value)
+ cond = cond.infer_objects()
msg = "Boolean array expected for the condition, not {dtype}"
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index d5b1292435f04..d0d29d871c7bb 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2735,6 +2735,13 @@ def fillna(self, value=None, downcast=None):
DataFrame.fillna : Fill NaN values of a DataFrame.
Series.fillna : Fill NaN Values of a Series.
"""
+ if downcast is not None:
+ warnings.warn(
+ "Index.fillna 'downcast' keyword is deprecated and will be "
+ "removed in a future version.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
value = self._require_scalar(value)
if self.hasnans:
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 6ef8d90d7dcf2..1806abd4de2bf 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -458,7 +458,7 @@ def fillna(
if self._can_hold_element(value):
nb = self if inplace else self.copy()
putmask_inplace(nb.values, mask, value)
- return nb._maybe_downcast([nb], downcast)
+ return nb._maybe_downcast([nb], downcast, deprecate=True)
if noop:
# we can't process the value, but nothing to do
@@ -515,17 +515,19 @@ def split_and_operate(self, func, *args, **kwargs) -> list[Block]:
return res_blocks
@final
- def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]:
+ def _maybe_downcast(
+ self, blocks: list[Block], downcast=None, deprecate: bool = False
+ ) -> list[Block]:
if self.dtype == _dtype_obj:
# GH#44241 We downcast regardless of the argument;
# respecting 'downcast=None' may be worthwhile at some point,
# but ATM it breaks too much existing code.
# split and convert the blocks
-
- return extend_blocks(
+ casted = extend_blocks(
[blk.convert(datetime=True, numeric=False) for blk in blocks]
)
+ return casted
if downcast is None:
return blocks
@@ -534,7 +536,19 @@ def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]:
# TODO: not reached, deprecate in favor of downcast=None
return blocks
- return extend_blocks([b._downcast_2d(downcast) for b in blocks])
+ casted = extend_blocks([b._downcast_2d(downcast) for b in blocks])
+ if deprecate and not all(is_dtype_equal(x.dtype, self.dtype) for x in casted):
+ # i.e. we did *some* casting
+ warnings.warn(
+ "Casting behavior of .fillna, .interpolate, .ffill, .bfill "
+ f"for {self.dtype}-dtype columns is deprecated. In a future version, "
+ "these columns will not be automatically downcast. To retain "
+ "the old behavior, explicitly cast the resulting columns "
+ "to the desired dtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return casted
@final
@maybe_split
@@ -1077,7 +1091,7 @@ def interpolate(
)
nb = self.make_block_same_class(data)
- return nb._maybe_downcast([nb], downcast)
+ return nb._maybe_downcast([nb], downcast, deprecate=True)
def take_nd(
self,
@@ -1808,6 +1822,11 @@ def fillna(
self, value, limit=None, inplace: bool = False, downcast=None
) -> list[Block]:
+ if not self.values._hasnans:
+ # Avoid possible upcast
+ # TODO: respect 'inplace' keyword
+ return self.copy()
+
if not self._can_hold_element(value) and self.dtype.kind != "m":
# We support filling a DatetimeTZ with a `value` whose timezone
# is different by coercing to object.
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index fc6db78320169..3f08efdffd0e2 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -23,6 +23,7 @@
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
from pandas.core.dtypes.common import (
+ is_integer,
is_integer_dtype,
is_list_like,
is_nested_list_like,
@@ -201,26 +202,30 @@ def __internal_pivot_table(
to_unstack.append(i)
else:
to_unstack.append(name)
- table = agged.unstack(to_unstack)
+
+ table = agged.unstack(to_unstack, fill_value=fill_value)
if not dropna:
if isinstance(table.index, MultiIndex):
m = MultiIndex.from_arrays(
cartesian_product(table.index.levels), names=table.index.names
)
- table = table.reindex(m, axis=0)
+ table = table.reindex(m, axis=0, fill_value=fill_value)
if isinstance(table.columns, MultiIndex):
m = MultiIndex.from_arrays(
cartesian_product(table.columns.levels), names=table.columns.names
)
- table = table.reindex(m, axis=1)
+ table = table.reindex(m, axis=1, fill_value=fill_value)
if isinstance(table, ABCDataFrame):
table = table.sort_index(axis=1)
if fill_value is not None:
- table = table.fillna(fill_value, downcast="infer")
+ table = table.fillna(fill_value)
+ table = table.infer_objects()
+ if aggfunc is len and not observed and is_integer(fill_value):
+ table = table.astype(np.int64)
if margins:
if dropna:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 83ebcd9ffb4b3..a3656f02f103f 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4876,7 +4876,7 @@ def fillna(
axis=None,
inplace=False,
limit=None,
- downcast=None,
+ downcast=lib.no_default,
) -> Series | None:
return super().fillna(
value=value,
@@ -5475,7 +5475,7 @@ def ffill(
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
- downcast=None,
+ downcast=lib.no_default,
) -> Series | None:
return super().ffill(axis, inplace, limit, downcast)
@@ -5485,7 +5485,7 @@ def bfill(
axis: None | Axis = None,
inplace: bool = False,
limit: None | int = None,
- downcast=None,
+ downcast=lib.no_default,
) -> Series | None:
return super().bfill(axis, inplace, limit, downcast)
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index 3d55ff5f98407..aa5be35360b64 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -504,8 +504,9 @@ def test_where_axis(self, using_array_manager):
tm.assert_frame_equal(result, expected)
warn = FutureWarning if using_array_manager else None
+ msg = "Downcasting integer-dtype"
expected = DataFrame([[0, np.nan], [0, np.nan]])
- with tm.assert_produces_warning(warn, match="Downcasting integer-dtype"):
+ with tm.assert_produces_warning(warn, match=msg):
result = df.where(mask, s, axis="columns")
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index b5bdf6a70199c..fd406b6533168 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -234,13 +234,15 @@ def test_fillna_downcast(self):
# GH#15277
# infer int64 from float64
df = DataFrame({"a": [1.0, np.nan]})
- result = df.fillna(0, downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match="Casting behavior"):
+ result = df.fillna(0, downcast="infer")
expected = DataFrame({"a": [1, 0]})
tm.assert_frame_equal(result, expected)
# infer int64 from float64 when fillna value is a dict
df = DataFrame({"a": [1.0, np.nan]})
- result = df.fillna({"a": 0}, downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match="Casting behavior"):
+ result = df.fillna({"a": 0}, downcast="infer")
expected = DataFrame({"a": [1, 0]})
tm.assert_frame_equal(result, expected)
@@ -563,7 +565,9 @@ def test_fill_corner(self, float_frame, float_string_frame):
def test_fillna_downcast_dict(self):
# GH#40809
df = DataFrame({"col1": [1, np.nan]})
- result = df.fillna({"col1": 2}, downcast={"col1": "int64"})
+ msg = "fillna 'downcast' keyword"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.fillna({"col1": 2}, downcast={"col1": "int64"})
expected = DataFrame({"col1": [1, 2]})
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index 37fb0754baffd..2ce4a959ce1ec 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -96,7 +96,8 @@ def test_interp_combo(self):
expected = Series([1.0, 2.0, 3.0, 4.0], name="A")
tm.assert_series_equal(result, expected)
- result = df["A"].interpolate(downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match="Casting behavior"):
+ result = df["A"].interpolate(downcast="infer")
expected = Series([1, 2, 3, 4], name="A")
tm.assert_series_equal(result, expected)
@@ -160,7 +161,8 @@ def test_interp_alt_scipy(self):
expected.loc[5, "A"] = 6
tm.assert_frame_equal(result, expected)
- result = df.interpolate(method="barycentric", downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match="Casting behavior"):
+ result = df.interpolate(method="barycentric", downcast="infer")
tm.assert_frame_equal(result, expected.astype(np.int64))
result = df.interpolate(method="krogh")
@@ -280,7 +282,8 @@ def test_interp_inplace(self):
tm.assert_frame_equal(result, expected)
result = df.copy()
- return_value = result["a"].interpolate(inplace=True, downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match="Casting behavior"):
+ return_value = result["a"].interpolate(inplace=True, downcast="infer")
assert return_value is None
tm.assert_frame_equal(result, expected.astype("int64"))
diff --git a/pandas/tests/frame/test_logical_ops.py b/pandas/tests/frame/test_logical_ops.py
index f509ae52ad5a5..08b15a45881bb 100644
--- a/pandas/tests/frame/test_logical_ops.py
+++ b/pandas/tests/frame/test_logical_ops.py
@@ -165,7 +165,9 @@ def test_logical_with_nas(self):
expected = Series([True, True])
tm.assert_series_equal(result, expected)
- result = d["a"].fillna(False, downcast=False) | d["b"]
+ msg = "Series.fillna 'downcast' keyword is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = d["a"].fillna(False, downcast=False) | d["b"]
expected = Series([True, True])
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 5ae929be1d8cf..494ae747e69d8 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -1242,7 +1242,8 @@ def test_seriesgroupby_observed_false_or_none(df_cat, observed, operation):
expected = Series(data=[2, 4, np.nan, 1, np.nan, 3], index=index, name="C")
if operation == "agg":
- expected = expected.fillna(0, downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match="Casting behavior"):
+ expected = expected.fillna(0, downcast="infer")
grouped = df_cat.groupby(["A", "B"], observed=observed)["C"]
result = getattr(grouped, operation)(sum)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 6b6caf1f8affd..49f701ad08480 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -519,7 +519,8 @@ def test_fillna(self, index):
msg = "does not support 'downcast'"
with pytest.raises(NotImplementedError, match=msg):
# For now at least, we only raise if there are NAs present
- idx.fillna(idx[0], downcast="infer")
+ with tm.assert_produces_warning(FutureWarning):
+ idx.fillna(idx[0], downcast="infer")
expected = np.array([False] * len(idx), dtype=bool)
expected[1] = True
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 19f61a0a2d6fc..e8c2d67d7a87d 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -178,14 +178,17 @@ def test_fillna_consistency(self):
def test_fillna_downcast(self):
# GH#15277
# infer int64 from float64
+ msg = "'downcast' keyword is deprecated"
ser = Series([1.0, np.nan])
- result = ser.fillna(0, downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = ser.fillna(0, downcast="infer")
expected = Series([1, 0])
tm.assert_series_equal(result, expected)
# infer int64 from float64 when fillna value is a dict
ser = Series([1.0, np.nan])
- result = ser.fillna({1: 0}, downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = ser.fillna({1: 0}, downcast="infer")
expected = Series([1, 0])
tm.assert_series_equal(result, expected)
@@ -198,15 +201,19 @@ def test_fillna_downcast_infer_objects_to_numeric(self):
ser = Series(arr)
- res = ser.fillna(3, downcast="infer")
+ msg = "'downcast' keyword is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.fillna(3, downcast="infer")
expected = Series(np.arange(5), dtype=np.int64)
tm.assert_series_equal(res, expected)
- res = ser.ffill(downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.ffill(downcast="infer")
expected = Series([0, 1, 2, 2, 4], dtype=np.int64)
tm.assert_series_equal(res, expected)
- res = ser.bfill(downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.bfill(downcast="infer")
expected = Series([0, 1, 2, 4, 4], dtype=np.int64)
tm.assert_series_equal(res, expected)
@@ -214,14 +221,17 @@ def test_fillna_downcast_infer_objects_to_numeric(self):
ser[2] = 2.5
expected = Series([0, 1, 2.5, 3, 4], dtype=np.float64)
- res = ser.fillna(3, downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.fillna(3, downcast="infer")
tm.assert_series_equal(res, expected)
- res = ser.ffill(downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.ffill(downcast="infer")
expected = Series([0, 1, 2.5, 2.5, 4], dtype=np.float64)
tm.assert_series_equal(res, expected)
- res = ser.bfill(downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = ser.bfill(downcast="infer")
expected = Series([0, 1, 2.5, 4, 4], dtype=np.float64)
tm.assert_series_equal(res, expected)
diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py
index 8ca2d37016691..5a1834681b146 100644
--- a/pandas/tests/series/methods/test_interpolate.py
+++ b/pandas/tests/series/methods/test_interpolate.py
@@ -281,6 +281,7 @@ def test_interp_scipy_basic(self):
result = s.interpolate(method="slinear")
tm.assert_series_equal(result, expected)
+ msg = "Casting behavior.* columns is deprecated"
result = s.interpolate(method="slinear", downcast="infer")
tm.assert_series_equal(result, expected)
# nearest
@@ -288,14 +289,16 @@ def test_interp_scipy_basic(self):
result = s.interpolate(method="nearest")
tm.assert_series_equal(result, expected.astype("float"))
- result = s.interpolate(method="nearest", downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = s.interpolate(method="nearest", downcast="infer")
tm.assert_series_equal(result, expected)
# zero
expected = Series([1, 3, 3, 12, 12, 25])
result = s.interpolate(method="zero")
tm.assert_series_equal(result, expected.astype("float"))
- result = s.interpolate(method="zero", downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = s.interpolate(method="zero", downcast="infer")
tm.assert_series_equal(result, expected)
# quadratic
# GH #15662.
diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py
index 4350a5d9ac989..6e6e33396a41f 100644
--- a/pandas/tests/series/methods/test_reindex.py
+++ b/pandas/tests/series/methods/test_reindex.py
@@ -134,7 +134,8 @@ def test_reindex_pad():
result = s.reindex(new_index).ffill()
tm.assert_series_equal(result, expected.astype("float64"))
- result = s.reindex(new_index).ffill(downcast="infer")
+ with tm.assert_produces_warning(FutureWarning, match="Casting behavior"):
+ result = s.reindex(new_index).ffill(downcast="infer")
tm.assert_series_equal(result, expected)
expected = Series([1, 5, 3, 5], index=new_index)
| - [x] closes #40988
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
I'm on the fence about this. `downcast="infer"` seems pretty useful, as evidenced by how often it shows up in the tests. We don't have anything analogous to `infer_objects` for "see if i can losslessly downcast numeric values".
If we go forward with this, probably need to deprecate within NDFrame.interpolate too, as apparently some but not all interpolate paths see this deprecation. | https://api.github.com/repos/pandas-dev/pandas/pulls/45105 | 2021-12-29T03:07:53Z | 2021-12-31T19:19:09Z | null | 2022-11-28T20:05:31Z |
DEPR: make to_datetime('now') match Timestamp('now') | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index d770782d5dc62..cfb9cef79cd46 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -640,6 +640,7 @@ Other Deprecations
- Deprecated passing non boolean argument to sort in :func:`concat` (:issue:`41518`)
- Deprecated passing arguments as positional for :func:`read_fwf` other than ``filepath_or_buffer`` (:issue:`41485`):
- Deprecated passing ``skipna=None`` for :meth:`DataFrame.mad` and :meth:`Series.mad`, pass ``skipna=True`` instead (:issue:`44580`)
+- Deprecated the behavior of :func:`to_datetime` with the string "now" with ``utc=False``; in a future version this will match ``Timestamp("now")``, which in turn matches :meth:`Timestamp.now` returning the local time (:issue:`18705`)
- Deprecated :meth:`DateOffset.apply`, use ``offset + other`` instead (:issue:`44522`)
- Deprecated parameter ``names`` in :meth:`Index.copy` (:issue:`44916`)
- A deprecation warning is now shown for :meth:`DataFrame.to_latex` indicating the arguments signature may change and emulate more the arguments to :meth:`.Styler.to_latex` in future versions (:issue:`44411`)
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 6feb9ec768655..2883c910b3833 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -1,3 +1,5 @@
+import warnings
+
import cython
from cpython.datetime cimport (
@@ -516,7 +518,7 @@ cpdef array_to_datetime(
if string_to_dts_failed:
# An error at this point is a _parsing_ error
# specifically _not_ OutOfBoundsDatetime
- if _parse_today_now(val, &iresult[i]):
+ if _parse_today_now(val, &iresult[i], utc):
continue
elif require_iso8601:
# if requiring iso8601 strings, skip trying
@@ -755,14 +757,23 @@ cdef _array_to_datetime_object(
return oresult, None
-cdef inline bint _parse_today_now(str val, int64_t* iresult):
+cdef inline bint _parse_today_now(str val, int64_t* iresult, bint utc):
# We delay this check for as long as possible
# because it catches relatively rare cases
- if val == 'now':
- # Note: this is *not* the same as Timestamp('now')
+ if val == "now":
iresult[0] = Timestamp.utcnow().value
+ if not utc:
+ # GH#18705 make sure to_datetime("now") matches Timestamp("now")
+ warnings.warn(
+ "The parsing of 'now' in pd.to_datetime without `utc=True` is "
+ "deprecated. In a future version, this will match Timestamp('now') "
+ "and Timestamp.now()",
+ FutureWarning,
+ stacklevel=1,
+ )
+
return True
- elif val == 'today':
+ elif val == "today":
iresult[0] = Timestamp.today().value
return True
return False
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 4414462dd9a48..212cfc267cb00 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -1679,8 +1679,8 @@ def test_dt64_series_arith_overflow(self):
tm.assert_series_equal(res, -expected)
def test_datetimeindex_sub_timestamp_overflow(self):
- dtimax = pd.to_datetime(["now", Timestamp.max])
- dtimin = pd.to_datetime(["now", Timestamp.min])
+ dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max])
+ dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min])
tsneg = Timestamp("1950-01-01")
ts_neg_variants = [
@@ -1718,8 +1718,8 @@ def test_datetimeindex_sub_timestamp_overflow(self):
def test_datetimeindex_sub_datetimeindex_overflow(self):
# GH#22492, GH#22508
- dtimax = pd.to_datetime(["now", Timestamp.max])
- dtimin = pd.to_datetime(["now", Timestamp.min])
+ dtimax = pd.to_datetime(["2021-12-28 17:19", Timestamp.max])
+ dtimin = pd.to_datetime(["2021-12-28 17:19", Timestamp.min])
ts_neg = pd.to_datetime(["1950-01-01", "1950-01-01"])
ts_pos = pd.to_datetime(["1980-01-01", "1980-01-01"])
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 50cb16c72953e..5d5e01084345d 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -591,9 +591,15 @@ def test_to_datetime_unparseable_ignore(self):
def test_to_datetime_now(self):
# See GH#18666
with tm.set_timezone("US/Eastern"):
- npnow = np.datetime64("now").astype("datetime64[ns]")
- pdnow = to_datetime("now")
- pdnow2 = to_datetime(["now"])[0]
+ msg = "The parsing of 'now' in pd.to_datetime"
+ with tm.assert_produces_warning(
+ FutureWarning, match=msg, check_stacklevel=False
+ ):
+ # checking stacklevel is tricky because we go through cython code
+ # GH#18705
+ npnow = np.datetime64("now").astype("datetime64[ns]")
+ pdnow = to_datetime("now")
+ pdnow2 = to_datetime(["now"])[0]
# These should all be equal with infinite perf; this gives
# a generous margin of 10 seconds
@@ -632,7 +638,12 @@ def test_to_datetime_today(self, tz):
@pytest.mark.parametrize("arg", ["now", "today"])
def test_to_datetime_today_now_unicode_bytes(self, arg):
- to_datetime([arg])
+ warn = FutureWarning if arg == "now" else None
+ msg = "The parsing of 'now' in pd.to_datetime"
+ with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
+ # checking stacklevel is tricky because we go through cython code
+ # GH#18705
+ to_datetime([arg])
@pytest.mark.parametrize(
"dt", [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")]
| - [x] closes #18705
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45104 | 2021-12-29T02:33:10Z | 2021-12-31T23:58:47Z | 2021-12-31T23:58:47Z | 2022-01-01T00:00:00Z |
CI: Ensure all minimum optional dependencies are tested | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml
index 2a40be680c681..bc3ee2e500d22 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -25,8 +25,8 @@ jobs:
strategy:
matrix:
settings: [
- [actions-38-db-min.yaml, "((not slow and not network and not clipboard) or (single and db))", "", "", "", "", ""],
- [actions-38-db.yaml, "((not slow and not network and not clipboard) or (single and db))", "", "", "", "", ""],
+ [actions-38-downstream_compat.yaml, "not slow and not network and not clipboard", "", "", "", "", ""],
+ [actions-38-minimum_versions.yaml, "slow", "", "", "", "", ""],
[actions-38-minimum_versions.yaml, "not slow and not network and not clipboard", "", "", "", "", ""],
[actions-38-locale_slow.yaml, "slow", "language-pack-it xsel", "it_IT.utf8", "it_IT.utf8", "", ""],
[actions-38.yaml, "not slow and not clipboard", "", "", "", "", ""],
diff --git a/ci/deps/actions-38-db-min.yaml b/ci/deps/actions-38-db-min.yaml
deleted file mode 100644
index f2b5a49ebfa97..0000000000000
--- a/ci/deps/actions-38-db-min.yaml
+++ /dev/null
@@ -1,45 +0,0 @@
-name: pandas-dev
-channels:
- - conda-forge
-dependencies:
- - python=3.8
-
- # tools
- - cython>=0.29.24
- - pytest>=6.0
- - pytest-cov
- - pytest-xdist>=1.31
- - hypothesis>=5.5.3
-
- # required
- - numpy<1.20 # GH#39541 compat for pyarrow<3
- - python-dateutil
- - pytz
-
- # optional
- - beautifulsoup4
- - blosc=1.20.1
- - python-blosc
- - fastparquet=0.4.0
- - html5lib
- - ipython
- - jinja2
- - lxml=4.5.0
- - matplotlib
- - nomkl
- - numexpr
- - openpyxl
- - pandas-gbq
- - protobuf>=3.12.4
- - pyarrow=1.0.1
- - pytables>=3.6.1
- - scipy
- - xarray=0.15.1
- - xlrd
- - xlsxwriter
- - xlwt
-
- # sql
- - psycopg2=2.8.4
- - pymysql=0.10.1
- - sqlalchemy=1.4.0
diff --git a/ci/deps/actions-38-db.yaml b/ci/deps/actions-38-downstream_compat.yaml
similarity index 74%
rename from ci/deps/actions-38-db.yaml
rename to ci/deps/actions-38-downstream_compat.yaml
index ced15bbc8d7cb..af4f7dee851d5 100644
--- a/ci/deps/actions-38-db.yaml
+++ b/ci/deps/actions-38-downstream_compat.yaml
@@ -1,3 +1,4 @@
+# Non-dependencies that pandas utilizes or has compatibility with pandas objects
name: pandas-dev
channels:
- conda-forge
@@ -5,28 +6,30 @@ dependencies:
- python=3.8
- pip
- # tools
+ # test dependencies
- cython>=0.29.24
- pytest>=6.0
- pytest-xdist>=1.31
- hypothesis>=5.5.3
- pytest-cov>=2.10.1 # this is only needed in the coverage build, ref: GH 35737
+ - nomkl
- # pandas dependencies
- - aiobotocore<2.0.0 # GH#44311 pinned to fix docbuild
+ # required dependencies
+ - numpy
+ - python-dateutil
+ - pytz
+
+ # optional dependencies
- beautifulsoup4
- - boto3
- - botocore>=1.11
- - dask
+ - blosc
- fastparquet>=0.4.0
- fsspec>=0.7.4
- - gcsfs>=0.6.0
- - geopandas
+ - gcsfs
- html5lib
+ - jinja2
+ - lxml
- matplotlib
- - nomkl
- numexpr
- - numpy=1.18
- odfpy
- openpyxl
- pandas-gbq
@@ -34,21 +37,30 @@ dependencies:
- pyarrow>=1.0.1
- pymysql
- pytables
- - python-snappy
- - python-dateutil
- - pytz
+ - pyxlsb
- s3fs>=0.4.0
- - scikit-learn
- scipy
- sqlalchemy
- - statsmodels
- xarray
- xlrd
- xlsxwriter
- xlwt
+
+ # downstream packages
+ - aiobotocore<2.0.0 # GH#44311 pinned to fix docbuild
+ - boto3
+ - botocore>=1.11
+ - dask
+ - ipython
+ - geopandas
+ - python-snappy
+ - seaborn
+ - scikit-learn
+ - statsmodels
- brotlipy
- coverage
- pandas-datareader
- - pyxlsb
+ - pyyaml
+ - py
- pip:
- torch
diff --git a/ci/deps/actions-38-locale.yaml b/ci/deps/actions-38-locale.yaml
index b9157a1e74b1c..ef2288e2a24a6 100644
--- a/ci/deps/actions-38-locale.yaml
+++ b/ci/deps/actions-38-locale.yaml
@@ -19,7 +19,7 @@ dependencies:
- jinja2
- jedi
- lxml
- - matplotlib<3.3.0
+ - matplotlib
- nomkl
- numexpr
- numpy<1.20 # GH#39541 compat with pyarrow<3
diff --git a/ci/deps/actions-38-locale_slow.yaml b/ci/deps/actions-38-locale_slow.yaml
index e90acafa8bb2b..b16153398163b 100644
--- a/ci/deps/actions-38-locale_slow.yaml
+++ b/ci/deps/actions-38-locale_slow.yaml
@@ -13,18 +13,18 @@ dependencies:
- hypothesis>=5.5.3
# pandas dependencies
- - beautifulsoup4=4.8.2
- - bottleneck=1.3.1
+ - beautifulsoup4
+ - bottleneck
- lxml
- - matplotlib=3.3.2
- - numpy=1.18
- - openpyxl=3.0.2
+ - matplotlib
+ - numpy
+ - openpyxl
- python-dateutil
- python-blosc
- pytz=2020.1
- scipy
- - sqlalchemy=1.4.0
- - xlrd=2.0.1
- - xlsxwriter=1.2.2
- - xlwt=1.3.0
- - html5lib=1.1
+ - sqlalchemy
+ - xlrd
+ - xlsxwriter
+ - xlwt
+ - html5lib
diff --git a/ci/deps/actions-38-minimum_versions.yaml b/ci/deps/actions-38-minimum_versions.yaml
index cc1fd022ad24c..8505dad542239 100644
--- a/ci/deps/actions-38-minimum_versions.yaml
+++ b/ci/deps/actions-38-minimum_versions.yaml
@@ -1,10 +1,12 @@
+# Minimum version of required + optional dependencies
+# Aligned with getting_started/install.rst and compat/_optional.py
name: pandas-dev
channels:
- conda-forge
dependencies:
- python=3.8.0
- # tools
+ # test dependencies
- cython=0.29.24
- pytest>=6.0
- pytest-cov
@@ -12,20 +14,39 @@ dependencies:
- hypothesis>=5.5.3
- psutil
- # pandas dependencies
+ # required dependencies
+ - python-dateutil=2.8.1
+ - numpy=1.18.5
+ - pytz=2020.1
+
+ # optional dependencies
- beautifulsoup4=4.8.2
+ - blosc=1.20.1
- bottleneck=1.3.1
+ - fastparquet=0.4.0
+ - fsspec=0.7.4
+ - html5lib=1.1
+ - gcsfs=0.6.0
- jinja2=2.11
+ - lxml=4.5.0
+ - matplotlib=3.3.2
- numba=0.50.1
- numexpr=2.7.1
- - numpy=1.18.5
- - openpyxl=3.0.2
+ - openpyxl=3.0.3
+ - odfpy=1.4.1
+ - pandas-gbq=0.14.0
+ - psycopg2=2.8.4
+ - pymysql=0.10.1
- pytables=3.6.1
- - python-dateutil=2.8.1
- - pytz=2020.1
- pyarrow=1.0.1
+ - pyreadstat
+ - pyxlsb=1.0.6
+ - s3fs=0.4.0
- scipy=1.4.1
+ - sqlalchemy=1.4.0
+ - tabulate=0.8.7
+ - xarray=0.15.1
- xlrd=2.0.1
- xlsxwriter=1.2.2
- xlwt=1.3.0
- - html5lib=1.1
+ - zstandard=0.15.2
diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 899913d6e8c70..2ad31ce82b855 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -17,4 +17,4 @@ dependencies:
- python-dateutil
- nomkl
- pytz
- - tabulate==0.8.7
+ - tabulate
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index 28b9da137e86d..05c47d5cdf4f7 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -291,7 +291,7 @@ Dependency Minimum Version Notes
xlrd 2.0.1 Reading Excel
xlwt 1.3.0 Writing Excel
xlsxwriter 1.2.2 Writing Excel
-openpyxl 3.0.2 Reading / writing for xlsx files
+openpyxl 3.0.3 Reading / writing for xlsx files
pyxlsb 1.0.6 Reading for xlsb files
========================= ================== =============================================================
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 7c03e10c86bd4..26f0aa38ee66d 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -430,7 +430,7 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| numba | 0.50.1 | X |
+-----------------+-----------------+---------+
-| openpyxl | 3.0.2 | X |
+| openpyxl | 3.0.3 | X |
+-----------------+-----------------+---------+
| pyarrow | 1.0.1 | X |
+-----------------+-----------------+---------+
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index c3b7cfa3e0026..a2be663504abe 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -19,7 +19,7 @@
"matplotlib": "3.3.2",
"numexpr": "2.7.1",
"odfpy": "1.4.1",
- "openpyxl": "3.0.2",
+ "openpyxl": "3.0.3",
"pandas_gbq": "0.14.0",
"pyarrow": "1.0.1",
"pytest": "6.0",
diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py
index bbfed852d8b38..e3e8358aa6340 100644
--- a/pandas/tests/io/test_fsspec.py
+++ b/pandas/tests/io/test_fsspec.py
@@ -3,6 +3,8 @@
import numpy as np
import pytest
+from pandas.compat._optional import VERSIONS
+
from pandas import (
DataFrame,
date_range,
@@ -289,7 +291,21 @@ def test_stata_options(fsspectest):
@td.skip_if_no("tabulate")
-def test_markdown_options(fsspectest):
+def test_markdown_options(request, fsspectest):
+ import fsspec
+
+ # error: Library stubs not installed for "tabulate"
+ # (or incompatible with Python 3.8)
+ import tabulate # type: ignore[import]
+
+ request.node.add_marker(
+ pytest.mark.xfail(
+ fsspec.__version__ == VERSIONS["fsspec"]
+ and tabulate.__version__ == VERSIONS["tabulate"],
+ reason="Fails on the min version build",
+ raises=FileNotFoundError,
+ )
+ )
df = DataFrame({"a": [0]})
df.to_markdown("testmem://afile", storage_options={"test": "md_write"})
assert fsspectest.test[0] == "md_write"
diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py
index 4350a5d9ac989..a500252a44e07 100644
--- a/pandas/tests/series/methods/test_reindex.py
+++ b/pandas/tests/series/methods/test_reindex.py
@@ -171,10 +171,6 @@ def test_reindex_nearest():
tm.assert_series_equal(expected, result)
-def test_reindex_backfill():
- pass
-
-
def test_reindex_int(datetime_series):
ts = datetime_series[::2]
int_ts = Series(np.zeros(len(ts), dtype=int), index=ts.index)
| - [x] tests added / passed
Progress towards https://github.com/pandas-dev/pandas/issues/29685
- `actions-38-minimum_versions.yaml` now contains all optional dependencies with their min versions
- Other builds that have min version pinned are now removed
- `actions-38-db.yaml` -> `actions-38-downstream_compat.yaml`
- Build for compat with libraries like statsmodels, pytorch, yaml, etc
- `actions-38-db-min.yaml` removed as redundant with `actions-38-minimum_versions.yaml`
Discoveries:
Min version of lxml and openpyxl with `.xlsm` or `.xlsx` doesn't seem to work. Need to bump to openpyxl to 3.0.9 https://openpyxl.readthedocs.io/en/stable/changes.html#id47 | https://api.github.com/repos/pandas-dev/pandas/pulls/45103 | 2021-12-29T01:14:09Z | 2022-01-05T00:48:18Z | 2022-01-05T00:48:18Z | 2022-01-05T00:53:23Z |
BUG: head and tail not dropping groups with nan | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 2c77b87f8efb6..8717e57868d82 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -894,6 +894,7 @@ Groupby/resample/rolling
- Bug in :meth:`GroupBy.nth` failing on ``axis=1`` (:issue:`43926`)
- Fixed bug in :meth:`Series.rolling` and :meth:`DataFrame.rolling` not respecting right bound on centered datetime-like windows, if the index contain duplicates (:issue:`3944`)
- Bug in :meth:`Series.rolling` and :meth:`DataFrame.rolling` when using a :class:`pandas.api.indexers.BaseIndexer` subclass that returned unequal start and end arrays would segfault instead of raising a ``ValueError`` (:issue:`44470`)
+- Bug in :meth:`GroupBy.head` and :meth:`GroupBy.tail` not dropping groups with ``NaN`` when ``dropna=True`` (:issue:`45089`)
- Fixed bug in :meth:`GroupBy.__iter__` after selecting a subset of columns in a :class:`GroupBy` object, which returned all columns instead of the chosen subset (:issue:`#44821`)
- Bug in :meth:`Groupby.rolling` when non-monotonic data passed, fails to correctly raise ``ValueError`` (:issue:`43909`)
- Fixed bug where grouping by a :class:`Series` that has a categorical data type and length unequal to the axis of grouping raised ``ValueError`` (:issue:`44179`)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index afd25fdff7614..4a42e2b61823d 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -3580,6 +3580,9 @@ def _mask_selected_obj(self, mask: np.ndarray) -> NDFrameT:
Series or DataFrame
Filtered _selected_obj.
"""
+ ids = self.grouper.group_info[0]
+ mask = mask & (ids != -1)
+
if self.axis == 0:
return self._selected_obj[mask]
else:
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py
index 8a5f972c22640..185b0b8ea8a71 100644
--- a/pandas/tests/groupby/test_nth.py
+++ b/pandas/tests/groupby/test_nth.py
@@ -809,3 +809,35 @@ def test_nth_slices_with_column_axis(
}[method](start, stop)
expected = DataFrame([expected_values], columns=expected_columns)
tm.assert_frame_equal(result, expected)
+
+
+def test_head_tail_dropna_true():
+ # GH#45089
+ df = DataFrame(
+ [["a", "z"], ["b", np.nan], ["c", np.nan], ["c", np.nan]], columns=["X", "Y"]
+ )
+ expected = DataFrame([["a", "z"]], columns=["X", "Y"])
+
+ result = df.groupby(["X", "Y"]).head(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"]).tail(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"]).nth(n=0).reset_index()
+ tm.assert_frame_equal(result, expected)
+
+
+def test_head_tail_dropna_false():
+ # GH#45089
+ df = DataFrame([["a", "z"], ["b", np.nan], ["c", np.nan]], columns=["X", "Y"])
+ expected = DataFrame([["a", "z"], ["b", np.nan], ["c", np.nan]], columns=["X", "Y"])
+
+ result = df.groupby(["X", "Y"], dropna=False).head(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"], dropna=False).tail(n=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby(["X", "Y"], dropna=False).nth(n=0).reset_index()
+ tm.assert_frame_equal(result, expected)
| - [x] closes #45089
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
We could also create a specific function for this.
Also that nth respects ``as_index`` while it is ignored by ``head`` and ``tail`` looks inconsistent | https://api.github.com/repos/pandas-dev/pandas/pulls/45102 | 2021-12-28T23:55:57Z | 2021-12-30T00:01:36Z | 2021-12-30T00:01:35Z | 2021-12-30T10:22:58Z |
DEPR: coercing bools to numeric on concat with numeric dtypes | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 1c1415255bf89..c11ccfdbe1b33 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -606,6 +606,7 @@ Other Deprecations
- Deprecated :meth:`DateOffset.apply`, use ``offset + other`` instead (:issue:`44522`)
- Deprecated parameter ``names`` in :meth:`Index.copy` (:issue:`44916`)
- A deprecation warning is now shown for :meth:`DataFrame.to_latex` indicating the arguments signature may change and emulate more the arguments to :meth:`.Styler.to_latex` in future versions (:issue:`44411`)
+- Deprecated behavior of :func:`concat` between objects with bool-dtype and numeric-dtypes; in a future version these will cast to object dtype instead of coercing bools to numeric values (:issue:`39817`)
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index 701f9fd4a9c99..2dc4241c6a303 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -5,6 +5,7 @@
TYPE_CHECKING,
cast,
)
+import warnings
import numpy as np
@@ -12,6 +13,7 @@
ArrayLike,
DtypeObj,
)
+from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.cast import (
astype_array,
@@ -144,8 +146,20 @@ def is_nonempty(x) -> bool:
else:
# coerce to object
to_concat = [x.astype("object") for x in to_concat]
-
- return np.concatenate(to_concat, axis=axis)
+ kinds = {"o"}
+
+ result = np.concatenate(to_concat, axis=axis)
+ if "b" in kinds and result.dtype.kind in ["i", "u", "f"]:
+ # GH#39817
+ warnings.warn(
+ "Behavior when concatenating bool-dtype and numeric-dtype arrays is "
+ "deprecated; in a future version these will cast to object dtype "
+ "(instead of coercing bools to numeric values). To retain the old "
+ "behavior, explicitly cast bool-dtype arrays to numeric dtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return result
def union_categoricals(
diff --git a/pandas/tests/reshape/concat/test_append_common.py b/pandas/tests/reshape/concat/test_append_common.py
index bb8027948c540..f36bee9dd8dec 100644
--- a/pandas/tests/reshape/concat/test_append_common.py
+++ b/pandas/tests/reshape/concat/test_append_common.py
@@ -204,13 +204,16 @@ def test_concatlike_dtypes_coercion(self, item, item2):
# instead of a list; we have separate dedicated tests for categorical
return
+ warn = None
# specify expected dtype
if typ1 == "bool" and typ2 in ("int64", "float64"):
# series coerces to numeric based on numpy rule
# index doesn't because bool is object dtype
exp_series_dtype = typ2
+ warn = FutureWarning
elif typ2 == "bool" and typ1 in ("int64", "float64"):
exp_series_dtype = typ1
+ warn = FutureWarning
elif (
typ1 == "datetime64[ns, US/Eastern]"
or typ2 == "datetime64[ns, US/Eastern]"
@@ -238,23 +241,33 @@ def test_concatlike_dtypes_coercion(self, item, item2):
# ----- Series ----- #
# series._append
- res = Series(vals1)._append(Series(vals2), ignore_index=True)
+ with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
+ # GH#39817
+ res = Series(vals1)._append(Series(vals2), ignore_index=True)
exp = Series(exp_data, dtype=exp_series_dtype)
tm.assert_series_equal(res, exp, check_index_type=True)
# concat
- res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True)
+ with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
+ # GH#39817
+ res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True)
tm.assert_series_equal(res, exp, check_index_type=True)
# 3 elements
- res = Series(vals1)._append([Series(vals2), Series(vals3)], ignore_index=True)
+ with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
+ # GH#39817
+ res = Series(vals1)._append(
+ [Series(vals2), Series(vals3)], ignore_index=True
+ )
exp = Series(exp_data3, dtype=exp_series_dtype)
tm.assert_series_equal(res, exp)
- res = pd.concat(
- [Series(vals1), Series(vals2), Series(vals3)],
- ignore_index=True,
- )
+ with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
+ # GH#39817
+ res = pd.concat(
+ [Series(vals1), Series(vals2), Series(vals3)],
+ ignore_index=True,
+ )
tm.assert_series_equal(res, exp)
def test_concatlike_common_coerce_to_pandas_object(self):
diff --git a/pandas/tests/reshape/concat/test_empty.py b/pandas/tests/reshape/concat/test_empty.py
index 92f91a6e53add..82d2a8a2b1fd2 100644
--- a/pandas/tests/reshape/concat/test_empty.py
+++ b/pandas/tests/reshape/concat/test_empty.py
@@ -109,7 +109,12 @@ def test_concat_empty_series_timelike(self, tz, values):
],
)
def test_concat_empty_series_dtypes(self, left, right, expected):
- result = concat([Series(dtype=left), Series(dtype=right)])
+ warn = None
+ if (left is np.bool_ or right is np.bool_) and expected is not np.object_:
+ warn = FutureWarning
+ with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
+ # GH#39817
+ result = concat([Series(dtype=left), Series(dtype=right)])
assert result.dtype == expected
@pytest.mark.parametrize(
| - [x] closes #39817
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45101 | 2021-12-28T23:06:16Z | 2021-12-29T14:27:39Z | 2021-12-29T14:27:39Z | 2021-12-29T15:36:06Z |
BUG: merge raising KeyError with differently named indexes and on keywords | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 2c77b87f8efb6..9e5e2b5db94b9 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -914,6 +914,7 @@ Reshaping
- Fixed metadata propagation in :meth:`Dataframe.apply` method, consequently fixing the same issue for :meth:`Dataframe.transform`, :meth:`Dataframe.nunique` and :meth:`Dataframe.mode` (:issue:`28283`)
- Bug in :func:`concat` casting levels of :class:`MultiIndex` to float if the only consist of missing values (:issue:`44900`)
- Bug in :meth:`DataFrame.stack` with ``ExtensionDtype`` columns incorrectly raising (:issue:`43561`)
+- Bug in :func:`merge` raising ``KeyError`` when joining over differently named indexes with on keywords (:issue:`45094`)
- Bug in :meth:`Series.unstack` with object doing unwanted type inference on resulting columns (:issue:`44595`)
- Bug in :class:`MultiIndex` failing join operations with overlapping ``IntervalIndex`` levels (:issue:`44096`)
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` results is different ``dtype`` based on ``regex`` parameter (:issue:`44864`)
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 9a534ef7625a4..412cc5a8b43a3 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -820,6 +820,7 @@ def _maybe_restore_index_levels(self, result: DataFrame) -> None:
if (
self.orig_left._is_level_reference(left_key)
and self.orig_right._is_level_reference(right_key)
+ and left_key == right_key
and name not in result.index.names
):
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 4365f61860209..1249194d3a36d 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -2620,3 +2620,12 @@ def test_merge_outer_with_NaN(dtype):
dtype=dtype,
)
tm.assert_frame_equal(result, expected)
+
+
+def test_merge_different_index_names():
+ # GH#45094
+ left = DataFrame({"a": [1]}, index=pd.Index([1], name="c"))
+ right = DataFrame({"a": [1]}, index=pd.Index([1], name="d"))
+ result = merge(left, right, left_on="c", right_on="d")
+ expected = DataFrame({"a_x": [1], "a_y": 1})
+ tm.assert_frame_equal(result, expected)
| - [x] closes #45094
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45100 | 2021-12-28T22:56:48Z | 2021-12-29T16:14:58Z | 2021-12-29T16:14:57Z | 2021-12-29T16:21:25Z |
TYP: Fix mypy error in core.py | diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 4108821054b1b..ca3eb75ede3f6 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -648,7 +648,7 @@ def _append_legend_handles_labels(self, handle: Artist, label: str) -> None:
self.legend_handles.append(handle)
self.legend_labels.append(label)
- def _make_legend(self):
+ def _make_legend(self) -> None:
ax, leg = self._get_ax_legend(self.axes[0])
handles = []
@@ -664,20 +664,11 @@ def _make_legend(self):
if self.legend:
if self.legend == "reverse":
- # error: Incompatible types in assignment (expression has type
- # "Iterator[Any]", variable has type "List[Any]")
- self.legend_handles = reversed( # type: ignore[assignment]
- self.legend_handles
- )
- # error: Incompatible types in assignment (expression has type
- # "Iterator[Hashable]", variable has type
- # "List[Hashable]")
- self.legend_labels = reversed( # type: ignore[assignment]
- self.legend_labels
- )
-
- handles += self.legend_handles
- labels += self.legend_labels
+ handles += reversed(self.legend_handles)
+ labels += reversed(self.legend_labels)
+ else:
+ handles += self.legend_handles
+ labels += self.legend_labels
if self.legend_title is not None:
title = self.legend_title
| xref #37715
Assign the values to ````handles```` and ````labels```` itself versus changing the types of the ````self.legend_handles```` and ````self.legend_labels```` | https://api.github.com/repos/pandas-dev/pandas/pulls/45098 | 2021-12-28T20:27:30Z | 2021-12-28T22:09:06Z | 2021-12-28T22:09:06Z | 2021-12-28T22:43:01Z |
CI: Split CI workflow into code checks, docbuild & web, and arraymanager | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
deleted file mode 100644
index d862fa1086f97..0000000000000
--- a/.github/workflows/ci.yml
+++ /dev/null
@@ -1,239 +0,0 @@
-name: CI
-
-on:
- push:
- branches:
- - master
- - 1.3.x
- pull_request:
- branches:
- - master
- - 1.3.x
-
-env:
- ENV_FILE: environment.yml
- PANDAS_CI: 1
-
-jobs:
- checks:
- name: Checks
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -l {0}
-
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-checks
- cancel-in-progress: true
-
- steps:
- - name: Checkout
- uses: actions/checkout@v2
- 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: Install node.js (for pyright)
- uses: actions/setup-node@v2
- with:
- node-version: "16"
-
- - name: Install pyright
- # note: keep version in sync with .pre-commit-config.yaml
- run: npm install -g pyright@1.1.200
-
- - name: Build Pandas
- uses: ./.github/actions/build_pandas
-
- - name: Checks on imported code
- run: ci/code_checks.sh code
- if: always()
-
- - name: Running doctests
- run: ci/code_checks.sh doctests
- if: always()
-
- - name: Docstring validation
- run: ci/code_checks.sh docstrings
- if: always()
-
- - name: Typing validation
- run: ci/code_checks.sh typing
- if: always()
-
- - name: Testing docstring validation script
- run: pytest scripts
- if: always()
-
- benchmarks:
- name: Benchmarks
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -l {0}
-
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-benchmarks
- cancel-in-progress: true
-
- steps:
- - name: Checkout
- uses: actions/checkout@v2
- 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: Build Pandas
- uses: ./.github/actions/build_pandas
-
- - name: Running 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: always()
-
- - name: Publish benchmarks artifact
- uses: actions/upload-artifact@master
- with:
- name: Benchmarks log
- path: asv_bench/benchmarks.log
- if: failure()
-
- web_and_docs:
- name: Web and docs
- 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@v2
- 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 | tee sphinx.log ; exit ${PIPESTATUS[0]}
-
- # This can be removed when the ipython directive fails when there are errors,
- # including the `tee sphinx.log` in te previous step (https://github.com/ipython/ipython/issues/11547)
- - name: Check ipython directive errors
- run: "! grep -B10 \"^<<<-------------------------------------------------------------------------$\" sphinx.log"
-
- - 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/master'}}
-
- - 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/master'}}
-
- - 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/master'}}
-
- - name: Move docs into site directory
- run: mv doc/build/html web/build/docs
-
- - name: Save website as an artifact
- uses: actions/upload-artifact@v2
- with:
- name: website
- path: web/build
- retention-days: 14
-
- data_manager:
- name: Test experimental data manager
- runs-on: ubuntu-latest
- services:
- moto:
- image: motoserver/moto
- env:
- AWS_ACCESS_KEY_ID: foobar_key
- AWS_SECRET_ACCESS_KEY: foobar_secret
- ports:
- - 5000:5000
- strategy:
- matrix:
- pattern: ["not slow and not network and not clipboard", "slow"]
- concurrency:
- # https://github.community/t/concurrecy-not-work-for-push/183068/7
- group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-data_manager-${{ matrix.pattern }}
- cancel-in-progress: true
-
- steps:
- - name: Checkout
- uses: actions/checkout@v2
- with:
- fetch-depth: 0
-
- - name: Set up pandas
- uses: ./.github/actions/setup
-
- - name: Run tests
- env:
- PANDAS_DATA_MANAGER: array
- PATTERN: ${{ matrix.pattern }}
- PYTEST_WORKERS: "auto"
- PYTEST_TARGET: pandas
- run: |
- source activate pandas-dev
- ci/run_tests.sh
-
- - name: Print skipped tests
- run: python ci/print_skipped.py
diff --git a/.github/workflows/code-checks.yml b/.github/workflows/code-checks.yml
new file mode 100644
index 0000000000000..3a84a75be838f
--- /dev/null
+++ b/.github/workflows/code-checks.yml
@@ -0,0 +1,158 @@
+name: Code Checks
+
+on:
+ push:
+ branches:
+ - master
+ - 1.3.x
+ pull_request:
+ branches:
+ - master
+ - 1.3.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@v2
+
+ - name: Install Python
+ uses: actions/setup-python@v2
+ 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 -l {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@v2
+ 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: Install node.js (for pyright)
+ uses: actions/setup-node@v2
+ with:
+ node-version: "16"
+
+ - name: Install pyright
+ # note: keep version in sync with .pre-commit-config.yaml
+ run: npm install -g pyright@1.1.200
+
+ - 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 -l {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@v2
+ 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: 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@master
+ with:
+ name: Benchmarks log
+ path: asv_bench/benchmarks.log
+ if: failure()
diff --git a/.github/workflows/datamanger.yml b/.github/workflows/datamanger.yml
new file mode 100644
index 0000000000000..d6c96926d0d92
--- /dev/null
+++ b/.github/workflows/datamanger.yml
@@ -0,0 +1,57 @@
+name: Data Manager
+
+on:
+ push:
+ branches:
+ - master
+ - 1.3.x
+ pull_request:
+ branches:
+ - master
+ - 1.3.x
+
+env:
+ ENV_FILE: environment.yml
+ PANDAS_CI: 1
+
+jobs:
+ data_manager:
+ name: Test experimental data manager
+ runs-on: ubuntu-latest
+ services:
+ moto:
+ image: motoserver/moto
+ env:
+ AWS_ACCESS_KEY_ID: foobar_key
+ AWS_SECRET_ACCESS_KEY: foobar_secret
+ ports:
+ - 5000:5000
+ strategy:
+ matrix:
+ pattern: ["not slow and not network and not clipboard", "slow"]
+ concurrency:
+ # https://github.community/t/concurrecy-not-work-for-push/183068/7
+ group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-data_manager-${{ matrix.pattern }}
+ cancel-in-progress: true
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v2
+ with:
+ fetch-depth: 0
+
+ - name: Set up pandas
+ uses: ./.github/actions/setup
+
+ - name: Run tests
+ env:
+ PANDAS_DATA_MANAGER: array
+ PATTERN: ${{ matrix.pattern }}
+ PYTEST_WORKERS: "auto"
+ PYTEST_TARGET: pandas
+ run: |
+ source activate pandas-dev
+ ci/run_tests.sh
+
+ - name: Print skipped tests
+ run: python ci/print_skipped.py
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml
new file mode 100644
index 0000000000000..7f830b59251d1
--- /dev/null
+++ b/.github/workflows/docbuild-and-upload.yml
@@ -0,0 +1,77 @@
+name: Doc Build and Upload
+
+on:
+ push:
+ branches:
+ - master
+ - 1.3.x
+ pull_request:
+ branches:
+ - master
+ - 1.3.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@v2
+ 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 | tee sphinx.log ; exit ${PIPESTATUS[0]}
+
+ # This can be removed when the ipython directive fails when there are errors,
+ # including the `tee sphinx.log` in te previous step (https://github.com/ipython/ipython/issues/11547)
+ - name: Check ipython directive errors
+ run: "! grep -B10 \"^<<<-------------------------------------------------------------------------$\" sphinx.log"
+
+ - 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/master'}}
+
+ - 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/master'}}
+
+ - 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/master'}}
+
+ - name: Move docs into site directory
+ run: mv doc/build/html web/build/docs
+
+ - name: Save website as an artifact
+ uses: actions/upload-artifact@v2
+ with:
+ name: website
+ path: web/build
+ retention-days: 14
diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml
deleted file mode 100644
index 2e6c2b3d53ae7..0000000000000
--- a/.github/workflows/pre-commit.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-name: pre-commit
-
-on:
- pull_request:
- push:
- branches:
- - master
- - 1.3.x
-
-jobs:
- 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:
- - uses: actions/checkout@v2
- - uses: actions/setup-python@v2
- with:
- python-version: '3.9.7'
- - uses: pre-commit/action@v2.0.0
| - [x] closes #37242
- [x] tests added / passed
`ci.yml` split into:
* `arraymanager.yml`
* `code-checks.yml` (includes `pre-commit.yml` now)
* `docbuild-and-upload.yml` | https://api.github.com/repos/pandas-dev/pandas/pulls/45097 | 2021-12-28T20:03:34Z | 2021-12-29T14:23:33Z | 2021-12-29T14:23:33Z | 2022-01-07T01:37:00Z |
ASV: Add benchmarks for isin | diff --git a/asv_bench/benchmarks/algos/isin.py b/asv_bench/benchmarks/algos/isin.py
index 5d7a76bc01d49..37fa0b490bd9e 100644
--- a/asv_bench/benchmarks/algos/isin.py
+++ b/asv_bench/benchmarks/algos/isin.py
@@ -2,6 +2,7 @@
from pandas import (
Categorical,
+ Index,
NaT,
Series,
date_range,
@@ -326,3 +327,16 @@ def setup(self):
def time_isin(self):
self.series.isin(self.values)
+
+
+class IsInIndexes:
+ def setup(self):
+ self.range_idx = Index(range(1000))
+ self.index = Index(list(range(1000)))
+ self.series = Series(np.random.randint(100_000, size=1000))
+
+ def time_isin_range_index(self):
+ self.series.isin(self.range_idx)
+
+ def time_isin_index(self):
+ self.series.isin(self.index)
| - [x] closes #32277
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45096 | 2021-12-28T19:52:54Z | 2021-12-28T21:24:39Z | 2021-12-28T21:24:39Z | 2021-12-28T22:28:32Z |
TST: Add regression tests for old issues | diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py
index fc485f14a4820..daddca7891b93 100644
--- a/pandas/tests/frame/methods/test_combine_first.py
+++ b/pandas/tests/frame/methods/test_combine_first.py
@@ -517,3 +517,12 @@ def test_combine_first_duplicates_rows_for_nan_index_values():
)
combined = df1.combine_first(df2)
tm.assert_frame_equal(combined, expected)
+
+
+def test_combine_first_int64_not_cast_to_float64():
+ # GH 28613
+ df_1 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
+ df_2 = DataFrame({"A": [1, 20, 30], "B": [40, 50, 60], "C": [12, 34, 65]})
+ result = df_1.combine_first(df_2)
+ expected = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [12, 34, 65]})
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py
index 43af48cf4a654..a707bbb377f24 100644
--- a/pandas/tests/frame/methods/test_reset_index.py
+++ b/pandas/tests/frame/methods/test_reset_index.py
@@ -15,11 +15,13 @@
CategoricalIndex,
DataFrame,
Index,
+ Interval,
IntervalIndex,
MultiIndex,
RangeIndex,
Series,
Timestamp,
+ cut,
date_range,
)
import pandas._testing as tm
@@ -682,3 +684,16 @@ def test_drop_pos_args_deprecation():
result = df.reset_index("a", False)
expected = DataFrame({"a": [1, 2, 3]})
tm.assert_frame_equal(result, expected)
+
+
+def test_reset_index_interval_columns_object_cast():
+ # GH 19136
+ df = DataFrame(
+ np.eye(2), index=Index([1, 2], name="Year"), columns=cut([1, 2], [0, 1, 2])
+ )
+ 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)]),
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index e81a902b84780..22a4ce327c150 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -1199,3 +1199,51 @@ def test_apply_index_key_error_bug(index_values):
lambda df: Series([df["b"].mean()], index=["b_mean"])
)
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "arg,idx",
+ [
+ [
+ [
+ 1,
+ 2,
+ 3,
+ ],
+ [
+ 0.1,
+ 0.3,
+ 0.2,
+ ],
+ ],
+ [
+ [
+ 1,
+ 2,
+ 3,
+ ],
+ [
+ 0.1,
+ 0.2,
+ 0.3,
+ ],
+ ],
+ [
+ [
+ 1,
+ 4,
+ 3,
+ ],
+ [
+ 0.1,
+ 0.4,
+ 0.2,
+ ],
+ ],
+ ],
+)
+def test_apply_nonmonotonic_float_index(arg, idx):
+ # GH 34455
+ expected = DataFrame({"col": arg}, index=idx)
+ result = expected.groupby("col").apply(lambda x: x)
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/concat/test_categorical.py b/pandas/tests/reshape/concat/test_categorical.py
index 93197a1814077..5bafd2e8e8503 100644
--- a/pandas/tests/reshape/concat/test_categorical.py
+++ b/pandas/tests/reshape/concat/test_categorical.py
@@ -223,3 +223,18 @@ def test_categorical_index_upcast(self):
exp = Series([1, 2, 4, 3], index=["foo", "bar", "baz", "bar"])
tm.assert_equal(res, exp)
+
+ def test_categorical_missing_from_one_frame(self):
+ # GH 25412
+ df1 = DataFrame({"f1": [1, 2, 3]})
+ df2 = DataFrame({"f1": [2, 3, 1], "f2": Series([4, 4, 4]).astype("category")})
+ result = pd.concat([df1, df2], sort=True)
+ dtype = CategoricalDtype([4])
+ expected = DataFrame(
+ {
+ "f1": [1, 2, 3, 2, 3, 1],
+ "f2": Categorical.from_codes([-1, -1, -1, 0, 0, 0], dtype=dtype),
+ },
+ index=[0, 1, 2, 0, 1, 2],
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py
index e0c18a7055a4e..2ff1de51c33ad 100644
--- a/pandas/tests/scalar/timestamp/test_arithmetic.py
+++ b/pandas/tests/scalar/timestamp/test_arithmetic.py
@@ -310,3 +310,12 @@ def test_addsub_m8ndarray_tzaware(self, shape):
msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'"
with pytest.raises(TypeError, match=msg):
other - ts
+
+ def test_subtract_different_utc_objects(self, utc_fixture, utc_fixture2):
+ # GH 32619
+ dt = datetime(2021, 1, 1)
+ ts1 = Timestamp(dt, tz=utc_fixture)
+ ts2 = Timestamp(dt, tz=utc_fixture2)
+ result = ts1 - ts2
+ expected = Timedelta(0)
+ assert result == expected
| - [x] closes #34455
- [x] closes #25412
- [x] closes #19136
- [x] closes #32619
- [x] closes #28613
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45095 | 2021-12-28T19:38:34Z | 2021-12-28T21:29:57Z | 2021-12-28T21:29:56Z | 2021-12-28T21:32:44Z |
REF: de-duplicate DataFrame indexing code | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 257916630e457..9ef6bda6f63af 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3865,7 +3865,7 @@ def _set_value(
loc = self.index.get_loc(index)
validate_numeric_casting(series.dtype, value)
- series._values[loc] = value
+ series._mgr.setitem_inplace(loc, value)
# Note: trying to use series._set_value breaks tests in
# tests.frame.indexing.test_indexing and tests.indexing.test_partial
except (KeyError, TypeError):
@@ -3908,7 +3908,7 @@ def _box_col_values(self, values: SingleDataManager, loc: int) -> Series:
name = self.columns[loc]
klass = self._constructor_sliced
# We get index=self.index bc values is a SingleDataManager
- return klass(values, name=name, fastpath=True)
+ return klass(values, name=name, fastpath=True).__finalize__(self)
# ----------------------------------------------------------------------
# Lookup Caching
@@ -3925,11 +3925,9 @@ def _get_item_cache(self, item: Hashable) -> Series:
# pending resolution of GH#33047
loc = self.columns.get_loc(item)
- col_mgr = self._mgr.iget(loc)
- res = self._box_col_values(col_mgr, loc).__finalize__(self)
+ res = self._ixs(loc, axis=1)
cache[item] = res
- res._set_as_cached(item, self)
# for a chain
res._is_copy = self._is_copy
diff --git a/pandas/tests/generic/test_duplicate_labels.py b/pandas/tests/generic/test_duplicate_labels.py
index 1c0ae46aa5500..43cd3039870d0 100644
--- a/pandas/tests/generic/test_duplicate_labels.py
+++ b/pandas/tests/generic/test_duplicate_labels.py
@@ -316,9 +316,7 @@ def test_series_raises(self):
pytest.param(
operator.itemgetter((0, [0, 0])), "iloc", marks=not_implemented
),
- pytest.param(
- operator.itemgetter(([0, 0], 0)), "iloc", marks=not_implemented
- ),
+ pytest.param(operator.itemgetter(([0, 0], 0)), "iloc"),
],
)
def test_getitem_raises(self, getter, target):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45092 | 2021-12-28T17:31:11Z | 2021-12-28T20:27:55Z | 2021-12-28T20:27:55Z | 2021-12-28T20:45:45Z |
wip REF: redirect `df.to_html` to Styler if new kwargs are used. | diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 9faef9b15bfb4..2448a00d7288f 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -21,7 +21,7 @@ The pandas I/O API is a set of top level ``reader`` functions accessed like
text;`CSV <https://en.wikipedia.org/wiki/Comma-separated_values>`__;:ref:`read_csv<io.read_csv_table>`;:ref:`to_csv<io.store_in_csv>`
text;Fixed-Width Text File;:ref:`read_fwf<io.fwf_reader>`
text;`JSON <https://www.json.org/>`__;:ref:`read_json<io.json_reader>`;:ref:`to_json<io.json_writer>`
- text;`HTML <https://en.wikipedia.org/wiki/HTML>`__;:ref:`read_html<io.read_html>`;:ref:`to_html<io.html>`
+ text;`HTML <https://en.wikipedia.org/wiki/HTML>`__;:ref:`read_html<io.read_html>`;:ref:`Styler.to_html<io.html>`
text;`LaTeX <https://en.wikipedia.org/wiki/LaTeX>`__;;:ref:`Styler.to_latex<io.latex>`
text;`XML <https://www.w3.org/standards/xml/core>`__;:ref:`read_xml<io.read_xml>`;:ref:`to_xml<io.xml>`
text; Local clipboard;:ref:`read_clipboard<io.clipboard>`;:ref:`to_clipboard<io.clipboard>`
@@ -2682,8 +2682,8 @@ Read in pandas ``to_html`` output (with some loss of floating point precision):
.. code-block:: python
df = pd.DataFrame(np.random.randn(2, 2))
- s = df.to_html(float_format="{0:.40g}".format)
- dfin = pd.read_html(s, index_col=0)
+ s = df.style.format("{0:.40g}").to_html()
+ dfin = pd.read_html(s, index_col=0)[0]
The ``lxml`` backend will raise an error on a failed parse if that is the only
parser you provide. If you only have a single parser you can provide just a
@@ -2714,156 +2714,34 @@ succeeds, the function will return*.
Writing to HTML files
''''''''''''''''''''''
-``DataFrame`` objects have an instance method ``to_html`` which renders the
-contents of the ``DataFrame`` as an HTML table. The function arguments are as
-in the method ``to_string`` described above.
-
.. note::
- Not all of the possible options for ``DataFrame.to_html`` are shown here for
- brevity's sake. See :func:`~pandas.core.frame.DataFrame.to_html` for the
- full set of options.
+ DataFrame *and* Styler objects currently have a ``to_html`` method. We recommend
+ using the :meth:`Styler.to_html <pandas.io.formats.style.Styler.to_html>` method
+ over :meth:`DataFrame.to_html` due to the former's greater flexibility with
+ conditional styling, and the latter's possible argument signature change and/or future deprecation.
-.. ipython:: python
- :suppress:
+Review the documentation for :meth:`Styler.to_html <pandas.io.formats.style.Styler.to_html>`,
+which gives examples of conditional styling and explains the operation of its keyword
+arguments. The ``to_html`` methods render the contents of the ``DataFrame`` as an HTML table.
- def write_html(df, filename, *args, **kwargs):
- static = os.path.abspath(os.path.join("source", "_static"))
- with open(os.path.join(static, filename + ".html"), "w") as f:
- df.to_html(f, *args, **kwargs)
+For simple application the following pattern is sufficient:
.. ipython:: python
df = pd.DataFrame(np.random.randn(2, 2))
df
- print(df.to_html()) # raw html
-
-.. ipython:: python
- :suppress:
-
- write_html(df, "basic")
-
-HTML:
-
-.. raw:: html
- :file: ../_static/basic.html
+ print(df.style.to_html()) # raw html
-The ``columns`` argument will limit the columns shown:
+To format values before output, chain the :meth:`Styler.format <pandas.io.formats.style.Styler.format>`
+and :meth:`Styler.format_index <pandas.io.formats.style.Styler.format_index>` methods.
.. ipython:: python
- print(df.to_html(columns=[0]))
-
-.. ipython:: python
- :suppress:
-
- write_html(df, "columns", columns=[0])
-
-HTML:
-
-.. raw:: html
- :file: ../_static/columns.html
-
-``float_format`` takes a Python callable to control the precision of floating
-point values:
-
-.. ipython:: python
-
- print(df.to_html(float_format="{0:.10f}".format))
-
-.. ipython:: python
- :suppress:
-
- write_html(df, "float_format", float_format="{0:.10f}".format)
-
-HTML:
-
-.. raw:: html
- :file: ../_static/float_format.html
-
-``bold_rows`` will make the row labels bold by default, but you can turn that
-off:
-
-.. ipython:: python
-
- print(df.to_html(bold_rows=False))
-
-.. ipython:: python
- :suppress:
-
- write_html(df, "nobold", bold_rows=False)
-
-.. raw:: html
- :file: ../_static/nobold.html
-
-The ``classes`` argument provides the ability to give the resulting HTML
-table CSS classes. Note that these classes are *appended* to the existing
-``'dataframe'`` class.
-
-.. ipython:: python
-
- print(df.to_html(classes=["awesome_table_class", "even_more_awesome_class"]))
-
-The ``render_links`` argument provides the ability to add hyperlinks to cells
-that contain URLs.
-
-.. ipython:: python
-
- url_df = pd.DataFrame(
- {
- "name": ["Python", "pandas"],
- "url": ["https://www.python.org/", "https://pandas.pydata.org"],
- }
- )
- print(url_df.to_html(render_links=True))
-
-.. ipython:: python
- :suppress:
-
- write_html(url_df, "render_links", render_links=True)
-
-HTML:
-
-.. raw:: html
- :file: ../_static/render_links.html
-
-Finally, the ``escape`` argument allows you to control whether the
-"<", ">" and "&" characters escaped in the resulting HTML (by default it is
-``True``). So to get the HTML without escaped characters pass ``escape=False``
-
-.. ipython:: python
-
- df = pd.DataFrame({"a": list("&<>"), "b": np.random.randn(3)})
-
-
-.. ipython:: python
- :suppress:
-
- write_html(df, "escape")
- write_html(df, "noescape", escape=False)
-
-Escaped:
-
-.. ipython:: python
-
- print(df.to_html())
-
-.. raw:: html
- :file: ../_static/escape.html
-
-Not escaped:
-
-.. ipython:: python
-
- print(df.to_html(escape=False))
-
-.. raw:: html
- :file: ../_static/noescape.html
-
-.. note::
+ print(df.style.format("€ {}").to_html())
- Some browsers may not show a difference in the rendering of the previous two
- HTML tables.
+Some browsers or browser applications may process and add css class styling by default to alter the appearance
+of HTML tables, such as Jupyter Notebook and Google Colab.
.. _io.html.gotchas:
diff --git a/doc/source/user_guide/scale.rst b/doc/source/user_guide/scale.rst
index 71aef4fdd75f6..edeebe2e8678c 100644
--- a/doc/source/user_guide/scale.rst
+++ b/doc/source/user_guide/scale.rst
@@ -275,6 +275,7 @@ column names and dtypes. That's because Dask hasn't actually read the data yet.
Rather than executing immediately, doing operations build up a **task graph**.
.. ipython:: python
+ :okwarning:
ddf
ddf["name"]
@@ -333,6 +334,7 @@ known automatically. In this case, since we created the parquet files manually,
we need to supply the divisions manually.
.. ipython:: python
+ :okwarning:
N = 12
starts = [f"20{i:>02d}-01-01" for i in range(N)]
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 5e74cf57e8718..a25117f878ce5 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -621,7 +621,7 @@ Other Deprecations
- Deprecated the behavior of :func:`to_datetime` with the string "now" with ``utc=False``; in a future version this will match ``Timestamp("now")``, which in turn matches :meth:`Timestamp.now` returning the local time (:issue:`18705`)
- Deprecated :meth:`DateOffset.apply`, use ``offset + other`` instead (:issue:`44522`)
- Deprecated parameter ``names`` in :meth:`Index.copy` (:issue:`44916`)
-- A deprecation warning is now shown for :meth:`DataFrame.to_latex` indicating the arguments signature may change and emulate more the arguments to :meth:`.Styler.to_latex` in future versions (:issue:`44411`)
+- A deprecation warning is now shown for both :meth:`DataFrame.to_html` and :meth:`DataFrame.to_latex` indicating the arguments signature may change and emulate more the arguments in :meth:`.Styler.to_html` and :meth:`.Styler.to_latex`, respectively, in future versions (:issue:`44411`, :issue:`44451`)
- Deprecated behavior of :func:`concat` between objects with bool-dtype and numeric-dtypes; in a future version these will cast to object dtype instead of coercing bools to numeric values (:issue:`39817`)
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
- Deprecated passing ``set`` or ``dict`` as indexer for :meth:`DataFrame.loc.__setitem__`, :meth:`DataFrame.loc.__getitem__`, :meth:`Series.loc.__setitem__`, :meth:`Series.loc.__getitem__`, :meth:`DataFrame.__getitem__`, :meth:`Series.__getitem__` and :meth:`Series.__setitem__` (:issue:`42825`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index cbc40c5d0aa75..1a817f2572e7e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2842,22 +2842,12 @@ def to_parquet(
**kwargs,
)
- @Substitution(
- header_type="bool",
- header="Whether to print column labels, default True",
- col_space_type="str or int, list or dict of int or str",
- col_space="The minimum width of each column in CSS length "
- "units. An int is assumed to be px units.\n\n"
- " .. versionadded:: 0.25.0\n"
- " Ability to use str",
- )
- @Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_html(
self,
buf: FilePath | WriteBuffer[str] | None = None,
columns: Sequence[str] | None = None,
col_space: ColspaceArgType | None = None,
- header: bool | Sequence[str] = True,
+ header: bool = True,
index: bool = True,
na_rep: str = "NaN",
formatters: FormattersType | None = None,
@@ -2867,75 +2857,652 @@ def to_html(
justify: str | None = None,
max_rows: int | None = None,
max_cols: int | None = None,
- show_dimensions: bool | str = False,
+ show_dimensions: bool | str | None = None,
decimal: str = ".",
- bold_rows: bool = True,
+ bold_rows: bool | None = None,
classes: str | list | tuple | None = None,
escape: bool = True,
- notebook: bool = False,
+ notebook: bool | None = None,
border: int | None = None,
table_id: str | None = None,
- render_links: bool = False,
+ render_links: bool | None = None,
encoding: str | None = None,
+ *,
+ table_attributes: str | None = None,
+ sparse_index: bool | None = None,
+ sparse_columns: bool | None = None,
+ caption: str | None = None,
+ max_columns: int | None = None,
+ doctype_html: bool | None = None,
+ formatter=None,
+ precision: int | None = None,
+ thousands: str | None = None,
+ hyperlinks: bool | None = None,
+ bold_headers: bool | None = None,
+ **kwargs,
):
"""
Render a DataFrame as an HTML table.
- %(shared_params)s
+
+ .. versionchanged:: 1.5.0
+ An alternative `Styler` implementation is invoked in certain cases.
+ See notes.
+
+ Parameters
+ ----------
+ buf : str, Path or StringIO-like, optional, default None
+ Buffer to write to. If None, the output is returned as a string.
+ columns : sequence, optional, default None
+ The subset of columns to write. Writes all by default.
+ col_space : str or int, list or dict of int or str, optional
+ The minimum width of each column in CSS length units. An int is assumed
+ to be px units.
+
+ .. deprecated:: 1.5.0
+ See notes for using CSS to control column width.
+ header : bool, optional, default True
+ Whether to print column labels.
+ index : bool, optional, default True
+ Whether to print index (row) labels.
+ na_rep : str, optional
+ String representation of `NaN` to use.
+ formatters : list, tuple or dict of one-parameter functions, optional
+ Formatter functions to apply to columns' elements by position or
+ name. The result of each function must be a unicode string. List or
+ tuple must be equal to the number of columns.
+
+ .. deprecated:: 1.5.0
+ The future ``Styler`` implementation will use the new ``formatter``, and
+ associated arguments. See notes.
+ float_format : one-parameter function, optional
+ Formatter function to apply to columns's elements if they are floats.
+ This function must return a unicode string and will be applied only to
+ the non-NaN elements, with NaN being handled by ``na_rep``.
+
+ .. versionchanged:: 1.2.0
+
+ .. deprecated:: 1.5.0
+ The ``Styler`` implementation will use the new ``precision`` and
+ associated arguments. See notes.
+ sparsify : bool, optional, default True
+ Set to `False` for a DataFrame with a hierarchical index to print
+ every multiindex key at each row.
+
+ .. deprecated:: 1.5.0
+ The ``Styler`` implementation will use the new ``sparse_index`` and
+ ``sparse_columns`` arguments. See notes.
+ index_names : bool, optional, default True
+ Whether to display the names of the indexes.
+ justify : str, default None
+ How to justify the column labels. If None uses the option from the
+ print configuration (controlled by set_option), `right` by default.
+ Valid values are:
+
+ - left
+ - right
+ - center
+ - justify
+ - justify-all
+ - start
+ - end
+ - inherit
+ - match-parent
+ - initial
+ - unset
+
+ .. deprecated:: 1.5.0
+ See notes on using CSS to control aspects of text positioning.
+ max_rows : int, optional
+ Maximum number of rows to display in the console.
+ show_dimensions : bool, default False
+ Display the DataFrame dimensions (number or rows by columns).
+
+ .. deprecated:: 1.5.0
+ See notes for the recommendation to add a ``caption``.
+ decimal : str, default "."
+ Character recognized as the decimal separator, e.g. `,` in Europe.
bold_rows : bool, default True
Make the row labels bold in the output.
+
+ .. deprecated:: 1.5.0
+ Replaced by ``bold_headers``, in the `Styler` implementation.
classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table.
+
+ .. deprecated:: 1.5.0
+ Replaced by ``table_attributes``. See notes.
escape : bool, default True
Convert the characters <, >, and & to HTML-safe sequences.
notebook : {True, False}, default False
Whether the generated HTML is for IPython Notebook.
+
+ .. deprecated:: 1.5.0
border : int
A ``border=border`` attribute is included in the opening
`<table>` tag. Default ``pd.options.display.html.border``.
+
+ .. deprecated:: 1.5.0
+ This produces deprecated HTML. See notes.
table_id : str, optional
A css id is included in the opening `<table>` tag if specified.
render_links : bool, default False
Convert URLs to HTML links.
+
+ .. deprecated:: 1.5.0
+ Replaced by ``hyperlinks`` in the `Styler` implementation.
encoding : str, default "utf-8"
Set character encoding.
.. versionadded:: 1.0
- %(returns)s
+ table_attributes : str, optional
+ Attributes to assign within the `<table>` HTML element in the format:
+
+ ``<table .. <table_attributes> >``.
+
+ .. versionadded:: 1.5.0
+ sparse_index : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each row.
+ Defaults to ``pandas.options.styler.sparse.index`` value.
+
+ .. versionadded:: 1.5.0
+ sparse_columns : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each
+ column. Defaults to ``pandas.options.styler.sparse.columns`` value.
+
+ .. versionadded:: 1.5.0
+ caption : str, optional
+ Set the HTML caption on Styler.
+
+ .. versionadded:: 1.5.0
+ max_columns : int, optional
+ The maximum number of columns that will be rendered. Defaults to
+ ``pandas.options.styler.render.max_columns``, which is None.
+
+ Rows and columns may be reduced if the number of total elements is
+ large. This value is set to ``pandas.options.styler.render.max_elements``,
+ which is 262144 (18 bit browser rendering).
+
+ .. versionadded:: 1.5.0
+ doctype_html : bool, default False
+ Whether to output a fully structured HTML file including all
+ HTML elements, or just the core ``<style>`` and ``<table>`` elements.
+
+ .. versionadded:: 1.5.0
+ formatter : str, callable, dict, optional
+ Object to define how values are displayed. See notes for ``Styler.format``.
+ Defaults to ``pandas.options.styler.format.formatter``, which is `None`.
+
+ .. versionadded:: 1.5.0
+ precision : int, optional
+ Floating point precision to use for display purposes, if not determined by
+ the specified ``formatter``. Defaults to
+ ``pandas.options.styler.format.precision``, which is 6.
+
+ .. versionadded:: 1.5.0
+ thousands : str, optional, default None
+ Character used as thousands separator for floats, complex and integers.
+ Defaults to ``pandas.options.styler.format.thousands``, which is `None`.
+
+ .. versionadded:: 1.5.0
+ hyperlinks : bool,
+ Convert string patterns containing `https://`, `http://`, `ftp://` or `www.`
+ to HTML <a> tags as clickable URL hyperlinks.
+
+ .. versionadded:: 1.5.0
+ bold_headers : bool
+ Make the row labels and/or column headers bold in the output, using
+ CSS.
+
+ .. versionadded:: 1.5.0
+ **kwargs
+ Any additional keyword arguments are passed through to the jinja2
+ ``self.template.render`` process. This is useful when you need to provide
+ additional variables for a custom template.
+
+ .. versionadded:: 1.5.0
+
+ Returns
+ -------
+ str or None
+ If ``buf`` is `None`, returns the result as a string. Otherwise
+ returns `None`.
+
See Also
--------
+ Styler.to_html : Convert a DataFrame to HTML with conditional formatting.
to_string : Convert DataFrame to a string.
+
+ Notes
+ -----
+ As of version 1.5.0 this method utilises the `Styler` implementation,
+ :meth:`Styler.to_html`, where possible. Where deprecated arguments are used,
+ or where none of the new `Styler` implementation arguments are used this method
+ falls back to its original implementation using the `DataFrameFormatter` and
+ `DataFrameRenderer`. If deprecated arguments are used as well as the new
+ arguments the new arguments will be ignored.
+
+ It is **also** possible to directly use the `Styler` implementation and all its
+ associated features by converting from:
+
+ .. code-block:: python
+
+ df.to_html()
+
+ to:
+
+ .. code-block:: python
+
+ styler = df.style
+ styler.to_html()
+
+ Options for customisation that are not directly available via the arguments to
+ this method may have a reasonably simple solution using the direct
+ `Styler` implementation. The following is a list of the deprecated arguments,
+ and how they can be emulated using `Styler`:
+
+ - ``col_space``: this will be removed since a CSS solution is recommended.
+
+ To control the width of all columns one possible option is:
+
+ .. code-block:: python
+
+ styler.set_table_styles([{"selector": "th", "props": "min-width:50px;"}])
+ styler.to_html()
+
+ To control the width of individual columns one option is:
+
+ .. code-block:: python
+
+ styler.set_table_styles({
+ "my col name": [{"selector": "th", "props": "min-width:50px;"}],
+ "other col name": [{"selector": "th", "props": "min-width:75px;"}],
+ })
+ styler.to_html()
+
+ - ``formatters`` and ``float_format``: these will be removed since the
+ `Styler` implementation uses its own :meth:`Styler.format` method with
+ a changed signature using the new ``formatter`` argument.
+
+ One option to control a specific string column and all other float/int
+ columns is the following:
+
+ .. code-block:: python
+
+ styler.format(
+ formatter={"my string column": str.upper},
+ precision=2,
+ decimal=",",
+ thousands="."
+ )
+ styler.to_html()
+
+ - ``sparsify``: this is replaced by ``sparse_index`` and ``sparse_columns``,
+ which control the sparsification of each index separately.
+ - ``justify``: this will be removed since a CSS solution is recommended, and
+ more flexible.
+
+ As an example of vertically and horizontally aligning the index labels:
+
+ .. code-block:: python
+
+ styler.set_table_styles([
+ {"selector": "tbody th",
+ "props": "text-align: left; vertical-align: top;"}
+ ])
+
+ Here is an example of a more specifically targeted alignment:
+
+ .. code-block:: python
+
+ number_css = {"selector": "td", "props": "text-align: right;"}
+ string_css = {"selector": "td", "props": "text-align: left;"}
+ custom_styles = {
+ col: [number_css if df[col].dtype == float else string_css]
+ for col in df.columns
+ }
+ styler.set_table_styles(custom_styles)
+ styler.to_html()
+
+ - ``show_dimension``: this is removed from the HTML result. A suggestion is
+ to utilise the new ``caption`` argument and populate it:
+
+ .. code-block:: python
+
+ styler.to_html(caption=f"dimensions: {df.shape}")
+
+ - ``classes``: this is replaced by ``table_attributes`` where the suggestion
+ is to set the new argument as follows:
+
+ .. code-block:: python
+
+ styler.to_html(table_attributes='class="my-cls other-cls"')
+
+ - ``border``: this removed due to deprecated HTML functionality. The
+ suggested action is to create a `Styler` object and add CSS styling to the
+ relevant table, rows, columns, or data cells as required:
+
+ .. code-block:: python
+
+ styler.set_table_styles([
+ {"selector": "", "props": "border: red solid 3px;"},
+ {"selector": "th", "props": "border: green dashed 2px;"},
+ {"selector": "td", "props": "border: blue dotted 1px;"},
+ ])
+ styler.to_html()
+
+ - ``render_links``: this is replaced by ``hyperlinks`` which has more
+ flexibility in detecting links contained within text,
+
+ .. code-block:: python
+
+ styler.format(hyperlinks="html")
+ styler.to_html()
+
+ - ``max_cols``: this is directly replaced by ``max_columns`` for library
+ naming consistency,
+ - ``bold_rows``: this is directly replaced by ``bold_headers``, which
+ implements a CSS solution,
+ - ``notebook``: this is removed as a legacy argument,
+
+ The new arguments in 1.5.0, which will invoke the Styler implementation are:
+
+ - ``table_attributes``,
+ - ``sparse_index`` and ``sparse_columns``,
+ - ``caption``,
+ - ``max_columns``,
+ - ``doctype_html``,
+ - ``hyperlinks``,
+ - ``formatter``,
+ - ``precision``,
+ - ``thousands``,
+ - ``bold_headers``
+ """
+
+ depr_arg_used = any(
+ [
+ col_space is not None,
+ formatters is not None,
+ float_format is not None,
+ sparsify is not None,
+ justify is not None,
+ max_cols is not None,
+ show_dimensions is not None,
+ bold_rows is not None,
+ classes is not None,
+ notebook is not None,
+ border is not None,
+ render_links is not None,
+ ]
+ )
+
+ styler_arg_used = any(
+ [
+ table_attributes is not None,
+ sparse_index is not None,
+ sparse_columns is not None,
+ caption is not None,
+ max_columns is not None,
+ doctype_html is not None,
+ hyperlinks is not None,
+ formatter is not None,
+ precision is not None,
+ thousands is not None,
+ bold_headers is not None,
+ ]
+ )
+
+ # reset defaults
+ show_dimensions = False if show_dimensions is None else show_dimensions
+ bold_rows = True if bold_rows is None else bold_rows
+ notebook = False if notebook is None else notebook
+ render_links = False if render_links is None else render_links
+
+ doctype_html = False if doctype_html is None else doctype_html
+ hyperlinks = False if hyperlinks is None else hyperlinks
+ bold_headers = False if bold_headers is None else bold_headers
+
+ if depr_arg_used or not styler_arg_used:
+ # use original HTMLFormatter
+ if depr_arg_used:
+ warning_msg = (
+ "You are using an argument which is deprecated or "
+ "subject to change in `DataFrame.to_html`. Please "
+ "review the documentation notes for further info on "
+ "how to update the method usage. "
+ )
+ warnings.warn(warning_msg, FutureWarning, stacklevel=find_stack_level())
+
+ if justify is not None and justify not in fmt._VALID_JUSTIFY_PARAMETERS:
+ raise ValueError("Invalid value for justify parameter")
+
+ formatter = fmt.DataFrameFormatter(
+ self,
+ columns=columns,
+ col_space=col_space,
+ na_rep=na_rep,
+ header=header,
+ index=index,
+ formatters=formatters,
+ float_format=float_format,
+ bold_rows=bold_rows,
+ sparsify=sparsify,
+ justify=justify,
+ index_names=index_names,
+ escape=escape,
+ decimal=decimal,
+ max_rows=max_rows,
+ max_cols=max_cols,
+ show_dimensions=show_dimensions,
+ )
+ # TODO: a generic formatter wld b in DataFrameFormatter
+ return fmt.DataFrameRenderer(formatter).to_html(
+ buf=buf,
+ classes=classes,
+ notebook=notebook,
+ border=border,
+ encoding=encoding,
+ table_id=table_id,
+ render_links=render_links,
+ )
+
+ else:
+ # no deprecated args are used so use Styler implementation
+ return self._to_html_via_styler(
+ buf=buf,
+ table_id=table_id,
+ table_attributes=table_attributes,
+ sparse_index=sparse_index,
+ sparse_columns=sparse_columns,
+ index=index,
+ header=header,
+ index_names="all" if index_names else "none",
+ columns=columns,
+ caption=caption,
+ max_rows=max_rows,
+ max_columns=max_columns,
+ encoding=encoding,
+ doctype_html=doctype_html,
+ formatter=formatter,
+ precision=precision,
+ na_rep=na_rep,
+ decimal=decimal,
+ thousands=thousands,
+ escape=escape,
+ hyperlinks=hyperlinks,
+ bold_headers=bold_headers,
+ **kwargs,
+ )
+
+ def _to_html_via_styler(
+ self,
+ buf: FilePath | WriteBuffer[str] | None = None,
+ *,
+ table_id: str | None = None,
+ table_attributes: str | None = None,
+ sparse_index: bool | None = None,
+ sparse_columns: bool | None = None,
+ index: bool = True,
+ header: bool = True,
+ index_names: str = "all",
+ columns: Sequence[str] | None = None,
+ caption: str | None = None,
+ max_rows: int | None = None,
+ max_columns: int | None = None,
+ encoding: str | None = None,
+ doctype_html: bool = False,
+ formatter=None,
+ precision: int | None = None,
+ na_rep: str | None = None,
+ decimal: str = ".",
+ thousands: str | None = None,
+ escape: bool | None = None,
+ hyperlinks: bool = False,
+ bold_headers: bool = False,
+ **kwargs,
+ ):
"""
- if justify is not None and justify not in fmt._VALID_JUSTIFY_PARAMETERS:
- raise ValueError("Invalid value for justify parameter")
+ Render a DataFrame as an HTML table or file.
- formatter = fmt.DataFrameFormatter(
+ .. versionadded:: 1.5.0
+
+ Parameters
+ ----------
+ buf : str, Path or StringIO-like, optional
+ Buffer to write to. If `None`, the output is returned as a string.
+ table_id : str, optional
+ Id attribute assigned to the <table> HTML element in the format:
+
+ ``<table id="T_<table_id>" ..>``
+
+ table_attributes : str, optional
+ Attributes to assign within the `<table>` HTML element in the format:
+
+ ``<table .. <table_attributes> >``
+
+ sparse_index : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each row.
+ Defaults to ``pandas.options.styler.sparse.index`` value.
+ sparse_columns : bool, optional
+ Whether to sparsify the display of a hierarchical index. Setting to False
+ will display each explicit level element in a hierarchical key for each
+ column. Defaults to ``pandas.options.styler.sparse.columns`` value.
+ index : bool
+ Whether to print index labels.
+ header : bool
+ Whether to print column headers.
+ index_names : {{"all", "index", "columns", "none"}}
+ Which index names to include in the output.
+ columns : list of label, optional
+ The subset of columns to write. Writes all columns by default.
+ caption : str, optional
+ Set the HTML caption on Styler.
+ max_rows : int, optional
+ The maximum number of rows that will be rendered. Defaults to
+ ``pandas.options.styler.render.max_rows/max_columns``.
+ max_columns : int, optional
+ The maximum number of columns that will be rendered. Defaults to
+ ``pandas.options.styler.render.max_columns``, which is None.
+
+ Rows and columns may be reduced if the number of total elements is
+ large. This value is set to ``pandas.options.styler.render.max_elements``,
+ which is 262144 (18 bit browser rendering).
+ encoding : str, optional
+ Character encoding setting for file output, and HTML meta tags.
+ Defaults to ``pandas.options.styler.render.encoding`` value of "utf-8".
+ doctype_html : bool, default False
+ Whether to output a fully structured HTML file including all
+ HTML elements, or just the core ``<style>`` and ``<table>`` elements.
+ formatter : str, callable, dict, optional
+ Object to define how values are displayed. See notes for ``Styler.format``.
+ Defaults to ``pandas.options.styler.format.formatter``, which is `None`.
+ precision : int, optional
+ Floating point precision to use for display purposes, if not determined by
+ the specified ``formatter``. Defaults to
+ ``pandas.options.styler.format.precision``, which is 6.
+ na_rep : str, optional
+ Representation for missing values.
+ Defaults to ``pandas.options.styler.format.na_rep``, which is `None`.
+ decimal : str, default "."
+ Character used as decimal separator for floats, complex and integers.
+ Defaults to ``pandas.options.styler.format.decimal``, which is ".".
+ thousands : str, optional, default None
+ Character used as thousands separator for floats, complex and integers.
+ Defaults to ``pandas.options.styler.format.thousands``, which is `None`.
+ escape : bool, optional
+ Replaces the characters ``&``, ``<``, ``>``, ``'``, and ``"``
+ in cell display string with HTML-safe sequences.
+ Escaping is done before ``formatter``.
+ Defaults to (``pandas.options.styler.format.escape`` `=="html"`), which
+ is `False`.
+ hyperlinks : bool,
+ Convert string patterns containing https://, http://, ftp:// or www. to
+ HTML <a> tags as clickable URL hyperlinks.
+ bold_headers : bool
+ Make the row labels and/or column headers bold in the output, using
+ CSS.
+ **kwargs
+ Any additional keyword arguments are passed through to the jinja2
+ ``self.template.render`` process. This is useful when you need to provide
+ additional variables for a custom template.
+
+ Returns
+ -------
+ str or None
+ If `buf` is None, returns the result as a string. Otherwise returns `None`.
+ """
+ from pandas.io.formats.style import Styler
+
+ # css styles are needed to render certain features, otherwise exclude.
+ exclude_styles = True if not bold_headers else False
+
+ is_html_escape = (
+ escape is None and get_option("styler.format.escape") == "html"
+ ) or escape is True
+ escape_: str | None = "html" if is_html_escape else None
+
+ styler = Styler(
self,
- columns=columns,
- col_space=col_space,
+ cell_ids=False,
+ )
+ styler.format(
+ formatter=formatter,
na_rep=na_rep,
- header=header,
- index=index,
- formatters=formatters,
- float_format=float_format,
- bold_rows=bold_rows,
- sparsify=sparsify,
- justify=justify,
- index_names=index_names,
- escape=escape,
+ precision=precision,
decimal=decimal,
- max_rows=max_rows,
- max_cols=max_cols,
- show_dimensions=show_dimensions,
+ thousands=thousands,
+ escape=escape_,
+ hyperlinks="html" if hyperlinks else None,
)
- # TODO: a generic formatter wld b in DataFrameFormatter
- return fmt.DataFrameRenderer(formatter).to_html(
+
+ if header is False:
+ styler.hide(axis=1)
+ if not index:
+ styler.hide(axis=0)
+ if index_names in ["none", "columns"]:
+ styler.hide(axis=0, names=True)
+ if index_names in ["none", "index"]:
+ styler.hide(axis=1, names=True)
+ if columns:
+ hidden = [col for col in styler.columns if col not in columns]
+ styler.hide(axis=1, subset=hidden)
+
+ return styler.to_html(
buf=buf,
- classes=classes,
- notebook=notebook,
- border=border,
+ table_uuid=table_id,
+ table_attributes=table_attributes,
+ sparse_index=sparse_index,
+ sparse_columns=sparse_columns,
+ max_rows=max_rows,
+ max_columns=max_columns,
+ caption=caption,
encoding=encoding,
- table_id=table_id,
- render_links=render_links,
+ doctype_html=doctype_html,
+ bold_headers=bold_headers,
+ exclude_styles=exclude_styles,
+ **kwargs,
)
@doc(
diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py
index aa8508d8e8942..55d7499797354 100644
--- a/pandas/tests/io/formats/test_to_html.py
+++ b/pandas/tests/io/formats/test_to_html.py
@@ -16,6 +16,8 @@
import pandas.io.formats.format as fmt
+pytestmark = pytest.mark.filterwarnings("ignore:You are using an arg:FutureWarning")
+
lorem_ipsum = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim "
@@ -888,3 +890,91 @@ def test_to_html_float_format_object_col(datapath):
result = df.to_html(float_format=lambda x: f"{x:,.0f}")
expected = expected_html(datapath, "gh40024_expected_output")
assert result == expected
+
+
+@pytest.mark.parametrize(
+ "kwarg",
+ [
+ {"col_space": 10},
+ {"formatters": ["{:.1f}".format]},
+ {"float_format": lambda x: x},
+ {"sparsify": True},
+ {"justify": "left"},
+ {"show_dimensions": False},
+ {"bold_rows": True},
+ {"classes": "my-cls"},
+ {"notebook": False},
+ {"border": 1},
+ {"render_links": False},
+ ],
+)
+def test_future_warning(kwarg):
+ # deprecation tests for 1.5.0
+ df = DataFrame([[1]])
+ msg = "You are using an argument which is deprecated"
+
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ df.to_html(**kwarg)
+
+
+@pytest.mark.parametrize(
+ "kwarg",
+ [
+ {"columns": [0]},
+ {"header": False},
+ {"index": False},
+ {"na_rep": "NAN"},
+ {"index_names": False},
+ {"max_rows": 10},
+ {"decimal": ","},
+ {"escape": False},
+ {"table_id": "my_id"},
+ ],
+)
+def test_no_future_warning(kwarg):
+ # deprecation tests for 1.5.0
+ df = DataFrame([[1]])
+ with tm.assert_produces_warning(None):
+ df.to_html(**kwarg)
+
+
+#####
+# Tests for Styler Implementation of DataFrame.to_html:
+# styler implementation has its own tests.
+# these test only the parsing of the kwargs to df.to_html and the appropriate action.
+#####
+
+
+@pytest.mark.parametrize("header", [True])
+@pytest.mark.parametrize("index_names", [True])
+@pytest.mark.parametrize("index", [True])
+def test_to_html_styler_header(header, index_names, index):
+ pytest.importorskip("jinja2")
+
+ df = DataFrame([[1]], index=["I"], columns=["C"])
+ df.columns.name, df.index.name = "Cname", "Iname"
+ result = df.to_html(
+ caption="styler_implementation",
+ index=index,
+ header=header,
+ index_names=index_names,
+ )
+
+ assert ("<th >Cname</th>" in result) is index_names
+ assert ("<th >Iname</th>" in result) is index_names
+ assert ("<th >C</th>" in result) is header
+ assert ("<th >I</th>" in result) is index
+
+ # check that the styler implementation was called..
+ assert result != df.to_html(index=index, header=header, index_name=index_names)
+
+
+def test_to_html_styler_columns_header():
+ pytest.importorskip("jinja2")
+
+ df_base = DataFrame([[1]], index=["I"], columns=["C"])
+ df = DataFrame([[1, 1]], index=["I"], columns=["C", "D"])
+
+ # test column subset is applied
+ result = df.to_html(caption="styler_implementation", columns=["C"])
+ assert result == df_base.to_html(caption="styler_implementation")
| This is an alternatative way of transitioning `DataFrame.to_html` to `Styler.to_html`.
It is a very minimalist introduction:
- It will **fallback to the original HTMLFormatter implementation** if:
- any of the deprecated kwargs are specifically input, and will show a **deprecation warning**.
- **none** of the new Styler implementation kwargs are input.
- It will **only use the new Styler implementation** if no deprecated kwargs are input and at least one **new** kwarg is used.
here is the rendered doc-strings:
<img width="602" alt="Screenshot 2022-01-02 at 15 46 11" src="https://user-images.githubusercontent.com/24256554/147883230-ff6e5e55-b30c-4429-bb9c-f6b4c6c0024c.png">
<img width="544" alt="Screenshot 2022-01-02 at 15 46 23" src="https://user-images.githubusercontent.com/24256554/147883233-d0b179a2-01ae-4a4a-b832-5666f13744dc.png">
<img width="571" alt="Screenshot 2022-01-02 at 15 46 34" src="https://user-images.githubusercontent.com/24256554/147883235-f37f1492-1526-47fe-aa73-db50f2a2e338.png">
<img width="561" alt="Screenshot 2022-01-02 at 15 46 45" src="https://user-images.githubusercontent.com/24256554/147883236-03132b3b-3626-4bb9-8948-07dc544b07a1.png">
<img width="574" alt="Screenshot 2022-01-02 at 15 46 56" src="https://user-images.githubusercontent.com/24256554/147883237-c589680e-4c8a-41e4-9c36-e8788701b364.png">
<img width="599" alt="Screenshot 2022-01-02 at 15 47 07" src="https://user-images.githubusercontent.com/24256554/147883238-c297586d-c5e4-4b19-87ea-4d1e64ccadb7.png">
<img width="606" alt="Screenshot 2022-01-02 at 15 47 17" src="https://user-images.githubusercontent.com/24256554/147883239-5e6607b9-dfc9-480a-97c2-3f35f2d855b4.png">
<img width="587" alt="Screenshot 2022-01-02 at 15 47 25" src="https://user-images.githubusercontent.com/24256554/147883240-658f752f-516d-4a80-963c-77a32289001d.png">
<img width="610" alt="Screenshot 2022-01-02 at 15 47 32" src="https://user-images.githubusercontent.com/24256554/147883242-6de1853c-04dc-4487-8173-41fd47c3f374.png">
| https://api.github.com/repos/pandas-dev/pandas/pulls/45090 | 2021-12-28T15:44:11Z | 2022-06-16T19:19:05Z | null | 2022-06-16T19:19:05Z |
CLN: TODOs and FIXMEs | diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx
index ab832c145a052..6ca43aebed89c 100644
--- a/pandas/_libs/tslibs/nattype.pyx
+++ b/pandas/_libs/tslibs/nattype.pyx
@@ -378,9 +378,6 @@ class NaTType(_NaT):
def __reduce__(self):
return (__nat_unpickle, (None, ))
- def __rdiv__(self, other):
- return _nat_rdivide_op(self, other)
-
def __rtruediv__(self, other):
return _nat_rdivide_op(self, other)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index a7252b6a7b7a2..f16ff32dee7bc 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -63,7 +63,10 @@
needs_i8_conversion,
)
from pandas.core.dtypes.concat import concat_compat
-from pandas.core.dtypes.dtypes import PandasDtype
+from pandas.core.dtypes.dtypes import (
+ ExtensionDtype,
+ PandasDtype,
+)
from pandas.core.dtypes.generic import (
ABCDatetimeArray,
ABCExtensionArray,
@@ -492,7 +495,7 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> npt.NDArray[np.bool_]:
elif needs_i8_conversion(values.dtype):
return isin(comps, values.astype(object))
- elif is_extension_array_dtype(values.dtype):
+ elif isinstance(values.dtype, ExtensionDtype):
return isin(np.asarray(comps), np.asarray(values))
# GH16012
@@ -511,19 +514,7 @@ def f(c, v):
f = np.in1d
else:
- # error: List item 0 has incompatible type "Union[Any, dtype[Any],
- # ExtensionDtype]"; expected "Union[dtype[Any], None, type, _SupportsDType, str,
- # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any,
- # Any]]"
- # error: List item 1 has incompatible type "Union[Any, ExtensionDtype]";
- # expected "Union[dtype[Any], None, type, _SupportsDType, str, Tuple[Any,
- # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]"
- # error: List item 1 has incompatible type "Union[dtype[Any], ExtensionDtype]";
- # expected "Union[dtype[Any], None, type, _SupportsDType, str, Tuple[Any,
- # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]"
- common = np.find_common_type(
- [values.dtype, comps.dtype], [] # type: ignore[list-item]
- )
+ common = np.find_common_type([values.dtype, comps.dtype], [])
values = values.astype(common, copy=False)
comps = comps.astype(common, copy=False)
f = htable.ismember
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index 4c868747fa930..e1f80c5894bb1 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -127,7 +127,7 @@ def coerce_to_array(
return values, mask
values = np.array(values, copy=copy)
- if is_object_dtype(values):
+ if is_object_dtype(values.dtype):
inferred_type = lib.infer_dtype(values, skipna=True)
if inferred_type == "empty":
pass
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 3587575503d33..443dfa4122389 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -177,7 +177,7 @@ def coerce_to_array(
values = np.array(values, copy=copy)
inferred_type = None
- if is_object_dtype(values) or is_string_dtype(values):
+ if is_object_dtype(values.dtype) or is_string_dtype(values.dtype):
inferred_type = lib.infer_dtype(values, skipna=True)
if inferred_type == "empty":
pass
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 285afc05f905c..ef3a60f46283a 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -55,6 +55,7 @@
from pandas.core import (
algorithms,
+ nanops,
ops,
)
from pandas.core.accessor import DirNamesMixin
@@ -70,7 +71,6 @@
ensure_wrapped_if_datetimelike,
extract_array,
)
-import pandas.core.nanops as nanops
if TYPE_CHECKING:
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index b70ea9f816aef..4f4eac828fd60 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -107,6 +107,8 @@
_int32_max = np.iinfo(np.int32).max
_int64_max = np.iinfo(np.int64).max
+_dtype_obj = np.dtype(object)
+
NumpyArrayT = TypeVar("NumpyArrayT", bound=np.ndarray)
@@ -123,7 +125,7 @@ def maybe_convert_platform(
# or ExtensionArray here.
arr = values
- if arr.dtype == object:
+ if arr.dtype == _dtype_obj:
arr = cast(np.ndarray, arr)
arr = lib.maybe_convert_objects(arr)
@@ -159,7 +161,7 @@ def maybe_box_datetimelike(value: Scalar, dtype: Dtype | None = None) -> Scalar:
-------
scalar
"""
- if dtype == object:
+ if dtype == _dtype_obj:
pass
elif isinstance(value, (np.datetime64, datetime)):
value = Timestamp(value)
@@ -662,9 +664,7 @@ def _ensure_dtype_type(value, dtype: np.dtype):
"""
# Start with exceptions in which we do _not_ cast to numpy types
- # error: Non-overlapping equality check (left operand type: "dtype[Any]", right
- # operand type: "Type[object_]")
- if dtype == np.object_: # type: ignore[comparison-overlap]
+ if dtype == _dtype_obj:
return value
# Note: before we get here we have already excluded isna(value)
@@ -1111,10 +1111,7 @@ def astype_nansafe(
raise ValueError("dtype must be np.dtype or ExtensionDtype")
if arr.dtype.kind in ["m", "M"] and (
- issubclass(dtype.type, str)
- # error: Non-overlapping equality check (left operand type: "dtype[Any]", right
- # operand type: "Type[object]")
- or dtype == object # type: ignore[comparison-overlap]
+ issubclass(dtype.type, str) or dtype == _dtype_obj
):
from pandas.core.construction import ensure_wrapped_if_datetimelike
@@ -1124,7 +1121,7 @@ def astype_nansafe(
if issubclass(dtype.type, str):
return lib.ensure_string_array(arr, skipna=skipna, convert_na_value=False)
- elif is_datetime64_dtype(arr):
+ elif is_datetime64_dtype(arr.dtype):
# Non-overlapping equality check (left operand type: "dtype[Any]", right
# operand type: "Type[signedinteger[Any]]")
if dtype == np.int64: # type: ignore[comparison-overlap]
@@ -1146,7 +1143,7 @@ def astype_nansafe(
raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]")
- elif is_timedelta64_dtype(arr):
+ elif is_timedelta64_dtype(arr.dtype):
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
# operand type: "Type[signedinteger[Any]]")
if dtype == np.int64: # type: ignore[comparison-overlap]
@@ -1170,7 +1167,7 @@ def astype_nansafe(
elif np.issubdtype(arr.dtype, np.floating) and np.issubdtype(dtype, np.integer):
return astype_float_to_int_nansafe(arr, dtype, copy)
- elif is_object_dtype(arr):
+ elif is_object_dtype(arr.dtype):
# work around NumPy brokenness, #1987
if np.issubdtype(dtype.type, np.integer):
@@ -1718,7 +1715,7 @@ def maybe_cast_to_datetime(
# and no coercion specified
value = sanitize_to_nanoseconds(value)
- elif value.dtype == object:
+ elif value.dtype == _dtype_obj:
value = maybe_infer_to_datetimelike(value)
elif isinstance(value, list):
@@ -1862,9 +1859,7 @@ def construct_2d_arraylike_from_scalar(
if dtype.kind in ["m", "M"]:
value = maybe_unbox_datetimelike_tz_deprecation(value, dtype)
- # error: Non-overlapping equality check (left operand type: "dtype[Any]", right
- # operand type: "Type[object]")
- elif dtype == object: # type: ignore[comparison-overlap]
+ elif dtype == _dtype_obj:
if isinstance(value, (np.timedelta64, np.datetime64)):
# calling np.array below would cast to pytimedelta/pydatetime
out = np.empty(shape, dtype=object)
@@ -2190,9 +2185,7 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool:
# ExtensionBlock._can_hold_element
return True
- # error: Non-overlapping equality check (left operand type: "dtype[Any]", right
- # operand type: "Type[object]")
- if dtype == object: # type: ignore[comparison-overlap]
+ if dtype == _dtype_obj:
return True
tipo = maybe_infer_dtype_type(element)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 257916630e457..922a5e5758979 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7997,13 +7997,13 @@ def pivot(self, index=None, columns=None, values=None) -> DataFrame:
... aggfunc={'D': np.mean,
... 'E': [min, max, np.mean]})
>>> table
- D E
- mean max mean min
+ D E
+ mean max mean min
A C
- bar large 5.500000 9.0 7.500000 6.0
- small 5.500000 9.0 8.500000 8.0
- foo large 2.000000 5.0 4.500000 4.0
- small 2.333333 6.0 4.333333 2.0
+ bar large 5.500000 9 7.500000 6
+ small 5.500000 9 8.500000 8
+ foo large 2.000000 5 4.500000 4
+ small 2.333333 6 4.333333 2
"""
@Substitution("")
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 74044e55b5de6..d5b1292435f04 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -443,9 +443,8 @@ def __new__(
return Index._simple_new(data, name=name)
elif is_ea_or_datetimelike_dtype(data_dtype):
- # Argument 1 to "_dtype_to_subclass" of "Index" has incompatible type
- # "Optional[Any]"; expected "Union[dtype[Any], ExtensionDtype]" [arg-type]
- klass = cls._dtype_to_subclass(data_dtype) # type: ignore[arg-type]
+ data_dtype = cast(DtypeObj, data_dtype)
+ klass = cls._dtype_to_subclass(data_dtype)
if klass is not Index:
result = klass(data, copy=copy, name=name, **kwargs)
if dtype is not None:
@@ -6245,7 +6244,7 @@ def _maybe_cast_slice_bound(self, label, side: str_t, kind=no_default):
# wish to have special treatment for floats/ints, e.g. Float64Index and
# datetimelike Indexes
# reject them, if index does not contain label
- if (is_float(label) or is_integer(label)) and label not in self._values:
+ if (is_float(label) or is_integer(label)) and label not in self:
raise self._invalid_indexer("slice", label)
return label
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 9558b82d95fde..6ef8d90d7dcf2 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -762,7 +762,7 @@ def replace_list(
src_len = len(pairs) - 1
- if is_string_dtype(values):
+ if is_string_dtype(values.dtype):
# Calculate the mask once, prior to the call of comp
# in order to avoid repeating the same computations
mask = ~isna(values)
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index d40f8c69e1b7c..fc6db78320169 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -60,11 +60,11 @@ def pivot_table(
columns=None,
aggfunc: AggFuncType = "mean",
fill_value=None,
- margins=False,
- dropna=True,
- margins_name="All",
- observed=False,
- sort=True,
+ margins: bool = False,
+ dropna: bool = True,
+ margins_name: str = "All",
+ observed: bool = False,
+ sort: bool = True,
) -> DataFrame:
index = _convert_by(index)
columns = _convert_by(columns)
@@ -178,13 +178,12 @@ def __internal_pivot_table(
and v in agged
and not is_integer_dtype(agged[v])
):
- if isinstance(agged[v], ABCDataFrame):
+ if not isinstance(agged[v], ABCDataFrame):
# exclude DataFrame case bc maybe_downcast_to_dtype expects
# ArrayLike
- # TODO: why does test_pivot_table_doctest_case fail if
- # we don't do this apparently-unnecessary setitem?
- agged[v] = agged[v]
- else:
+ # e.g. test_pivot_table_multiindex_columns_doctest_case
+ # agged.columns is a MultiIndex and 'v' is indexing only
+ # on its first level.
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
@@ -253,7 +252,7 @@ def __internal_pivot_table(
def _add_margins(
table: DataFrame | Series,
- data,
+ data: DataFrame,
values,
rows,
cols,
@@ -331,7 +330,7 @@ def _add_margins(
return result
-def _compute_grand_margin(data, values, aggfunc, margins_name: str = "All"):
+def _compute_grand_margin(data: DataFrame, values, aggfunc, margins_name: str = "All"):
if values:
grand_margin = {}
@@ -522,7 +521,7 @@ def crosstab(
rownames=None,
colnames=None,
aggfunc=None,
- margins=False,
+ margins: bool = False,
margins_name: str = "All",
dropna: bool = True,
normalize=False,
@@ -682,7 +681,9 @@ def crosstab(
return table
-def _normalize(table, normalize, margins: bool, margins_name="All"):
+def _normalize(
+ table: DataFrame, normalize, margins: bool, margins_name="All"
+) -> DataFrame:
if not isinstance(normalize, (bool, str)):
axis_subs = {0: "index", 1: "columns"}
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index c2cd73584b7da..01f0efea15b89 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -679,7 +679,7 @@ def _stack_multi_column_index(columns: MultiIndex) -> MultiIndex:
def _stack_multi_columns(frame, level_num=-1, dropna=True):
- def _convert_level_number(level_num, columns):
+ def _convert_level_number(level_num: int, columns):
"""
Logic for converting the level number to something we can safely pass
to swaplevel.
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 88607f4b036a0..035e886f1906e 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -2077,11 +2077,12 @@ def agg(arr):
with pytest.raises(KeyError, match="notpresent"):
foo.pivot_table("notpresent", "X", "Y", aggfunc=agg)
- def test_pivot_table_doctest_case(self):
- # TODO: better name. the relevant characteristic is that
- # the call to maybe_downcast_to_dtype(agged[v], data[v].dtype) in
+ def test_pivot_table_multiindex_columns_doctest_case(self):
+ # The relevant characteristic is that the call
+ # to maybe_downcast_to_dtype(agged[v], data[v].dtype) in
# __internal_pivot_table has `agged[v]` a DataFrame instead of Series,
- # i.e agged.columns is not unique
+ # In this case this is because agged.columns is a MultiIndex and 'v'
+ # is only indexing on its first level.
df = DataFrame(
{
"A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
@@ -2124,6 +2125,8 @@ def test_pivot_table_doctest_case(self):
]
)
expected = DataFrame(vals, columns=cols, index=index)
+ expected[("E", "min")] = expected[("E", "min")].astype(np.int64)
+ expected[("E", "max")] = expected[("E", "max")].astype(np.int64)
tm.assert_frame_equal(table, expected)
def test_pivot_table_sort_false(self):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45088 | 2021-12-28T05:22:56Z | 2021-12-28T14:20:20Z | 2021-12-28T14:20:20Z | 2021-12-28T17:11:58Z |
BUG: Timestamp.to_pydatetime losing 'fold' | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 5dd6fa0d4f72d..ac638e6bd3c6e 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -724,6 +724,7 @@ Datetimelike
- ``np.maximum.reduce`` and ``np.minimum.reduce`` now correctly return :class:`Timestamp` and :class:`Timedelta` objects when operating on :class:`Series`, :class:`DataFrame`, or :class:`Index` with ``datetime64[ns]`` or ``timedelta64[ns]`` dtype (:issue:`43923`)
- Bug in adding a ``np.timedelta64`` object to a :class:`BusinessDay` or :class:`CustomBusinessDay` object incorrectly raising (:issue:`44532`)
- Bug in :meth:`Index.insert` for inserting ``np.datetime64``, ``np.timedelta64`` or ``tuple`` into :class:`Index` with ``dtype='object'`` with negative loc adding ``None`` and replacing existing value (:issue:`44509`)
+- 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`)
- 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`)
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index b13b77506ecc7..92a00d682a7e5 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -898,7 +898,7 @@ cdef class _Timestamp(ABCTimestamp):
return datetime(self.year, self.month, self.day,
self.hour, self.minute, self.second,
- self.microsecond, self.tzinfo)
+ self.microsecond, self.tzinfo, fold=self.fold)
cpdef to_datetime64(self):
"""
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py
index f734c331e3def..5f7cca99f75c6 100644
--- a/pandas/tests/scalar/timestamp/test_timestamp.py
+++ b/pandas/tests/scalar/timestamp/test_timestamp.py
@@ -592,6 +592,13 @@ def test_conversion(self):
assert type(result) == type(expected)
assert result.dtype == expected.dtype
+ def test_to_pydatetime_fold(self):
+ # GH#45087
+ tzstr = "dateutil/usr/share/zoneinfo/America/Chicago"
+ ts = Timestamp(year=2013, month=11, day=3, hour=1, minute=0, fold=1, tz=tzstr)
+ dt = ts.to_pydatetime()
+ assert dt.fold == 1
+
def test_to_pydatetime_nonzero_nano(self):
ts = Timestamp("2011-01-01 9:00:00.123456789")
diff --git a/pandas/tests/scalar/timestamp/test_timezones.py b/pandas/tests/scalar/timestamp/test_timezones.py
index 9ba4a2c1f77cd..a7f7393fb3263 100644
--- a/pandas/tests/scalar/timestamp/test_timezones.py
+++ b/pandas/tests/scalar/timestamp/test_timezones.py
@@ -166,9 +166,9 @@ def test_tz_localize_ambiguous_compat(self):
assert result_pytz.value == 1382835600000000000
# fixed ambiguous behavior
- # see gh-14621
+ # see gh-14621, GH#45087
assert result_pytz.to_pydatetime().tzname() == "GMT"
- assert result_dateutil.to_pydatetime().tzname() == "BST"
+ assert result_dateutil.to_pydatetime().tzname() == "GMT"
assert str(result_pytz) == str(result_dateutil)
# 1 hour difference
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45087 | 2021-12-28T05:13:13Z | 2022-01-12T13:49:07Z | 2022-01-12T13:49:07Z | 2022-01-12T16:33:13Z |
TST: More pytest idioms in tests/generic | diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index 2e9f92ebc7cb7..b3fcff21f0f1f 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -82,6 +82,7 @@
assert_interval_array_equal,
assert_is_sorted,
assert_is_valid_plot_return_object,
+ assert_metadata_equivalent,
assert_numpy_array_equal,
assert_period_array_equal,
assert_series_equal,
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index d59ad72d74d73..77c477d3f9229 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -1470,3 +1470,15 @@ def assert_indexing_slices_equivalent(ser: Series, l_slc: slice, i_slc: slice):
if not ser.index.is_integer():
# For integer indices, .loc and plain getitem are position-based.
assert_series_equal(ser[l_slc], expected)
+
+
+def assert_metadata_equivalent(left, right):
+ """
+ Check that ._metadata attributes are equivalent.
+ """
+ for attr in left._metadata:
+ val = getattr(left, attr, None)
+ if right is None:
+ assert val is None
+ else:
+ assert val == getattr(right, attr, None)
diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py
index 3588cd56d1060..2b248afb42057 100644
--- a/pandas/tests/generic/test_frame.py
+++ b/pandas/tests/generic/test_frame.py
@@ -12,13 +12,9 @@
date_range,
)
import pandas._testing as tm
-from pandas.tests.generic.test_generic import Generic
-class TestDataFrame(Generic):
- _typ = DataFrame
- _comparator = lambda self, x, y: tm.assert_frame_equal(x, y)
-
+class TestDataFrame:
@pytest.mark.parametrize("func", ["_set_axis_name", "rename_axis"])
def test_set_axis_name(self, func):
df = DataFrame([[1, 2], [3, 4]])
@@ -76,7 +72,7 @@ def test_metadata_propagation_indiv_groupby(self):
}
)
result = df.groupby("A").sum()
- self.check_metadata(df, result)
+ tm.assert_metadata_equivalent(df, result)
def test_metadata_propagation_indiv_resample(self):
# resample
@@ -85,7 +81,7 @@ def test_metadata_propagation_indiv_resample(self):
index=date_range("20130101", periods=1000, freq="s"),
)
result = df.resample("1T")
- self.check_metadata(df, result)
+ tm.assert_metadata_equivalent(df, result)
def test_metadata_propagation_indiv(self, monkeypatch):
# merging with override
@@ -148,7 +144,7 @@ def test_deepcopy_empty(self):
empty_frame = DataFrame(data=[], index=[], columns=["A"])
empty_frame_copy = deepcopy(empty_frame)
- self._compare(empty_frame_copy, empty_frame)
+ tm.assert_frame_equal(empty_frame_copy, empty_frame)
# formerly in Generic but only test DataFrame
diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py
index 0eaf5fc6d6e1a..5c1eb28ed6099 100644
--- a/pandas/tests/generic/test_generic.py
+++ b/pandas/tests/generic/test_generic.py
@@ -18,108 +18,95 @@
# Generic types test cases
-class Generic:
- @property
- def _ndim(self):
- return self._typ._AXIS_LEN
-
- def _axes(self):
- """return the axes for my object typ"""
- return self._typ._AXIS_ORDERS
-
- def _construct(self, shape, value=None, dtype=None, **kwargs):
- """
- construct an object for the given shape
- if value is specified use that if its a scalar
- if value is an array, repeat it as needed
- """
- if isinstance(shape, int):
- shape = tuple([shape] * self._ndim)
- if value is not None:
- if is_scalar(value):
- if value == "empty":
- arr = None
- dtype = np.float64
-
- # remove the info axis
- kwargs.pop(self._typ._info_axis_name, None)
- else:
- arr = np.empty(shape, dtype=dtype)
- arr.fill(value)
+def construct(box, shape, value=None, dtype=None, **kwargs):
+ """
+ construct an object for the given shape
+ if value is specified use that if its a scalar
+ if value is an array, repeat it as needed
+ """
+ if isinstance(shape, int):
+ shape = tuple([shape] * box._AXIS_LEN)
+ if value is not None:
+ if is_scalar(value):
+ if value == "empty":
+ arr = None
+ dtype = np.float64
+
+ # remove the info axis
+ kwargs.pop(box._info_axis_name, None)
else:
- fshape = np.prod(shape)
- arr = value.ravel()
- new_shape = fshape / arr.shape[0]
- if fshape % arr.shape[0] != 0:
- raise Exception("invalid value passed in _construct")
-
- arr = np.repeat(arr, new_shape).reshape(shape)
+ arr = np.empty(shape, dtype=dtype)
+ arr.fill(value)
else:
- arr = np.random.randn(*shape)
- return self._typ(arr, dtype=dtype, **kwargs)
+ fshape = np.prod(shape)
+ arr = value.ravel()
+ new_shape = fshape / arr.shape[0]
+ if fshape % arr.shape[0] != 0:
+ raise Exception("invalid value passed in construct")
- def _compare(self, result, expected):
- self._comparator(result, expected)
+ arr = np.repeat(arr, new_shape).reshape(shape)
+ else:
+ arr = np.random.randn(*shape)
+ return box(arr, dtype=dtype, **kwargs)
- def test_rename(self):
+
+class Generic:
+ @pytest.mark.parametrize(
+ "func",
+ [
+ str.lower,
+ {x: x.lower() for x in list("ABCD")},
+ Series({x: x.lower() for x in list("ABCD")}),
+ ],
+ )
+ def test_rename(self, frame_or_series, func):
# single axis
idx = list("ABCD")
- # relabeling values passed into self.rename
- args = [
- str.lower,
- {x: x.lower() for x in idx},
- Series({x: x.lower() for x in idx}),
- ]
- for axis in self._axes():
+ for axis in frame_or_series._AXIS_ORDERS:
kwargs = {axis: idx}
- obj = self._construct(4, **kwargs)
+ obj = construct(4, **kwargs)
- for arg in args:
- # rename a single axis
- result = obj.rename(**{axis: arg})
- expected = obj.copy()
- setattr(expected, axis, list("abcd"))
- self._compare(result, expected)
+ # rename a single axis
+ result = obj.rename(**{axis: func})
+ expected = obj.copy()
+ setattr(expected, axis, list("abcd"))
+ tm.assert_equal(result, expected)
- # multiple axes at once
-
- def test_get_numeric_data(self):
+ def test_get_numeric_data(self, frame_or_series):
n = 4
kwargs = {
- self._typ._get_axis_name(i): list(range(n)) for i in range(self._ndim)
+ frame_or_series._get_axis_name(i): list(range(n))
+ for i in range(frame_or_series._AXIS_LEN)
}
# get the numeric data
- o = self._construct(n, **kwargs)
+ o = construct(n, **kwargs)
result = o._get_numeric_data()
- self._compare(result, o)
+ tm.assert_equal(result, o)
# non-inclusion
result = o._get_bool_data()
- expected = self._construct(n, value="empty", **kwargs)
+ expected = construct(n, value="empty", **kwargs)
if isinstance(o, DataFrame):
# preserve columns dtype
expected.columns = o.columns[:0]
- self._compare(result, expected)
+ tm.assert_equal(result, expected)
# get the bool data
arr = np.array([True, True, False, True])
- o = self._construct(n, value=arr, **kwargs)
+ o = construct(n, value=arr, **kwargs)
result = o._get_numeric_data()
- self._compare(result, o)
+ tm.assert_equal(result, o)
- # _get_numeric_data is includes _get_bool_data, so can't test for
- # non-inclusion
-
- def test_nonzero(self):
+ def test_nonzero(self, frame_or_series):
# GH 4633
# look at the boolean/nonzero behavior for objects
- obj = self._construct(shape=4)
- msg = f"The truth value of a {self._typ.__name__} is ambiguous"
+ obj = construct(frame_or_series, shape=4)
+ msg = f"The truth value of a {frame_or_series.__name__} is ambiguous"
with pytest.raises(ValueError, match=msg):
bool(obj == 0)
with pytest.raises(ValueError, match=msg):
@@ -127,7 +114,7 @@ def test_nonzero(self):
with pytest.raises(ValueError, match=msg):
bool(obj)
- obj = self._construct(shape=4, value=1)
+ obj = construct(frame_or_series, shape=4, value=1)
with pytest.raises(ValueError, match=msg):
bool(obj == 0)
with pytest.raises(ValueError, match=msg):
@@ -135,7 +122,7 @@ def test_nonzero(self):
with pytest.raises(ValueError, match=msg):
bool(obj)
- obj = self._construct(shape=4, value=np.nan)
+ obj = construct(frame_or_series, shape=4, value=np.nan)
with pytest.raises(ValueError, match=msg):
bool(obj == 0)
with pytest.raises(ValueError, match=msg):
@@ -144,14 +131,14 @@ def test_nonzero(self):
bool(obj)
# empty
- obj = self._construct(shape=0)
+ obj = construct(frame_or_series, shape=0)
with pytest.raises(ValueError, match=msg):
bool(obj)
# invalid behaviors
- obj1 = self._construct(shape=4, value=1)
- obj2 = self._construct(shape=4, value=1)
+ obj1 = construct(frame_or_series, shape=4, value=1)
+ obj2 = construct(frame_or_series, shape=4, value=1)
with pytest.raises(ValueError, match=msg):
if obj1:
@@ -164,16 +151,16 @@ def test_nonzero(self):
with pytest.raises(ValueError, match=msg):
not obj1
- def test_constructor_compound_dtypes(self):
+ def test_frame_or_series_compound_dtypes(self, frame_or_series):
# see gh-5191
# Compound dtypes should raise NotImplementedError.
def f(dtype):
- return self._construct(shape=3, value=1, dtype=dtype)
+ return construct(frame_or_series, shape=3, value=1, dtype=dtype)
msg = (
"compound dtypes are not implemented "
- f"in the {self._typ.__name__} constructor"
+ f"in the {frame_or_series.__name__} frame_or_series"
)
with pytest.raises(NotImplementedError, match=msg):
@@ -184,20 +171,12 @@ def f(dtype):
f("float64")
f("M8[ns]")
- def check_metadata(self, x, y=None):
- for m in x._metadata:
- v = getattr(x, m, None)
- if y is None:
- assert v is None
- else:
- assert v == getattr(y, m, None)
-
- def test_metadata_propagation(self):
+ def test_metadata_propagation(self, frame_or_series):
# check that the metadata matches up on the resulting ops
- o = self._construct(shape=3)
+ o = construct(frame_or_series, shape=3)
o.name = "foo"
- o2 = self._construct(shape=3)
+ o2 = construct(frame_or_series, shape=3)
o2.name = "bar"
# ----------
@@ -207,23 +186,23 @@ def test_metadata_propagation(self):
# simple ops with scalars
for op in ["__add__", "__sub__", "__truediv__", "__mul__"]:
result = getattr(o, op)(1)
- self.check_metadata(o, result)
+ tm.assert_metadata_equivalent(o, result)
# ops with like
for op in ["__add__", "__sub__", "__truediv__", "__mul__"]:
result = getattr(o, op)(o)
- self.check_metadata(o, result)
+ tm.assert_metadata_equivalent(o, result)
# simple boolean
for op in ["__eq__", "__le__", "__ge__"]:
v1 = getattr(o, op)(o)
- self.check_metadata(o, v1)
- self.check_metadata(o, v1 & v1)
- self.check_metadata(o, v1 | v1)
+ tm.assert_metadata_equivalent(o, v1)
+ tm.assert_metadata_equivalent(o, v1 & v1)
+ tm.assert_metadata_equivalent(o, v1 | v1)
# combine_first
result = o.combine_first(o2)
- self.check_metadata(o, result)
+ tm.assert_metadata_equivalent(o, result)
# ---------------------------
# non-preserving (by default)
@@ -231,7 +210,7 @@ def test_metadata_propagation(self):
# add non-like
result = o + o2
- self.check_metadata(result)
+ tm.assert_metadata_equivalent(result)
# simple boolean
for op in ["__eq__", "__le__", "__ge__"]:
@@ -239,27 +218,27 @@ def test_metadata_propagation(self):
# this is a name matching op
v1 = getattr(o, op)(o)
v2 = getattr(o, op)(o2)
- self.check_metadata(v2)
- self.check_metadata(v1 & v2)
- self.check_metadata(v1 | v2)
+ tm.assert_metadata_equivalent(v2)
+ tm.assert_metadata_equivalent(v1 & v2)
+ tm.assert_metadata_equivalent(v1 | v2)
- def test_size_compat(self):
+ def test_size_compat(self, frame_or_series):
# GH8846
# size property should be defined
- o = self._construct(shape=10)
+ o = construct(frame_or_series, shape=10)
assert o.size == np.prod(o.shape)
assert o.size == 10 ** len(o.axes)
- def test_split_compat(self):
+ def test_split_compat(self, frame_or_series):
# xref GH8846
- o = self._construct(shape=10)
+ o = construct(frame_or_series, shape=10)
assert len(np.array_split(o, 5)) == 5
assert len(np.array_split(o, 2)) == 2
# See gh-12301
- def test_stat_unexpected_keyword(self):
- obj = self._construct(5)
+ def test_stat_unexpected_keyword(self, frame_or_series):
+ obj = construct(frame_or_series, 5)
starwars = "Star Wars"
errmsg = "unexpected keyword"
@@ -273,18 +252,18 @@ def test_stat_unexpected_keyword(self):
obj.any(epic=starwars) # logical_function
@pytest.mark.parametrize("func", ["sum", "cumsum", "any", "var"])
- def test_api_compat(self, func):
+ def test_api_compat(self, func, frame_or_series):
# GH 12021
# compat for __name__, __qualname__
- obj = self._construct(5)
+ obj = (frame_or_series, 5)
f = getattr(obj, func)
assert f.__name__ == func
assert f.__qualname__.endswith(func)
- def test_stat_non_defaults_args(self):
- obj = self._construct(5)
+ def test_stat_non_defaults_args(self, frame_or_series):
+ obj = construct(frame_or_series, 5)
out = np.array([0])
errmsg = "the 'out' parameter is not supported"
@@ -297,34 +276,34 @@ def test_stat_non_defaults_args(self):
with pytest.raises(ValueError, match=errmsg):
obj.any(out=out) # logical_function
- def test_truncate_out_of_bounds(self):
+ def test_truncate_out_of_bounds(self, frame_or_series):
# GH11382
# small
- shape = [2000] + ([1] * (self._ndim - 1))
- small = self._construct(shape, dtype="int8", value=1)
- self._compare(small.truncate(), small)
- self._compare(small.truncate(before=0, after=3e3), small)
- self._compare(small.truncate(before=-1, after=2e3), small)
+ shape = [2000] + ([1] * (frame_or_series._AXIS_LEN - 1))
+ small = construct(frame_or_series, shape, dtype="int8", value=1)
+ tm.assert_equal(small.truncate(), small)
+ tm.assert_equal(small.truncate(before=0, after=3e3), small)
+ tm.assert_equal(small.truncate(before=-1, after=2e3), small)
# big
- shape = [2_000_000] + ([1] * (self._ndim - 1))
- big = self._construct(shape, dtype="int8", value=1)
- self._compare(big.truncate(), big)
- self._compare(big.truncate(before=0, after=3e6), big)
- self._compare(big.truncate(before=-1, after=2e6), big)
+ shape = [2_000_000] + ([1] * (frame_or_series._AXIS_LEN - 1))
+ big = construct(frame_or_series, shape, dtype="int8", value=1)
+ tm.assert_equal(big.truncate(), big)
+ tm.assert_equal(big.truncate(before=0, after=3e6), big)
+ tm.assert_equal(big.truncate(before=-1, after=2e6), big)
@pytest.mark.parametrize(
"func",
[copy, deepcopy, lambda x: x.copy(deep=False), lambda x: x.copy(deep=True)],
)
@pytest.mark.parametrize("shape", [0, 1, 2])
- def test_copy_and_deepcopy(self, shape, func):
+ def test_copy_and_deepcopy(self, frame_or_series, shape, func):
# GH 15444
- obj = self._construct(shape)
+ obj = construct(frame_or_series, shape)
obj_copy = func(obj)
assert obj_copy is not obj
- self._compare(obj_copy, obj)
+ tm.assert_equal(obj_copy, obj)
class TestNDFrame:
diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py
index 784ced96286a6..dd2380e2647d3 100644
--- a/pandas/tests/generic/test_series.py
+++ b/pandas/tests/generic/test_series.py
@@ -10,13 +10,9 @@
date_range,
)
import pandas._testing as tm
-from pandas.tests.generic.test_generic import Generic
-class TestSeries(Generic):
- _typ = Series
- _comparator = lambda self, x, y: tm.assert_series_equal(x, y)
-
+class TestSeries:
@pytest.mark.parametrize("func", ["rename_axis", "_set_axis_name"])
def test_set_axis_name_mi(self, func):
ser = Series(
@@ -41,7 +37,7 @@ def test_set_axis_name_raises(self):
def test_get_bool_data_preserve_dtype(self):
ser = Series([True, False, True])
result = ser._get_bool_data()
- self._compare(result, ser)
+ tm.assert_series_equal(result, ser)
def test_nonzero_single_element(self):
@@ -101,13 +97,13 @@ def test_metadata_propagation_indiv_resample(self):
name="foo",
)
result = ts.resample("1T").mean()
- self.check_metadata(ts, result)
+ tm.assert_metadata_equivalent(ts, result)
result = ts.resample("1T").min()
- self.check_metadata(ts, result)
+ tm.assert_metadata_equivalent(ts, result)
result = ts.resample("1T").apply(lambda x: x.sum())
- self.check_metadata(ts, result)
+ tm.assert_metadata_equivalent(ts, result)
def test_metadata_propagation_indiv(self, monkeypatch):
# check that the metadata matches up on the resulting ops
@@ -118,7 +114,7 @@ def test_metadata_propagation_indiv(self, monkeypatch):
ser2.name = "bar"
result = ser.T
- self.check_metadata(ser, result)
+ tm.assert_metadata_equivalent(ser, result)
def finalize(self, other, method=None, **kwargs):
for name in self._metadata:
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45086 | 2021-12-28T04:44:01Z | 2021-12-28T20:32:31Z | 2021-12-28T20:32:31Z | 2021-12-28T20:32:47Z |
BUG: Unstack/pivot raising ValueError on large result | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index c743e38a118f7..df3ec3b9da8b1 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -364,10 +364,29 @@ second column is instead renamed to ``a.2``.
res
-.. _whatsnew_140.notable_bug_fixes.notable_bug_fix3:
+.. _whatsnew_140.notable_bug_fixes.unstack_pivot_int32_limit:
-notable_bug_fix3
-^^^^^^^^^^^^^^^^
+unstack and pivot_table no longer raises ValueError for result that would exceed int32 limit
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Previously :meth:`DataFrame.pivot_table` and :meth:`DataFrame.unstack` would raise a ``ValueError`` if the operation
+could produce a result with more than ``2**31 - 1`` elements. This operation now raises a :class:`errors.PerformanceWarning`
+instead (:issue:`26314`).
+
+*Previous behavior*:
+
+.. code-block:: ipython
+
+ In [3]: df = DataFrame({"ind1": np.arange(2 ** 16), "ind2": np.arange(2 ** 16), "count": 0})
+ In [4]: df.pivot_table(index="ind1", columns="ind2", values="count", aggfunc="count")
+ ValueError: Unstacked DataFrame is too big, causing int32 overflow
+
+*New behavior*:
+
+.. code-block:: python
+
+ In [4]: df.pivot_table(index="ind1", columns="ind2", values="count", aggfunc="count")
+ PerformanceWarning: The following operation may generate 4294967296 cells in the resulting pandas object.
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index c2cd73584b7da..a570af1f949d7 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -2,6 +2,7 @@
import itertools
from typing import TYPE_CHECKING
+import warnings
import numpy as np
@@ -11,6 +12,7 @@
Dtype,
npt,
)
+from pandas.errors import PerformanceWarning
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.cast import maybe_promote
@@ -125,10 +127,15 @@ def __init__(self, index: MultiIndex, level=-1, constructor=None):
num_columns = self.removed_level.size
# GH20601: This forces an overflow if the number of cells is too high.
- num_cells = np.multiply(num_rows, num_columns, dtype=np.int32)
-
- if num_rows > 0 and num_columns > 0 and num_cells <= 0:
- raise ValueError("Unstacked DataFrame is too big, causing int32 overflow")
+ num_cells = num_rows * num_columns
+
+ # GH 26314: Previous ValueError raised was too restrictive for many users.
+ if num_cells > np.iinfo(np.int32).max:
+ warnings.warn(
+ f"The following operation may generate {num_cells} cells "
+ f"in the resulting pandas object.",
+ PerformanceWarning,
+ )
self._make_selectors()
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 689c54b03b507..4b3ddbc6c193c 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -5,6 +5,8 @@
import numpy as np
import pytest
+from pandas.errors import PerformanceWarning
+
import pandas as pd
from pandas import (
DataFrame,
@@ -1819,11 +1821,17 @@ def test_unstack_unobserved_keys(self):
@pytest.mark.slow
def test_unstack_number_of_levels_larger_than_int32(self):
# GH#20601
+ # GH 26314: Change ValueError to PerformanceWarning
df = DataFrame(
np.random.randn(2 ** 16, 2), index=[np.arange(2 ** 16), np.arange(2 ** 16)]
)
- with pytest.raises(ValueError, match="int32 overflow"):
- df.unstack()
+ msg = "The following operation may generate"
+ with tm.assert_produces_warning(PerformanceWarning, match=msg):
+ try:
+ df.unstack()
+ except MemoryError:
+ # Just checking the warning
+ return
def test_stack_order_with_unsorted_levels(self):
# GH#16323
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 88607f4b036a0..9bfda33956287 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -8,6 +8,8 @@
import numpy as np
import pytest
+from pandas.errors import PerformanceWarning
+
import pandas as pd
from pandas import (
Categorical,
@@ -1991,15 +1993,20 @@ def test_pivot_string_func_vs_func(self, f, f_numpy):
@pytest.mark.slow
def test_pivot_number_of_levels_larger_than_int32(self):
# GH 20601
+ # GH 26314: Change ValueError to PerformanceWarning
df = DataFrame(
{"ind1": np.arange(2 ** 16), "ind2": np.arange(2 ** 16), "count": 0}
)
- msg = "Unstacked DataFrame is too big, causing int32 overflow"
- with pytest.raises(ValueError, match=msg):
- df.pivot_table(
- index="ind1", columns="ind2", values="count", aggfunc="count"
- )
+ msg = "The following operation may generate"
+ with tm.assert_produces_warning(PerformanceWarning, match=msg):
+ try:
+ df.pivot_table(
+ index="ind1", columns="ind2", values="count", aggfunc="count"
+ )
+ except MemoryError:
+ # Just checking the warning
+ return
def test_pivot_table_aggfunc_dropna(self, dropna):
# GH 22159
| - [x] closes #26314
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45084 | 2021-12-28T01:56:59Z | 2021-12-28T14:07:56Z | 2021-12-28T14:07:56Z | 2021-12-29T18:51:16Z |
BUG+DEPR: Timestamp.fromtimestamp tz arg | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index c743e38a118f7..0b73575bf7aa6 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -590,6 +590,7 @@ Other Deprecations
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
- Deprecated ``numeric_only=None`` in :meth:`DataFrame.rank`; in a future version ``numeric_only`` must be either ``True`` or ``False`` (the default) (:issue:`45036`)
+- Deprecated the behavior of :meth:`Timestamp.utcfromtimestamp`, in the future it will return a timezone-aware UTC :class:`Timestamp` (:issue:`22451`)
- Deprecated :meth:`NaT.freq` (:issue:`45071`)
-
@@ -682,6 +683,7 @@ Datetimelike
- Bug in :meth:`Index.insert` for inserting ``np.datetime64``, ``np.timedelta64`` or ``tuple`` into :class:`Index` with ``dtype='object'`` with negative loc adding ``None`` and replacing existing value (:issue:`44509`)
- Bug in :meth:`Series.mode` with ``DatetimeTZDtype`` incorrectly returning timezone-naive and ``PeriodDtype`` incorrectly raising (:issue:`41927`)
- 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`)
-
Timedelta
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 1c26793876e5a..307b6f2949881 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -1164,10 +1164,20 @@ class Timestamp(_Timestamp):
>>> pd.Timestamp.utcfromtimestamp(1584199972)
Timestamp('2020-03-14 15:32:52')
"""
+ # GH#22451
+ warnings.warn(
+ "The behavior of Timestamp.utcfromtimestamp is deprecated, in a "
+ "future version will return a timezone-aware Timestamp with UTC "
+ "timezone. To keep the old behavior, use "
+ "Timestamp.utcfromtimestamp(ts).tz_localize(None). "
+ "To get the future behavior, use Timestamp.fromtimestamp(ts, 'UTC')",
+ FutureWarning,
+ stacklevel=1,
+ )
return cls(datetime.utcfromtimestamp(ts))
@classmethod
- def fromtimestamp(cls, ts):
+ def fromtimestamp(cls, ts, tz=None):
"""
Timestamp.fromtimestamp(ts)
@@ -1180,7 +1190,8 @@ class Timestamp(_Timestamp):
Note that the output may change depending on your local time.
"""
- return cls(datetime.fromtimestamp(ts))
+ tz = maybe_get_tz(tz)
+ return cls(datetime.fromtimestamp(ts, tz))
def strftime(self, format):
"""
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py
index 9c9e11c6a4ba4..008731b13172e 100644
--- a/pandas/tests/scalar/timestamp/test_timestamp.py
+++ b/pandas/tests/scalar/timestamp/test_timestamp.py
@@ -292,13 +292,27 @@ def compare(x, y):
compare(Timestamp.utcnow(), datetime.utcnow())
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
+ msg = "timezone-aware Timestamp with UTC"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#22451
+ ts_utc = Timestamp.utcfromtimestamp(current_time)
compare(
- Timestamp.utcfromtimestamp(current_time),
+ ts_utc,
datetime.utcfromtimestamp(current_time),
)
compare(
Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)
)
+ compare(
+ # Support tz kwarg in Timestamp.fromtimestamp
+ Timestamp.fromtimestamp(current_time, "UTC"),
+ datetime.fromtimestamp(current_time, utc),
+ )
+ compare(
+ # Support tz kwarg in Timestamp.fromtimestamp
+ Timestamp.fromtimestamp(current_time, tz="UTC"),
+ datetime.fromtimestamp(current_time, utc),
+ )
date_component = datetime.utcnow()
time_component = (date_component + timedelta(minutes=10)).time()
@@ -322,8 +336,14 @@ def compare(x, y):
compare(Timestamp.utcnow(), datetime.utcnow())
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
+
+ msg = "timezone-aware Timestamp with UTC"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ # GH#22451
+ ts_utc = Timestamp.utcfromtimestamp(current_time)
+
compare(
- Timestamp.utcfromtimestamp(current_time),
+ ts_utc,
datetime.utcfromtimestamp(current_time),
)
compare(
| - [x] closes #22451
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45083 | 2021-12-28T00:16:51Z | 2021-12-28T14:46:32Z | 2021-12-28T14:46:32Z | 2021-12-28T17:03:38Z |
TST: Split/parameterize test_frame_apply.py | diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py
index 6cfcfa778b105..98872571ae2bb 100644
--- a/pandas/tests/apply/test_frame_apply.py
+++ b/pandas/tests/apply/test_frame_apply.py
@@ -36,6 +36,8 @@ def test_apply(float_frame):
assert result[d] == expected
assert result.index is float_frame.index
+
+def test_apply_categorical_func():
# GH 9573
df = DataFrame({"c0": ["A", "A", "B", "B"], "c1": ["C", "C", "D", "D"]})
result = df.apply(lambda ts: ts.astype("category"))
@@ -76,16 +78,16 @@ def test_apply_mixed_datetimelike():
tm.assert_frame_equal(result, expected)
-def test_apply_empty(float_frame):
+@pytest.mark.parametrize("func", [np.sqrt, np.mean])
+def test_apply_empty(func):
# empty
empty_frame = DataFrame()
- result = empty_frame.apply(np.sqrt)
+ result = empty_frame.apply(func)
assert result.empty
- result = empty_frame.apply(np.mean)
- assert result.empty
+def test_apply_float_frame(float_frame):
no_rows = float_frame[:0]
result = no_rows.apply(lambda x: x.mean())
expected = Series(np.nan, index=float_frame.columns)
@@ -96,6 +98,8 @@ def test_apply_empty(float_frame):
expected = Series(np.nan, index=float_frame.index)
tm.assert_series_equal(result, expected)
+
+def test_apply_empty_except_index():
# GH 2476
expected = DataFrame(index=["a"])
result = expected.apply(lambda x: x["a"], axis=1)
@@ -158,18 +162,21 @@ def test_apply_standard_nonunique():
tm.assert_series_equal(result, expected)
-def test_apply_broadcast(float_frame, int_frame_const_col):
-
+def test_apply_broadcast_scalars(float_frame):
# scalars
result = float_frame.apply(np.mean, result_type="broadcast")
expected = DataFrame([float_frame.mean()], index=float_frame.index)
tm.assert_frame_equal(result, expected)
+
+def test_apply_broadcast_scalars_axis1(float_frame):
result = float_frame.apply(np.mean, axis=1, result_type="broadcast")
m = float_frame.mean(axis=1)
expected = DataFrame({c: m for c in float_frame.columns})
tm.assert_frame_equal(result, expected)
+
+def test_apply_broadcast_lists_columns(float_frame):
# lists
result = float_frame.apply(
lambda x: list(range(len(float_frame.columns))),
@@ -185,6 +192,8 @@ def test_apply_broadcast(float_frame, int_frame_const_col):
)
tm.assert_frame_equal(result, expected)
+
+def test_apply_broadcast_lists_index(float_frame):
result = float_frame.apply(
lambda x: list(range(len(float_frame.index))), result_type="broadcast"
)
@@ -196,11 +205,15 @@ def test_apply_broadcast(float_frame, int_frame_const_col):
)
tm.assert_frame_equal(result, expected)
+
+def test_apply_broadcast_list_lambda_func(int_frame_const_col):
# preserve columns
df = int_frame_const_col
result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="broadcast")
tm.assert_frame_equal(result, df)
+
+def test_apply_broadcast_series_lambda_func(int_frame_const_col):
df = int_frame_const_col
result = df.apply(
lambda x: Series([1, 2, 3], index=list("abc")),
@@ -211,30 +224,37 @@ def test_apply_broadcast(float_frame, int_frame_const_col):
tm.assert_frame_equal(result, expected)
-def test_apply_raw(float_frame, mixed_type_frame):
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_raw_float_frame(float_frame, axis):
def _assert_raw(x):
assert isinstance(x, np.ndarray)
assert x.ndim == 1
- float_frame.apply(_assert_raw, raw=True)
- float_frame.apply(_assert_raw, axis=1, raw=True)
+ float_frame.apply(_assert_raw, axis=axis, raw=True)
- result = float_frame.apply(np.mean, raw=True)
- expected = float_frame.apply(lambda x: x.values.mean())
- tm.assert_series_equal(result, expected)
- result = float_frame.apply(np.mean, axis=1, raw=True)
- expected = float_frame.apply(lambda x: x.values.mean(), axis=1)
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_raw_float_frame_lambda(float_frame, axis):
+ result = float_frame.apply(np.mean, axis=axis, raw=True)
+ expected = float_frame.apply(lambda x: x.values.mean(), axis=axis)
tm.assert_series_equal(result, expected)
+
+def test_apply_raw_float_frame_no_reduction(float_frame):
# no reduction
result = float_frame.apply(lambda x: x * 2, raw=True)
expected = float_frame * 2
tm.assert_frame_equal(result, expected)
+
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_raw_mixed_type_frame(mixed_type_frame, axis):
+ def _assert_raw(x):
+ assert isinstance(x, np.ndarray)
+ assert x.ndim == 1
+
# Mixed dtype (GH-32423)
- mixed_type_frame.apply(_assert_raw, raw=True)
- mixed_type_frame.apply(_assert_raw, axis=1, raw=True)
+ mixed_type_frame.apply(_assert_raw, axis=axis, raw=True)
def test_apply_axis1(float_frame):
@@ -252,6 +272,8 @@ def test_apply_mixed_dtype_corner():
expected = Series(np.nan, index=pd.Index([], dtype="int64"))
tm.assert_series_equal(result, expected)
+
+def test_apply_mixed_dtype_corner_indexing():
df = DataFrame({"A": ["foo"], "B": [1.0]})
result = df.apply(lambda x: x["A"], axis=1)
expected = Series(["foo"], index=[0])
@@ -262,58 +284,58 @@ def test_apply_mixed_dtype_corner():
tm.assert_series_equal(result, expected)
-def test_apply_empty_infer_type():
- no_cols = DataFrame(index=["a", "b", "c"])
- no_index = DataFrame(columns=["a", "b", "c"])
+@pytest.mark.parametrize("ax", ["index", "columns"])
+@pytest.mark.parametrize(
+ "func", [lambda x: x, lambda x: x.mean()], ids=["identity", "mean"]
+)
+@pytest.mark.parametrize("raw", [True, False])
+@pytest.mark.parametrize("axis", [0, 1])
+def test_apply_empty_infer_type(ax, func, raw, axis):
+ df = DataFrame(**{ax: ["a", "b", "c"]})
- def _check(df, f):
+ with np.errstate(all="ignore"):
with warnings.catch_warnings(record=True):
warnings.simplefilter("ignore", RuntimeWarning)
- test_res = f(np.array([], dtype="f8"))
+ test_res = func(np.array([], dtype="f8"))
is_reduction = not isinstance(test_res, np.ndarray)
- def _checkit(axis=0, raw=False):
- result = df.apply(f, axis=axis, raw=raw)
- if is_reduction:
- agg_axis = df._get_agg_axis(axis)
- assert isinstance(result, Series)
- assert result.index is agg_axis
- else:
- assert isinstance(result, DataFrame)
-
- _checkit()
- _checkit(axis=1)
- _checkit(raw=True)
- _checkit(axis=0, raw=True)
+ result = df.apply(func, axis=axis, raw=raw)
+ if is_reduction:
+ agg_axis = df._get_agg_axis(axis)
+ assert isinstance(result, Series)
+ assert result.index is agg_axis
+ else:
+ assert isinstance(result, DataFrame)
- with np.errstate(all="ignore"):
- _check(no_cols, lambda x: x)
- _check(no_cols, lambda x: x.mean())
- _check(no_index, lambda x: x)
- _check(no_index, lambda x: x.mean())
+def test_apply_empty_infer_type_broadcast():
+ no_cols = DataFrame(index=["a", "b", "c"])
result = no_cols.apply(lambda x: x.mean(), result_type="broadcast")
assert isinstance(result, DataFrame)
-def test_apply_with_args_kwds(float_frame):
+def test_apply_with_args_kwds_add_some(float_frame):
def add_some(x, howmuch=0):
return x + howmuch
- def agg_and_add(x, howmuch=0):
- return x.mean() + howmuch
-
- def subtract_and_divide(x, sub, divide=1):
- return (x - sub) / divide
-
result = float_frame.apply(add_some, howmuch=2)
expected = float_frame.apply(lambda x: x + 2)
tm.assert_frame_equal(result, expected)
+
+def test_apply_with_args_kwds_agg_and_add(float_frame):
+ def agg_and_add(x, howmuch=0):
+ return x.mean() + howmuch
+
result = float_frame.apply(agg_and_add, howmuch=2)
expected = float_frame.apply(lambda x: x.mean() + 2)
tm.assert_series_equal(result, expected)
+
+def test_apply_with_args_kwds_subtract_and_divide(float_frame):
+ def subtract_and_divide(x, sub, divide=1):
+ return (x - sub) / divide
+
result = float_frame.apply(subtract_and_divide, args=(2,), divide=2)
expected = float_frame.apply(lambda x: (x - 2.0) / 2.0)
tm.assert_frame_equal(result, expected)
@@ -448,10 +470,14 @@ def test_apply_attach_name(float_frame):
expected = Series(float_frame.columns, index=float_frame.columns)
tm.assert_series_equal(result, expected)
+
+def test_apply_attach_name_axis1(float_frame):
result = float_frame.apply(lambda x: x.name, axis=1)
expected = Series(float_frame.index, index=float_frame.index)
tm.assert_series_equal(result, expected)
+
+def test_apply_attach_name_non_reduction(float_frame):
# non-reductions
result = float_frame.apply(lambda x: np.repeat(x.name, len(x)))
expected = DataFrame(
@@ -461,6 +487,8 @@ def test_apply_attach_name(float_frame):
)
tm.assert_frame_equal(result, expected)
+
+def test_apply_attach_name_non_reduction_axis1(float_frame):
result = float_frame.apply(lambda x: np.repeat(x.name, len(x)), axis=1)
expected = Series(
np.repeat(t[0], len(float_frame.columns)) for t in float_frame.itertuples()
@@ -469,7 +497,7 @@ def test_apply_attach_name(float_frame):
tm.assert_series_equal(result, expected)
-def test_apply_multi_index(float_frame):
+def test_apply_multi_index():
index = MultiIndex.from_arrays([["a", "a", "b"], ["c", "d", "d"]])
s = DataFrame([[1, 2], [3, 4], [5, 6]], index=index, columns=["col1", "col2"])
result = s.apply(lambda x: Series({"min": min(x), "max": max(x)}), 1)
@@ -477,23 +505,26 @@ def test_apply_multi_index(float_frame):
tm.assert_frame_equal(result, expected, check_like=True)
-def test_apply_dict():
-
+@pytest.mark.parametrize(
+ "df, dicts",
+ [
+ [
+ DataFrame([["foo", "bar"], ["spam", "eggs"]]),
+ Series([{0: "foo", 1: "spam"}, {0: "bar", 1: "eggs"}]),
+ ],
+ [DataFrame([[0, 1], [2, 3]]), Series([{0: 0, 1: 2}, {0: 1, 1: 3}])],
+ ],
+)
+def test_apply_dict(df, dicts):
# GH 8735
- A = DataFrame([["foo", "bar"], ["spam", "eggs"]])
- A_dicts = Series([{0: "foo", 1: "spam"}, {0: "bar", 1: "eggs"}])
- B = DataFrame([[0, 1], [2, 3]])
- B_dicts = Series([{0: 0, 1: 2}, {0: 1, 1: 3}])
fn = lambda x: x.to_dict()
+ reduce_true = df.apply(fn, result_type="reduce")
+ reduce_false = df.apply(fn, result_type="expand")
+ reduce_none = df.apply(fn)
- for df, dicts in [(A, A_dicts), (B, B_dicts)]:
- reduce_true = df.apply(fn, result_type="reduce")
- reduce_false = df.apply(fn, result_type="expand")
- reduce_none = df.apply(fn)
-
- tm.assert_series_equal(reduce_true, dicts)
- tm.assert_frame_equal(reduce_false, df)
- tm.assert_series_equal(reduce_none, dicts)
+ tm.assert_series_equal(reduce_true, dicts)
+ tm.assert_frame_equal(reduce_false, df)
+ tm.assert_series_equal(reduce_none, dicts)
def test_applymap(float_frame):
@@ -505,15 +536,16 @@ def test_applymap(float_frame):
result = float_frame.applymap(lambda x: (x, x))["A"][0]
assert isinstance(result, tuple)
+
+@pytest.mark.parametrize("val", [1, 1.0])
+def test_applymap_float_object_conversion(val):
# GH 2909: object conversion to float in constructor?
- df = DataFrame(data=[1, "a"])
+ df = DataFrame(data=[val, "a"])
result = df.applymap(lambda x: x).dtypes[0]
assert result == object
- df = DataFrame(data=[1.0, "a"])
- result = df.applymap(lambda x: x).dtypes[0]
- assert result == object
+def test_applymap_str():
# GH 2786
df = DataFrame(np.random.random((3, 4)))
df2 = df.copy()
@@ -525,24 +557,33 @@ def test_applymap(float_frame):
result = df.applymap(str)
tm.assert_frame_equal(result, expected)
+
+@pytest.mark.parametrize(
+ "col, val",
+ [["datetime", Timestamp("20130101")], ["timedelta", pd.Timedelta("1 min")]],
+)
+def test_applymap_datetimelike(col, val):
# datetime/timedelta
- df["datetime"] = Timestamp("20130101")
- df["timedelta"] = pd.Timedelta("1 min")
+ df = DataFrame(np.random.random((3, 4)))
+ df[col] = val
result = df.applymap(str)
- for f in ["datetime", "timedelta"]:
- assert result.loc[0, f] == str(df.loc[0, f])
+ assert result.loc[0, col] == str(df.loc[0, col])
- # GH 8222
- empty_frames = [
+
+@pytest.mark.parametrize(
+ "expected",
+ [
DataFrame(),
DataFrame(columns=list("ABC")),
DataFrame(index=list("ABC")),
DataFrame({"A": [], "B": [], "C": []}),
- ]
- for expected in empty_frames:
- for func in [round, lambda x: x]:
- result = expected.applymap(func)
- tm.assert_frame_equal(result, expected)
+ ],
+)
+@pytest.mark.parametrize("func", [round, lambda x: x])
+def test_applymap_empty(expected, func):
+ # GH 8222
+ result = expected.applymap(func)
+ tm.assert_frame_equal(result, expected)
def test_applymap_kwargs():
@@ -630,6 +671,8 @@ def test_apply_non_numpy_dtype():
)
tm.assert_frame_equal(result, expected)
+
+def test_apply_non_numpy_dtype_category():
df = DataFrame({"dt": ["a", "b", "c", "a"]}, dtype="category")
result = df.apply(lambda x: x)
tm.assert_frame_equal(result, df)
@@ -732,7 +775,7 @@ def test_apply_with_byte_string():
# GH 34529
df = DataFrame(np.array([b"abcd", b"efgh"]), columns=["col"])
expected = DataFrame(np.array([b"abcd", b"efgh"]), columns=["col"], dtype=object)
- # After we make the aply we exect a dataframe just
+ # After we make the apply we expect a dataframe just
# like the original but with the object datatype
result = df.apply(lambda x: x.astype("object"))
tm.assert_frame_equal(result, expected)
@@ -786,6 +829,8 @@ def test_with_dictlike_columns():
expected = Series([{"s": 3}, {"s": 3}])
tm.assert_series_equal(result, expected)
+
+def test_with_dictlike_columns_with_datetime():
# GH 18775
df = DataFrame()
df["author"] = ["X", "Y", "Z"]
@@ -831,6 +876,8 @@ def test_with_listlike_columns():
expected = Series([t[1:] for t in df[["a", "ts"]].itertuples()])
tm.assert_series_equal(result, expected)
+
+def test_with_listlike_columns_returning_list():
# GH 18919
df = DataFrame({"x": Series([["a", "b"], ["q"]]), "y": Series([["z"], ["q", "t"]])})
df.index = MultiIndex.from_tuples([("i0", "j0"), ("i1", "j1")])
@@ -871,17 +918,18 @@ def test_infer_output_shape_listlike_columns():
expected = Series([[1, 2] for t in df.itertuples()])
tm.assert_series_equal(result, expected)
+
+@pytest.mark.parametrize("val", [1, 2])
+def test_infer_output_shape_listlike_columns_np_func(val):
# GH 17970
df = DataFrame({"a": [1, 2, 3]}, index=list("abc"))
- result = df.apply(lambda row: np.ones(1), axis=1)
- expected = Series([np.ones(1) for t in df.itertuples()], index=df.index)
+ result = df.apply(lambda row: np.ones(val), axis=1)
+ expected = Series([np.ones(val) for t in df.itertuples()], index=df.index)
tm.assert_series_equal(result, expected)
- result = df.apply(lambda row: np.ones(2), axis=1)
- expected = Series([np.ones(2) for t in df.itertuples()], index=df.index)
- tm.assert_series_equal(result, expected)
+def test_infer_output_shape_listlike_columns_with_timestamp():
# GH 17892
df = DataFrame(
{
@@ -905,17 +953,14 @@ def fun(x):
tm.assert_series_equal(result, expected)
-def test_consistent_coerce_for_shapes():
+@pytest.mark.parametrize("lst", [[1, 2, 3], [1, 2]])
+def test_consistent_coerce_for_shapes(lst):
# we want column names to NOT be propagated
# just because the shape matches the input shape
df = DataFrame(np.random.randn(4, 3), columns=["A", "B", "C"])
- result = df.apply(lambda x: [1, 2, 3], axis=1)
- expected = Series([[1, 2, 3] for t in df.itertuples()])
- tm.assert_series_equal(result, expected)
-
- result = df.apply(lambda x: [1, 2], axis=1)
- expected = Series([[1, 2] for t in df.itertuples()])
+ result = df.apply(lambda x: lst, axis=1)
+ expected = Series([lst for t in df.itertuples()])
tm.assert_series_equal(result, expected)
@@ -946,16 +991,31 @@ def test_result_type(int_frame_const_col):
expected.columns = [0, 1, 2]
tm.assert_frame_equal(result, expected)
+
+def test_result_type_shorter_list(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
result = df.apply(lambda x: [1, 2], axis=1, result_type="expand")
expected = df[["A", "B"]].copy()
expected.columns = [0, 1]
tm.assert_frame_equal(result, expected)
+
+def test_result_type_broadcast(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
# broadcast result
result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="broadcast")
expected = df.copy()
tm.assert_frame_equal(result, expected)
+
+def test_result_type_broadcast_series_func(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
columns = ["other", "col", "names"]
result = df.apply(
lambda x: Series([1, 2, 3], index=columns), axis=1, result_type="broadcast"
@@ -963,11 +1023,21 @@ def test_result_type(int_frame_const_col):
expected = df.copy()
tm.assert_frame_equal(result, expected)
+
+def test_result_type_series_result(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
# series result
result = df.apply(lambda x: Series([1, 2, 3], index=x.index), axis=1)
expected = df.copy()
tm.assert_frame_equal(result, expected)
+
+def test_result_type_series_result_other_index(int_frame_const_col):
+ # result_type should be consistent no matter which
+ # path we take in the code
+ df = int_frame_const_col
# series result with other index
columns = ["other", "col", "names"]
result = df.apply(lambda x: Series([1, 2, 3], index=columns), axis=1)
@@ -1042,6 +1112,10 @@ def test_demo():
)
tm.assert_frame_equal(result, expected)
+
+def test_demo_dict_agg():
+ # demonstration tests
+ df = DataFrame({"A": range(5), "B": 5})
result = df.agg({"A": ["min", "max"], "B": ["sum", "max"]})
expected = DataFrame(
{"A": [4.0, 0.0, np.nan], "B": [5.0, np.nan, 25.0]},
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45082 | 2021-12-27T22:11:13Z | 2021-12-28T14:05:23Z | 2021-12-28T14:05:23Z | 2021-12-28T17:57:20Z |
BUG: Series.replace with value=None explicitly | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 2c77b87f8efb6..c3c035b835425 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -939,6 +939,8 @@ ExtensionArray
- Bug in :func:`array` incorrectly raising when passed a ``ndarray`` with ``float16`` dtype (:issue:`44715`)
- Bug in calling ``np.sqrt`` on :class:`BooleanArray` returning a malformed :class:`FloatingArray` (:issue:`44715`)
- Bug in :meth:`Series.where` with ``ExtensionDtype`` when ``other`` is a NA scalar incompatible with the series dtype (e.g. ``NaT`` with a numeric dtype) incorrectly casting to a compatible NA value (:issue:`44697`)
+- Fixed bug in :meth:`Series.replace` where explicitly passing ``value=None`` is treated as if no ``value`` was passed, and ``None`` not being in the result (:issue:`36984`, :issue:`19998`)
+- Fixed bug in :meth:`Series.replace` with unwanted downcasting being done in no-op replacements (:issue:`44498`)
- Fixed bug in :meth:`Series.replace` with ``FloatDtype``, ``string[python]``, or ``string[pyarrow]`` dtype not being preserved when possible (:issue:`33484`, :issue:`40732`, :issue:`31644`, :issue:`41215`, :issue:`25438`)
-
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c02749320e991..2a92d8b4964f1 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5265,11 +5265,11 @@ def pop(self, item: Hashable) -> Series:
def replace(
self,
to_replace=None,
- value=None,
+ value=lib.no_default,
inplace: bool = False,
limit=None,
regex: bool = False,
- method: str = "pad",
+ method: str | lib.NoDefault = lib.no_default,
):
return super().replace(
to_replace=to_replace,
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index de40ad36a7d02..0034d0511c15e 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6515,11 +6515,11 @@ def bfill(
def replace(
self,
to_replace=None,
- value=None,
+ value=lib.no_default,
inplace: bool_t = False,
limit: int | None = None,
regex=False,
- method="pad",
+ method=lib.no_default,
):
if not (
is_scalar(to_replace)
@@ -6538,7 +6538,15 @@ def replace(
self._consolidate_inplace()
- if value is None:
+ if value is lib.no_default or method is not lib.no_default:
+ # GH#36984 if the user explicitly passes value=None we want to
+ # respect that. We have the corner case where the user explicitly
+ # passes value=None *and* a method, which we interpret as meaning
+ # they want the (documented) default behavior.
+ if method is lib.no_default:
+ # TODO: get this to show up as the default in the docs?
+ method = "pad"
+
# passing a single value that is scalar like
# when value is None (GH5319), for compat
if not is_dict_like(to_replace) and not is_dict_like(regex):
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 6ef8d90d7dcf2..41512ff9be82f 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -679,7 +679,12 @@ def replace(
elif self._can_hold_element(value):
blk = self if inplace else self.copy()
putmask_inplace(blk.values, mask, value)
- blocks = blk.convert(numeric=False, copy=False)
+ if not (self.is_object and value is None):
+ # if the user *explicitly* gave None, we keep None, otherwise
+ # may downcast to NaN
+ blocks = blk.convert(numeric=False, copy=False)
+ else:
+ blocks = [blk]
return blocks
elif self.ndim == 1 or self.shape[0] == 1:
@@ -802,7 +807,8 @@ def replace_list(
inplace=inplace,
regex=regex,
)
- if convert and blk.is_object:
+ if convert and blk.is_object and not all(x is None for x in dest_list):
+ # GH#44498 avoid unwanted cast-back
result = extend_blocks(
[b.convert(numeric=False, copy=True) for b in result]
)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 83ebcd9ffb4b3..d9c1ab0cb426c 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4924,11 +4924,11 @@ def pop(self, item: Hashable) -> Any:
def replace(
self,
to_replace=None,
- value=None,
+ value=lib.no_default,
inplace=False,
limit=None,
regex=False,
- method="pad",
+ method: str | lib.NoDefault = lib.no_default,
):
return super().replace(
to_replace=to_replace,
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py
index d853f728f64a3..f79fd3ed09f8d 100644
--- a/pandas/core/shared_docs.py
+++ b/pandas/core/shared_docs.py
@@ -693,18 +693,30 @@
4 None
dtype: object
- When ``value=None`` and `to_replace` is a scalar, list or
- tuple, `replace` uses the method parameter (default 'pad') to do the
+ When ``value`` is not explicitly passed and `to_replace` is a scalar, list
+ or tuple, `replace` uses the method parameter (default 'pad') to do the
replacement. So this is why the 'a' values are being replaced by 10
in rows 1 and 2 and 'b' in row 4 in this case.
- The command ``s.replace('a', None)`` is actually equivalent to
- ``s.replace(to_replace='a', value=None, method='pad')``:
- >>> s.replace('a', None)
+ >>> s.replace('a')
0 10
1 10
2 10
3 b
4 b
dtype: object
+
+ On the other hand, if ``None`` is explicitly passed for ``value``, it will
+ be respected:
+
+ >>> s.replace('a', None)
+ 0 10
+ 1 None
+ 2 None
+ 3 b
+ 4 None
+ dtype: object
+
+ .. versionchanged:: 1.4.0
+ Previously the explicit ``None`` was silently ignored.
"""
diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py
index c0234ee2649b5..6a8dacfda5e78 100644
--- a/pandas/tests/series/methods/test_replace.py
+++ b/pandas/tests/series/methods/test_replace.py
@@ -9,6 +9,45 @@
class TestSeriesReplace:
+ def test_replace_explicit_none(self):
+ # GH#36984 if the user explicitly passes value=None, give it to them
+ ser = pd.Series([0, 0, ""], dtype=object)
+ result = ser.replace("", None)
+ expected = pd.Series([0, 0, None], dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ df = pd.DataFrame(np.zeros((3, 3)))
+ df.iloc[2, 2] = ""
+ result = df.replace("", None)
+ expected = pd.DataFrame(
+ {
+ 0: np.zeros(3),
+ 1: np.zeros(3),
+ 2: np.array([0.0, 0.0, None], dtype=object),
+ }
+ )
+ assert expected.iloc[2, 2] is None
+ tm.assert_frame_equal(result, expected)
+
+ # GH#19998 same thing with object dtype
+ ser = pd.Series([10, 20, 30, "a", "a", "b", "a"])
+ result = ser.replace("a", None)
+ expected = pd.Series([10, 20, 30, None, None, "b", None])
+ assert expected.iloc[-1] is None
+ tm.assert_series_equal(result, expected)
+
+ def test_replace_noop_doesnt_downcast(self):
+ # GH#44498
+ ser = pd.Series([None, None, pd.Timestamp("2021-12-16 17:31")], dtype=object)
+ res = ser.replace({np.nan: None}) # should be a no-op
+ tm.assert_series_equal(res, ser)
+ assert res.dtype == object
+
+ # same thing but different calling convention
+ res = ser.replace(np.nan, None)
+ tm.assert_series_equal(res, ser)
+ assert res.dtype == object
+
def test_replace(self):
N = 100
ser = pd.Series(np.random.randn(N))
| - [x] closes #36984
- [x] closes #19998
- [x] closes #44498
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
Not sure if there is a way to keep the default values rendered in the docs unchanged. | https://api.github.com/repos/pandas-dev/pandas/pulls/45081 | 2021-12-27T20:12:55Z | 2021-12-29T15:35:59Z | 2021-12-29T15:35:59Z | 2021-12-29T15:44:40Z |
TST: Parameterize series/test_cummulative.py | diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py
index 74ab9376ed00f..f970d88e310e1 100644
--- a/pandas/tests/series/test_cumulative.py
+++ b/pandas/tests/series/test_cumulative.py
@@ -20,28 +20,23 @@
}
-def _check_accum_op(name, series, check_dtype=True):
- func = getattr(np, name)
- tm.assert_numpy_array_equal(
- func(series).values, func(np.array(series)), check_dtype=check_dtype
- )
-
- # with missing values
- ts = series.copy()
- ts[::2] = np.NaN
-
- result = func(ts)[1::2]
- expected = func(np.array(ts.dropna()))
-
- tm.assert_numpy_array_equal(result.values, expected, check_dtype=False)
+class TestSeriesCumulativeOps:
+ @pytest.mark.parametrize("func", [np.cumsum, np.cumprod])
+ def test_datetime_series(self, datetime_series, func):
+ tm.assert_numpy_array_equal(
+ func(datetime_series).values,
+ func(np.array(datetime_series)),
+ check_dtype=True,
+ )
+ # with missing values
+ ts = datetime_series.copy()
+ ts[::2] = np.NaN
-class TestSeriesCumulativeOps:
- def test_cumsum(self, datetime_series):
- _check_accum_op("cumsum", datetime_series)
+ result = func(ts)[1::2]
+ expected = func(np.array(ts.dropna()))
- def test_cumprod(self, datetime_series):
- _check_accum_op("cumprod", datetime_series)
+ tm.assert_numpy_array_equal(result.values, expected, check_dtype=False)
@pytest.mark.parametrize("method", ["cummin", "cummax"])
def test_cummin_cummax(self, datetime_series, method):
@@ -67,64 +62,70 @@ def test_cummin_cummax(self, datetime_series, method):
pd.Timestamp("1999-12-31").tz_localize("US/Pacific"),
],
)
- def test_cummin_cummax_datetimelike(self, ts):
+ @pytest.mark.parametrize(
+ "method, skipna, exp_tdi",
+ [
+ ["cummax", True, ["NaT", "2 days", "NaT", "2 days", "NaT", "3 days"]],
+ ["cummin", True, ["NaT", "2 days", "NaT", "1 days", "NaT", "1 days"]],
+ [
+ "cummax",
+ False,
+ ["NaT", "2 days", "2 days", "2 days", "2 days", "3 days"],
+ ],
+ [
+ "cummin",
+ False,
+ ["NaT", "2 days", "2 days", "1 days", "1 days", "1 days"],
+ ],
+ ],
+ )
+ def test_cummin_cummax_datetimelike(self, ts, method, skipna, exp_tdi):
# with ts==pd.Timedelta(0), we are testing td64; with naive Timestamp
# we are testing datetime64[ns]; with Timestamp[US/Pacific]
# we are testing dt64tz
tdi = pd.to_timedelta(["NaT", "2 days", "NaT", "1 days", "NaT", "3 days"])
ser = pd.Series(tdi + ts)
- exp_tdi = pd.to_timedelta(["NaT", "2 days", "NaT", "2 days", "NaT", "3 days"])
- expected = pd.Series(exp_tdi + ts)
- result = ser.cummax(skipna=True)
- tm.assert_series_equal(expected, result)
-
- exp_tdi = pd.to_timedelta(["NaT", "2 days", "NaT", "1 days", "NaT", "1 days"])
- expected = pd.Series(exp_tdi + ts)
- result = ser.cummin(skipna=True)
- tm.assert_series_equal(expected, result)
-
- exp_tdi = pd.to_timedelta(
- ["NaT", "2 days", "2 days", "2 days", "2 days", "3 days"]
- )
+ exp_tdi = pd.to_timedelta(exp_tdi)
expected = pd.Series(exp_tdi + ts)
- result = ser.cummax(skipna=False)
+ result = getattr(ser, method)(skipna=skipna)
tm.assert_series_equal(expected, result)
- exp_tdi = pd.to_timedelta(
- ["NaT", "2 days", "2 days", "1 days", "1 days", "1 days"]
- )
- expected = pd.Series(exp_tdi + ts)
- result = ser.cummin(skipna=False)
- tm.assert_series_equal(expected, result)
-
- def test_cummethods_bool(self):
+ @pytest.mark.parametrize(
+ "arg",
+ [
+ [False, False, False, True, True, False, False],
+ [False, False, False, False, False, False, False],
+ ],
+ )
+ @pytest.mark.parametrize(
+ "func", [lambda x: x, lambda x: ~x], ids=["identity", "inverse"]
+ )
+ @pytest.mark.parametrize("method", methods.keys())
+ def test_cummethods_bool(self, arg, func, method):
# GH#6270
# checking Series method vs the ufunc applied to the values
- a = pd.Series([False, False, False, True, True, False, False])
- c = pd.Series([False] * len(a))
-
- for method in methods:
- for ser in [a, ~a, c, ~c]:
- ufunc = methods[method]
-
- exp_vals = ufunc(ser.values)
- expected = pd.Series(exp_vals)
+ ser = func(pd.Series(arg))
+ ufunc = methods[method]
- result = getattr(ser, method)()
+ exp_vals = ufunc(ser.values)
+ expected = pd.Series(exp_vals)
- tm.assert_series_equal(result, expected)
+ result = getattr(ser, method)()
- def test_cummethods_bool_in_object_dtype(self):
+ tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize(
+ "method, expected",
+ [
+ ["cumsum", pd.Series([0, 1, np.nan, 1], dtype=object)],
+ ["cumprod", pd.Series([False, 0, np.nan, 0])],
+ ["cummin", pd.Series([False, False, np.nan, False])],
+ ["cummax", pd.Series([False, True, np.nan, True])],
+ ],
+ )
+ def test_cummethods_bool_in_object_dtype(self, method, expected):
ser = pd.Series([False, True, np.nan, False])
- cse = pd.Series([0, 1, np.nan, 1], dtype=object)
- cpe = pd.Series([False, 0, np.nan, 0])
- cmin = pd.Series([False, False, np.nan, False])
- cmax = pd.Series([False, True, np.nan, True])
- expecteds = {"cumsum": cse, "cumprod": cpe, "cummin": cmin, "cummax": cmax}
-
- for method in methods:
- res = getattr(ser, method)()
- tm.assert_series_equal(res, expecteds[method])
+ result = getattr(ser, method)()
+ tm.assert_series_equal(result, expected)
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45080 | 2021-12-27T19:08:46Z | 2021-12-28T00:57:53Z | 2021-12-28T00:57:53Z | 2021-12-28T01:02:48Z |
TST: Split and parameterize series/test_api.py | diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py
index a01b8d304d05d..146663d90f752 100644
--- a/pandas/tests/series/test_api.py
+++ b/pandas/tests/series/test_api.py
@@ -25,12 +25,14 @@ def test_tab_completion(self):
assert "dt" not in dir(s)
assert "cat" not in dir(s)
+ def test_tab_completion_dt(self):
# similarly for .dt
s = Series(date_range("1/1/2015", periods=5))
assert "dt" in dir(s)
assert "str" not in dir(s)
assert "cat" not in dir(s)
+ def test_tab_completion_cat(self):
# Similarly for .cat, but with the twist that str and dt should be
# there if the categories are of that type first cat and str.
s = Series(list("abbcd"), dtype="category")
@@ -38,6 +40,7 @@ def test_tab_completion(self):
assert "str" in dir(s) # as it is a string categorical
assert "dt" not in dir(s)
+ def test_tab_completion_cat_str(self):
# similar to cat and str
s = Series(date_range("1/1/2015", periods=5)).astype("category")
assert "cat" in dir(s)
@@ -60,12 +63,8 @@ def test_tab_completion_with_categorical(self):
"as_unordered",
]
- def get_dir(s):
- results = [r for r in s.cat.__dir__() if not r.startswith("_")]
- return sorted(set(results))
-
s = Series(list("aabbcde")).astype("category")
- results = get_dir(s)
+ results = sorted({r for r in s.cat.__dir__() if not r.startswith("_")})
tm.assert_almost_equal(results, sorted(set(ok_for_cat)))
@pytest.mark.parametrize(
@@ -98,14 +97,11 @@ def test_index_tab_completion(self, index):
else:
assert x not in dir_s
- def test_not_hashable(self):
- s_empty = Series(dtype=object)
- s = Series([1])
+ @pytest.mark.parametrize("ser", [Series(dtype=object), Series([1])])
+ def test_not_hashable(self, ser):
msg = "unhashable type: 'Series'"
with pytest.raises(TypeError, match=msg):
- hash(s_empty)
- with pytest.raises(TypeError, match=msg):
- hash(s)
+ hash(ser)
def test_contains(self, datetime_series):
tm.assert_contains_all(datetime_series.index, datetime_series)
@@ -138,12 +134,14 @@ def f(x):
expected = tsdf.max()
tm.assert_series_equal(result, expected)
+ def test_ndarray_compat_like_func(self):
# using an ndarray like function
s = Series(np.random.randn(10))
result = Series(np.ones_like(s))
expected = Series(1, index=range(10), dtype="float64")
tm.assert_series_equal(result, expected)
+ def test_ndarray_compat_ravel(self):
# ravel
s = Series(np.random.randn(10))
tm.assert_almost_equal(s.ravel(order="F"), s.values.ravel(order="F"))
@@ -152,15 +150,15 @@ def test_empty_method(self):
s_empty = Series(dtype=object)
assert s_empty.empty
- s2 = Series(index=[1], dtype=object)
- for full_series in [Series([1]), s2]:
- assert not full_series.empty
+ @pytest.mark.parametrize("dtype", ["int64", object])
+ def test_empty_method_full_series(self, dtype):
+ full_series = Series(index=[1], dtype=dtype)
+ assert not full_series.empty
- def test_integer_series_size(self):
+ @pytest.mark.parametrize("dtype", [None, "Int64"])
+ def test_integer_series_size(self, dtype):
# GH 25580
- s = Series(range(9))
- assert s.size == 9
- s = Series(range(9), dtype="Int64")
+ s = Series(range(9), dtype=dtype)
assert s.size == 9
def test_attrs(self):
@@ -186,12 +184,12 @@ def test_unknown_attribute(self):
with pytest.raises(AttributeError, match=msg):
ser.foo
- def test_datetime_series_no_datelike_attrs(self, datetime_series):
+ @pytest.mark.parametrize("op", ["year", "day", "second", "weekday"])
+ def test_datetime_series_no_datelike_attrs(self, op, datetime_series):
# GH#7206
- for op in ["year", "day", "second", "weekday"]:
- msg = f"'Series' object has no attribute '{op}'"
- with pytest.raises(AttributeError, match=msg):
- getattr(datetime_series, op)
+ msg = f"'Series' object has no attribute '{op}'"
+ with pytest.raises(AttributeError, match=msg):
+ getattr(datetime_series, op)
def test_series_datetimelike_attribute_access(self):
# attribute access should still work!
@@ -199,6 +197,9 @@ def test_series_datetimelike_attribute_access(self):
assert ser.year == 2000
assert ser.month == 1
assert ser.day == 10
+
+ def test_series_datetimelike_attribute_access_invalid(self):
+ ser = Series({"year": 2000, "month": 1, "day": 10})
msg = "'Series' object has no attribute 'weekday'"
with pytest.raises(AttributeError, match=msg):
ser.weekday
diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py
index 8052a81036e51..d956b2c3fcd42 100644
--- a/pandas/tests/series/test_missing.py
+++ b/pandas/tests/series/test_missing.py
@@ -36,17 +36,19 @@ def test_isna_for_inf(self):
tm.assert_series_equal(r, e)
tm.assert_series_equal(dr, de)
- def test_isnull_for_inf_deprecated(self):
+ @pytest.mark.parametrize(
+ "method, expected",
+ [
+ ["isna", Series([False, True, True, False])],
+ ["dropna", Series(["a", 1.0], index=[0, 3])],
+ ],
+ )
+ def test_isnull_for_inf_deprecated(self, method, expected):
# gh-17115
s = Series(["a", np.inf, np.nan, 1.0])
with pd.option_context("mode.use_inf_as_null", True):
- r = s.isna()
- dr = s.dropna()
-
- e = Series([False, True, True, False])
- de = Series(["a", 1.0], index=[0, 3])
- tm.assert_series_equal(r, e)
- tm.assert_series_equal(dr, de)
+ result = getattr(s, method)()
+ tm.assert_series_equal(result, expected)
def test_timedelta64_nan(self):
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45079 | 2021-12-27T19:06:53Z | 2021-12-27T22:02:41Z | 2021-12-27T22:02:41Z | 2021-12-27T22:05:33Z |
TST: Parameterize/split series/test_repr.py | diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py
index 930202a7ce1bd..e243f609145f3 100644
--- a/pandas/tests/series/test_repr.py
+++ b/pandas/tests/series/test_repr.py
@@ -41,7 +41,7 @@ def test_multilevel_name_print(self, lexsorted_two_level_string_multiindex):
expected = "\n".join(expected)
assert repr(ser) == expected
- def test_name_printing(self):
+ def test_small_name_printing(self):
# Test small Series.
s = Series([0, 1, 2])
@@ -51,6 +51,7 @@ def test_name_printing(self):
s.name = None
assert "Name:" not in repr(s)
+ def test_big_name_printing(self):
# Test big Series (diff code path).
s = Series(range(1000))
@@ -60,32 +61,39 @@ def test_name_printing(self):
s.name = None
assert "Name:" not in repr(s)
+ def test_empty_name_printing(self):
s = Series(index=date_range("20010101", "20020101"), name="test", dtype=object)
assert "Name: test" in repr(s)
- def test_repr(self, datetime_series, string_series, object_series):
- str(datetime_series)
- str(string_series)
- str(string_series.astype(int))
- str(object_series)
-
- str(Series(np.random.randn(1000), index=np.arange(1000)))
- str(Series(np.random.randn(1000), index=np.arange(1000, 0, step=-1)))
+ @pytest.mark.parametrize("args", [(), (0, -1)])
+ def test_float_range(self, args):
+ str(Series(np.random.randn(1000), index=np.arange(1000, *args)))
+ def test_empty_object(self):
# empty
str(Series(dtype=object))
+ def test_string(self, string_series):
+ str(string_series)
+ str(string_series.astype(int))
+
# with NaNs
string_series[5:7] = np.NaN
str(string_series)
+ def test_object(self, object_series):
+ str(object_series)
+
+ def test_datetime(self, datetime_series):
+ str(datetime_series)
# with Nones
ots = datetime_series.astype("O")
ots[::2] = None
repr(ots)
- # various names
- for name in [
+ @pytest.mark.parametrize(
+ "name",
+ [
"",
1,
1.2,
@@ -97,36 +105,43 @@ def test_repr(self, datetime_series, string_series, object_series):
("foo", 1, 2.3),
("\u03B1", "\u03B2", "\u03B3"),
("\u03B1", "bar"),
- ]:
- string_series.name = name
- repr(string_series)
+ ],
+ )
+ def test_various_names(self, name, string_series):
+ # various names
+ string_series.name = name
+ repr(string_series)
+ def test_tuple_name(self):
biggie = Series(
np.random.randn(1000), index=np.arange(1000), name=("foo", "bar", "baz")
)
repr(biggie)
- # 0 as name
- ser = Series(np.random.randn(100), name=0)
- rep_str = repr(ser)
- assert "Name: 0" in rep_str
-
+ @pytest.mark.parametrize("arg", [100, 1001])
+ def test_tidy_repr_name_0(self, arg):
# tidy repr
- ser = Series(np.random.randn(1001), name=0)
+ ser = Series(np.random.randn(arg), name=0)
rep_str = repr(ser)
assert "Name: 0" in rep_str
+ def test_newline(self):
ser = Series(["a\n\r\tb"], name="a\n\r\td", index=["a\n\r\tf"])
assert "\t" not in repr(ser)
assert "\r" not in repr(ser)
assert "a\n" not in repr(ser)
+ @pytest.mark.parametrize(
+ "name, expected",
+ [
+ ["foo", "Series([], Name: foo, dtype: int64)"],
+ [None, "Series([], dtype: int64)"],
+ ],
+ )
+ def test_empty_int64(self, name, expected):
# with empty series (#4651)
- s = Series([], dtype=np.int64, name="foo")
- assert repr(s) == "Series([], Name: foo, dtype: int64)"
-
- s = Series([], dtype=np.int64, name=None)
- assert repr(s) == "Series([], dtype: int64)"
+ s = Series([], dtype=np.int64, name=name)
+ assert repr(s) == expected
def test_tidy_repr(self):
a = Series(["\u05d0"] * 1000)
diff --git a/pandas/tests/series/test_subclass.py b/pandas/tests/series/test_subclass.py
index c34dceab12749..fd6f4e0083b08 100644
--- a/pandas/tests/series/test_subclass.py
+++ b/pandas/tests/series/test_subclass.py
@@ -1,22 +1,22 @@
import numpy as np
+import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesSubclassing:
- def test_indexing_sliced(self):
+ @pytest.mark.parametrize(
+ "idx_method, indexer, exp_data, exp_idx",
+ [
+ ["loc", ["a", "b"], [1, 2], "ab"],
+ ["iloc", [2, 3], [3, 4], "cd"],
+ ],
+ )
+ def test_indexing_sliced(self, idx_method, indexer, exp_data, exp_idx):
s = tm.SubclassedSeries([1, 2, 3, 4], index=list("abcd"))
- res = s.loc[["a", "b"]]
- exp = tm.SubclassedSeries([1, 2], index=list("ab"))
- tm.assert_series_equal(res, exp)
-
- res = s.iloc[[2, 3]]
- exp = tm.SubclassedSeries([3, 4], index=list("cd"))
- tm.assert_series_equal(res, exp)
-
- res = s.loc[["a", "b"]]
- exp = tm.SubclassedSeries([1, 2], index=list("ab"))
+ res = getattr(s, idx_method)[indexer]
+ exp = tm.SubclassedSeries(exp_data, index=list(exp_idx))
tm.assert_series_equal(res, exp)
def test_to_frame(self):
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45078 | 2021-12-27T19:04:42Z | 2021-12-28T02:43:15Z | 2021-12-28T02:43:15Z | 2021-12-28T03:02:46Z |
DEPR: resample/groupby.pad/backfill in favor of ffill/bfill | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 241c005c400cd..8be3fd1f72cb3 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -609,6 +609,10 @@ Other Deprecations
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
+- Deprecated :meth:`.Groupby.pad` in favor of :meth:`.Groupby.ffill` (:issue:`33396`)
+- Deprecated :meth:`.Groupby.backfill` in favor of :meth:`.Groupby.bfill` (:issue:`33396`)
+- Deprecated :meth:`.Resample.pad` in favor of :meth:`.Resample.ffill` (:issue:`33396`)
+- Deprecated :meth:`.Resample.backfill` in favor of :meth:`.Resample.bfill` (:issue:`33396`)
- Deprecated ``numeric_only=None`` in :meth:`DataFrame.rank`; in a future version ``numeric_only`` must be either ``True`` or ``False`` (the default) (:issue:`45036`)
- Deprecated the behavior of :meth:`Timestamp.utcfromtimestamp`, in the future it will return a timezone-aware UTC :class:`Timestamp` (:issue:`22451`)
- Deprecated :meth:`NaT.freq` (:issue:`45071`)
diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py
index 48faa1fc46759..0c8474c9badc7 100644
--- a/pandas/core/groupby/base.py
+++ b/pandas/core/groupby/base.py
@@ -90,6 +90,17 @@ class OutputKey:
# List of transformation functions.
# a transformation is a function that, for each group,
# produces a result that has the same shape as the group.
+
+
+# TODO(2.0) Remove after pad/backfill deprecation enforced
+def maybe_normalize_deprecated_kernels(kernel):
+ if kernel == "backfill":
+ kernel = "bfill"
+ elif kernel == "pad":
+ kernel = "ffill"
+ return kernel
+
+
transformation_kernels = frozenset(
[
"backfill",
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index acf65a464a45f..afd25fdff7614 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -2547,7 +2547,7 @@ def blk_func(values: ArrayLike) -> ArrayLike:
@final
@Substitution(name="groupby")
- def pad(self, limit=None):
+ def ffill(self, limit=None):
"""
Forward fill the values.
@@ -2563,18 +2563,27 @@ def pad(self, limit=None):
See Also
--------
- Series.pad: Returns Series with minimum number of char in object.
- DataFrame.pad: Object with missing values filled or None if inplace=True.
+ Series.ffill: Returns Series with minimum number of char in object.
+ DataFrame.ffill: Object with missing values filled or None if inplace=True.
Series.fillna: Fill NaN values of a Series.
DataFrame.fillna: Fill NaN values of a DataFrame.
"""
return self._fill("ffill", limit=limit)
- ffill = pad
+ def pad(self, limit=None):
+ warnings.warn(
+ "pad is deprecated and will be removed in a future version. "
+ "Use ffill instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return self.ffill(limit=limit)
+
+ pad.__doc__ = ffill.__doc__
@final
@Substitution(name="groupby")
- def backfill(self, limit=None):
+ def bfill(self, limit=None):
"""
Backward fill the values.
@@ -2590,14 +2599,23 @@ def backfill(self, limit=None):
See Also
--------
- Series.backfill : Backward fill the missing values in the dataset.
- DataFrame.backfill: Backward fill the missing values in the dataset.
+ Series.bfill : Backward fill the missing values in the dataset.
+ DataFrame.bfill: Backward fill the missing values in the dataset.
Series.fillna: Fill NaN values of a Series.
DataFrame.fillna: Fill NaN values of a DataFrame.
"""
return self._fill("bfill", limit=limit)
- bfill = backfill
+ def backfill(self, limit=None):
+ warnings.warn(
+ "backfill is deprecated and will be removed in a future version. "
+ "Use bfill instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return self.bfill(limit=limit)
+
+ backfill.__doc__ = bfill.__doc__
@final
@Substitution(name="groupby")
@@ -3435,7 +3453,7 @@ def shift(self, periods=1, freq=None, axis=0, fill_value=None):
@final
@Substitution(name="groupby")
@Appender(_common_see_also)
- def pct_change(self, periods=1, fill_method="pad", limit=None, freq=None, axis=0):
+ def pct_change(self, periods=1, fill_method="ffill", limit=None, freq=None, axis=0):
"""
Calculate pct_change of each value to previous entry in group.
@@ -3457,7 +3475,7 @@ def pct_change(self, periods=1, fill_method="pad", limit=None, freq=None, axis=0
)
)
if fill_method is None: # GH30463
- fill_method = "pad"
+ fill_method = "ffill"
limit = 0
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes, axis=self.axis)
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index e00defcfcffd1..e0b9eac618bc9 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -11,6 +11,7 @@
final,
no_type_check,
)
+import warnings
import numpy as np
@@ -40,6 +41,7 @@
deprecate_nonkeyword_arguments,
doc,
)
+from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -509,7 +511,7 @@ def _wrap_result(self, result):
return result
- def pad(self, limit=None):
+ def ffill(self, limit=None):
"""
Forward fill the values.
@@ -527,9 +529,18 @@ def pad(self, limit=None):
Series.fillna: Fill NA/NaN values using the specified method.
DataFrame.fillna: Fill NA/NaN values using the specified method.
"""
- return self._upsample("pad", limit=limit)
+ return self._upsample("ffill", limit=limit)
+
+ def pad(self, limit=None):
+ warnings.warn(
+ "pad is deprecated and will be removed in a future version. "
+ "Use ffill instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return self.ffill(limit=limit)
- ffill = pad
+ pad.__doc__ = ffill.__doc__
def nearest(self, limit=None):
"""
@@ -591,7 +602,7 @@ def nearest(self, limit=None):
"""
return self._upsample("nearest", limit=limit)
- def backfill(self, limit=None):
+ def bfill(self, limit=None):
"""
Backward fill the new missing values in the resampled data.
@@ -618,7 +629,7 @@ def backfill(self, limit=None):
fillna : Fill NaN values using the specified method, which can be
'backfill'.
nearest : Fill NaN values with nearest neighbor starting from center.
- pad : Forward fill NaN values.
+ ffill : Forward fill NaN values.
Series.fillna : Fill NaN values in the Series using the
specified method, which can be 'backfill'.
DataFrame.fillna : Fill NaN values in the DataFrame using the
@@ -640,7 +651,7 @@ def backfill(self, limit=None):
2018-01-01 02:00:00 3
Freq: H, dtype: int64
- >>> s.resample('30min').backfill()
+ >>> s.resample('30min').bfill()
2018-01-01 00:00:00 1
2018-01-01 00:30:00 2
2018-01-01 01:00:00 2
@@ -648,7 +659,7 @@ def backfill(self, limit=None):
2018-01-01 02:00:00 3
Freq: 30T, dtype: int64
- >>> s.resample('15min').backfill(limit=2)
+ >>> s.resample('15min').bfill(limit=2)
2018-01-01 00:00:00 1.0
2018-01-01 00:15:00 NaN
2018-01-01 00:30:00 2.0
@@ -671,7 +682,7 @@ def backfill(self, limit=None):
2018-01-01 01:00:00 NaN 3
2018-01-01 02:00:00 6.0 5
- >>> df.resample('30min').backfill()
+ >>> df.resample('30min').bfill()
a b
2018-01-01 00:00:00 2.0 1
2018-01-01 00:30:00 NaN 3
@@ -679,7 +690,7 @@ def backfill(self, limit=None):
2018-01-01 01:30:00 6.0 5
2018-01-01 02:00:00 6.0 5
- >>> df.resample('15min').backfill(limit=2)
+ >>> df.resample('15min').bfill(limit=2)
a b
2018-01-01 00:00:00 2.0 1.0
2018-01-01 00:15:00 NaN NaN
@@ -691,9 +702,18 @@ def backfill(self, limit=None):
2018-01-01 01:45:00 6.0 5.0
2018-01-01 02:00:00 6.0 5.0
"""
- return self._upsample("backfill", limit=limit)
+ return self._upsample("bfill", limit=limit)
+
+ def backfill(self, limit=None):
+ warnings.warn(
+ "backfill is deprecated and will be removed in a future version. "
+ "Use bfill instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return self.bfill(limit=limit)
- bfill = backfill
+ backfill.__doc__ = bfill.__doc__
def fillna(self, method, limit=None):
"""
@@ -727,8 +747,8 @@ def fillna(self, method, limit=None):
See Also
--------
- backfill : Backward fill NaN values in the resampled data.
- pad : Forward fill NaN values in the resampled data.
+ bfill : Backward fill NaN values in the resampled data.
+ ffill : Forward fill NaN values in the resampled data.
nearest : Fill NaN values in the resampled data
with nearest neighbor starting from center.
interpolate : Fill NaN values using interpolation.
diff --git a/pandas/tests/apply/test_str.py b/pandas/tests/apply/test_str.py
index a292b05ee444d..82997328529cd 100644
--- a/pandas/tests/apply/test_str.py
+++ b/pandas/tests/apply/test_str.py
@@ -12,6 +12,7 @@
Series,
)
import pandas._testing as tm
+from pandas.core.groupby.base import maybe_normalize_deprecated_kernels
from pandas.tests.apply.common import (
frame_transform_kernels,
series_transform_kernels,
@@ -245,7 +246,8 @@ def test_agg_cython_table_transform_frame(df, func, expected, axis):
@pytest.mark.parametrize("op", series_transform_kernels)
def test_transform_groupby_kernel_series(string_series, op):
# GH 35964
-
+ # TODO(2.0) Remove after pad/backfill deprecation enforced
+ op = maybe_normalize_deprecated_kernels(op)
args = [0.0] if op == "fillna" else []
ones = np.ones(string_series.shape[0])
expected = string_series.groupby(ones).transform(op, *args)
@@ -257,6 +259,8 @@ def test_transform_groupby_kernel_series(string_series, op):
def test_transform_groupby_kernel_frame(
axis, float_frame, op, using_array_manager, request
):
+ # TODO(2.0) Remove after pad/backfill deprecation enforced
+ op = maybe_normalize_deprecated_kernels(op)
# GH 35964
if using_array_manager and op == "pct_change" and axis in (1, "columns"):
# TODO(ArrayManager) shift with axis=1
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 78631cafc722d..fb2b9f0632f0d 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -29,6 +29,7 @@
)
from pandas.core.base import SpecificationError
import pandas.core.common as com
+from pandas.core.groupby.base import maybe_normalize_deprecated_kernels
def test_repr():
@@ -2269,7 +2270,8 @@ def test_groupby_duplicate_index():
def test_dup_labels_output_shape(groupby_func, idx):
if groupby_func in {"size", "ngroup", "cumcount"}:
pytest.skip("Not applicable")
-
+ # TODO(2.0) Remove after pad/backfill deprecation enforced
+ groupby_func = maybe_normalize_deprecated_kernels(groupby_func)
df = DataFrame([[1, 1]], columns=idx)
grp_by = df.groupby([0])
@@ -2614,3 +2616,12 @@ def test_rolling_wrong_param_min_period():
result_error_msg = r"__init__\(\) got an unexpected keyword argument 'min_period'"
with pytest.raises(TypeError, match=result_error_msg):
test_df.groupby("name")["val"].rolling(window=2, min_period=1).sum()
+
+
+def test_pad_backfill_deprecation():
+ # GH 33396
+ s = Series([1, 2, 3])
+ with tm.assert_produces_warning(FutureWarning, match="backfill"):
+ s.groupby(level=0).backfill()
+ with tm.assert_produces_warning(FutureWarning, match="pad"):
+ s.groupby(level=0).pad()
diff --git a/pandas/tests/groupby/test_groupby_subclass.py b/pandas/tests/groupby/test_groupby_subclass.py
index 8008c6c98acc9..cc8d4176ca054 100644
--- a/pandas/tests/groupby/test_groupby_subclass.py
+++ b/pandas/tests/groupby/test_groupby_subclass.py
@@ -8,6 +8,7 @@
Series,
)
import pandas._testing as tm
+from pandas.core.groupby.base import maybe_normalize_deprecated_kernels
@pytest.mark.parametrize(
@@ -23,7 +24,8 @@ def test_groupby_preserves_subclass(obj, groupby_func):
if isinstance(obj, Series) and groupby_func in {"corrwith"}:
pytest.skip("Not applicable")
-
+ # TODO(2.0) Remove after pad/backfill deprecation enforced
+ groupby_func = maybe_normalize_deprecated_kernels(groupby_func)
grouped = obj.groupby(np.arange(0, 10))
# Groups should preserve subclass type
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index 2057486ae401a..12a25a1e61211 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -20,6 +20,7 @@
date_range,
)
import pandas._testing as tm
+from pandas.core.groupby.base import maybe_normalize_deprecated_kernels
from pandas.core.groupby.generic import (
DataFrameGroupBy,
SeriesGroupBy,
@@ -171,6 +172,9 @@ def test_transform_axis_1(request, transformation_func, using_array_manager):
request.node.add_marker(
pytest.mark.xfail(reason="ArrayManager: shift axis=1 not yet implemented")
)
+ # TODO(2.0) Remove after pad/backfill deprecation enforced
+ transformation_func = maybe_normalize_deprecated_kernels(transformation_func)
+
warn = None
if transformation_func == "tshift":
warn = FutureWarning
@@ -357,7 +361,8 @@ def test_transform_transformation_func(request, transformation_func):
},
index=date_range("2020-01-01", "2020-01-07"),
)
-
+ # TODO(2.0) Remove after pad/backfill deprecation enforced
+ transformation_func = maybe_normalize_deprecated_kernels(transformation_func)
if transformation_func == "cumcount":
test_op = lambda x: x.transform("cumcount")
mock_op = lambda x: Series(range(len(x)), x.index)
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index 6a039e6e22f60..8b4fc4e84baab 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -438,7 +438,7 @@ def test_resample_upsample():
s = Series(np.random.rand(len(dti)), dti)
# to minutely, by padding
- result = s.resample("Min").pad()
+ result = s.resample("Min").ffill()
assert len(result) == 12961
assert result[0] == s[0]
assert result[-1] == s[-1]
@@ -1810,7 +1810,7 @@ def test_resample_calendar_day_with_dst(
):
# GH 35219
ts = Series(1.0, date_range(first, last, freq=freq_in, tz="Europe/Amsterdam"))
- result = ts.resample(freq_out).pad()
+ result = ts.resample(freq_out).ffill()
expected = Series(
1.0, date_range(first, exp_last, freq=freq_out, tz="Europe/Amsterdam")
)
diff --git a/pandas/tests/resample/test_deprecated.py b/pandas/tests/resample/test_deprecated.py
index 3aac7a961fa19..126ca05ca1546 100644
--- a/pandas/tests/resample/test_deprecated.py
+++ b/pandas/tests/resample/test_deprecated.py
@@ -305,3 +305,12 @@ def test_interpolate_posargs_deprecation():
expected.index._data.freq = "3s"
tm.assert_series_equal(result, expected)
+
+
+def test_pad_backfill_deprecation():
+ # GH 33396
+ s = Series([1, 2, 3], index=date_range("20180101", periods=3, freq="h"))
+ with tm.assert_produces_warning(FutureWarning, match="backfill"):
+ s.resample("30min").backfill()
+ with tm.assert_produces_warning(FutureWarning, match="pad"):
+ s.resample("30min").pad()
diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py
index 594b6b44aafa1..dab340486cd8c 100644
--- a/pandas/tests/resample/test_resampler_grouper.py
+++ b/pandas/tests/resample/test_resampler_grouper.py
@@ -227,7 +227,7 @@ def test_methods():
expected = g.B.apply(lambda x: getattr(x.resample("2s"), f)())
tm.assert_series_equal(result, expected)
- for f in ["nearest", "backfill", "ffill", "asfreq"]:
+ for f in ["nearest", "bfill", "ffill", "asfreq"]:
result = getattr(r, f)()
expected = g.apply(lambda x: getattr(x.resample("2s"), f)())
tm.assert_frame_equal(result, expected)
| - [x] closes #33396
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45076 | 2021-12-27T01:44:18Z | 2021-12-28T21:23:42Z | 2021-12-28T21:23:42Z | 2021-12-28T21:27:57Z |
Groupby Agg not working if different partials with same name on the same column | diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 2ab553434873c..4932f77ec0908 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -62,6 +62,26 @@ def test_agg_ser_multi_key(df):
tm.assert_series_equal(results, expected)
+def test_agg_different_partials():
+ # GH 28570
+
+ quant50 = partial(np.percentile, q=50)
+ quant50.__name__ = "quant50"
+ quant70 = partial(np.percentile, q=70)
+ quant70.__name__ = "quant70"
+
+ df = pd.DataFrame({"col1": ["a", "a", "b", "b", "b"], "col2": [1, 2, 3, 4, 5]})
+ result = df.groupby("col1").agg({"col2": [quant50, quant70]})
+
+ expected = pd.DataFrame(
+ {"col1": ["a", "b"], "quant50": [1.5, 4.0], "quant70": [1.7, 4.4]}
+ )
+ expected = expected.set_index("col1")
+ expected.columns = pd.MultiIndex.from_product([["col2"], expected.columns])
+
+ tm.assert_frame_equal(result, expected)
+
+
def test_groupby_aggregation_mixed_dtype():
# GH 6212
expected = DataFrame(
| - [x] closes #28570
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
a unit test was added in accordance with issue [28570](https://github.com/pandas-dev/pandas/issues/28570). It asserts the equality of the expected output with the tested df.
| https://api.github.com/repos/pandas-dev/pandas/pulls/45075 | 2021-12-26T23:56:59Z | 2022-03-06T01:33:44Z | null | 2022-03-06T01:33:44Z |
DOC: version kwargs in build_table_schema | diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py
index cb2d426f6b81b..c630f0d7613e0 100644
--- a/pandas/io/json/_table_schema.py
+++ b/pandas/io/json/_table_schema.py
@@ -231,7 +231,8 @@ def build_table_schema(
level or levels if the index is unique.
version : bool, default True
Whether to include a field `pandas_version` with the version
- of pandas that generated the schema.
+ of pandas that last revised the table schema. This version
+ can be different from the installed pandas version.
Returns
-------
| - [x] closes #28455
| https://api.github.com/repos/pandas-dev/pandas/pulls/45074 | 2021-12-26T19:59:53Z | 2021-12-27T13:43:54Z | 2021-12-27T13:43:53Z | 2021-12-27T18:43:16Z |
CI/TST: Ignore Matplotlib related ResouceWarnings from assert_produces_warning | diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py
index b78cfd3fb39fb..44a62e607555e 100644
--- a/pandas/_testing/_warnings.py
+++ b/pandas/_testing/_warnings.py
@@ -2,6 +2,7 @@
from contextlib import contextmanager
import re
+import subprocess
from typing import (
Sequence,
Type,
@@ -147,17 +148,27 @@ def _assert_caught_no_extra_warnings(
for actual_warning in caught_warnings:
if _is_unexpected_warning(actual_warning, expected_warning):
- # GH 44732: Don't make the CI flaky by filtering SSL-related
- # ResourceWarning from dependencies
# GH#38630 pytest.filterwarnings does not suppress these.
- unclosed_ssl = (
- "unclosed transport <asyncio.sslproto._SSLProtocolTransport",
- "unclosed <ssl.SSLSocket",
- )
- if actual_warning.category == ResourceWarning and any(
- msg in str(actual_warning.message) for msg in unclosed_ssl
- ):
- continue
+ if actual_warning.category == ResourceWarning:
+ # GH 44732: Don't make the CI flaky by filtering SSL-related
+ # ResourceWarning from dependencies
+ unclosed_ssl = (
+ "unclosed transport <asyncio.sslproto._SSLProtocolTransport",
+ "unclosed <ssl.SSLSocket",
+ )
+ if any(msg in str(actual_warning.message) for msg in unclosed_ssl):
+ continue
+ # GH 44844: Matplotlib leaves font files open during the entire process
+ # Don't make CI flaky if ResourceWarning raised due to these open files.
+ try:
+ lsof = subprocess.check_output(
+ ["lsof", "-d", "0-25", "-F", "n"]
+ ).decode("utf-8")
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ # FileNotFoundError for Windows
+ lsof = ""
+ if re.search(r"\.ttf|\.ttc|\.otf", lsof):
+ continue
extra_warnings.append(
(
| cc @jbrockmendel went with a version of 7) in https://github.com/pandas-dev/pandas/issues/44844#issuecomment-998216752
Couldn't find a reliable way to close font files from Matplotlib, so if `ResourceWarning` is seen while a font file is open fromm `lsof`, ignore.
| https://api.github.com/repos/pandas-dev/pandas/pulls/45073 | 2021-12-26T06:30:44Z | 2021-12-27T13:45:42Z | 2021-12-27T13:45:42Z | 2021-12-27T18:45:22Z |
DEPR/ENH: support axis=None in min/max | diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py
index 9a646ddc6ca7e..7fa231846e721 100644
--- a/pandas/core/arraylike.py
+++ b/pandas/core/arraylike.py
@@ -521,10 +521,12 @@ def dispatch_reduction_ufunc(self, ufunc: np.ufunc, method: str, *inputs, **kwar
if "axis" not in kwargs:
# For DataFrame reductions we don't want the default axis=0
- # FIXME: DataFrame.min ignores axis=None
- # FIXME: np.minimum.reduce(df) gets here bc axis is not in kwargs,
- # but np.minimum.reduce(df.values) behaves as if axis=0
- kwargs["axis"] = None
+ # Note: np.min is not a ufunc, but uses array_function_dispatch,
+ # so calls DataFrame.min (without ever getting here) with the np.min
+ # default of axis=None, which DataFrame.min catches and changes to axis=0.
+ # np.minimum.reduce(df) gets here bc axis is not in kwargs,
+ # so we set axis=0 to match the behaviorof np.minimum.reduce(df.values)
+ kwargs["axis"] = 0
# By default, numpy's reductions do not skip NaNs, so we have to
# pass skipna=False
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 2ebdfccc88f4e..e3989238be849 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -562,7 +562,14 @@ def require_length_match(data, index: Index):
)
-_builtin_table = {builtins.sum: np.sum, builtins.max: np.max, builtins.min: np.min}
+# the ufuncs np.maximum.reduce and np.minimum.reduce default to axis=0,
+# whereas np.min and np.max (which directly call obj.min and obj.max)
+# default to axis=None.
+_builtin_table = {
+ builtins.sum: np.sum,
+ builtins.max: np.maximum.reduce,
+ builtins.min: np.minimum.reduce,
+}
_cython_table = {
builtins.sum: "sum",
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index d85c15493bed1..de40ad36a7d02 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -10556,7 +10556,7 @@ def _stat_function(
self,
name: str,
func,
- axis: Axis | None = None,
+ axis: Axis | None | lib.NoDefault = None,
skipna: bool_t = True,
level: Level | None = None,
numeric_only: bool_t | None = None,
@@ -10569,8 +10569,22 @@ def _stat_function(
validate_bool_kwarg(skipna, "skipna", none_allowed=False)
+ if axis is None and level is None and self.ndim > 1:
+ # user must have explicitly passed axis=None
+ # GH#21597
+ warnings.warn(
+ f"In a future version, DataFrame.{name}(axis=None) will return a "
+ f"scalar {name} over the entire DataFrame. To retain the old "
+ f"behavior, use 'frame.{name}(axis=0)' or just 'frame.{name}()'",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ if axis is lib.no_default:
+ axis = None
+
if axis is None:
axis = self._stat_axis_number
+ axis = cast(Axis, axis)
if level is not None:
warnings.warn(
"Using the level keyword in DataFrame and Series aggregations is "
@@ -10588,31 +10602,43 @@ def _stat_function(
def min(
self,
- axis: Axis | None = None,
+ axis: Axis | None | lib.NoDefault = lib.no_default,
skipna: bool_t = True,
level: Level | None = None,
numeric_only: bool_t | None = None,
**kwargs,
):
return self._stat_function(
- "min", nanops.nanmin, axis, skipna, level, numeric_only, **kwargs
+ "min",
+ nanops.nanmin,
+ axis,
+ skipna,
+ level,
+ numeric_only,
+ **kwargs,
)
def max(
self,
- axis: Axis | None = None,
+ axis: Axis | None | lib.NoDefault = lib.no_default,
skipna: bool_t = True,
level: Level | None = None,
numeric_only: bool_t | None = None,
**kwargs,
):
return self._stat_function(
- "max", nanops.nanmax, axis, skipna, level, numeric_only, **kwargs
+ "max",
+ nanops.nanmax,
+ axis,
+ skipna,
+ level,
+ numeric_only,
+ **kwargs,
)
def mean(
self,
- axis: Axis | None = None,
+ axis: Axis | None | lib.NoDefault = lib.no_default,
skipna: bool_t = True,
level: Level | None = None,
numeric_only: bool_t | None = None,
@@ -10624,7 +10650,7 @@ def mean(
def median(
self,
- axis: Axis | None = None,
+ axis: Axis | None | lib.NoDefault = lib.no_default,
skipna: bool_t = True,
level: Level | None = None,
numeric_only: bool_t | None = None,
@@ -10636,7 +10662,7 @@ def median(
def skew(
self,
- axis: Axis | None = None,
+ axis: Axis | None | lib.NoDefault = lib.no_default,
skipna: bool_t = True,
level: Level | None = None,
numeric_only: bool_t | None = None,
@@ -10648,7 +10674,7 @@ def skew(
def kurt(
self,
- axis: Axis | None = None,
+ axis: Axis | None | lib.NoDefault = lib.no_default,
skipna: bool_t = True,
level: Level | None = None,
numeric_only: bool_t | None = None,
@@ -10699,6 +10725,7 @@ def _min_count_stat_function(
min_count=min_count,
numeric_only=numeric_only,
)
+
return self._reduce(
func,
name=name,
@@ -11039,7 +11066,14 @@ def prod(
see_also="",
examples="",
)
- def mean(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
+ def mean(
+ self,
+ axis: int | None | lib.NoDefault = lib.no_default,
+ skipna=True,
+ level=None,
+ numeric_only=None,
+ **kwargs,
+ ):
return NDFrame.mean(self, axis, skipna, level, numeric_only, **kwargs)
setattr(cls, "mean", mean)
@@ -11054,7 +11088,14 @@ def mean(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
see_also="",
examples="",
)
- def skew(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
+ def skew(
+ self,
+ axis: int | None | lib.NoDefault = lib.no_default,
+ skipna=True,
+ level=None,
+ numeric_only=None,
+ **kwargs,
+ ):
return NDFrame.skew(self, axis, skipna, level, numeric_only, **kwargs)
setattr(cls, "skew", skew)
@@ -11072,7 +11113,14 @@ def skew(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
see_also="",
examples="",
)
- def kurt(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
+ def kurt(
+ self,
+ axis: Axis | None | lib.NoDefault = lib.no_default,
+ skipna=True,
+ level=None,
+ numeric_only=None,
+ **kwargs,
+ ):
return NDFrame.kurt(self, axis, skipna, level, numeric_only, **kwargs)
setattr(cls, "kurt", kurt)
@@ -11089,13 +11137,19 @@ def kurt(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
examples="",
)
def median(
- self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs
+ self,
+ axis: int | None | lib.NoDefault = lib.no_default,
+ skipna=True,
+ level=None,
+ numeric_only=None,
+ **kwargs,
):
return NDFrame.median(self, axis, skipna, level, numeric_only, **kwargs)
setattr(cls, "median", median)
- @doc(
+ # error: Untyped decorator makes function "max" untyped
+ @doc( # type: ignore[misc]
_num_doc,
desc="Return the maximum of the values over the requested axis.\n\n"
"If you want the *index* of the maximum, use ``idxmax``. This is "
@@ -11107,12 +11161,20 @@ def median(
see_also=_stat_func_see_also,
examples=_max_examples,
)
- def max(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
+ def max(
+ self,
+ axis: int | None | lib.NoDefault = lib.no_default,
+ skipna=True,
+ level=None,
+ numeric_only=None,
+ **kwargs,
+ ):
return NDFrame.max(self, axis, skipna, level, numeric_only, **kwargs)
setattr(cls, "max", max)
- @doc(
+ # error: Untyped decorator makes function "max" untyped
+ @doc( # type: ignore[misc]
_num_doc,
desc="Return the minimum of the values over the requested axis.\n\n"
"If you want the *index* of the minimum, use ``idxmin``. This is "
@@ -11124,7 +11186,14 @@ def max(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
see_also=_stat_func_see_also,
examples=_min_examples,
)
- def min(self, axis=None, skipna=True, level=None, numeric_only=None, **kwargs):
+ def min(
+ self,
+ axis: int | None | lib.NoDefault = lib.no_default,
+ skipna=True,
+ level=None,
+ numeric_only=None,
+ **kwargs,
+ ):
return NDFrame.min(self, axis, skipna, level, numeric_only, **kwargs)
setattr(cls, "min", min)
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 6429544869ac2..585176fc6a2d7 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -1765,3 +1765,20 @@ def test_prod_sum_min_count_mixed_object():
msg = re.escape("unsupported operand type(s) for +: 'int' and 'str'")
with pytest.raises(TypeError, match=msg):
df.sum(axis=0, min_count=1, numeric_only=False)
+
+
+@pytest.mark.parametrize("method", ["min", "max", "mean", "median", "skew", "kurt"])
+def test_reduction_axis_none_deprecation(method):
+ # GH#21597 deprecate axis=None defaulting to axis=0 so that we can change it
+ # to reducing over all axes.
+
+ df = DataFrame(np.random.randn(4, 4))
+ meth = getattr(df, method)
+
+ msg = f"scalar {method} over the entire DataFrame"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = meth(axis=None)
+ with tm.assert_produces_warning(None):
+ expected = meth()
+ tm.assert_series_equal(res, expected)
+ tm.assert_series_equal(res, meth(axis=0))
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 585491f8664b3..5ae929be1d8cf 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -81,7 +81,7 @@ def get_stats(group):
assert result.index.names[0] == "C"
-def test_basic():
+def test_basic(): # TODO: split this test
cats = Categorical(
["a", "a", "a", "b", "b", "b", "c", "c", "c"],
@@ -142,9 +142,24 @@ def f(x):
df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"]
)
tm.assert_frame_equal(df.groupby(c, observed=False).transform(sum), df[["a"]])
- tm.assert_frame_equal(
- df.groupby(c, observed=False).transform(lambda xs: np.max(xs)), df[["a"]]
- )
+
+ gbc = df.groupby(c, observed=False)
+ with tm.assert_produces_warning(
+ FutureWarning, match="scalar max", check_stacklevel=False
+ ):
+ # stacklevel is thrown off (i think) bc the stack goes through numpy C code
+ result = gbc.transform(lambda xs: np.max(xs))
+ tm.assert_frame_equal(result, df[["a"]])
+
+ with tm.assert_produces_warning(None):
+ result2 = gbc.transform(lambda xs: np.max(xs, axis=0))
+ result3 = gbc.transform(max)
+ result4 = gbc.transform(np.maximum.reduce)
+ result5 = gbc.transform(lambda xs: np.maximum.reduce(xs))
+ tm.assert_frame_equal(result2, df[["a"]], check_dtype=False)
+ tm.assert_frame_equal(result3, df[["a"]], check_dtype=False)
+ tm.assert_frame_equal(result4, df[["a"]])
+ tm.assert_frame_equal(result5, df[["a"]])
# Filter
tm.assert_series_equal(df.a.groupby(c, observed=False).filter(np.all), df["a"])
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index 39a3e82fc2d98..06f00634802b4 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -69,20 +69,33 @@ def test_builtins_apply(keys, f):
df = DataFrame(np.random.randint(1, 50, (1000, 2)), columns=["jim", "joe"])
df["jolie"] = np.random.randn(1000)
+ gb = df.groupby(keys)
+
fname = f.__name__
- result = df.groupby(keys).apply(f)
+ result = gb.apply(f)
ngroups = len(df.drop_duplicates(subset=keys))
assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))"
assert result.shape == (ngroups, 3), assert_msg
- tm.assert_frame_equal(
- result, # numpy's equivalent function
- df.groupby(keys).apply(getattr(np, fname)),
- )
+ npfunc = getattr(np, fname) # numpy's equivalent function
+ if f in [max, min]:
+ warn = FutureWarning
+ else:
+ warn = None
+ msg = "scalar (max|min) over the entire DataFrame"
+ with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
+ # stacklevel can be thrown off because (i think) the stack
+ # goes through some of numpy's C code.
+ expected = gb.apply(npfunc)
+ tm.assert_frame_equal(result, expected)
+
+ with tm.assert_produces_warning(None):
+ expected2 = gb.apply(lambda x: npfunc(x, axis=0))
+ tm.assert_frame_equal(result, expected2)
if f != sum:
- expected = df.groupby(keys).agg(fname).reset_index()
+ expected = gb.agg(fname).reset_index()
expected.set_index(keys, inplace=True, drop=False)
tm.assert_frame_equal(result, expected, check_dtype=False)
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index 1e78bb1e58583..2057486ae401a 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -483,9 +483,16 @@ def test_transform_coercion():
g = df.groupby("A")
expected = g.transform(np.mean)
- result = g.transform(lambda x: np.mean(x))
+
+ msg = "will return a scalar mean"
+ with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False):
+ result = g.transform(lambda x: np.mean(x))
tm.assert_frame_equal(result, expected)
+ with tm.assert_produces_warning(None):
+ result2 = g.transform(lambda x: np.mean(x, axis=0))
+ tm.assert_frame_equal(result2, expected)
+
def test_groupby_transform_with_int():
diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py
index ad43a02724960..7ba81e84dfe3e 100644
--- a/pandas/tests/window/test_expanding.py
+++ b/pandas/tests/window/test_expanding.py
@@ -348,7 +348,12 @@ def test_expanding_corr_pairwise(frame):
@pytest.mark.parametrize(
"func,static_comp",
- [("sum", np.sum), ("mean", np.mean), ("max", np.max), ("min", np.min)],
+ [
+ ("sum", np.sum),
+ ("mean", lambda x: np.mean(x, axis=0)),
+ ("max", lambda x: np.max(x, axis=0)),
+ ("min", lambda x: np.min(x, axis=0)),
+ ],
ids=["sum", "mean", "max", "min"],
)
def test_expanding_func(func, static_comp, frame_or_series):
@@ -356,12 +361,11 @@ def test_expanding_func(func, static_comp, frame_or_series):
result = getattr(data.expanding(min_periods=1, axis=0), func)()
assert isinstance(result, frame_or_series)
+ expected = static_comp(data[:11])
if frame_or_series is Series:
- tm.assert_almost_equal(result[10], static_comp(data[:11]))
+ tm.assert_almost_equal(result[10], expected)
else:
- tm.assert_series_equal(
- result.iloc[10], static_comp(data[:11]), check_names=False
- )
+ tm.assert_series_equal(result.iloc[10], expected, check_names=False)
@pytest.mark.parametrize(
@@ -404,9 +408,11 @@ def test_expanding_apply(engine_and_raw, frame_or_series):
assert isinstance(result, frame_or_series)
if frame_or_series is Series:
- tm.assert_almost_equal(result[9], np.mean(data[:11]))
+ tm.assert_almost_equal(result[9], np.mean(data[:11], axis=0))
else:
- tm.assert_series_equal(result.iloc[9], np.mean(data[:11]), check_names=False)
+ tm.assert_series_equal(
+ result.iloc[9], np.mean(data[:11], axis=0), check_names=False
+ )
def test_expanding_min_periods_apply(engine_and_raw):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
Deprecate the current axis=None behavior so we can change it in 2.0 xref #21597 | https://api.github.com/repos/pandas-dev/pandas/pulls/45072 | 2021-12-26T04:33:12Z | 2021-12-28T14:57:40Z | 2021-12-28T14:57:40Z | 2021-12-28T17:00:21Z |
CLN: comments, docstrings, depr NaT.freq | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index ccad93d83eb5b..adffeec3f533a 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -547,6 +547,7 @@ Other Deprecations
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
+- Deprecated :meth:`NaT.freq` (:issue:`45071`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index 77d3f954a9a5d..0446b675e07d7 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -1228,9 +1228,7 @@ cdef class PyObjectHashTable(HashTable):
hash(val)
if ignore_na and (
- (val is C_NA)
- or (val != val)
- or (val is None)
+ checknull(val)
or (use_na_value and val == na_value)
):
# if missing values do not count as unique values (i.e. if
diff --git a/pandas/_libs/tslibs/nattype.pxd b/pandas/_libs/tslibs/nattype.pxd
index b7c14e0a5b068..5e5f4224f902f 100644
--- a/pandas/_libs/tslibs/nattype.pxd
+++ b/pandas/_libs/tslibs/nattype.pxd
@@ -10,7 +10,6 @@ cdef set c_nat_strings
cdef class _NaT(datetime):
cdef readonly:
int64_t value
- object freq
cdef _NaT c_NaT
diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx
index 141bc01716c4d..ab832c145a052 100644
--- a/pandas/_libs/tslibs/nattype.pyx
+++ b/pandas/_libs/tslibs/nattype.pyx
@@ -357,10 +357,18 @@ class NaTType(_NaT):
base = _NaT.__new__(cls, 1, 1, 1)
base.value = NPY_NAT
- base.freq = None
return base
+ @property
+ def freq(self):
+ warnings.warn(
+ "NaT.freq is deprecated and will be removed in a future version.",
+ FutureWarning,
+ stacklevel=1,
+ )
+ return None
+
def __reduce_ex__(self, protocol):
# python 3.6 compat
# https://bugs.python.org/issue28730
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index 5154626dc3c7c..2e9f92ebc7cb7 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -1078,6 +1078,8 @@ def shares_memory(left, right) -> bool:
return shares_memory(left._ndarray, right)
if isinstance(left, pd.core.arrays.SparseArray):
return shares_memory(left.sp_values, right)
+ if isinstance(left, pd.core.arrays.IntervalArray):
+ return shares_memory(left._left, right) or shares_memory(left._right, right)
if isinstance(left, ExtensionArray) and left.dtype == "string[pyarrow]":
# https://github.com/pandas-dev/pandas/pull/43930#discussion_r736862669
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index b12e5be7722d0..5e82e4e1d2426 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -119,7 +119,7 @@ def _ensure_data(values: ArrayLike) -> np.ndarray:
This will coerce:
- ints -> int64
- uint -> uint64
- - bool -> uint64 (TODO this should be uint8)
+ - bool -> uint8
- datetimelike -> i8
- datetime64tz -> i8 (in local tz)
- categorical -> codes
@@ -899,7 +899,6 @@ def value_counts_arraylike(values, dropna: bool):
original = values
values = _ensure_data(values)
- # TODO: handle uint8
keys, counts = htable.value_count(values, dropna)
if needs_i8_conversion(original.dtype):
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index fc915f5f84d8b..c27ed13d6dd1e 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -1500,6 +1500,11 @@ def _fill_mask_inplace(
def _empty(cls, shape: Shape, dtype: ExtensionDtype):
"""
Create an ExtensionArray with the given shape and dtype.
+
+ See also
+ --------
+ ExtensionDtype.empty
+ ExtensionDtype.empty is the 'official' public version of this API.
"""
obj = cls._from_sequence([], dtype=dtype)
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 53fc38a973110..42dff27866d84 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -355,6 +355,8 @@ def copy(self) -> ArrowStringArray:
"""
Return a shallow copy of the array.
+ Underlying ChunkedArray is immutable, so a deep copy is unnecessary.
+
Returns
-------
ArrowStringArray
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index cf8cd070ec562..17fa2d6e2f388 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -388,10 +388,9 @@ def extract_array(
----------
obj : object
For Series / Index, the underlying ExtensionArray is unboxed.
- For Numpy-backed ExtensionArrays, the ndarray is extracted.
extract_numpy : bool, default False
- Whether to extract the ndarray from a PandasArray
+ Whether to extract the ndarray from a PandasArray.
extract_range : bool, default False
If we have a RangeIndex, return range._values if True
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index afd0d69e7e829..fa07b5fea5ea3 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -215,6 +215,10 @@ def empty(self, shape: Shape) -> type_t[ExtensionArray]:
Analogous to numpy.empty.
+ Parameters
+ ----------
+ shape : int or tuple[int]
+
Returns
-------
ExtensionArray
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 03c9addefecc0..794fb2afc7f9e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5847,6 +5847,9 @@ def isna(self) -> DataFrame:
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isnull(self) -> DataFrame:
+ """
+ DataFrame.isnull is an alias for DataFrame.isna.
+ """
return self.isna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
@@ -5855,6 +5858,9 @@ def notna(self) -> DataFrame:
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notnull(self) -> DataFrame:
+ """
+ DataFrame.notnull is an alias for DataFrame.notna.
+ """
return ~self.isna()
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self"])
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index edd3599aabe35..8949ad3c8fca0 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -221,9 +221,7 @@ def __internal_pivot_table(
table = table.sort_index(axis=1)
if fill_value is not None:
- _table = table.fillna(fill_value, downcast="infer")
- assert _table is not None # needed for mypy
- table = _table
+ table = table.fillna(fill_value, downcast="infer")
if margins:
if dropna:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 15805c0aa94ed..746512e8fb7d6 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -5231,6 +5231,9 @@ def isna(self) -> Series:
# error: Cannot determine type of 'isna'
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) # type: ignore[has-type]
def isnull(self) -> Series:
+ """
+ Series.isnull is an alias for Series.isna.
+ """
return super().isnull()
# error: Cannot determine type of 'notna'
@@ -5241,6 +5244,9 @@ def notna(self) -> Series:
# error: Cannot determine type of 'notna'
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) # type: ignore[has-type]
def notnull(self) -> Series:
+ """
+ Series.notnull is an alias for Series.notna.
+ """
return super().notnull()
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self"])
diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py
index 8372ec92ec26e..e4fbbc07c688a 100644
--- a/pandas/tests/base/test_misc.py
+++ b/pandas/tests/base/test_misc.py
@@ -21,6 +21,19 @@
import pandas._testing as tm
+def test_isnull_notnull_docstrings():
+ # GH#41855 make sure its clear these are aliases
+ doc = pd.DataFrame.notnull.__doc__
+ assert doc.startswith("\nDataFrame.notnull is an alias for DataFrame.notna.\n")
+ doc = pd.DataFrame.isnull.__doc__
+ assert doc.startswith("\nDataFrame.isnull is an alias for DataFrame.isna.\n")
+
+ doc = Series.notnull.__doc__
+ assert doc.startswith("\nSeries.notnull is an alias for Series.notna.\n")
+ doc = Series.isnull.__doc__
+ assert doc.startswith("\nSeries.isnull is an alias for Series.isna.\n")
+
+
@pytest.mark.parametrize(
"op_name, op",
[
diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py
index cfb3b504f7a79..7850a20efc878 100644
--- a/pandas/tests/scalar/test_nat.py
+++ b/pandas/tests/scalar/test_nat.py
@@ -718,3 +718,8 @@ def test_pickle():
# GH#4606
p = tm.round_trip_pickle(NaT)
assert p is NaT
+
+
+def test_freq_deprecated():
+ with tm.assert_produces_warning(FutureWarning, match="deprecated"):
+ NaT.freq
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 013af7eb90cd3..2adb9933da662 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -1649,7 +1649,8 @@ def test_to_datetime_respects_dayfirst(self, cache):
with pytest.raises(ValueError, match=msg):
# if dayfirst is respected, then this would parse as month=13, which
# would raise
- to_datetime("01-13-2012", dayfirst=True, cache=cache)
+ with tm.assert_produces_warning(UserWarning, match="Provide format"):
+ to_datetime("01-13-2012", dayfirst=True, cache=cache)
def test_to_datetime_on_datetime64_series(self, cache):
# #2699
diff --git a/pandas/tests/util/test_shares_memory.py b/pandas/tests/util/test_shares_memory.py
new file mode 100644
index 0000000000000..ed8227a5c4307
--- /dev/null
+++ b/pandas/tests/util/test_shares_memory.py
@@ -0,0 +1,13 @@
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_shares_memory_interval():
+ obj = pd.interval_range(1, 5)
+
+ assert tm.shares_memory(obj, obj)
+ assert tm.shares_memory(obj, obj._data)
+ assert tm.shares_memory(obj, obj[::-1])
+ assert tm.shares_memory(obj, obj[:2])
+
+ assert not tm.shares_memory(obj, obj._data.copy())
diff --git a/setup.py b/setup.py
index ca71510c5f051..db65ea72e4a96 100755
--- a/setup.py
+++ b/setup.py
@@ -392,8 +392,8 @@ def run(self):
# ----------------------------------------------------------------------
# Specification of Dependencies
-# TODO: Need to check to see if e.g. `linetrace` has changed and possibly
-# re-compile.
+# TODO(cython#4518): Need to check to see if e.g. `linetrace` has changed and
+# possibly re-compile.
def maybe_cythonize(extensions, *args, **kwargs):
"""
Render tempita templates before calling cythonize. This is skipped for
| - [x] closes #41855
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45071 | 2021-12-26T00:11:39Z | 2021-12-27T13:50:45Z | 2021-12-27T13:50:44Z | 2021-12-27T16:04:22Z |
TYP: Add new variable and then convert to ndarray in timedeltas.py | diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index 4e58ebc518bb4..79387cc2584da 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -748,12 +748,8 @@ def __rfloordiv__(self, other):
return result
elif is_object_dtype(other.dtype):
- # error: Incompatible types in assignment (expression has type
- # "List[Any]", variable has type "ndarray")
- result = [ # type: ignore[assignment]
- other[n] // self[n] for n in range(len(self))
- ]
- result = np.array(result)
+ result_list = [other[n] // self[n] for n in range(len(self))]
+ result = np.array(result_list)
return result
else:
| xref #37715
Added a ```result_list``` which is then converted to ndarray for ````result```` to return.
| https://api.github.com/repos/pandas-dev/pandas/pulls/45068 | 2021-12-25T16:27:29Z | 2021-12-27T00:06:34Z | 2021-12-27T00:06:34Z | 2021-12-27T14:24:14Z |
TYP: mypy 0.930 and pyright 1.1.200 | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b9a85e25e60ef..d862fa1086f97 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -55,7 +55,7 @@ jobs:
- name: Install pyright
# note: keep version in sync with .pre-commit-config.yaml
- run: npm install -g pyright@1.1.171
+ run: npm install -g pyright@1.1.200
- name: Build Pandas
uses: ./.github/actions/build_pandas
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index ea15e135455ba..c222f810441f5 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -88,7 +88,7 @@ repos:
types: [python]
stages: [manual]
# note: keep version in sync with .github/workflows/ci.yml
- additional_dependencies: ['pyright@1.1.171']
+ additional_dependencies: ['pyright@1.1.200']
- repo: local
hooks:
- id: flake8-rst
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 7218c77e43409..c47752d521f49 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -398,7 +398,7 @@ If installed, we now require:
+-----------------+-----------------+----------+---------+
| pytest (dev) | 6.0 | | |
+-----------------+-----------------+----------+---------+
-| mypy (dev) | 0.920 | | X |
+| mypy (dev) | 0.930 | | X |
+-----------------+-----------------+----------+---------+
For `optional libraries <https://pandas.pydata.org/docs/getting_started/install.html>`_ the general recommendation is to use the latest version.
diff --git a/environment.yml b/environment.yml
index 0e303d1fa7da2..18f5d6f19297d 100644
--- a/environment.yml
+++ b/environment.yml
@@ -24,7 +24,7 @@ dependencies:
- flake8-bugbear=21.3.2 # used by flake8, find likely bugs
- flake8-comprehensions=3.1.0 # used by flake8, linting of unnecessary comprehensions
- isort>=5.2.1 # check that imports are in the right order
- - mypy=0.920
+ - mypy=0.930
- pre-commit>=2.9.2
- pycodestyle # used by flake8
- pyupgrade
diff --git a/pandas/compat/chainmap.py b/pandas/compat/chainmap.py
index 035963e8255ea..9af7962fe4ad0 100644
--- a/pandas/compat/chainmap.py
+++ b/pandas/compat/chainmap.py
@@ -1,8 +1,6 @@
from typing import (
ChainMap,
- MutableMapping,
TypeVar,
- cast,
)
_KT = TypeVar("_KT")
@@ -18,11 +16,10 @@ class DeepChainMap(ChainMap[_KT, _VT]):
def __setitem__(self, key: _KT, value: _VT) -> None:
for mapping in self.maps:
- mutable_mapping = cast(MutableMapping[_KT, _VT], mapping)
- if key in mutable_mapping:
- mutable_mapping[key] = value
+ if key in mapping:
+ mapping[key] = value
return
- cast(MutableMapping[_KT, _VT], self.maps[0])[key] = value
+ self.maps[0][key] = value
def __delitem__(self, key: _KT) -> None:
"""
@@ -32,8 +29,7 @@ def __delitem__(self, key: _KT) -> None:
If `key` doesn't exist.
"""
for mapping in self.maps:
- mutable_mapping = cast(MutableMapping[_KT, _VT], mapping)
if key in mapping:
- del mutable_mapping[key]
+ del mapping[key]
return
raise KeyError(key)
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index 1a876b05d2073..a40be5a988f26 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -138,13 +138,11 @@ def view(self, dtype: Dtype | None = None) -> ArrayLike:
return TimedeltaArray(arr.view("i8"), dtype=dtype)
- # error: Incompatible return value type (got "ndarray", expected
- # "ExtensionArray")
# error: Argument "dtype" to "view" of "_ArrayOrScalarCommon" has incompatible
# type "Union[ExtensionDtype, dtype[Any]]"; expected "Union[dtype[Any], None,
# type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int,
# Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
- return arr.view(dtype=dtype) # type: ignore[return-value,arg-type]
+ return arr.view(dtype=dtype) # type: ignore[arg-type]
def take(
self: NDArrayBackedExtensionArrayT,
@@ -276,13 +274,9 @@ def __getitem__(
return self._box_func(result)
return self._from_backing_data(result)
- # error: Value of type variable "AnyArrayLike" of "extract_array" cannot be
- # "Union[int, slice, ndarray]"
# error: Incompatible types in assignment (expression has type "ExtensionArray",
# variable has type "Union[int, slice, ndarray]")
- key = extract_array( # type: ignore[type-var,assignment]
- key, extract_numpy=True
- )
+ key = extract_array(key, extract_numpy=True) # type: ignore[assignment]
key = check_array_indexer(self, key)
result = self._ndarray[key]
if lib.is_scalar(result):
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index c6987d9a11e4c..2bf8452903302 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -545,12 +545,10 @@ def _str_map(
mask.view("uint8"),
convert=False,
na_value=na_value,
- # error: Value of type variable "_DTypeScalar" of "dtype" cannot be
- # "object"
# error: Argument 1 to "dtype" has incompatible type
# "Union[ExtensionDtype, str, dtype[Any], Type[object]]"; expected
# "Type[object]"
- dtype=np.dtype(dtype), # type: ignore[type-var,arg-type]
+ dtype=np.dtype(dtype), # type: ignore[arg-type]
)
if not na_value_is_na:
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 42dff27866d84..fb16834e5b4b2 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -675,12 +675,10 @@ def _str_map(
mask.view("uint8"),
convert=False,
na_value=na_value,
- # error: Value of type variable "_DTypeScalar" of "dtype" cannot be
- # "object"
# error: Argument 1 to "dtype" has incompatible type
# "Union[ExtensionDtype, str, dtype[Any], Type[object]]"; expected
# "Type[object]"
- dtype=np.dtype(dtype), # type: ignore[type-var,arg-type]
+ dtype=np.dtype(dtype), # type: ignore[arg-type]
)
if not na_value_is_na:
diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py
index d4fbe226a3ae2..a561824f868f2 100644
--- a/pandas/core/computation/scope.py
+++ b/pandas/core/computation/scope.py
@@ -232,8 +232,7 @@ def swapkey(self, old_key: str, new_key: str, new_value=None) -> None:
for mapping in maps:
if old_key in mapping:
- # error: Unsupported target for indexed assignment ("Mapping[Any, Any]")
- mapping[new_key] = new_value # type: ignore[index]
+ mapping[new_key] = new_value
return
def _get_vars(self, stack, scopes: list[str]) -> None:
diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py
index 3956dbaba5a68..ed5cf047ab59f 100644
--- a/pandas/core/indexes/frozen.py
+++ b/pandas/core/indexes/frozen.py
@@ -105,6 +105,6 @@ def __repr__(self) -> str:
return f"{type(self).__name__}({str(self)})"
__setitem__ = __setslice__ = _disabled # type: ignore[assignment]
- __delitem__ = __delslice__ = _disabled # type: ignore[assignment]
- pop = append = extend = _disabled # type: ignore[assignment]
+ __delitem__ = __delslice__ = _disabled
+ pop = append = extend = _disabled
remove = sort = insert = _disabled # type: ignore[assignment]
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 960b8faec7c59..46b2e5d29d247 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -2154,11 +2154,9 @@ def _factorize_keys(
# variable has type "ExtensionArray")
lk, _ = lk._values_for_factorize()
- # error: Incompatible types in assignment (expression has type
- # "ndarray", variable has type "ExtensionArray")
# error: Item "ndarray" of "Union[Any, ndarray]" has no attribute
# "_values_for_factorize"
- rk, _ = rk._values_for_factorize() # type: ignore[union-attr,assignment]
+ rk, _ = rk._values_for_factorize() # type: ignore[union-attr]
klass: type[libhashtable.Factorizer] | type[libhashtable.Int64Factorizer]
if is_integer_dtype(lk.dtype) and is_integer_dtype(rk.dtype):
diff --git a/pyproject.toml b/pyproject.toml
index 0c3e078d8761a..4455df705fc3f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -159,6 +159,7 @@ reportImportCycles = false
reportIncompatibleMethodOverride = false
reportIncompatibleVariableOverride = false
reportMissingModuleSource = false
+reportMissingParameterType = false
reportMissingTypeArgument = false
reportMissingTypeStubs = false
reportOptionalCall = false
diff --git a/requirements-dev.txt b/requirements-dev.txt
index a7bdc972fb203..e83ec00d492bf 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -12,7 +12,7 @@ flake8==3.9.2
flake8-bugbear==21.3.2
flake8-comprehensions==3.1.0
isort>=5.2.1
-mypy==0.920
+mypy==0.930
pre-commit>=2.9.2
pycodestyle
pyupgrade
| ~~Waiting for Mypy 0.930 being available through conda forge https://anaconda.org/conda-forge/mypy~~ | https://api.github.com/repos/pandas-dev/pandas/pulls/45067 | 2021-12-25T15:59:59Z | 2021-12-27T18:14:23Z | 2021-12-27T18:14:23Z | 2021-12-27T18:14:23Z |
TYP: localization.py | diff --git a/pandas/_config/localization.py b/pandas/_config/localization.py
index bc76aca93da2a..2a487fa4b6877 100644
--- a/pandas/_config/localization.py
+++ b/pandas/_config/localization.py
@@ -3,16 +3,24 @@
Name `localization` is chosen to avoid overlap with builtin `locale` module.
"""
+from __future__ import annotations
+
from contextlib import contextmanager
import locale
import re
import subprocess
+from typing import (
+ Callable,
+ Iterator,
+)
from pandas._config.config import options
@contextmanager
-def set_locale(new_locale, lc_var: int = locale.LC_ALL):
+def set_locale(
+ new_locale: str | tuple[str, str], lc_var: int = locale.LC_ALL
+) -> Iterator[str | tuple[str, str]]:
"""
Context manager for temporarily setting a locale.
@@ -71,7 +79,7 @@ def can_set_locale(lc: str, lc_var: int = locale.LC_ALL) -> bool:
return True
-def _valid_locales(locales, normalize):
+def _valid_locales(locales: list[str] | str, normalize: bool) -> list[str]:
"""
Return a list of normalized locales that do not throw an ``Exception``
when set.
@@ -98,11 +106,15 @@ def _valid_locales(locales, normalize):
]
-def _default_locale_getter():
+def _default_locale_getter() -> bytes:
return subprocess.check_output(["locale -a"], shell=True)
-def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_getter):
+def get_locales(
+ prefix: str | None = None,
+ normalize: bool = True,
+ locale_getter: Callable[[], bytes] = _default_locale_getter,
+) -> list[str] | None:
"""
Get all the locales that are available on the system.
@@ -142,9 +154,9 @@ def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_gette
# raw_locales is "\n" separated list of locales
# it may contain non-decodable parts, so split
# extract what we can and then rejoin.
- raw_locales = raw_locales.split(b"\n")
+ split_raw_locales = raw_locales.split(b"\n")
out_locales = []
- for x in raw_locales:
+ for x in split_raw_locales:
try:
out_locales.append(str(x, encoding=options.display.encoding))
except UnicodeError:
diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py
index 76b5b835754aa..d4a87e6a8b65c 100644
--- a/pandas/tests/indexes/datetimes/test_misc.py
+++ b/pandas/tests/indexes/datetimes/test_misc.py
@@ -191,8 +191,9 @@ def test_datetimeindex_accessors6(self):
assert [d.weekofyear for d in dates] == expected
# GH 12806
+ # error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
- "time_locale", [None] if tm.get_locales() is None else [None] + tm.get_locales()
+ "time_locale", [None] + (tm.get_locales() or []) # type: ignore[operator]
)
def test_datetime_name_accessors(self, time_locale):
# Test Monday -> Sunday and January -> December, in that sequence
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py
index 03ba6b12599a6..9c9e11c6a4ba4 100644
--- a/pandas/tests/scalar/timestamp/test_timestamp.py
+++ b/pandas/tests/scalar/timestamp/test_timestamp.py
@@ -154,8 +154,9 @@ def check(value, equal):
"data",
[Timestamp("2017-08-28 23:00:00"), Timestamp("2017-08-28 23:00:00", tz="EST")],
)
+ # error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
- "time_locale", [None] if tm.get_locales() is None else [None] + tm.get_locales()
+ "time_locale", [None] + (tm.get_locales() or []) # type: ignore[operator]
)
def test_names(self, data, time_locale):
# GH 17354
diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py
index 48a3ebd25c239..15e13e5567310 100644
--- a/pandas/tests/series/accessors/test_dt_accessor.py
+++ b/pandas/tests/series/accessors/test_dt_accessor.py
@@ -426,8 +426,9 @@ def test_dt_accessor_no_new_attributes(self):
with pytest.raises(AttributeError, match="You cannot add any new attribute"):
ser.dt.xlabel = "a"
+ # error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
- "time_locale", [None] if tm.get_locales() is None else [None] + tm.get_locales()
+ "time_locale", [None] + (tm.get_locales() or []) # type: ignore[operator]
)
def test_dt_accessor_datetime_name_accessors(self, time_locale):
# Test Monday -> Sunday and January -> December, in that sequence
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45065 | 2021-12-25T06:32:56Z | 2021-12-27T13:49:37Z | 2021-12-27T13:49:36Z | 2021-12-27T18:45:58Z |
CI: Fix pytorch installation error | diff --git a/ci/deps/actions-38-db.yaml b/ci/deps/actions-38-db.yaml
index f445225a44dcb..ced15bbc8d7cb 100644
--- a/ci/deps/actions-38-db.yaml
+++ b/ci/deps/actions-38-db.yaml
@@ -3,6 +3,7 @@ channels:
- conda-forge
dependencies:
- python=3.8
+ - pip
# tools
- cython>=0.29.24
@@ -33,7 +34,6 @@ dependencies:
- pyarrow>=1.0.1
- pymysql
- pytables
- - pytorch
- python-snappy
- python-dateutil
- pytz
@@ -50,3 +50,5 @@ dependencies:
- coverage
- pandas-datareader
- pyxlsb
+ - pip:
+ - torch
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
The conda installation expects mkl locally, which does not work . So installing via pip for now to get ci back to green | https://api.github.com/repos/pandas-dev/pandas/pulls/45064 | 2021-12-25T00:37:09Z | 2021-12-25T01:36:52Z | 2021-12-25T01:36:52Z | 2021-12-25T09:38:36Z |
DOC: Fixed links to the contributing pages in the README. | diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 49200523df40f..d27eab5b9c95c 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -1,23 +1,3 @@
# Contributing to pandas
-Whether you are a novice or experienced software developer, all contributions and suggestions are welcome!
-
-Our main contributing guide can be found [in this repo](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst) or [on the website](https://pandas.pydata.org/docs/dev/development/contributing.html). If you do not want to read it in its entirety, we will summarize the main ways in which you can contribute and point to relevant sections of that document for further information.
-
-## Getting Started
-
-If you are looking to contribute to the *pandas* codebase, the best place to start is the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues). This is also a great place for filing bug reports and making suggestions for ways in which we can improve the code and documentation.
-
-If you have additional questions, feel free to ask them on the [mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata) or on [Gitter](https://gitter.im/pydata/pandas). Further information can also be found in the "[Where to start?](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#where-to-start)" section.
-
-## Filing Issues
-
-If you notice a bug in the code or documentation, or have suggestions for how we can improve either, feel free to create an issue on the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues) using [GitHub's "issue" form](https://github.com/pandas-dev/pandas/issues/new). The form contains some questions that will help us best address your issue. For more information regarding how to file issues against *pandas*, please refer to the "[Bug reports and enhancement requests](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#bug-reports-and-enhancement-requests)" section.
-
-## Contributing to the Codebase
-
-The code is hosted on [GitHub](https://www.github.com/pandas-dev/pandas), so you will need to use [Git](https://git-scm.com/) to clone the project and make changes to the codebase. Once you have obtained a copy of the code, you should create a development environment that is separate from your existing Python environment so that you can make and test changes without compromising your own work environment. For more information, please refer to the "[Working with the code](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#working-with-the-code)" section.
-
-Before submitting your changes for review, make sure to check that your changes do not break any tests. You can find more information about our test suites in the "[Test-driven development/code writing](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#test-driven-development-code-writing)" section. We also have guidelines regarding coding style that will be enforced during testing, which can be found in the "[Code standards](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#code-standards)" section.
-
-Once your changes are ready to be submitted, make sure to push your changes to GitHub before creating a pull request. Details about how to do that can be found in the "[Contributing your changes to pandas](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#contributing-your-changes-to-pandas)" section. We will review your changes, and you will most likely be asked to make additional changes before it is finally ready to merge. However, once it's ready, we will merge it, and you will have successfully contributed to the codebase!
+A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**.
diff --git a/README.md b/README.md
index 7bb77c70ab682..bde815939239d 100644
--- a/README.md
+++ b/README.md
@@ -160,7 +160,7 @@ Most development discussions take place on GitHub in this repo. Further, the [pa
All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome.
-A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**. There is also an [overview](.github/CONTRIBUTING.md) on GitHub.
+A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**.
If you are simply looking to start working with the pandas codebase, navigate to the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues) and start looking through interesting issues. There are a number of issues listed under [Docs](https://github.com/pandas-dev/pandas/issues?labels=Docs&sort=updated&state=open) and [good first issue](https://github.com/pandas-dev/pandas/issues?labels=good+first+issue&sort=updated&state=open) where you could start out.
| Also replaced the CONTRIBUTING file text with a link to the contributing pages.
- [x] closes #44985
| https://api.github.com/repos/pandas-dev/pandas/pulls/45063 | 2021-12-25T00:30:11Z | 2021-12-27T14:35:13Z | 2021-12-27T14:35:13Z | 2021-12-27T14:35:17Z |
BUG: Series[object].fillna ignoring downcast='infer' | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index ccad93d83eb5b..a2a5660a3404e 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -732,6 +732,8 @@ Missing
- Bug in :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` with ``inplace=True`` not writing to the underlying array(s) in-place (:issue:`44749`)
- Bug in :meth:`Index.fillna` incorrectly returning an un-filled :class:`Index` when NA values are present and ``downcast`` argument is specified. This now raises ``NotImplementedError`` instead; do not pass ``downcast`` argument (:issue:`44873`)
- Bug in :meth:`DataFrame.dropna` changing :class:`Index` even if no entries were dropped (:issue:`41965`)
+- Bug in :meth:`Series.fillna` with an object-dtype incorrectly ignoring ``downcast="infer"`` (:issue:`44241`)
+-
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index fc15c846b1907..7efbb299727e8 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6399,6 +6399,11 @@ def fillna(
else:
if self.ndim == 1:
if isinstance(value, (dict, ABCSeries)):
+ if not len(value):
+ # test_fillna_nonscalar
+ if inplace:
+ return None
+ return self.copy()
value = create_series_with_explicit_dtype(
value, dtype_if_empty=object
)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 3f50cb2c601b5..9558b82d95fde 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -518,11 +518,11 @@ def split_and_operate(self, func, *args, **kwargs) -> list[Block]:
def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]:
if self.dtype == _dtype_obj:
- # TODO: why is behavior different for object dtype?
- if downcast is not None:
- return blocks
-
+ # GH#44241 We downcast regardless of the argument;
+ # respecting 'downcast=None' may be worthwhile at some point,
+ # but ATM it breaks too much existing code.
# split and convert the blocks
+
return extend_blocks(
[blk.convert(datetime=True, numeric=False) for blk in blocks]
)
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 160eb4774d1a0..19f61a0a2d6fc 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -189,6 +189,42 @@ def test_fillna_downcast(self):
expected = Series([1, 0])
tm.assert_series_equal(result, expected)
+ def test_fillna_downcast_infer_objects_to_numeric(self):
+ # GH#44241 if we have object-dtype, 'downcast="infer"' should
+ # _actually_ infer
+
+ arr = np.arange(5).astype(object)
+ arr[3] = np.nan
+
+ ser = Series(arr)
+
+ res = ser.fillna(3, downcast="infer")
+ expected = Series(np.arange(5), dtype=np.int64)
+ tm.assert_series_equal(res, expected)
+
+ res = ser.ffill(downcast="infer")
+ expected = Series([0, 1, 2, 2, 4], dtype=np.int64)
+ tm.assert_series_equal(res, expected)
+
+ res = ser.bfill(downcast="infer")
+ expected = Series([0, 1, 2, 4, 4], dtype=np.int64)
+ tm.assert_series_equal(res, expected)
+
+ # with a non-round float present, we will downcast to float64
+ ser[2] = 2.5
+
+ expected = Series([0, 1, 2.5, 3, 4], dtype=np.float64)
+ res = ser.fillna(3, downcast="infer")
+ tm.assert_series_equal(res, expected)
+
+ res = ser.ffill(downcast="infer")
+ expected = Series([0, 1, 2.5, 2.5, 4], dtype=np.float64)
+ tm.assert_series_equal(res, expected)
+
+ res = ser.bfill(downcast="infer")
+ expected = Series([0, 1, 2.5, 4, 4], dtype=np.float64)
+ tm.assert_series_equal(res, expected)
+
def test_timedelta_fillna(self, frame_or_series):
# GH#3371
ser = Series(
| - [x] closes #44241
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45062 | 2021-12-24T23:08:31Z | 2021-12-27T17:07:15Z | 2021-12-27T17:07:14Z | 2021-12-27T17:09:53Z |
ENH: Index[bool] | diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst
index 3829306f77a0b..4a11028950966 100644
--- a/doc/source/whatsnew/v1.5.0.rst
+++ b/doc/source/whatsnew/v1.5.0.rst
@@ -37,6 +37,7 @@ Other enhancements
- :meth:`to_numeric` now preserves float64 arrays when downcasting would generate values not representable in float32 (:issue:`43693`)
- :meth:`Series.reset_index` and :meth:`DataFrame.reset_index` now support the argument ``allow_duplicates`` (:issue:`44410`)
- :meth:`.GroupBy.min` and :meth:`.GroupBy.max` now supports `Numba <https://numba.pydata.org/>`_ execution with the ``engine`` keyword (:issue:`45428`)
+- Implemented a ``bool``-dtype :class:`Index`, passing a bool-dtype arraylike to ``pd.Index`` will now retain ``bool`` dtype instead of casting to ``object`` (:issue:`45061`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/index.pyi b/pandas/_libs/index.pyi
index 86f2429575ebb..184bad1c080b3 100644
--- a/pandas/_libs/index.pyi
+++ b/pandas/_libs/index.pyi
@@ -42,6 +42,7 @@ class ObjectEngine(IndexEngine): ...
class DatetimeEngine(Int64Engine): ...
class TimedeltaEngine(DatetimeEngine): ...
class PeriodEngine(Int64Engine): ...
+class BoolEngine(UInt8Engine): ...
class BaseMultiIndexCodesEngine:
levels: list[np.ndarray]
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index d8311282d1193..0e9a330587f07 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -802,6 +802,13 @@ cdef class BaseMultiIndexCodesEngine:
include "index_class_helper.pxi"
+cdef class BoolEngine(UInt8Engine):
+ cdef _check_type(self, object val):
+ if not util.is_bool_object(val):
+ raise KeyError(val)
+ return <uint8_t>val
+
+
@cython.internal
@cython.freelist(32)
cdef class SharedEngine:
diff --git a/pandas/conftest.py b/pandas/conftest.py
index ba90c9eedb53c..a9c8ab833b40f 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -555,7 +555,8 @@ def _create_mi_with_dt64tz_level():
"num_uint8": tm.makeNumericIndex(100, dtype="uint8"),
"num_float64": tm.makeNumericIndex(100, dtype="float64"),
"num_float32": tm.makeNumericIndex(100, dtype="float32"),
- "bool": tm.makeBoolIndex(10),
+ "bool-object": tm.makeBoolIndex(10).astype(object),
+ "bool-dtype": Index(np.random.randn(10) < 0),
"categorical": tm.makeCategoricalIndex(100),
"interval": tm.makeIntervalIndex(100),
"empty": Index([]),
@@ -630,7 +631,7 @@ def index_flat_unique(request):
key
for key in indices_dict
if not (
- key in ["int", "uint", "range", "empty", "repeats"]
+ key in ["int", "uint", "range", "empty", "repeats", "bool-dtype"]
or key.startswith("num_")
)
and not isinstance(indices_dict[key], MultiIndex)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 36eabe93dbd7e..ddb8e19d1c558 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -220,9 +220,6 @@ def _reconstruct_data(
elif is_bool_dtype(dtype):
values = values.astype(dtype, copy=False)
- # we only support object dtypes bool Index
- if isinstance(original, ABCIndex):
- values = values.astype(object, copy=False)
elif dtype is not None:
if is_datetime64_dtype(dtype):
dtype = np.dtype("datetime64[ns]")
@@ -830,7 +827,10 @@ def value_counts(
-------
Series
"""
- from pandas.core.series import Series
+ from pandas import (
+ Index,
+ Series,
+ )
name = getattr(values, "name", None)
@@ -868,7 +868,13 @@ def value_counts(
else:
keys, counts = value_counts_arraylike(values, dropna)
- result = Series(counts, index=keys, name=name)
+ # For backwards compatibility, we let Index do its normal type
+ # inference, _except_ for if if infers from object to bool.
+ idx = Index._with_infer(keys)
+ if idx.dtype == bool and keys.dtype == object:
+ idx = idx.astype(object)
+
+ result = Series(counts, index=idx, name=name)
if sort:
result = result.sort_values(ascending=ascending)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index f6feec5fd97a6..847c5a607c086 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -505,6 +505,10 @@ def __new__(
if data.dtype.kind in ["i", "u", "f"]:
# maybe coerce to a sub-class
arr = data
+ elif data.dtype.kind == "b":
+ # No special subclass, and Index._ensure_array won't do this
+ # for us.
+ arr = np.asarray(data)
else:
arr = com.asarray_tuplesafe(data, dtype=_dtype_obj)
@@ -702,7 +706,7 @@ def _with_infer(cls, *args, **kwargs):
# "Union[ExtensionArray, ndarray[Any, Any]]"; expected
# "ndarray[Any, Any]"
values = lib.maybe_convert_objects(result._values) # type: ignore[arg-type]
- if values.dtype.kind in ["i", "u", "f"]:
+ if values.dtype.kind in ["i", "u", "f", "b"]:
return Index(values, name=result.name)
return result
@@ -872,9 +876,12 @@ def _engine(
):
return libindex.ExtensionEngine(target_values)
+ target_values = cast(np.ndarray, target_values)
# to avoid a reference cycle, bind `target_values` to a local variable, so
# `self` is not passed into the lambda.
- target_values = cast(np.ndarray, target_values)
+ if target_values.dtype == bool:
+ return libindex.BoolEngine(target_values)
+
# error: Argument 1 to "ExtensionEngine" has incompatible type
# "ndarray[Any, Any]"; expected "ExtensionArray"
return self._engine_type(target_values) # type:ignore[arg-type]
@@ -2680,7 +2687,6 @@ def _is_all_dates(self) -> bool:
"""
Whether or not the index values only consist of dates.
"""
-
if needs_i8_conversion(self.dtype):
return True
elif self.dtype != _dtype_obj:
@@ -7302,7 +7308,7 @@ def _maybe_cast_data_without_dtype(
FutureWarning,
stacklevel=3,
)
- if result.dtype.kind in ["b", "c"]:
+ if result.dtype.kind in ["c"]:
return subarr
result = ensure_wrapped_if_datetimelike(result)
return result
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 4d9420fc0510d..3f0a5deb97548 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -1076,6 +1076,8 @@ def to_datetime(
result = convert_listlike(arg, format)
else:
result = convert_listlike(np.array([arg]), format)[0]
+ if isinstance(arg, bool) and isinstance(result, np.bool_):
+ result = bool(result) # TODO: avoid this kludge.
# error: Incompatible return value type (got "Union[Timestamp, NaTType,
# Series, Index]", expected "Union[DatetimeIndex, Series, float, str,
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py
index 892fa83f98755..79db60ab5a7ce 100644
--- a/pandas/core/util/hashing.py
+++ b/pandas/core/util/hashing.py
@@ -319,7 +319,7 @@ def _hash_ndarray(
# First, turn whatever array this is into unsigned 64-bit ints, if we can
# manage it.
- elif isinstance(dtype, bool):
+ elif dtype == bool:
vals = vals.astype("u8")
elif issubclass(dtype.type, (np.datetime64, np.timedelta64)):
vals = vals.view("i8").astype("u8", copy=False)
diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py
index 13bf096cfe167..c46f1b036dbee 100644
--- a/pandas/tests/base/test_value_counts.py
+++ b/pandas/tests/base/test_value_counts.py
@@ -284,7 +284,7 @@ def test_value_counts_with_nan(dropna, index_or_series):
obj = klass(values)
res = obj.value_counts(dropna=dropna)
if dropna is True:
- expected = Series([1], index=[True])
+ expected = Series([1], index=Index([True], dtype=obj.dtype))
else:
expected = Series([1, 1, 1], index=[True, pd.NA, np.nan])
tm.assert_series_equal(res, expected)
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 0cf66c0814293..3f8c679c6162f 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -216,6 +216,8 @@ def test_ensure_copied_data(self, index):
# RangeIndex cannot be initialized from data
# MultiIndex and CategoricalIndex are tested separately
return
+ elif index.dtype == object and index.inferred_type == "boolean":
+ init_kwargs["dtype"] = index.dtype
index_type = type(index)
result = index_type(index.values, copy=True, **init_kwargs)
@@ -522,6 +524,9 @@ def test_fillna(self, index):
# GH 11343
if len(index) == 0:
return
+ elif index.dtype == bool:
+ # can't hold NAs
+ return
elif isinstance(index, NumericIndex) and is_integer_dtype(index.dtype):
return
elif isinstance(index, MultiIndex):
diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py
index 599455b2d2ba1..9626352ac7e36 100644
--- a/pandas/tests/indexes/multi/test_indexing.py
+++ b/pandas/tests/indexes/multi/test_indexing.py
@@ -621,13 +621,22 @@ def test_get_loc_implicit_cast(self, level, dtypes):
idx = MultiIndex.from_product(levels)
assert idx.get_loc(tuple(key)) == 3
- def test_get_loc_cast_bool(self):
- # GH 19086 : int is casted to bool, but not vice-versa
- levels = [[False, True], np.arange(2, dtype="int64")]
+ @pytest.mark.parametrize("dtype", [bool, object])
+ def test_get_loc_cast_bool(self, dtype):
+ # GH 19086 : int is casted to bool, but not vice-versa (for object dtype)
+ # With bool dtype, we don't cast in either direction.
+ levels = [Index([False, True], dtype=dtype), np.arange(2, dtype="int64")]
idx = MultiIndex.from_product(levels)
- assert idx.get_loc((0, 1)) == 1
- assert idx.get_loc((1, 0)) == 2
+ if dtype is bool:
+ with pytest.raises(KeyError, match=r"^\(0, 1\)$"):
+ assert idx.get_loc((0, 1)) == 1
+ with pytest.raises(KeyError, match=r"^\(1, 0\)$"):
+ assert idx.get_loc((1, 0)) == 2
+ else:
+ # We use python object comparisons, which treat 0 == False and 1 == True
+ assert idx.get_loc((0, 1)) == 1
+ assert idx.get_loc((1, 0)) == 2
with pytest.raises(KeyError, match=r"^\(False, True\)$"):
idx.get_loc((False, True))
diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py
index c7aae5d69b8e3..8f0d1179a99c1 100644
--- a/pandas/tests/indexes/test_any_index.py
+++ b/pandas/tests/indexes/test_any_index.py
@@ -49,6 +49,10 @@ def test_mutability(index):
def test_map_identity_mapping(index):
# GH#12766
result = index.map(lambda x: x)
+ if index.dtype == object and result.dtype == bool:
+ assert (index == result).all()
+ # TODO: could work that into the 'exact="equiv"'?
+ return # FIXME: doesn't belong in this file anymore!
tm.assert_index_equal(result, index, exact="equiv")
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index b2b902bd816c8..9df759588033f 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -321,15 +321,21 @@ def test_view_with_args(self, index):
"unicode",
"string",
pytest.param("categorical", marks=pytest.mark.xfail(reason="gh-25464")),
- "bool",
+ "bool-object",
+ "bool-dtype",
"empty",
],
indirect=True,
)
def test_view_with_args_object_array_raises(self, index):
- msg = "Cannot change data-type for object array"
- with pytest.raises(TypeError, match=msg):
- index.view("i8")
+ if index.dtype == bool:
+ msg = "When changing to a larger dtype"
+ with pytest.raises(ValueError, match=msg):
+ index.view("i8")
+ else:
+ msg = "Cannot change data-type for object array"
+ with pytest.raises(TypeError, match=msg):
+ index.view("i8")
@pytest.mark.parametrize("index", ["int", "range"], indirect=True)
def test_astype(self, index):
@@ -397,9 +403,9 @@ def test_is_(self):
def test_asof_numeric_vs_bool_raises(self):
left = Index([1, 2, 3])
- right = Index([True, False])
+ right = Index([True, False], dtype=object)
- msg = "Cannot compare dtypes int64 and object"
+ msg = "Cannot compare dtypes int64 and bool"
with pytest.raises(TypeError, match=msg):
left.asof(right[0])
# TODO: should right.asof(left[0]) also raise?
@@ -591,7 +597,8 @@ def test_append_empty_preserve_name(self, name, expected):
"index, expected",
[
("string", False),
- ("bool", False),
+ ("bool-object", False),
+ ("bool-dtype", False),
("categorical", False),
("int", True),
("datetime", False),
@@ -606,7 +613,8 @@ def test_is_numeric(self, index, expected):
"index, expected",
[
("string", True),
- ("bool", True),
+ ("bool-object", True),
+ ("bool-dtype", False),
("categorical", False),
("int", False),
("datetime", False),
@@ -621,7 +629,8 @@ def test_is_object(self, index, expected):
"index, expected",
[
("string", False),
- ("bool", False),
+ ("bool-object", False),
+ ("bool-dtype", False),
("categorical", False),
("int", False),
("datetime", True),
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 6159c53ea5bf4..ce5166aa8cf0b 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -88,7 +88,9 @@ def test_constructor_non_hashable_name(self, index_flat):
def test_constructor_unwraps_index(self, index_flat):
a = index_flat
- b = type(a)(a)
+ # Passing dtype is necessary for Index([True, False], dtype=object)
+ # case.
+ b = type(a)(a, dtype=a.dtype)
tm.assert_equal(a._data, b._data)
def test_to_flat_index(self, index_flat):
@@ -426,6 +428,9 @@ def test_hasnans_isnans(self, index_flat):
return
elif isinstance(index, NumericIndex) and is_integer_dtype(index.dtype):
return
+ elif index.dtype == bool:
+ # values[1] = np.nan below casts to True!
+ return
values[1] = np.nan
diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py
index 5f57e03ea9444..3052c9d7ee69b 100644
--- a/pandas/tests/indexes/test_index_new.py
+++ b/pandas/tests/indexes/test_index_new.py
@@ -74,7 +74,7 @@ def test_constructor_dtypes_to_object(self, cast_index, vals):
index = Index(vals)
assert type(index) is Index
- assert index.dtype == object
+ assert index.dtype == bool
def test_constructor_categorical_to_object(self):
# GH#32167 Categorical data and dtype=object should return object-dtype
diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py
index 8f3ecce223afa..7d46f6d18a318 100644
--- a/pandas/tests/indexes/test_numpy_compat.py
+++ b/pandas/tests/indexes/test_numpy_compat.py
@@ -68,8 +68,10 @@ def test_numpy_ufuncs_basic(index, func):
with tm.external_error_raised((TypeError, AttributeError)):
with np.errstate(all="ignore"):
func(index)
- elif isinstance(index, NumericIndex) or (
- not isinstance(index.dtype, np.dtype) and index.dtype._is_numeric
+ elif (
+ isinstance(index, NumericIndex)
+ or (not isinstance(index.dtype, np.dtype) and index.dtype._is_numeric)
+ or index.dtype == bool
):
# coerces to float (e.g. np.sin)
with np.errstate(all="ignore"):
@@ -77,7 +79,7 @@ def test_numpy_ufuncs_basic(index, func):
exp = Index(func(index.values), name=index.name)
tm.assert_index_equal(result, exp)
- if type(index) is not Index:
+ if type(index) is not Index or index.dtype == bool:
# i.e NumericIndex
assert isinstance(result, Float64Index)
else:
@@ -117,8 +119,10 @@ def test_numpy_ufuncs_other(index, func):
with tm.external_error_raised(TypeError):
func(index)
- elif isinstance(index, NumericIndex) or (
- not isinstance(index.dtype, np.dtype) and index.dtype._is_numeric
+ elif (
+ isinstance(index, NumericIndex)
+ or (not isinstance(index.dtype, np.dtype) and index.dtype._is_numeric)
+ or index.dtype == bool
):
# Results in bool array
result = func(index)
diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py
index bad75b7429efb..f4f572d8f79fc 100644
--- a/pandas/tests/indexes/test_setops.py
+++ b/pandas/tests/indexes/test_setops.py
@@ -9,7 +9,6 @@
import pytest
from pandas.core.dtypes.cast import find_common_type
-from pandas.core.dtypes.common import is_dtype_equal
from pandas import (
CategoricalIndex,
@@ -55,14 +54,20 @@ def test_union_different_types(index_flat, index_flat2, request):
if (
not idx1.is_unique
+ and not idx2.is_unique
+ and not idx2.is_monotonic_decreasing
and idx1.dtype.kind == "i"
- and is_dtype_equal(idx2.dtype, "boolean")
+ and idx2.dtype.kind == "b"
) or (
not idx2.is_unique
+ and not idx1.is_unique
+ and not idx1.is_monotonic_decreasing
and idx2.dtype.kind == "i"
- and is_dtype_equal(idx1.dtype, "boolean")
+ and idx1.dtype.kind == "b"
):
- mark = pytest.mark.xfail(reason="GH#44000 True==1", raises=ValueError)
+ mark = pytest.mark.xfail(
+ reason="GH#44000 True==1", raises=ValueError, strict=False
+ )
request.node.add_marker(mark)
common_dtype = find_common_type([idx1.dtype, idx2.dtype])
@@ -231,7 +236,11 @@ def test_union_base(self, index):
def test_difference_base(self, sort, index):
first = index[2:]
second = index[:4]
- if isinstance(index, CategoricalIndex) or index.is_boolean():
+ if index.is_boolean():
+ # i think (TODO: be sure) there assumptions baked in about
+ # the index fixture that don't hold here?
+ answer = set(first).difference(set(second))
+ elif isinstance(index, CategoricalIndex):
answer = []
else:
answer = index[4:]
diff --git a/pandas/tests/reshape/concat/test_append_common.py b/pandas/tests/reshape/concat/test_append_common.py
index 36bca1c2b654e..0a330fd12d76d 100644
--- a/pandas/tests/reshape/concat/test_append_common.py
+++ b/pandas/tests/reshape/concat/test_append_common.py
@@ -61,10 +61,7 @@ def _check_expected_dtype(self, obj, label):
considering not-supported dtypes
"""
if isinstance(obj, Index):
- if label == "bool":
- assert obj.dtype == "object"
- else:
- assert obj.dtype == label
+ assert obj.dtype == label
elif isinstance(obj, Series):
if label.startswith("period"):
assert obj.dtype == "Period[M]"
@@ -185,7 +182,7 @@ def test_concatlike_same_dtypes(self, item):
with pytest.raises(TypeError, match=msg):
pd.concat([Series(vals1), Series(vals2), vals3])
- def test_concatlike_dtypes_coercion(self, item, item2):
+ def test_concatlike_dtypes_coercion(self, item, item2, request):
# GH 13660
typ1, vals1 = item
typ2, vals2 = item2
@@ -210,9 +207,13 @@ def test_concatlike_dtypes_coercion(self, item, item2):
# series coerces to numeric based on numpy rule
# index doesn't because bool is object dtype
exp_series_dtype = typ2
+ mark = pytest.mark.xfail(reason="GH#39187 casting to object")
+ request.node.add_marker(mark)
warn = FutureWarning
elif typ2 == "bool" and typ1 in ("int64", "float64"):
exp_series_dtype = typ1
+ mark = pytest.mark.xfail(reason="GH#39187 casting to object")
+ request.node.add_marker(mark)
warn = FutureWarning
elif (
typ1 == "datetime64[ns, US/Eastern]"
@@ -229,7 +230,9 @@ def test_concatlike_dtypes_coercion(self, item, item2):
# ----- Index ----- #
# index.append
- res = Index(vals1).append(Index(vals2))
+ with tm.assert_produces_warning(warn, match="concatenating bool-dtype"):
+ # GH#39817
+ res = Index(vals1).append(Index(vals2))
exp = Index(exp_data, dtype=exp_index_dtype)
tm.assert_index_equal(res, exp)
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index a994c902f0b16..6a48d452f9624 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -758,26 +758,26 @@ def test_series_where(self, obj, key, expected, val, is_inplace):
self._check_inplace(is_inplace, orig, arr, obj)
def test_index_where(self, obj, key, expected, val):
- if obj.dtype == bool or obj.dtype.kind == "c" or expected.dtype.kind == "c":
- # TODO(GH#45061): Should become unreachable (at least the bool part)
+ if obj.dtype.kind == "c" or expected.dtype.kind == "c":
+ # TODO(Index[complex]): Should become unreachable
pytest.skip("test not applicable for this dtype")
mask = np.zeros(obj.shape, dtype=bool)
mask[key] = True
res = Index(obj).where(~mask, val)
- tm.assert_index_equal(res, Index(expected))
+ tm.assert_index_equal(res, Index(expected, dtype=expected.dtype))
def test_index_putmask(self, obj, key, expected, val):
- if obj.dtype == bool or obj.dtype.kind == "c" or expected.dtype.kind == "c":
- # TODO(GH#45061): Should become unreachable (at least the bool part)
+ if obj.dtype.kind == "c" or expected.dtype.kind == "c":
+ # TODO(Index[complex]): Should become unreachable
pytest.skip("test not applicable for this dtype")
mask = np.zeros(obj.shape, dtype=bool)
mask[key] = True
res = Index(obj).putmask(mask, val)
- tm.assert_index_equal(res, Index(expected))
+ tm.assert_index_equal(res, Index(expected, dtype=expected.dtype))
@pytest.mark.parametrize(
diff --git a/pandas/tests/series/methods/test_drop.py b/pandas/tests/series/methods/test_drop.py
index 59a60019bb1c1..a625e890393a6 100644
--- a/pandas/tests/series/methods/test_drop.py
+++ b/pandas/tests/series/methods/test_drop.py
@@ -54,7 +54,8 @@ def test_drop_with_ignore_errors():
# GH 8522
ser = Series([2, 3], index=[True, False])
- assert ser.index.is_object()
+ assert not ser.index.is_object()
+ assert ser.index.dtype == bool
result = ser.drop(True)
expected = Series([3], index=[False])
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_value_counts.py b/pandas/tests/series/methods/test_value_counts.py
index c914dba75dc35..1977bf88481a5 100644
--- a/pandas/tests/series/methods/test_value_counts.py
+++ b/pandas/tests/series/methods/test_value_counts.py
@@ -194,7 +194,7 @@ def test_value_counts_categorical_with_nan(self):
(
Series([False, True, True, pd.NA]),
True,
- Series([2, 1], index=[True, False]),
+ Series([2, 1], index=pd.Index([True, False], dtype=object)),
),
(
Series(range(3), index=[True, False, np.nan]).index,
diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py
index 9648b01492e02..38e3c5ec8a6f2 100644
--- a/pandas/tests/series/test_logical_ops.py
+++ b/pandas/tests/series/test_logical_ops.py
@@ -268,7 +268,9 @@ def test_logical_ops_with_index(self, op):
def test_reversed_xor_with_index_returns_index(self):
# GH#22092, GH#19792
ser = Series([True, True, False, False])
- idx1 = Index([True, False, True, False])
+ idx1 = Index(
+ [True, False, True, False], dtype=object
+ ) # TODO: raises if bool-dtype
idx2 = Index([1, 0, 1, 0])
msg = "operating as a set operation"
@@ -325,7 +327,7 @@ def test_reversed_logical_op_with_index_returns_series(self, op):
[
(ops.rand_, Index([False, True])),
(ops.ror_, Index([False, True])),
- (ops.rxor, Index([])),
+ (ops.rxor, Index([], dtype=bool)),
],
)
def test_reverse_ops_with_index(self, op, expected):
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 749ed1bb979e9..84e8d72711305 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -56,6 +56,12 @@ def test_factorize(self, index_or_series_obj, sort):
if isinstance(obj, MultiIndex):
constructor = MultiIndex.from_tuples
expected_uniques = constructor(obj.unique())
+ if (
+ isinstance(obj, Index)
+ and expected_uniques.dtype == bool
+ and obj.dtype == object
+ ):
+ expected_uniques = expected_uniques.astype(object)
if sort:
expected_uniques = expected_uniques.sort_values()
@@ -1240,7 +1246,7 @@ def test_dropna(self):
tm.assert_series_equal(
Series([True] * 3 + [False] * 2 + [None] * 5).value_counts(dropna=True),
- Series([3, 2], index=[True, False]),
+ Series([3, 2], index=Index([True, False], dtype=object)),
)
tm.assert_series_equal(
Series([True] * 5 + [False] * 3 + [None] * 2).value_counts(dropna=False),
| - [x] closes #15890
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45061 | 2021-12-24T23:02:04Z | 2022-02-05T19:01:22Z | 2022-02-05T19:01:21Z | 2022-02-05T19:46:21Z |
CI: Merge database workflow into posix workflow | diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
deleted file mode 100644
index 294091ec9852e..0000000000000
--- a/.github/workflows/database.yml
+++ /dev/null
@@ -1,123 +0,0 @@
-name: Database
-
-on:
- push:
- branches:
- - master
- - 1.3.x
- pull_request:
- branches:
- - master
- - 1.3.x
- paths-ignore:
- - "doc/**"
-
-env:
- PYTEST_WORKERS: "auto"
- PANDAS_CI: 1
- PATTERN: ((not slow and not network and not clipboard) or (single and db))
- COVERAGE: true
-
-jobs:
- Linux_py38_IO:
- runs-on: ubuntu-latest
- defaults:
- run:
- shell: bash -l {0}
-
- strategy:
- matrix:
- ENV_FILE: [ci/deps/actions-38-db-min.yaml, ci/deps/actions-38-db.yaml]
- fail-fast: false
-
- 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 }}
- 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@v2
- 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('${{ matrix.ENV_FILE }}') }}
-
- - uses: conda-incubator/setup-miniconda@v2
- with:
- mamba-version: "*"
- channels: conda-forge
- activate-environment: pandas-dev
- channel-priority: strict
- environment-file: ${{ matrix.ENV_FILE }}
- use-only-tar-bz2: true
-
- - name: Build Pandas
- uses: ./.github/actions/build_pandas
-
- - name: Test
- run: pytest -m "${{ env.PATTERN }}" -n 2 --dist=loadfile --cov=pandas --cov-report=xml pandas/tests/io
- if: always()
-
- - name: Build Version
- run: pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd
-
- - name: Publish test results
- uses: actions/upload-artifact@master
- with:
- name: Test results
- path: test-data.xml
- if: failure()
-
- - name: Print skipped tests
- run: python ci/print_skipped.py
-
- - 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/posix.yml b/.github/workflows/posix.yml
index 3fa9341bd0fef..2a40be680c681 100644
--- a/.github/workflows/posix.yml
+++ b/.github/workflows/posix.yml
@@ -25,6 +25,8 @@ jobs:
strategy:
matrix:
settings: [
+ [actions-38-db-min.yaml, "((not slow and not network and not clipboard) or (single and db))", "", "", "", "", ""],
+ [actions-38-db.yaml, "((not slow and not network and not clipboard) or (single and db))", "", "", "", "", ""],
[actions-38-minimum_versions.yaml, "not slow and not network and not clipboard", "", "", "", "", ""],
[actions-38-locale_slow.yaml, "slow", "language-pack-it xsel", "it_IT.utf8", "it_IT.utf8", "", ""],
[actions-38.yaml, "not slow and not clipboard", "", "", "", "", ""],
@@ -52,7 +54,35 @@ jobs:
# https://github.community/t/concurrecy-not-work-for-push/183068/7
group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.settings[0] }}
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:
diff --git a/pandas/tests/arrays/floating/test_construction.py b/pandas/tests/arrays/floating/test_construction.py
index 169b23c31f863..6fa3744429e5d 100644
--- a/pandas/tests/arrays/floating/test_construction.py
+++ b/pandas/tests/arrays/floating/test_construction.py
@@ -5,7 +5,7 @@
from pandas.compat import (
is_platform_windows,
- np_version_under1p19,
+ np_version_under1p20,
)
import pandas as pd
@@ -56,7 +56,7 @@ def test_floating_array_disallows_float16(request):
with pytest.raises(TypeError, match=msg):
FloatingArray(arr, mask)
- if np_version_under1p19 or (
+ if np_version_under1p20 or (
locale.getlocale()[0] != "en_US" and not is_platform_windows()
):
# the locale condition may need to be refined; this fails on
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 013af7eb90cd3..cc1917933ee6e 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -44,6 +44,7 @@
from pandas.core.arrays import DatetimeArray
from pandas.core.tools import datetimes as tools
from pandas.core.tools.datetimes import start_caching_at
+from pandas.util.version import Version
@pytest.fixture(params=[True, False])
@@ -810,11 +811,20 @@ def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype):
tm.assert_series_equal(result, expected)
@td.skip_if_no("psycopg2")
- def test_to_datetime_tz_psycopg2(self, cache):
+ def test_to_datetime_tz_psycopg2(self, request, cache):
# xref 8260
import psycopg2
+ # https://www.psycopg.org/docs/news.html#what-s-new-in-psycopg-2-9
+ request.node.add_marker(
+ pytest.mark.xfail(
+ Version(psycopg2.__version__.split()[0]) > Version("2.8.7"),
+ raises=AttributeError,
+ reason="psycopg2.tz is deprecated (and appears dropped) in 2.9",
+ )
+ )
+
# misc cases
tz1 = psycopg2.tz.FixedOffsetTimezone(offset=-300, name=None)
tz2 = psycopg2.tz.FixedOffsetTimezone(offset=-240, name=None)
| These two workflows are essentially identical besides the extra service containers.
Additionally found 2 errors in our tests since we weren't running these dependencies across all of `pandas/tests` | https://api.github.com/repos/pandas-dev/pandas/pulls/45060 | 2021-12-24T22:33:18Z | 2021-12-27T13:48:16Z | 2021-12-27T13:48:16Z | 2021-12-27T18:45:32Z |
DEPR: numeric_only=None in DataFrame.rank | diff --git a/doc/source/whatsnew/v0.18.0.rst b/doc/source/whatsnew/v0.18.0.rst
index 829c04dac9f2d..a05b9bb1a88ef 100644
--- a/doc/source/whatsnew/v0.18.0.rst
+++ b/doc/source/whatsnew/v0.18.0.rst
@@ -669,9 +669,9 @@ New signature
.. ipython:: python
- pd.Series([0,1]).rank(axis=0, method='average', numeric_only=None,
+ pd.Series([0,1]).rank(axis=0, method='average', numeric_only=False,
na_option='keep', ascending=True, pct=False)
- pd.DataFrame([0,1]).rank(axis=0, method='average', numeric_only=None,
+ pd.DataFrame([0,1]).rank(axis=0, method='average', numeric_only=False,
na_option='keep', ascending=True, pct=False)
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 7218c77e43409..a6960d266bb04 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -547,6 +547,7 @@ Other Deprecations
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
+- Deprecated ``numeric_only=None`` in :meth:`DataFrame.rank`; in a future version ``numeric_only`` must be either ``True`` or ``False`` (the default) (:issue:`45036`)
- Deprecated :meth:`NaT.freq` (:issue:`45071`)
-
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index fc15c846b1907..770e08ead31bb 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8401,7 +8401,7 @@ def rank(
self: NDFrameT,
axis=0,
method: str = "average",
- numeric_only: bool_t | None = None,
+ numeric_only: bool_t | None | lib.NoDefault = lib.no_default,
na_option: str = "keep",
ascending: bool_t = True,
pct: bool_t = False,
@@ -8487,6 +8487,20 @@ def rank(
3 spider 8.0 4.0 4.0 4.0 1.000
4 snake NaN NaN NaN 5.0 NaN
"""
+ warned = False
+ if numeric_only is None:
+ # GH#45036
+ warnings.warn(
+ f"'numeric_only=None' in {type(self).__name__}.rank is deprecated "
+ "and will raise in a future version. Pass either 'True' or "
+ "'False'. 'False' will be the default.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ warned = True
+ elif numeric_only is lib.no_default:
+ numeric_only = None
+
axis = self._get_axis_number(axis)
if na_option not in {"keep", "top", "bottom"}:
@@ -8516,6 +8530,16 @@ def ranker(data):
return ranker(self)
except TypeError:
numeric_only = True
+ if not warned:
+ # Only warn here if we didn't already issue a warning above
+ # GH#45036
+ warnings.warn(
+ f"Dropping of nuisance columns in {type(self).__name__}.rank "
+ "is deprecated; in a future version this will raise TypeError. "
+ "Select only valid columns before calling rank.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
if numeric_only:
data = self._get_numeric_data()
diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py
index 6c5831ad897d1..48188b66c45b5 100644
--- a/pandas/tests/frame/methods/test_rank.py
+++ b/pandas/tests/frame/methods/test_rank.py
@@ -136,7 +136,10 @@ def test_rank_mixed_frame(self, float_string_frame):
float_string_frame["datetime"] = datetime.now()
float_string_frame["timedelta"] = timedelta(days=1, seconds=1)
- result = float_string_frame.rank(1)
+ with tm.assert_produces_warning(FutureWarning, match="numeric_only=None"):
+ float_string_frame.rank(numeric_only=None)
+ with tm.assert_produces_warning(FutureWarning, match="Dropping of nuisance"):
+ result = float_string_frame.rank(1)
expected = float_string_frame.rank(1, numeric_only=True)
tm.assert_frame_equal(result, expected)
@@ -489,5 +492,7 @@ def test_rank_object_first(self, frame_or_series, na_option, ascending, expected
)
def test_rank_mixed_axis_zero(self, data, expected):
df = DataFrame(data)
- result = df.rank()
+ msg = "Dropping of nuisance columns"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ result = df.rank()
tm.assert_frame_equal(result, expected)
| - [x] closes #45036
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45059 | 2021-12-24T21:28:00Z | 2021-12-27T17:07:49Z | 2021-12-27T17:07:49Z | 2021-12-27T17:08:59Z |
ENH: add render_links for Styler.to_html formatting | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 9d788ffcfabe1..330d64ea88b8c 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -111,6 +111,7 @@ Additionally there are specific enhancements to the HTML specific rendering:
- :meth:`.Styler.to_html` introduces keyword arguments ``sparse_index``, ``sparse_columns``, ``bold_headers``, ``caption``, ``max_rows`` and ``max_columns`` (:issue:`41946`, :issue:`43149`, :issue:`42972`).
- :meth:`.Styler.to_html` omits CSSStyle rules for hidden table elements as a performance enhancement (:issue:`43619`)
- Custom CSS classes can now be directly specified without string replacement (:issue:`43686`)
+ - Ability to render hyperlinks automatically via a new ``hyperlinks`` formatting keyword argument (:issue:`45058`)
There are also some LaTeX specific enhancements:
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index d9550f0940376..a196ec60c4012 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -623,6 +623,7 @@ def to_latex(
| \\sisetup{detect-all = true} *(within {document})*
environment \\usepackage{longtable} if arg is "longtable"
| or any other relevant environment package
+ hyperlinks \\usepackage{hyperref}
===================== ==========================================================
**Cell Styles**
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index dcb1f9a2a70dc..a6b8913b23d9d 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -798,6 +798,7 @@ def format(
decimal: str = ".",
thousands: str | None = None,
escape: str | None = None,
+ hyperlinks: str | None = None,
) -> StylerRenderer:
r"""
Format the text display value of cells.
@@ -842,6 +843,13 @@ def format(
.. versionadded:: 1.3.0
+ hyperlinks : {"html", "latex"}, optional
+ Convert string patterns containing https://, http://, ftp:// or www. to
+ HTML <a> tags as clickable URL hyperlinks if "html", or LaTeX \href
+ commands if "latex".
+
+ .. versionadded:: 1.4.0
+
Returns
-------
self : Styler
@@ -958,6 +966,7 @@ def format(
thousands is None,
na_rep is None,
escape is None,
+ hyperlinks is None,
)
):
self._display_funcs.clear()
@@ -980,6 +989,7 @@ def format(
decimal=decimal,
thousands=thousands,
escape=escape,
+ hyperlinks=hyperlinks,
)
for ri in ris:
self._display_funcs[(ri, ci)] = format_func
@@ -996,6 +1006,7 @@ def format_index(
decimal: str = ".",
thousands: str | None = None,
escape: str | None = None,
+ hyperlinks: str | None = None,
) -> StylerRenderer:
r"""
Format the text display value of index labels or column headers.
@@ -1027,6 +1038,10 @@ def format_index(
``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with
LaTeX-safe sequences.
Escaping is done before ``formatter``.
+ hyperlinks : {"html", "latex"}, optional
+ Convert string patterns containing https://, http://, ftp:// or www. to
+ HTML <a> tags as clickable URL hyperlinks if "html", or LaTeX \href
+ commands if "latex".
Returns
-------
@@ -1128,6 +1143,7 @@ def format_index(
thousands is None,
na_rep is None,
escape is None,
+ hyperlinks is None,
)
):
display_funcs_.clear()
@@ -1149,6 +1165,7 @@ def format_index(
decimal=decimal,
thousands=thousands,
escape=escape,
+ hyperlinks=hyperlinks,
)
for idx in [(i, lvl) if axis == 0 else (lvl, i) for i in range(len(obj))]:
@@ -1391,6 +1408,20 @@ def _str_escape(x, escape):
return x
+def _render_href(x, format):
+ """uses regex to detect a common URL pattern and converts to href tag in format."""
+ if isinstance(x, str):
+ if format == "html":
+ href = '<a href="{0}" target="_blank">{0}</a>'
+ elif format == "latex":
+ href = r"\href{{{0}}}{{{0}}}"
+ else:
+ raise ValueError("``hyperlinks`` format can only be 'html' or 'latex'")
+ pat = r"(https?:\/\/|ftp:\/\/|www.)[\w/\-?=%.]+\.[\w/\-&?=%.]+"
+ return re.sub(pat, lambda m: href.format(m.group(0)), x)
+ return x
+
+
def _maybe_wrap_formatter(
formatter: BaseFormatter | None = None,
na_rep: str | None = None,
@@ -1398,6 +1429,7 @@ def _maybe_wrap_formatter(
decimal: str = ".",
thousands: str | None = None,
escape: str | None = None,
+ hyperlinks: str | None = None,
) -> Callable:
"""
Allows formatters to be expressed as str, callable or None, where None returns
@@ -1431,11 +1463,17 @@ def _maybe_wrap_formatter(
else:
func_2 = func_1
+ # Render links
+ if hyperlinks is not None:
+ func_3 = lambda x: func_2(_render_href(x, format=hyperlinks))
+ else:
+ func_3 = func_2
+
# Replace missing values if na_rep
if na_rep is None:
- return func_2
+ return func_3
else:
- return lambda x: na_rep if isna(x) else func_2(x)
+ return lambda x: na_rep if isna(x) else func_3(x)
def non_reducing_slice(slice_: Subset):
diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py
index 2143ef40582a5..fad289d5e0d2c 100644
--- a/pandas/tests/io/formats/style/test_html.py
+++ b/pandas/tests/io/formats/style/test_html.py
@@ -764,3 +764,43 @@ def test_hiding_index_columns_multiindex_trimming():
)
assert result == expected
+
+
+@pytest.mark.parametrize("type", ["data", "index"])
+@pytest.mark.parametrize(
+ "text, exp, found",
+ [
+ ("no link, just text", False, ""),
+ ("subdomain not www: sub.web.com", False, ""),
+ ("www subdomain: www.web.com other", True, "www.web.com"),
+ ("scheme full structure: http://www.web.com", True, "http://www.web.com"),
+ ("scheme no top-level: http://www.web", True, "http://www.web"),
+ ("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"),
+ ("subdirectories: www.web.com/directory", True, "www.web.com/directory"),
+ ("Multiple domains: www.1.2.3.4", True, "www.1.2.3.4"),
+ ],
+)
+def test_rendered_links(type, text, exp, found):
+ if type == "data":
+ df = DataFrame([text])
+ styler = df.style.format(hyperlinks="html")
+ else:
+ df = DataFrame([0], index=[text])
+ styler = df.style.format_index(hyperlinks="html")
+
+ rendered = '<a href="{0}" target="_blank">{0}</a>'.format(found)
+ result = styler.to_html()
+ assert (rendered in result) is exp
+ assert (text in result) is not exp # test conversion done when expected and not
+
+
+def test_multiple_rendered_links():
+ links = ("www.a.b", "http://a.c", "https://a.d", "ftp://a.e")
+ df = DataFrame(["text {} {} text {} {}".format(*links)])
+ result = df.style.format(hyperlinks="html").to_html()
+ href = '<a href="{0}" target="_blank">{0}</a>'
+ for link in links:
+ assert href.format(link) in result
+ assert href.format("text") not in result
diff --git a/pandas/tests/io/formats/style/test_to_latex.py b/pandas/tests/io/formats/style/test_to_latex.py
index 9c2a364b396b8..0ecf6079044e0 100644
--- a/pandas/tests/io/formats/style/test_to_latex.py
+++ b/pandas/tests/io/formats/style/test_to_latex.py
@@ -845,3 +845,11 @@ def test_latex_hiding_index_columns_multiindex_alignment():
"""
)
assert result == expected
+
+
+def test_rendered_links():
+ # note the majority of testing is done in test_html.py: test_rendered_links
+ # these test only the alternative latex format is functional
+ df = DataFrame(["text www.domain.com text"])
+ result = df.style.format(hyperlinks="latex").to_latex()
+ assert r"text \href{www.domain.com}{www.domain.com} text" in result
| This came about as a requirement for converting DataFrame.to_html into Styler.to_html, citing @jorisvandenbossche in favour of the functionality.
Note that the `DataFrame.to_html` `render_links` argument is rather limited to just detecting only a URL in a cell.
The function added for Styler here is a more general pattern search, and it allows the result to be viewed in Jupyter Notebook directly, which the precursor does not.

| https://api.github.com/repos/pandas-dev/pandas/pulls/45058 | 2021-12-24T21:13:20Z | 2021-12-28T15:07:19Z | 2021-12-28T15:07:19Z | 2021-12-28T15:37:19Z |
PERF: avoid copies in lib.infer_dtype | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 9a82e89481b45..23faa3e0304a9 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -97,7 +97,6 @@ from pandas._libs.missing cimport (
is_matching_na,
is_null_datetime64,
is_null_timedelta64,
- isnaobj,
)
from pandas._libs.tslibs.conversion cimport convert_to_tsobject
from pandas._libs.tslibs.nattype cimport (
@@ -1454,6 +1453,7 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
ndarray values
bint seen_pdnat = False
bint seen_val = False
+ flatiter it
if util.is_array(value):
values = value
@@ -1491,24 +1491,22 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
# This should not be reached
values = values.astype(object)
- # for f-contiguous array 1000 x 1000, passing order="K" gives 5000x speedup
- values = values.ravel(order="K")
-
- if skipna:
- values = values[~isnaobj(values)]
-
n = cnp.PyArray_SIZE(values)
if n == 0:
return "empty"
# Iterate until we find our first valid value. We will use this
# value to decide which of the is_foo_array functions to call.
+ it = PyArray_IterNew(values)
for i in range(n):
- val = values[i]
+ # The PyArray_GETITEM and PyArray_ITER_NEXT are faster
+ # equivalents to `val = values[i]`
+ val = PyArray_GETITEM(values, PyArray_ITER_DATA(it))
+ PyArray_ITER_NEXT(it)
# do not use checknull to keep
# np.datetime64('nat') and np.timedelta64('nat')
- if val is None or util.is_nan(val):
+ if val is None or util.is_nan(val) or val is C_NA:
pass
elif val is NaT:
seen_pdnat = True
@@ -1520,23 +1518,25 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
if seen_val is False and seen_pdnat is True:
return "datetime"
# float/object nan is handled in latter logic
+ if seen_val is False and skipna:
+ return "empty"
if util.is_datetime64_object(val):
- if is_datetime64_array(values):
+ if is_datetime64_array(values, skipna=skipna):
return "datetime64"
elif is_timedelta(val):
- if is_timedelta_or_timedelta64_array(values):
+ if is_timedelta_or_timedelta64_array(values, skipna=skipna):
return "timedelta"
elif util.is_integer_object(val):
# ordering matters here; this check must come after the is_timedelta
# check otherwise numpy timedelta64 objects would come through here
- if is_integer_array(values):
+ if is_integer_array(values, skipna=skipna):
return "integer"
- elif is_integer_float_array(values):
- if is_integer_na_array(values):
+ elif is_integer_float_array(values, skipna=skipna):
+ if is_integer_na_array(values, skipna=skipna):
return "integer-na"
else:
return "mixed-integer-float"
@@ -1557,7 +1557,7 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
return "time"
elif is_decimal(val):
- if is_decimal_array(values):
+ if is_decimal_array(values, skipna=skipna):
return "decimal"
elif util.is_complex_object(val):
@@ -1567,8 +1567,8 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
elif util.is_float_object(val):
if is_float_array(values):
return "floating"
- elif is_integer_float_array(values):
- if is_integer_na_array(values):
+ elif is_integer_float_array(values, skipna=skipna):
+ if is_integer_na_array(values, skipna=skipna):
return "integer-na"
else:
return "mixed-integer-float"
@@ -1586,15 +1586,18 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
return "bytes"
elif is_period_object(val):
- if is_period_array(values):
+ if is_period_array(values, skipna=skipna):
return "period"
elif is_interval(val):
if is_interval_array(values):
return "interval"
+ cnp.PyArray_ITER_RESET(it)
for i in range(n):
- val = values[i]
+ val = PyArray_GETITEM(values, PyArray_ITER_DATA(it))
+ PyArray_ITER_NEXT(it)
+
if util.is_integer_object(val):
return "mixed-integer"
@@ -1823,10 +1826,11 @@ cdef class IntegerValidator(Validator):
# Note: only python-exposed for tests
-cpdef bint is_integer_array(ndarray values):
+cpdef bint is_integer_array(ndarray values, bint skipna=True):
cdef:
IntegerValidator validator = IntegerValidator(len(values),
- values.dtype)
+ values.dtype,
+ skipna=skipna)
return validator.validate(values)
@@ -1837,10 +1841,10 @@ cdef class IntegerNaValidator(Validator):
or (util.is_nan(value) and util.is_float_object(value)))
-cdef bint is_integer_na_array(ndarray values):
+cdef bint is_integer_na_array(ndarray values, bint skipna=True):
cdef:
IntegerNaValidator validator = IntegerNaValidator(len(values),
- values.dtype)
+ values.dtype, skipna=skipna)
return validator.validate(values)
@@ -1853,10 +1857,11 @@ cdef class IntegerFloatValidator(Validator):
return issubclass(self.dtype.type, np.integer)
-cdef bint is_integer_float_array(ndarray values):
+cdef bint is_integer_float_array(ndarray values, bint skipna=True):
cdef:
IntegerFloatValidator validator = IntegerFloatValidator(len(values),
- values.dtype)
+ values.dtype,
+ skipna=skipna)
return validator.validate(values)
@@ -1900,9 +1905,11 @@ cdef class DecimalValidator(Validator):
return is_decimal(value)
-cdef bint is_decimal_array(ndarray values):
+cdef bint is_decimal_array(ndarray values, bint skipna=False):
cdef:
- DecimalValidator validator = DecimalValidator(len(values), values.dtype)
+ DecimalValidator validator = DecimalValidator(
+ len(values), values.dtype, skipna=skipna
+ )
return validator.validate(values)
@@ -1997,10 +2004,10 @@ cdef class Datetime64Validator(DatetimeValidator):
# Note: only python-exposed for tests
-cpdef bint is_datetime64_array(ndarray values):
+cpdef bint is_datetime64_array(ndarray values, bint skipna=True):
cdef:
Datetime64Validator validator = Datetime64Validator(len(values),
- skipna=True)
+ skipna=skipna)
return validator.validate(values)
@@ -2012,10 +2019,10 @@ cdef class AnyDatetimeValidator(DatetimeValidator):
)
-cdef bint is_datetime_or_datetime64_array(ndarray values):
+cdef bint is_datetime_or_datetime64_array(ndarray values, bint skipna=True):
cdef:
AnyDatetimeValidator validator = AnyDatetimeValidator(len(values),
- skipna=True)
+ skipna=skipna)
return validator.validate(values)
@@ -2069,13 +2076,13 @@ cdef class AnyTimedeltaValidator(TimedeltaValidator):
# Note: only python-exposed for tests
-cpdef bint is_timedelta_or_timedelta64_array(ndarray values):
+cpdef bint is_timedelta_or_timedelta64_array(ndarray values, bint skipna=True):
"""
Infer with timedeltas and/or nat/none.
"""
cdef:
AnyTimedeltaValidator validator = AnyTimedeltaValidator(len(values),
- skipna=True)
+ skipna=skipna)
return validator.validate(values)
@@ -2105,20 +2112,28 @@ cpdef bint is_time_array(ndarray values, bint skipna=False):
return validator.validate(values)
-cdef bint is_period_array(ndarray[object] values):
+# FIXME: actually use skipna
+cdef bint is_period_array(ndarray values, bint skipna=True):
"""
Is this an ndarray of Period objects (or NaT) with a single `freq`?
"""
+ # values should be object-dtype, but ndarray[object] assumes 1D, while
+ # this _may_ be 2D.
cdef:
- Py_ssize_t i, n = len(values)
+ Py_ssize_t i, N = values.size
int dtype_code = -10000 # i.e. c_FreqGroup.FR_UND
object val
+ flatiter it
- if len(values) == 0:
+ if N == 0:
return False
- for i in range(n):
- val = values[i]
+ it = PyArray_IterNew(values)
+ for i in range(N):
+ # The PyArray_GETITEM and PyArray_ITER_NEXT are faster
+ # equivalents to `val = values[i]`
+ val = PyArray_GETITEM(values, PyArray_ITER_DATA(it))
+ PyArray_ITER_NEXT(it)
if is_period_object(val):
if dtype_code == -10000:
diff --git a/pandas/conftest.py b/pandas/conftest.py
index feb5bf3928b50..e61d9ee18cadb 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -1549,6 +1549,7 @@ def any_numpy_dtype(request):
_any_skipna_inferred_dtype = [
("string", ["a", np.nan, "c"]),
("string", ["a", pd.NA, "c"]),
+ ("mixed", ["a", pd.NaT, "c"]), # pd.NaT not considered valid by is_string_array
("bytes", [b"a", np.nan, b"c"]),
("empty", [np.nan, np.nan, np.nan]),
("empty", []),
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index 04ce3bce06e4d..aa36ceca83736 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -116,13 +116,7 @@ def coerce_to_array(
inferred_type = lib.infer_dtype(values, skipna=True)
if inferred_type == "empty":
pass
- elif inferred_type not in [
- "floating",
- "integer",
- "mixed-integer",
- "integer-na",
- "mixed-integer-float",
- ]:
+ elif inferred_type == "boolean":
raise TypeError(f"{values.dtype} cannot be converted to a FloatingDtype")
elif is_bool_dtype(values) and is_float_dtype(dtype):
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 99a586fbcaea7..0441c315f151b 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -166,16 +166,8 @@ def coerce_to_array(
inferred_type = lib.infer_dtype(values, skipna=True)
if inferred_type == "empty":
pass
- elif inferred_type not in [
- "floating",
- "integer",
- "mixed-integer",
- "integer-na",
- "mixed-integer-float",
- "string",
- "unicode",
- ]:
- raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype")
+ elif inferred_type == "boolean":
+ raise TypeError(f"{values.dtype} cannot be converted to a FloatingDtype")
elif is_bool_dtype(values) and is_integer_dtype(dtype):
values = np.array(values, dtype=int, copy=copy)
diff --git a/pandas/tests/arrays/floating/test_construction.py b/pandas/tests/arrays/floating/test_construction.py
index f2b31b8f64a98..523fb015dc2a9 100644
--- a/pandas/tests/arrays/floating/test_construction.py
+++ b/pandas/tests/arrays/floating/test_construction.py
@@ -131,6 +131,7 @@ def test_to_array_error(values):
"cannot be converted to a FloatingDtype",
"values must be a 1D list-like",
"Cannot pass scalar",
+ r"float\(\) argument must be a string or a (real )?number, not 'dict'",
]
)
with pytest.raises((TypeError, ValueError), match=msg):
diff --git a/pandas/tests/arrays/integer/test_construction.py b/pandas/tests/arrays/integer/test_construction.py
index e5fd4977ec2b8..fa61f23fc5d64 100644
--- a/pandas/tests/arrays/integer/test_construction.py
+++ b/pandas/tests/arrays/integer/test_construction.py
@@ -139,6 +139,7 @@ def test_to_integer_array_error(values):
r"invalid literal for int\(\) with base 10:",
r"values must be a 1D list-like",
r"Cannot pass scalar",
+ r"int\(\) argument must be a string",
]
)
with pytest.raises((ValueError, TypeError), match=msg):
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 0919d57f9e612..afeeee3d02f9d 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -266,12 +266,26 @@ def test_constructor_raises(cls):
with pytest.raises(ValueError, match=msg):
cls(np.array([]))
- with pytest.raises(ValueError, match=msg):
- cls(np.array(["a", np.datetime64("nat")], dtype=object))
+ if cls is pd.arrays.StringArray:
+ # GH#45057 np.nan and None do NOT raise, as they are considered valid NAs
+ # for string dtype
+ cls(np.array(["a", np.nan], dtype=object))
+ cls(np.array(["a", None], dtype=object))
+ else:
+ with pytest.raises(ValueError, match=msg):
+ cls(np.array(["a", np.nan], dtype=object))
+ with pytest.raises(ValueError, match=msg):
+ cls(np.array(["a", None], dtype=object))
with pytest.raises(ValueError, match=msg):
cls(np.array(["a", pd.NaT], dtype=object))
+ with pytest.raises(ValueError, match=msg):
+ cls(np.array(["a", np.datetime64("NaT", "ns")], dtype=object))
+
+ with pytest.raises(ValueError, match=msg):
+ cls(np.array(["a", np.timedelta64("NaT", "ns")], dtype=object))
+
@pytest.mark.parametrize("na", [np.nan, np.float64("nan"), float("nan"), None, pd.NA])
def test_constructor_nan_like(na):
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 9ae5b42161b73..3691324318ee5 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -1134,10 +1134,20 @@ def test_unicode(self):
# This could also return "string" or "mixed-string"
assert result == "mixed"
+ # even though we use skipna, we are only skipping those NAs that are
+ # considered matching by is_string_array
arr = ["a", np.nan, "c"]
result = lib.infer_dtype(arr, skipna=True)
assert result == "string"
+ arr = ["a", pd.NA, "c"]
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "string"
+
+ arr = ["a", pd.NaT, "c"]
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "mixed"
+
arr = ["a", "c"]
result = lib.infer_dtype(arr, skipna=False)
assert result == "string"
@@ -1544,15 +1554,24 @@ def test_is_string_array(self):
assert lib.is_string_array(
np.array(["foo", "bar", pd.NA], dtype=object), skipna=True
)
+ # we allow NaN/None in the StringArray constructor, so its allowed here
assert lib.is_string_array(
np.array(["foo", "bar", None], dtype=object), skipna=True
)
assert lib.is_string_array(
np.array(["foo", "bar", np.nan], dtype=object), skipna=True
)
+ # But not e.g. datetimelike or Decimal NAs
assert not lib.is_string_array(
np.array(["foo", "bar", pd.NaT], dtype=object), skipna=True
)
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", np.datetime64("NaT")], dtype=object), skipna=True
+ )
+ assert not lib.is_string_array(
+ np.array(["foo", "bar", Decimal("NaN")], dtype=object), skipna=True
+ )
+
assert not lib.is_string_array(
np.array(["foo", "bar", None], dtype=object), skipna=False
)
| - [x] closes #45022
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
In the `skipna=True` case, instead of doing `values = values[~isnaobj(values)]`, just pass `skipna` to the relevant validator functions. This causes trouble because those validator functions have different rules about what NA values they allow (analogous to is_valid_na_for_dtype).
I'm down to 1 test case failing locally, fixing it will require changing the StringArray constructor to allow None and np.nan (xref #40839) in addition to just pd.NA (AFAICT pd.array and pd.Series(... dtype="string") will not be affected). I'm fine with that, but someone more involved with the string code might want to weigh in cc @simonjayhawkins
```
In [1]: import numpy as np
In [2]: arr = np.arange(10**5).astype(object)
In [3]: from pandas._libs import lib
In [4]: %timeit lib.infer_dtype(arr, skipna=True)
962 µs ± 77 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # <- PR
3.81 ms ± 33 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) # <- master
In [7]: %load_ext memory_profiler
In [16]: arr = arr.repeat(100)
In [18]: %memit lib.infer_dtype(arr, skipna=True)
peak memory: 169.24 MiB, increment: 0.00 MiB # <- PR
peak memory: 265.39 MiB, increment: 95.38 MiB # <- master
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/45057 | 2021-12-24T20:54:40Z | 2022-01-17T13:47:48Z | 2022-01-17T13:47:48Z | 2022-01-17T16:04:50Z |
DOC: Run doctests over pandas directory | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index f3a8d6b12b970..4498585e36ce5 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -65,23 +65,8 @@ fi
if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
MSG='Doctests' ; echo $MSG
- python -m pytest --doctest-modules \
- pandas/_config/ \
- pandas/_libs/ \
- pandas/_testing/ \
- pandas/api/ \
- pandas/arrays/ \
- pandas/compat/ \
- pandas/core \
- pandas/errors/ \
- pandas/io/ \
- pandas/plotting/ \
- pandas/tseries/ \
- pandas/util/ \
- pandas/_typing.py \
- pandas/_version.py \
- pandas/conftest.py \
- pandas/testing.py
+ # Ignore test_*.py files or else the unit tests will run
+ python -m pytest --doctest-modules --ignore-glob="**/test_*.py" pandas
RET=$(($RET + $?)) ; echo $MSG "DONE"
MSG='Cython Doctests' ; echo $MSG
diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py
index 01b447aa855a3..49a6e442f890f 100644
--- a/pandas/tests/arithmetic/conftest.py
+++ b/pandas/tests/arithmetic/conftest.py
@@ -24,7 +24,9 @@ def switch_numexpr_min_elements(request):
# ------------------------------------------------------------------
-
+# doctest with +SKIP for one fixture fails during setup with
+# 'DoctestItem' object has no attribute 'callspec'
+# due to switch_numexpr_min_elements fixture
@pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
def one(request):
"""
@@ -37,11 +39,11 @@ def one(request):
Examples
--------
- >>> dti = pd.date_range('2016-01-01', periods=2, freq='H')
- >>> dti
+ dti = pd.date_range('2016-01-01', periods=2, freq='H')
+ dti
DatetimeIndex(['2016-01-01 00:00:00', '2016-01-01 01:00:00'],
dtype='datetime64[ns]', freq='H')
- >>> dti + one
+ dti + one
DatetimeIndex(['2016-01-01 01:00:00', '2016-01-01 02:00:00'],
dtype='datetime64[ns]', freq='H')
"""
@@ -61,6 +63,9 @@ def one(request):
zeros.extend([0, 0.0, -0.0])
+# doctest with +SKIP for zero fixture fails during setup with
+# 'DoctestItem' object has no attribute 'callspec'
+# due to switch_numexpr_min_elements fixture
@pytest.fixture(params=zeros)
def zero(request):
"""
@@ -74,8 +79,8 @@ def zero(request):
Examples
--------
- >>> arr = RangeIndex(5)
- >>> arr / zeros
+ arr = RangeIndex(5)
+ arr / zeros
Float64Index([nan, inf, inf, inf, inf], dtype='float64')
"""
return request.param
| - [x] closes #22459
`--ignore-glob="**/test_*.py"` is necessary or else unit tests are collected and run
```
% pytest --doctest-modules pandas --collect-only
...
<Function test_rolling_consistency_var_debiasing_factors[all_data16-rolling_consistency_cases0-False]>
<Function test_rolling_consistency_var_debiasing_factors[all_data16-rolling_consistency_cases1-True]>
<Function test_rolling_consistency_var_debiasing_factors[all_data16-rolling_consistency_cases1-False]>
<Function test_rolling_consistency_var_debiasing_factors[all_data17-rolling_consistency_cases0-True]>
<Function test_rolling_consistency_var_debiasing_factors[all_data17-rolling_consistency_cases0-False]>
<Function test_rolling_consistency_var_debiasing_factors[all_data17-rolling_consistency_cases1-True]>
<Function test_rolling_consistency_var_debiasing_factors[all_data17-rolling_consistency_cases1-False]>
<Package tseries>
<DoctestModule frequencies.py>
<DoctestItem pandas.tseries.frequencies.infer_freq>
<DoctestModule holiday.py>
<DoctestItem pandas.tseries.holiday.Holiday.__init__>
<Package util>
<DoctestModule _decorators.py>
<DoctestItem pandas.util._decorators.deprecate_kwarg>
<DoctestModule _validators.py>
<DoctestItem pandas.util._validators.validate_axis_style_args>
=================================================================== 153109 tests collected in 46.60s ===================================================================
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/45056 | 2021-12-24T20:27:25Z | 2021-12-27T13:48:57Z | 2021-12-27T13:48:56Z | 2021-12-27T18:45:42Z |
BUG: allow Series[Period].astype(dt64) | diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst
index 3fd6fe67772bc..6df234a027ee9 100644
--- a/doc/source/user_guide/timeseries.rst
+++ b/doc/source/user_guide/timeseries.rst
@@ -2102,19 +2102,14 @@ The ``period`` dtype can be used in ``.astype(...)``. It allows one to change th
# change monthly freq to daily freq
pi.astype("period[D]")
+ # convert to DatetimeIndex
+ pi.astype("datetime64[ns]")
+
# convert to PeriodIndex
dti = pd.date_range("2011-01-01", freq="M", periods=3)
dti
dti.astype("period[M]")
-.. deprecated:: 1.4.0
- Converting PeriodIndex to DatetimeIndex with ``.astype(...)`` is deprecated and will raise in a future version. Use ``obj.to_timestamp(how).tz_localize(dtype.tz)`` instead.
-
-.. ipython:: python
-
- # convert to DatetimeIndex
- pi.to_timestamp(how="start")
-
PeriodIndex partial string indexing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index ccad93d83eb5b..83816c59a2712 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -537,7 +537,6 @@ Other Deprecations
- Deprecated casting behavior when passing an item with mismatched-timezone to :meth:`DatetimeIndex.insert`, :meth:`DatetimeIndex.putmask`, :meth:`DatetimeIndex.where` :meth:`DatetimeIndex.fillna`, :meth:`Series.mask`, :meth:`Series.where`, :meth:`Series.fillna`, :meth:`Series.shift`, :meth:`Series.replace`, :meth:`Series.reindex` (and :class:`DataFrame` column analogues). In the past this has cast to object dtype. In a future version, these will cast the passed item to the index or series's timezone (:issue:`37605`,:issue:`44940`)
- Deprecated the 'errors' keyword argument in :meth:`Series.where`, :meth:`DataFrame.where`, :meth:`Series.mask`, and :meth:`DataFrame.mask`; in a future version the argument will be removed (:issue:`44294`)
- Deprecated the ``prefix`` keyword argument in :func:`read_csv` and :func:`read_table`, in a future version the argument will be removed (:issue:`43396`)
-- Deprecated :meth:`PeriodIndex.astype` to ``datetime64[ns]`` or ``DatetimeTZDtype``, use ``obj.to_timestamp(how).tz_localize(dtype.tz)`` instead (:issue:`44398`)
- Deprecated passing non boolean argument to sort in :func:`concat` (:issue:`41518`)
- Deprecated passing arguments as positional for :func:`read_fwf` other than ``filepath_or_buffer`` (:issue:`41485`):
- Deprecated passing ``skipna=None`` for :meth:`DataFrame.mad` and :meth:`Series.mad`, pass ``skipna=True`` instead (:issue:`44580`)
@@ -673,6 +672,7 @@ Conversion
- Bug in :meth:`DataFrame.astype` not propagating ``attrs`` from the original :class:`DataFrame` (:issue:`44414`)
- Bug in :meth:`DataFrame.convert_dtypes` result losing ``columns.names`` (:issue:`41435`)
- Bug in constructing a ``IntegerArray`` from pyarrow data failing to validate dtypes (:issue:`44891`)
+- Bug in :meth:`Series.astype` not allowing converting from a ``PeriodDtype`` to ``datetime64`` dtype, inconsistent with the :class:`PeriodIndex` behavior (:issue:`45038`)
-
Strings
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 6112ccccb89ff..487b51735bd4e 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -53,6 +53,7 @@
from pandas.core.dtypes.common import (
TD64NS_DTYPE,
ensure_object,
+ is_datetime64_any_dtype,
is_datetime64_dtype,
is_dtype_equal,
is_float_dtype,
@@ -666,6 +667,12 @@ def astype(self, dtype, copy: bool = True):
return self.copy()
if is_period_dtype(dtype):
return self.asfreq(dtype.freq)
+
+ if is_datetime64_any_dtype(dtype):
+ # GH#45038 match PeriodIndex behavior.
+ tz = getattr(dtype, "tz", None)
+ return self.to_timestamp().tz_localize(tz)
+
return super().astype(dtype, copy=copy)
def searchsorted(
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 8dcd379a4eb9b..aba834a47ffef 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -358,14 +358,9 @@ def astype(self, dtype, copy: bool = True, how=lib.no_default):
if is_datetime64_any_dtype(dtype):
# 'how' is index-specific, isn't part of the EA interface.
- # GH#44398 deprecate astype(dt64), matching Series behavior
- warnings.warn(
- f"Converting {type(self).__name__} to DatetimeIndex with "
- "'astype' is deprecated and will raise in a future version. "
- "Use `obj.to_timestamp(how).tz_localize(dtype.tz)` instead.",
- FutureWarning,
- stacklevel=find_stack_level(),
- )
+ # GH#45038 implement this for PeriodArray (but without "how")
+ # once the "how" deprecation is enforced we can just dispatch
+ # directly to PeriodArray.
tz = getattr(dtype, "tz", None)
return self.to_timestamp(how=how).tz_localize(tz)
diff --git a/pandas/tests/arrays/period/test_astype.py b/pandas/tests/arrays/period/test_astype.py
index 52cd28c8d5acc..e16220acd3210 100644
--- a/pandas/tests/arrays/period/test_astype.py
+++ b/pandas/tests/arrays/period/test_astype.py
@@ -66,5 +66,12 @@ def test_astype_period():
def test_astype_datetime(other):
arr = period_array(["2000", "2001", None], freq="D")
# slice off the [ns] so that the regex matches.
- with pytest.raises(TypeError, match=other[:-4]):
- arr.astype(other)
+ if other == "timedelta64[ns]":
+ with pytest.raises(TypeError, match=other[:-4]):
+ arr.astype(other)
+
+ else:
+ # GH#45038 allow period->dt64 because we allow dt64->period
+ result = arr.astype(other)
+ expected = pd.DatetimeIndex(["2000", "2001", pd.NaT])._data
+ tm.assert_datetime_array_equal(result, expected)
diff --git a/pandas/tests/indexes/period/methods/test_astype.py b/pandas/tests/indexes/period/methods/test_astype.py
index c44f2efed1fcc..e2340a2db02f7 100644
--- a/pandas/tests/indexes/period/methods/test_astype.py
+++ b/pandas/tests/indexes/period/methods/test_astype.py
@@ -164,10 +164,7 @@ def test_period_astype_to_timestamp(self):
assert res.freq == exp.freq
exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern")
- msg = "Use `obj.to_timestamp"
- with tm.assert_produces_warning(FutureWarning, match=msg):
- # GH#44398
- res = pi.astype("datetime64[ns, US/Eastern]")
+ res = pi.astype("datetime64[ns, US/Eastern]")
tm.assert_index_equal(res, exp)
assert res.freq == exp.freq
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index 0407dc02833fd..50770f5bb38f2 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -393,9 +393,6 @@ def test_astype_preserves_name(self, index, dtype):
):
# This astype is deprecated in favor of tz_localize
warn = FutureWarning
- elif isinstance(index, PeriodIndex) and dtype == "datetime64[ns]":
- # Deprecated in favor of to_timestamp GH#44398
- warn = FutureWarning
try:
# Some of these conversions cannot succeed so we use a try / except
with tm.assert_produces_warning(warn):
| - [x] closes #45038
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45055 | 2021-12-24T17:45:38Z | 2021-12-27T17:11:09Z | 2021-12-27T17:11:09Z | 2021-12-27T17:13:55Z |
STYLE: upgrade flake8 to version 4+ | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index ea15e135455ba..6ab940efaddd4 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -35,25 +35,15 @@ repos:
# we can lint all header files since they aren't "generated" like C files are.
exclude: ^pandas/_libs/src/(klib|headers)/
args: [--quiet, '--extensions=c,h', '--headers=h', --recursive, '--filter=-readability/casting,-runtime/int,-build/include_subdir']
-- repo: https://gitlab.com/pycqa/flake8
- rev: 3.9.2
+- repo: https://github.com/PyCQA/flake8
+ rev: 4.0.1
hooks:
- id: flake8
additional_dependencies: &flake8_dependencies
- - flake8==3.9.2
- - flake8-comprehensions==3.1.0
+ - flake8==4.0.1
+ - flake8-comprehensions==3.7.0
- flake8-bugbear==21.3.2
- pandas-dev-flaker==0.2.0
- - id: flake8
- alias: flake8-cython
- name: flake8 (cython)
- types: [cython]
- args: [--append-config=flake8/cython.cfg]
- - id: flake8
- name: flake8 (cython template)
- files: \.pxi\.in$
- types: [text]
- args: [--append-config=flake8/cython-template.cfg]
- repo: https://github.com/PyCQA/isort
rev: 5.10.1
hooks:
diff --git a/environment.yml b/environment.yml
index 0e303d1fa7da2..ef6ec7352db05 100644
--- a/environment.yml
+++ b/environment.yml
@@ -20,9 +20,9 @@ dependencies:
# code checks
- black=21.5b2
- cpplint
- - flake8=3.9.2
+ - flake8=4.0.1
- flake8-bugbear=21.3.2 # used by flake8, find likely bugs
- - flake8-comprehensions=3.1.0 # used by flake8, linting of unnecessary comprehensions
+ - flake8-comprehensions=3.7.0 # used by flake8, linting of unnecessary comprehensions
- isort>=5.2.1 # check that imports are in the right order
- mypy=0.920
- pre-commit>=2.9.2
diff --git a/flake8/cython-template.cfg b/flake8/cython-template.cfg
deleted file mode 100644
index 3d7b288fd8055..0000000000000
--- a/flake8/cython-template.cfg
+++ /dev/null
@@ -1,3 +0,0 @@
-[flake8]
-filename = *.pxi.in
-select = E501,E302,E203,E111,E114,E221,E303,E231,E126,F403
diff --git a/flake8/cython.cfg b/flake8/cython.cfg
deleted file mode 100644
index bf1f41647b34e..0000000000000
--- a/flake8/cython.cfg
+++ /dev/null
@@ -1,13 +0,0 @@
-[flake8]
-filename = *.pyx,*.pxd
-extend_ignore=
- # whitespace before '('
- E211,
- # missing whitespace around operator
- E225,
- # missing whitespace around arithmetic operator
- E226,
- # missing whitespace around bitwise or shift operator
- E227,
- # invalid syntax
- E999,
diff --git a/requirements-dev.txt b/requirements-dev.txt
index a7bdc972fb203..2f80440e71d16 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -8,9 +8,9 @@ asv
cython>=0.29.24
black==21.5b2
cpplint
-flake8==3.9.2
+flake8==4.0.1
flake8-bugbear==21.3.2
-flake8-comprehensions==3.1.0
+flake8-comprehensions==3.7.0
isort>=5.2.1
mypy==0.920
pre-commit>=2.9.2
| - [x] closes #45051
- [x] tests passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] bumping version of flake8 and update repo url
| https://api.github.com/repos/pandas-dev/pandas/pulls/45053 | 2021-12-24T16:45:20Z | 2021-12-27T16:35:44Z | 2021-12-27T16:35:44Z | 2021-12-30T02:03:53Z |
DEPR: Deprecate set and dict as indexers | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index febf08f2c47aa..1fde030d4b7a8 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -545,6 +545,7 @@ Other Deprecations
- Deprecated parameter ``names`` in :meth:`Index.copy` (:issue:`44916`)
- A deprecation warning is now shown for :meth:`DataFrame.to_latex` indicating the arguments signature may change and emulate more the arguments to :meth:`.Styler.to_latex` in future versions (:issue:`44411`)
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
+- Deprecated passing ``set`` or ``dict`` as indexer for :meth:`DataFrame.loc.__setitem__`, :meth:`DataFrame.loc.__getitem__`, :meth:`Series.loc.__setitem__`, :meth:`Series.loc.__getitem__`, :meth:`DataFrame.__getitem__`, :meth:`Series.__getitem__` and :meth:`Series.__setitem__` (:issue:`42825`)
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
-
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 03c9addefecc0..fd5163bcb14ed 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -170,6 +170,7 @@
)
from pandas.core.indexing import (
check_bool_indexer,
+ check_deprecated_indexers,
convert_to_index_sliceable,
)
from pandas.core.internals import (
@@ -3457,6 +3458,7 @@ def _iter_column_arrays(self) -> Iterator[ArrayLike]:
yield self._get_column_array(i)
def __getitem__(self, key):
+ check_deprecated_indexers(key)
key = lib.item_from_zerodim(key)
key = com.apply_if_callable(key, self)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index f043a8cee308c..19fbc43fea3b3 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -641,6 +641,10 @@ def _get_setitem_indexer(self, key):
if self.name == "loc":
self._ensure_listlike_indexer(key)
+ if isinstance(key, tuple):
+ for x in key:
+ check_deprecated_indexers(x)
+
if self.axis is not None:
return self._convert_tuple(key)
@@ -698,6 +702,7 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None):
)
def __setitem__(self, key, value):
+ check_deprecated_indexers(key)
if isinstance(key, tuple):
key = tuple(list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
@@ -890,6 +895,9 @@ def _getitem_nested_tuple(self, tup: tuple):
# we have a nested tuple so have at least 1 multi-index level
# we should be able to match up the dimensionality here
+ for key in tup:
+ check_deprecated_indexers(key)
+
# we have too many indexers for our dim, but have at least 1
# multi-index dimension, try to see if we have something like
# a tuple passed to a series with a multi-index
@@ -943,6 +951,7 @@ def _convert_to_indexer(self, key, axis: int):
raise AbstractMethodError(self)
def __getitem__(self, key):
+ check_deprecated_indexers(key)
if type(key) is tuple:
key = tuple(list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
@@ -2444,3 +2453,29 @@ def need_slice(obj: slice) -> bool:
or obj.stop is not None
or (obj.step is not None and obj.step != 1)
)
+
+
+def check_deprecated_indexers(key) -> None:
+ """Checks if the key is a deprecated indexer."""
+ if (
+ isinstance(key, set)
+ or isinstance(key, tuple)
+ and any(isinstance(x, set) for x in key)
+ ):
+ warnings.warn(
+ "Passing a set as an indexer is deprecated and will raise in "
+ "a future version. Use a list instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ if (
+ isinstance(key, dict)
+ or isinstance(key, tuple)
+ and any(isinstance(x, dict) for x in key)
+ ):
+ warnings.warn(
+ "Passing a dict as an indexer is deprecated and will raise in "
+ "a future version. Use a list instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 15805c0aa94ed..2c747b20e0a0a 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -124,7 +124,10 @@
ensure_index,
)
import pandas.core.indexes.base as ibase
-from pandas.core.indexing import check_bool_indexer
+from pandas.core.indexing import (
+ check_bool_indexer,
+ check_deprecated_indexers,
+)
from pandas.core.internals import (
SingleArrayManager,
SingleBlockManager,
@@ -939,6 +942,7 @@ def _slice(self, slobj: slice, axis: int = 0) -> Series:
return self._get_values(slobj)
def __getitem__(self, key):
+ check_deprecated_indexers(key)
key = com.apply_if_callable(key, self)
if key is Ellipsis:
@@ -1065,6 +1069,7 @@ def _get_value(self, label, takeable: bool = False):
return self.index._get_values_for_loc(self, loc, label)
def __setitem__(self, key, value) -> None:
+ check_deprecated_indexers(key)
key = com.apply_if_callable(key, self)
cacher_needs_updating = self._check_is_chained_assignment_possible()
diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py
index 3028a433f2dae..0d4ab84175aab 100644
--- a/pandas/tests/frame/indexing/test_getitem.py
+++ b/pandas/tests/frame/indexing/test_getitem.py
@@ -134,7 +134,11 @@ def test_getitem_listlike(self, idx_type, levels, float_frame):
idx = idx_type(keys)
idx_check = list(idx_type(keys))
- result = frame[idx]
+ if isinstance(idx, (set, dict)):
+ with tm.assert_produces_warning(FutureWarning):
+ result = frame[idx]
+ else:
+ result = frame[idx]
expected = frame.loc[:, idx_check]
expected.columns.names = frame.columns.names
@@ -143,7 +147,8 @@ def test_getitem_listlike(self, idx_type, levels, float_frame):
idx = idx_type(keys + [missing])
with pytest.raises(KeyError, match="not in index"):
- frame[idx]
+ with tm.assert_produces_warning(FutureWarning):
+ frame[idx]
def test_getitem_iloc_generator(self):
# GH#39614
@@ -388,3 +393,14 @@ def test_getitem_datetime_slice(self):
),
)
tm.assert_frame_equal(result, expected)
+
+
+class TestGetitemDeprecatedIndexers:
+ @pytest.mark.parametrize("key", [{"a", "b"}, {"a": "a"}])
+ def test_getitem_dict_and_set_deprecated(self, key):
+ # GH#42825
+ df = DataFrame(
+ [[1, 2], [3, 4]], columns=MultiIndex.from_tuples([("a", 1), ("b", 2)])
+ )
+ with tm.assert_produces_warning(FutureWarning):
+ df[key]
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 2194fb4d5b1bd..bee8ccb125315 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -1526,3 +1526,65 @@ def test_loc_iloc_setitem_non_categorical_rhs(
# "c" not part of the categories
with pytest.raises(TypeError, match=msg1):
indexer(df)[key] = ["c", "c"]
+
+
+class TestDepreactedIndexers:
+ @pytest.mark.parametrize(
+ "key", [{1}, {1: 1}, ({1}, "a"), ({1: 1}, "a"), (1, {"a"}), (1, {"a": "a"})]
+ )
+ def test_getitem_dict_and_set_deprecated(self, key):
+ # GH#42825
+ df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
+ with tm.assert_produces_warning(FutureWarning):
+ df.loc[key]
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ {1},
+ {1: 1},
+ (({1}, 2), "a"),
+ (({1: 1}, 2), "a"),
+ ((1, 2), {"a"}),
+ ((1, 2), {"a": "a"}),
+ ],
+ )
+ def test_getitem_dict_and_set_deprecated_multiindex(self, key):
+ # GH#42825
+ df = DataFrame(
+ [[1, 2], [3, 4]],
+ columns=["a", "b"],
+ index=MultiIndex.from_tuples([(1, 2), (3, 4)]),
+ )
+ with tm.assert_produces_warning(FutureWarning):
+ df.loc[key]
+
+ @pytest.mark.parametrize(
+ "key", [{1}, {1: 1}, ({1}, "a"), ({1: 1}, "a"), (1, {"a"}), (1, {"a": "a"})]
+ )
+ def test_setitem_dict_and_set_deprecated(self, key):
+ # GH#42825
+ df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
+ with tm.assert_produces_warning(FutureWarning):
+ df.loc[key] = 1
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ {1},
+ {1: 1},
+ (({1}, 2), "a"),
+ (({1: 1}, 2), "a"),
+ ((1, 2), {"a"}),
+ ((1, 2), {"a": "a"}),
+ ],
+ )
+ def test_setitem_dict_and_set_deprecated_multiindex(self, key):
+ # GH#42825
+ df = DataFrame(
+ [[1, 2], [3, 4]],
+ columns=["a", "b"],
+ index=MultiIndex.from_tuples([(1, 2), (3, 4)]),
+ )
+ with tm.assert_produces_warning(FutureWarning):
+ df.loc[key] = 1
diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py
index 1756cc3ae707c..6e59311634c76 100644
--- a/pandas/tests/indexing/multiindex/test_loc.py
+++ b/pandas/tests/indexing/multiindex/test_loc.py
@@ -339,8 +339,11 @@ def convert_nested_indexer(indexer_type, keys):
convert_nested_indexer(indexer_type, k)
for indexer_type, k in zip(types, keys)
)
-
- result = df.loc[indexer, "Data"]
+ if indexer_type_1 is set or indexer_type_2 is set:
+ with tm.assert_produces_warning(FutureWarning):
+ result = df.loc[indexer, "Data"]
+ else:
+ result = df.loc[indexer, "Data"]
expected = Series(
[1, 2, 4, 5], name="Data", index=MultiIndex.from_product(keys)
)
diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py
index dabe3d480ff19..0da376ccac450 100644
--- a/pandas/tests/series/indexing/test_getitem.py
+++ b/pandas/tests/series/indexing/test_getitem.py
@@ -696,3 +696,19 @@ def test_duplicated_index_getitem_positional_indexer(index_vals):
s = Series(range(5), index=list(index_vals))
result = s[3]
assert result == 3
+
+
+class TestGetitemDeprecatedIndexers:
+ @pytest.mark.parametrize("key", [{1}, {1: 1}])
+ def test_getitem_dict_and_set_deprecated(self, key):
+ # GH#42825
+ ser = Series([1, 2, 3])
+ with tm.assert_produces_warning(FutureWarning):
+ ser[key]
+
+ @pytest.mark.parametrize("key", [{1}, {1: 1}])
+ def test_setitem_dict_and_set_deprecated(self, key):
+ # GH#42825
+ ser = Series([1, 2, 3])
+ with tm.assert_produces_warning(FutureWarning):
+ ser[key] = 1
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index 31c21e123a0de..ff0a4ae1b5564 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -8,6 +8,7 @@
from pandas import (
DataFrame,
IndexSlice,
+ MultiIndex,
Series,
Timedelta,
Timestamp,
@@ -316,3 +317,33 @@ def test_frozenset_index():
assert s[idx1] == 2
s[idx1] = 3
assert s[idx1] == 3
+
+
+class TestDepreactedIndexers:
+ @pytest.mark.parametrize("key", [{1}, {1: 1}])
+ def test_getitem_dict_and_set_deprecated(self, key):
+ # GH#42825
+ ser = Series([1, 2])
+ with tm.assert_produces_warning(FutureWarning):
+ ser.loc[key]
+
+ @pytest.mark.parametrize("key", [{1}, {1: 1}, ({1}, 2), ({1: 1}, 2)])
+ def test_getitem_dict_and_set_deprecated_multiindex(self, key):
+ # GH#42825
+ ser = Series([1, 2], index=MultiIndex.from_tuples([(1, 2), (3, 4)]))
+ with tm.assert_produces_warning(FutureWarning):
+ ser.loc[key]
+
+ @pytest.mark.parametrize("key", [{1}, {1: 1}])
+ def test_setitem_dict_and_set_deprecated(self, key):
+ # GH#42825
+ ser = Series([1, 2])
+ with tm.assert_produces_warning(FutureWarning):
+ ser.loc[key] = 1
+
+ @pytest.mark.parametrize("key", [{1}, {1: 1}, ({1}, 2), ({1: 1}, 2)])
+ def test_setitem_dict_and_set_deprecated_multiindex(self, key):
+ # GH#42825
+ ser = Series([1, 2], index=MultiIndex.from_tuples([(1, 2), (3, 4)]))
+ with tm.assert_produces_warning(FutureWarning):
+ ser.loc[key] = 1
| - [x] closes #42825
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
- ``DataFrame.__setitem__`` does not work for unhashable object
- ``iloc`` does not work for unhashable objects for __getitem__ and __setitem__ | https://api.github.com/repos/pandas-dev/pandas/pulls/45052 | 2021-12-24T16:12:48Z | 2021-12-29T20:22:55Z | 2021-12-29T20:22:55Z | 2021-12-29T20:24:13Z |
TST: implement deserialization tests for older schema versions | diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py
index b204d3bb97b6e..f7aade1f27529 100644
--- a/pandas/tests/io/json/test_json_table_schema.py
+++ b/pandas/tests/io/json/test_json_table_schema.py
@@ -789,3 +789,25 @@ def test_empty_frame_roundtrip(self):
out = df.to_json(orient="table")
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(expected, result)
+
+ def test_read_json_orient_table_old_schema_version(self):
+ df_json = """
+ {
+ "schema":{
+ "fields":[
+ {"name":"index","type":"integer"},
+ {"name":"a","type":"string"}
+ ],
+ "primaryKey":["index"],
+ "pandas_version":"0.20.0"
+ },
+ "data":[
+ {"index":0,"a":1},
+ {"index":1,"a":2.0},
+ {"index":2,"a":"s"}
+ ]
+ }
+ """
+ expected = DataFrame({"a": [1, 2.0, "s"]})
+ result = pd.read_json(df_json, orient="table")
+ tm.assert_frame_equal(expected, result)
| - [X] closes #44995
- [x] tests added / passed (see #45047)
- [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45048 | 2021-12-24T12:46:24Z | 2021-12-24T16:31:33Z | 2021-12-24T16:31:32Z | 2021-12-24T16:31:36Z |
CI: Remove always true azure posix command | diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml
index 36721037e55eb..b7c36bb87353b 100644
--- a/ci/azure/posix.yml
+++ b/ci/azure/posix.yml
@@ -8,17 +8,16 @@ jobs:
vmImage: ${{ parameters.vmImage }}
strategy:
matrix:
- ${{ if eq(parameters.name, 'macOS') }}:
- py38_macos_1:
- ENV_FILE: ci/deps/azure-macos-38.yaml
- CONDA_PY: "38"
- PATTERN: "not slow"
- PYTEST_TARGET: "pandas/tests/[a-h]*"
- py38_macos_2:
- ENV_FILE: ci/deps/azure-macos-38.yaml
- CONDA_PY: "38"
- PATTERN: "not slow"
- PYTEST_TARGET: "pandas/tests/[i-z]*"
+ py38_macos_1:
+ ENV_FILE: ci/deps/azure-macos-38.yaml
+ CONDA_PY: "38"
+ PATTERN: "not slow"
+ PYTEST_TARGET: "pandas/tests/[a-h]*"
+ py38_macos_2:
+ ENV_FILE: ci/deps/azure-macos-38.yaml
+ CONDA_PY: "38"
+ PATTERN: "not slow"
+ PYTEST_TARGET: "pandas/tests/[i-z]*"
steps:
- script: echo '##vso[task.prependpath]$(HOME)/miniconda3/bin'
| `ci/azure/posix.yml` only runs macOS so this if statement is always true | https://api.github.com/repos/pandas-dev/pandas/pulls/45043 | 2021-12-24T05:44:27Z | 2021-12-24T16:35:11Z | 2021-12-24T16:35:11Z | 2021-12-24T19:13:39Z |
CLN: Remove unused db setup_env.sh commands | diff --git a/ci/setup_env.sh b/ci/setup_env.sh
index 6d466072067a6..d51ff98b241a6 100755
--- a/ci/setup_env.sh
+++ b/ci/setup_env.sh
@@ -87,11 +87,6 @@ echo "w/o removing anything else"
conda remove pandas -y --force || true
pip uninstall -y pandas || true
-echo
-echo "remove postgres if has been installed with conda"
-echo "we use the one from the CI"
-conda remove postgresql -y --force || true
-
echo
echo "remove qt"
echo "causes problems with the clipboard, we use xsel for that"
@@ -117,13 +112,4 @@ echo
echo "conda list"
conda list
-# Install DB for Linux
-
-if [[ -n ${SQL:0} ]]; then
- echo "installing dbs"
- mysql -e 'create database pandas_nosetest;'
- psql -c 'create database pandas_nosetest;' -U postgres
-else
- echo "not using dbs on non-linux Travis builds or Azure Pipelines"
-fi
echo "done"
| No longer needed since we're using DB containers in Github Actions | https://api.github.com/repos/pandas-dev/pandas/pulls/45042 | 2021-12-24T05:32:44Z | 2021-12-24T16:35:35Z | 2021-12-24T16:35:35Z | 2021-12-24T19:13:25Z |
BUG: DataFrame(nested_object_ndarray) match DataFrame(nested_pandas_array) | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 7218c77e43409..7b60e29f6c57f 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -669,6 +669,7 @@ Conversion
^^^^^^^^^^
- Bug in :class:`UInt64Index` constructor when passing a list containing both positive integers small enough to cast to int64 and integers too large too hold in int64 (:issue:`42201`)
- Bug in :class:`Series` constructor returning 0 for missing values with dtype ``int64`` and ``False`` for dtype ``bool`` (:issue:`43017`, :issue:`43018`)
+- Bug in constructing a :class:`DataFrame` from a :class:`PandasArray` containing :class:`Series` objects behaving differently than an equivalent ``np.ndarray`` (:issue:`43986`)
- Bug in :class:`IntegerDtype` not allowing coercion from string dtype (:issue:`25472`)
- Bug in :func:`to_datetime` with ``arg:xr.DataArray`` and ``unit="ns"`` specified raises TypeError (:issue:`44053`)
- Bug in :meth:`DataFrame.convert_dtypes` not returning the correct type when a subclass does not overload :meth:`_constructor_sliced` (:issue:`43201`)
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 291ad2b071665..64ee843f1d946 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -57,7 +57,6 @@
)
import pandas.core.common as com
from pandas.core.construction import (
- array as pd_array,
create_series_with_explicit_dtype,
ensure_wrapped_if_datetimelike,
)
@@ -1142,9 +1141,9 @@ def apply_standard(self) -> DataFrame | Series:
)
if len(mapped) and isinstance(mapped[0], ABCSeries):
- # GH 25959 use pd.array instead of tolist
- # so extension arrays can be used
- return obj._constructor_expanddim(pd_array(mapped), index=obj.index)
+ # GH#43986 Need to do list(mapped) in order to get treated as nested
+ # See also GH#25959 regarding EA support
+ return obj._constructor_expanddim(list(mapped), index=obj.index)
else:
return obj._constructor(mapped, index=obj.index).__finalize__(
obj, method="apply"
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 794fb2afc7f9e..ae1e083e6604f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -666,7 +666,7 @@ def __init__(
typ=manager,
)
- elif isinstance(data, (np.ndarray, Series, Index)):
+ elif isinstance(data, (np.ndarray, Series, Index, ExtensionArray)):
if data.dtype.names:
# i.e. numpy structured array
data = cast(np.ndarray, data)
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index e7c2e17bc9ac1..b7d553707a91b 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -1305,6 +1305,20 @@ def test_constructor_list_of_lists(self):
result = DataFrame(data)
tm.assert_frame_equal(result, expected)
+ def test_nested_pandasarray_matches_nested_ndarray(self):
+ # GH#43986
+ ser = Series([1, 2])
+
+ arr = np.array([None, None], dtype=object)
+ arr[0] = ser
+ arr[1] = ser * 2
+
+ df = DataFrame(arr)
+ expected = DataFrame(pd.array(arr))
+ tm.assert_frame_equal(df, expected)
+ assert df.shape == (2, 1)
+ tm.assert_numpy_array_equal(df[0].values, arr)
+
def test_constructor_list_like_data_nested_list_column(self):
# GH 32173
arrays = [list("abcd"), list("cdef")]
| - [x] closes #43986
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45040 | 2021-12-24T03:19:40Z | 2021-12-27T20:07:03Z | 2021-12-27T20:07:03Z | 2021-12-27T20:24:02Z |
DOC: to_hdf() method docstring updated with dropna and index | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index fc15c846b1907..3adf30037d22f 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2684,21 +2684,25 @@ def to_hdf(
like searching / selecting subsets of the data.
- If None, pd.get_option('io.hdf.default_format') is checked,
followed by fallback to "fixed".
- errors : str, default 'strict'
- Specifies how encoding and decoding errors are to be handled.
- See the errors argument for :func:`open` for a full list
- of options.
- encoding : str, default "UTF-8"
+ index : bool, default True
+ Write DataFrame index as a column.
min_itemsize : dict or int, optional
Map column names to minimum string sizes for columns.
nan_rep : Any, optional
How to represent null values as str.
Not allowed with append=True.
+ dropna : bool, default True
+ Remove missing values.
data_columns : list of columns or True, optional
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
Applicable only to format='table'.
+ errors : str, default 'strict'
+ Specifies how encoding and decoding errors are to be handled.
+ See the errors argument for :func:`open` for a full list
+ of options.
+ encoding : str, default "UTF-8"
See Also
--------
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 3ce5cb31a127a..075a6a2b128ac 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -1103,16 +1103,34 @@ def put(
subsets of the data.
append : bool, default False
This will force Table format, append the input data to the existing.
+ complib : {‘zlib’, ‘lzo’, ‘bzip2’, ‘blosc’}, default ‘zlib’
+ Specifies the compression library to be used.
+ As of v0.20.2 these additional compressors for Blosc are supported:
+ (default if no compressor specified: ‘blosc:blosclz’):
+ {‘blosc:blosclz’, ‘blosc:lz4’, ‘blosc:lz4hc’, ‘blosc:snappy’,
+ ‘blosc:zlib’, ‘blosc:zstd’}.
+ Specifying a compression library which is not available issues a ValueError.
+ complevel : Optional int, default None
+ Level of compression.
+ min_itemsize : int|dict(str,int])|None, default None:
+ Map column names to minimum string sizes for columns.
+ nan_rep : Any, optional
+ How to represent null values as str.
data_columns : list of columns or True, default None
List of columns to create as data columns, or True to use all columns.
See `here
<https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#query-via-data-columns>`__.
encoding : str, default None
Provide an encoding for strings.
+ errors : str, default 'Strict'
+ Specifies how encoding and decoding errors are to be handled.
+ See the errors argument for open() for a full list of options.
track_times : bool, default True
Parameter is propagated to 'create_table' method of 'PyTables'.
If set to False it enables to have the same h5 files (same hashes)
independent on creation time.
+ dropna : bool, default False
+ Determine if rows which contain missing values are removed.
.. versionadded:: 1.1.0
"""
@@ -1228,8 +1246,27 @@ def append(
Table format. Write as a PyTables Table structure which may perform
worse but allow more flexible operations like searching / selecting
subsets of the data.
+ axes : Optional, specify rows or columns
+ index : bool, default True
+ Includes index values.
append : bool, default True
Append the input data to the existing.
+ complib : {‘zlib’, ‘lzo’, ‘bzip2’, ‘blosc’}, default ‘zlib’
+ Specifies the compression library to be used.
+ As of v0.20.2 these additional compressors for Blosc are supported:
+ (default if no compressor specified: ‘blosc:blosclz’):
+ {‘blosc:blosclz’, ‘blosc:lz4’,
+ ‘blosc:lz4hc’, ‘blosc:snappy’, ‘blosc:zlib’, ‘blosc:zstd’}.
+ Specifying a compression library which is not available issues a ValueError.
+ complevel : int|None, default None
+ Level of compression.
+ columns : Optional, list of columns
+ min_itemsize : int|dict(str,int])|None, default None:
+ Map column names to minimum string sizes for columns.
+ nan_rep : Any, optional
+ How to represent null values as str.
+ chunksize : Optional, size to chunk the writing
+ expectedrows : Optional, expected TOTAL row size of this table
data_columns : list of columns, or True, default None
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
@@ -1243,6 +1280,15 @@ def append(
dropna : bool, default False
Do not write an ALL nan row to the store settable
by the option 'io.hdf.dropna_table'.
+ data_columns : list of columns or True, default None
+ List of columns to create as data columns, or True to use all columns.
+ See `here
+ <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#query-via-data-columns>`__.
+ encoding : Optional str, default None
+ Provide an encoding for strings.
+ errors : str, default 'Strict'
+ Specifies how encoding and decoding errors are to be handled.
+ See the errors argument for open() for a full list of options.
Notes
-----
| Resolves GitHub Issue #45030
- [x] closes #45030
- [ ] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45039 | 2021-12-24T02:25:44Z | 2022-02-22T05:23:27Z | null | 2022-02-22T05:23:27Z |
REF: dispatch Series.rank to EA | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index b12e5be7722d0..d2e4a5b7e75bf 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -286,8 +286,6 @@ def _get_hashtable_algo(values: np.ndarray):
def _get_values_for_rank(values: ArrayLike) -> np.ndarray:
- if is_categorical_dtype(values):
- values = cast("Categorical", values)._values_for_rank()
values = _ensure_data(values)
if values.dtype.kind in ["i", "u", "f"]:
@@ -993,13 +991,13 @@ def rank(
na_option: str = "keep",
ascending: bool = True,
pct: bool = False,
-) -> np.ndarray:
+) -> npt.NDArray[np.float64]:
"""
Rank the values along a given axis.
Parameters
----------
- values : array-like
+ values : np.ndarray or ExtensionArray
Array whose values will be ranked. The number of dimensions in this
array must not exceed 2.
axis : int, default 0
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index fc915f5f84d8b..b884ee1e0a395 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -73,6 +73,7 @@
from pandas.core.algorithms import (
factorize_array,
isin,
+ rank,
unique,
)
from pandas.core.array_algos.quantile import quantile_with_mask
@@ -1496,6 +1497,32 @@ def _fill_mask_inplace(
self[mask] = new_values[mask]
return
+ def _rank(
+ self,
+ *,
+ axis: int = 0,
+ method: str = "average",
+ na_option: str = "keep",
+ ascending: bool = True,
+ pct: bool = False,
+ ):
+ """
+ See Series.rank.__doc__.
+ """
+ if axis != 0:
+ raise NotImplementedError
+
+ # TODO: we only have tests that get here with dt64 and td64
+ # TODO: all tests that get here use the defaults for all the kwds
+ return rank(
+ self,
+ axis=axis,
+ method=method,
+ na_option=na_option,
+ ascending=ascending,
+ pct=pct,
+ )
+
@classmethod
def _empty(cls, shape: Shape, dtype: ExtensionDtype):
"""
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 0ce7e0fbfb80a..9d59386cda9c3 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -1842,6 +1842,30 @@ def sort_values(
codes = self._codes[sorted_idx]
return self._from_backing_data(codes)
+ def _rank(
+ self,
+ *,
+ axis: int = 0,
+ method: str = "average",
+ na_option: str = "keep",
+ ascending: bool = True,
+ pct: bool = False,
+ ):
+ """
+ See Series.rank.__doc__.
+ """
+ if axis != 0:
+ raise NotImplementedError
+ vff = self._values_for_rank()
+ return algorithms.rank(
+ vff,
+ axis=axis,
+ method=method,
+ na_option=na_option,
+ ascending=ascending,
+ pct=pct,
+ )
+
def _values_for_rank(self):
"""
For correctly ranking ordered categorical data. See GH#15420
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index fc15c846b1907..7190251c0dfd0 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8494,19 +8494,32 @@ def rank(
raise ValueError(msg)
def ranker(data):
- ranks = algos.rank(
- data.values,
- axis=axis,
- method=method,
- ascending=ascending,
- na_option=na_option,
- pct=pct,
- )
- # error: Argument 1 to "NDFrame" has incompatible type "ndarray"; expected
- # "Union[ArrayManager, BlockManager]"
- ranks_obj = self._constructor(
- ranks, **data._construct_axes_dict() # type: ignore[arg-type]
- )
+ if data.ndim == 2:
+ # i.e. DataFrame, we cast to ndarray
+ values = data.values
+ else:
+ # i.e. Series, can dispatch to EA
+ values = data._values
+
+ if isinstance(values, ExtensionArray):
+ ranks = values._rank(
+ axis=axis,
+ method=method,
+ ascending=ascending,
+ na_option=na_option,
+ pct=pct,
+ )
+ else:
+ ranks = algos.rank(
+ values,
+ axis=axis,
+ method=method,
+ ascending=ascending,
+ na_option=na_option,
+ pct=pct,
+ )
+
+ ranks_obj = self._constructor(ranks, **data._construct_axes_dict())
return ranks_obj.__finalize__(self, method="rank")
# if numeric_only is None, and we can't get anything, we try with
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
Test coverage is severely lacking here.
Maybe could implement the general case in terms of argsort? cc @TomAugspurger @jorisvandenbossche | https://api.github.com/repos/pandas-dev/pandas/pulls/45037 | 2021-12-24T00:01:35Z | 2021-12-27T18:24:41Z | 2021-12-27T18:24:41Z | 2021-12-27T18:38:24Z |
DOC: Fixups for whatsnew 1.4 | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index c4b82b8c2df9a..50a11c4cb6639 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -268,8 +268,8 @@ Ignoring dtypes in concat with empty or all-NA columns
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When using :func:`concat` to concatenate two or more :class:`DataFrame` objects,
-if one of the DataFrames was empty or had all-NA values, its dtype was _sometimes_
-ignored when finding the concatenated dtype. These are now consistently _not_ ignored (:issue:`43507`).
+if one of the DataFrames was empty or had all-NA values, its dtype was *sometimes*
+ignored when finding the concatenated dtype. These are now consistently *not* ignored (:issue:`43507`).
.. ipython:: python
@@ -297,7 +297,7 @@ Now the float-dtype is respected. Since the common dtype for these DataFrames is
res
-.. _whatsnew_140.notable_bug_fixes.value_counts_and_mode_do_not_coerse_to_nan:
+.. _whatsnew_140.notable_bug_fixes.value_counts_and_mode_do_not_coerce_to_nan:
Null-values are no longer coerced to NaN-value in value_counts and mode
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -535,7 +535,7 @@ Other Deprecations
- Deprecated silent dropping of columns that raised a ``TypeError``, ``DataError``, and some cases of ``ValueError`` in :meth:`Series.aggregate`, :meth:`DataFrame.aggregate`, :meth:`Series.groupby.aggregate`, and :meth:`DataFrame.groupby.aggregate` when used with a list (:issue:`43740`)
- Deprecated casting behavior when setting timezone-aware value(s) into a timezone-aware :class:`Series` or :class:`DataFrame` column when the timezones do not match. Previously this cast to object dtype. In a future version, the values being inserted will be converted to the series or column's existing timezone (:issue:`37605`)
- Deprecated casting behavior when passing an item with mismatched-timezone to :meth:`DatetimeIndex.insert`, :meth:`DatetimeIndex.putmask`, :meth:`DatetimeIndex.where` :meth:`DatetimeIndex.fillna`, :meth:`Series.mask`, :meth:`Series.where`, :meth:`Series.fillna`, :meth:`Series.shift`, :meth:`Series.replace`, :meth:`Series.reindex` (and :class:`DataFrame` column analogues). In the past this has cast to object dtype. In a future version, these will cast the passed item to the index or series's timezone (:issue:`37605`,:issue:`44940`)
-- Deprecated the 'errors' keyword argument in :meth:`Series.where`, :meth:`DataFrame.where`, :meth:`Series.mask`, and meth:`DataFrame.mask`; in a future version the argument will be removed (:issue:`44294`)
+- Deprecated the 'errors' keyword argument in :meth:`Series.where`, :meth:`DataFrame.where`, :meth:`Series.mask`, and :meth:`DataFrame.mask`; in a future version the argument will be removed (:issue:`44294`)
- Deprecated the ``prefix`` keyword argument in :func:`read_csv` and :func:`read_table`, in a future version the argument will be removed (:issue:`43396`)
- Deprecated :meth:`PeriodIndex.astype` to ``datetime64[ns]`` or ``DatetimeTZDtype``, use ``obj.to_timestamp(how).tz_localize(dtype.tz)`` instead (:issue:`44398`)
- Deprecated passing non boolean argument to sort in :func:`concat` (:issue:`41518`)
@@ -636,7 +636,7 @@ Datetimelike
- Bug in adding a ``np.timedelta64`` object to a :class:`BusinessDay` or :class:`CustomBusinessDay` object incorrectly raising (:issue:`44532`)
- Bug in :meth:`Index.insert` for inserting ``np.datetime64``, ``np.timedelta64`` or ``tuple`` into :class:`Index` with ``dtype='object'`` with negative loc adding ``None`` and replacing existing value (:issue:`44509`)
- Bug in :meth:`Series.mode` with ``DatetimeTZDtype`` incorrectly returning timezone-naive and ``PeriodDtype`` incorrectly raising (:issue:`41927`)
-- 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`)
-
Timedelta
@@ -718,14 +718,14 @@ Indexing
- Bug in :meth:`IntervalIndex.get_indexer_non_unique` returning boolean mask instead of array of integers for a non unique and non monotonic index (:issue:`44084`)
- Bug in :meth:`IntervalIndex.get_indexer_non_unique` not handling targets of ``dtype`` 'object' with NaNs correctly (:issue:`44482`)
- Fixed regression where a single column ``np.matrix`` was no longer coerced to a 1d ``np.ndarray`` when added to a :class:`DataFrame` (:issue:`42376`)
-- Bug in :meth:`Series.__getitem__` with a :class:`CategoricalIndex` of integers treating lists of integers as positional indexers, inconsistent with the behavior with a single scalar integer (:issue:`15470`,:issue:`14865`)
+- Bug in :meth:`Series.__getitem__` with a :class:`CategoricalIndex` of integers treating lists of integers as positional indexers, inconsistent with the behavior with a single scalar integer (:issue:`15470`, :issue:`14865`)
-
Missing
^^^^^^^
- Bug in :meth:`DataFrame.fillna` with limit and no method ignores axis='columns' or ``axis = 1`` (:issue:`40989`)
- Bug in :meth:`DataFrame.fillna` not replacing missing values when using a dict-like ``value`` and duplicate column names (:issue:`43476`)
-- Bug in constructing a :class:`DataFrame` with a dictionary ``np.datetime64`` as a value and ``dtype='timedelta64[ns]'``, or vice-versa, incorrectly casting instead of raising (:issue:`??`)
+- Bug in constructing a :class:`DataFrame` with a dictionary ``np.datetime64`` as a value and ``dtype='timedelta64[ns]'``, or vice-versa, incorrectly casting instead of raising (:issue:`44428`)
- Bug in :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` with ``inplace=True`` not writing to the underlying array(s) in-place (:issue:`44749`)
- Bug in :meth:`Index.fillna` incorrectly returning an un-filled :class:`Index` when NA values are present and ``downcast`` argument is specified. This now raises ``NotImplementedError`` instead; do not pass ``downcast`` argument (:issue:`44873`)
- Bug in :meth:`DataFrame.dropna` changing :class:`Index` even if no entries were dropped (:issue:`41965`)
@@ -749,7 +749,7 @@ I/O
- Column headers are dropped when constructing a :class:`DataFrame` from a sqlalchemy's ``Row`` object (:issue:`40682`)
- Bug in unpickling a :class:`Index` with object dtype incorrectly inferring numeric dtypes (:issue:`43188`)
- Bug in :func:`read_csv` where reading multi-header input with unequal lengths incorrectly raising uncontrolled ``IndexError`` (:issue:`43102`)
-- Bug in :func:`read_csv` raising ``ParserError`` when reading file in chunks and aome chunk blocks have fewer columns than header for ``engine="c"`` (:issue:`21211`)
+- Bug in :func:`read_csv` raising ``ParserError`` when reading file in chunks and some chunk blocks have fewer columns than header for ``engine="c"`` (:issue:`21211`)
- Bug in :func:`read_csv`, changed exception class when expecting a file path name or file-like object from ``OSError`` to ``TypeError`` (:issue:`43366`)
- Bug in :func:`read_csv` and :func:`read_fwf` ignoring all ``skiprows`` except first when ``nrows`` is specified for ``engine='python'`` (:issue:`44021`, :issue:`10261`)
- Bug in :func:`read_csv` keeping the original column in object format when ``keep_date_col=True`` is set (:issue:`13378`)
@@ -775,7 +775,7 @@ I/O
- Bug in :func:`read_csv` where reading a mixed column of booleans and missing values to a float type results in the missing values becoming 1.0 rather than NaN (:issue:`42808`, :issue:`34120`)
- Bug in :func:`read_csv` when passing simultaneously a parser in ``date_parser`` and ``parse_dates=False``, the parsing was still called (:issue:`44366`)
- Bug in :func:`read_csv` not setting name of :class:`MultiIndex` columns correctly when ``index_col`` is not the first column (:issue:`38549`)
-- Bug in :func:`read_csv` silently ignoring errors when failling to create a memory-mapped file (:issue:`44766`)
+- Bug in :func:`read_csv` silently ignoring errors when failing to create a memory-mapped file (:issue:`44766`)
- Bug in :func:`read_csv` when passing a ``tempfile.SpooledTemporaryFile`` opened in binary mode (:issue:`44748`)
-
@@ -789,7 +789,7 @@ Period
Plotting
^^^^^^^^
-- When given non-numeric data, :meth:`DataFrame.boxplot` now raises a ``ValueError`` rather than a cryptic ``KeyError`` or ``ZeroDivsionError``, in line with other plotting functions like :meth:`DataFrame.hist`. (:issue:`43480`)
+- When given non-numeric data, :meth:`DataFrame.boxplot` now raises a ``ValueError`` rather than a cryptic ``KeyError`` or ``ZeroDivisionError``, in line with other plotting functions like :meth:`DataFrame.hist`. (:issue:`43480`)
-
Groupby/resample/rolling
@@ -849,7 +849,7 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
- Bug in :func:`array` failing to preserve :class:`PandasArray` (:issue:`43887`)
-- NumPy ufuncs ``np.abs``, ``np.positive``, ``np.negative`` now correctly preserve dtype when called on ExtensionArrays that implement ``__abs__, __pos__, __neg__``, respectively. In particular this is fixed for :class:`TimedeltaArray` (:issue:`43899`,:issue:`23316`)
+- NumPy ufuncs ``np.abs``, ``np.positive``, ``np.negative`` now correctly preserve dtype when called on ExtensionArrays that implement ``__abs__, __pos__, __neg__``, respectively. In particular this is fixed for :class:`TimedeltaArray` (:issue:`43899`, :issue:`23316`)
- NumPy ufuncs ``np.minimum.reduce`` and ``np.maximum.reduce`` now work correctly instead of raising ``NotImplementedError`` on :class:`Series` with ``IntegerDtype`` or ``FloatDtype`` (:issue:`43923`)
- Avoid raising ``PerformanceWarning`` about fragmented DataFrame when using many columns with an extension dtype (:issue:`44098`)
- Bug in :class:`IntegerArray` and :class:`FloatingArray` construction incorrectly coercing mismatched NA values (e.g. ``np.timedelta64("NaT")``) to numeric NA (:issue:`44514`)
@@ -857,7 +857,7 @@ ExtensionArray
- Bug in :func:`array` incorrectly raising when passed a ``ndarray`` with ``float16`` dtype (:issue:`44715`)
- Bug in calling ``np.sqrt`` on :class:`BooleanArray` returning a malformed :class:`FloatingArray` (:issue:`44715`)
- Bug in :meth:`Series.where` with ``ExtensionDtype`` when ``other`` is a NA scalar incompatible with the series dtype (e.g. ``NaT`` with a numeric dtype) incorrectly casting to a compatible NA value (:issue:`44697`)
-- Fixed bug in :meth:`Series.replace` with ``FloatDtype``, ``string[python]``, or ``string[pyarrow]`` dtype not being preserved when possible (:issue:`33484`,:issue:`40732`,:issue:`31644`,:issue:`41215`,:issue:`25438`)
+- Fixed bug in :meth:`Series.replace` with ``FloatDtype``, ``string[python]``, or ``string[pyarrow]`` dtype not being preserved when possible (:issue:`33484`, :issue:`40732`, :issue:`31644`, :issue:`41215`, :issue:`25438`)
-
Styler
@@ -879,7 +879,7 @@ Other
- Bug in :meth:`RangeIndex.union` with another ``RangeIndex`` with matching (even) ``step`` and starts differing by strictly less than ``step / 2`` (:issue:`44019`)
- Bug in :meth:`RangeIndex.difference` with ``sort=None`` and ``step<0`` failing to sort (:issue:`44085`)
- Bug in :meth:`Series.to_frame` and :meth:`Index.to_frame` ignoring the ``name`` argument when ``name=None`` is explicitly passed (:issue:`44212`)
-- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` with ``value=None`` and ExtensionDtypes (:issue:`44270`,:issue:`37899`)
+- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` with ``value=None`` and ExtensionDtypes (:issue:`44270`, :issue:`37899`)
- Bug in :meth:`FloatingArray.equals` failing to consider two arrays equal if they contain ``np.nan`` values (:issue:`44382`)
- Bug in :meth:`DataFrame.shift` with ``axis=1`` and ``ExtensionDtype`` columns incorrectly raising when an incompatible ``fill_value`` is passed (:issue:`44564`)
- Bug in :meth:`DataFrame.shift` with ``axis=1`` and ``periods`` larger than ``len(frame.columns)`` producing an invalid :class:`DataFrame` (:issue:`44978`)
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them | https://api.github.com/repos/pandas-dev/pandas/pulls/45035 | 2021-12-23T23:31:17Z | 2021-12-24T16:35:47Z | 2021-12-24T16:35:47Z | 2021-12-24T16:36:19Z |
REF: Implement EA._mode, de-special-case categorical/dtlike | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index a7252b6a7b7a2..1d7b5ad781236 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -935,7 +935,7 @@ def duplicated(
return htable.duplicated(values, keep=keep)
-def mode(values, dropna: bool = True) -> Series:
+def mode(values: ArrayLike, dropna: bool = True) -> ArrayLike:
"""
Returns the mode(s) of an array.
@@ -948,27 +948,17 @@ def mode(values, dropna: bool = True) -> Series:
Returns
-------
- mode : Series
+ np.ndarray or ExtensionArray
"""
- from pandas import Series
- from pandas.core.indexes.api import default_index
-
values = _ensure_arraylike(values)
original = values
- # categorical is a fast-path
- if is_categorical_dtype(values.dtype):
- if isinstance(values, Series):
- # TODO: should we be passing `name` below?
- return Series(values._values.mode(dropna=dropna), name=values.name)
- return values.mode(dropna=dropna)
-
if needs_i8_conversion(values.dtype):
- if dropna:
- mask = values.isna()
- values = values[~mask]
- modes = mode(values.view("i8"))
- return modes.view(original.dtype)
+ # Got here with ndarray; dispatch to DatetimeArray/TimedeltaArray.
+ values = ensure_wrapped_if_datetimelike(values)
+ # error: Item "ndarray[Any, Any]" of "Union[ExtensionArray,
+ # ndarray[Any, Any]]" has no attribute "_mode"
+ return values._mode(dropna=dropna) # type: ignore[union-attr]
values = _ensure_data(values)
@@ -979,8 +969,7 @@ def mode(values, dropna: bool = True) -> Series:
warn(f"Unable to sort modes: {err}")
result = _reconstruct_data(npresult, original.dtype, original)
- # Ensure index is type stable (should always use int index)
- return Series(result, index=default_index(len(result)))
+ return result
def rank(
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 26869b431bd35..e2462b6277556 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -73,6 +73,7 @@
from pandas.core.algorithms import (
factorize_array,
isin,
+ mode,
rank,
unique,
)
@@ -1578,6 +1579,26 @@ def _quantile(
return result
+ def _mode(self: ExtensionArrayT, dropna: bool = True) -> ExtensionArrayT:
+ """
+ Returns the mode(s) of the ExtensionArray.
+
+ Always returns `ExtensionArray` even if only one value.
+
+ Parameters
+ ----------
+ dropna : bool, default True
+ Don't consider counts of NA values.
+
+ Returns
+ -------
+ same type as self
+ Sorted, if possible.
+ """
+ # error: Incompatible return value type (got "Union[ExtensionArray,
+ # ndarray[Any, Any]]", expected "ExtensionArrayT")
+ return mode(self, dropna=dropna) # type: ignore[return-value]
+
def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
if any(
isinstance(other, (ABCSeries, ABCIndex, ABCDataFrame)) for other in inputs
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 9d59386cda9c3..851bd941a5297 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2229,7 +2229,7 @@ def max(self, *, skipna=True, **kwargs):
pointer = self._codes.max()
return self._wrap_reduction_result(None, pointer)
- def mode(self, dropna=True):
+ def mode(self, dropna: bool = True) -> Categorical:
"""
Returns the mode(s) of the Categorical.
@@ -2244,6 +2244,15 @@ def mode(self, dropna=True):
-------
modes : `Categorical` (sorted)
"""
+ warn(
+ "Categorical.mode is deprecated and will be removed in a future version. "
+ "Use Series.mode instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+ return self._mode(dropna=dropna)
+
+ def _mode(self, dropna: bool = True) -> Categorical:
codes = self._codes
if dropna:
good = self._codes != -1
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 80d8af63d7b88..e814cb8f996c2 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -99,6 +99,7 @@
from pandas.core.algorithms import (
checked_add_with_arr,
isin,
+ mode,
unique1d,
)
from pandas.core.arraylike import OpsMixin
@@ -1531,6 +1532,17 @@ def median(self, *, axis: int | None = None, skipna: bool = True, **kwargs):
result = nanops.nanmedian(self._ndarray, axis=axis, skipna=skipna)
return self._wrap_reduction_result(axis, result)
+ def _mode(self, dropna: bool = True):
+ values = self
+ if dropna:
+ mask = values.isna()
+ values = values[~mask]
+
+ i8modes = mode(values.view("i8"))
+ npmodes = i8modes.view(self._ndarray.dtype)
+ npmodes = cast(np.ndarray, npmodes)
+ return self._from_backing_data(npmodes)
+
class DatelikeOps(DatetimeLikeArrayMixin):
"""
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 746512e8fb7d6..84ede4ea34d56 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1999,7 +1999,16 @@ def mode(self, dropna: bool = True) -> Series:
Modes of the Series in sorted order.
"""
# TODO: Add option for bins like value_counts()
- return algorithms.mode(self, dropna=dropna)
+ values = self._values
+ if isinstance(values, np.ndarray):
+ res_values = algorithms.mode(values, dropna=dropna)
+ else:
+ res_values = values._mode(dropna=dropna)
+
+ # Ensure index is type stable (should always use int index)
+ return self._constructor(
+ res_values, index=range(len(res_values)), name=self.name
+ )
def unique(self) -> ArrayLike:
"""
diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py
index 89f2241fc6993..17384f3136a5a 100644
--- a/pandas/tests/arrays/categorical/test_analytics.py
+++ b/pandas/tests/arrays/categorical/test_analytics.py
@@ -147,7 +147,9 @@ def test_numpy_min_max_axis_equals_none(self, method, expected):
)
def test_mode(self, values, categories, exp_mode):
s = Categorical(values, categories=categories, ordered=True)
- res = s.mode()
+ msg = "Use Series.mode instead"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = s.mode()
exp = Categorical(exp_mode, categories=categories, ordered=True)
tm.assert_categorical_equal(res, exp)
diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py
index c5b0428131973..8fb51af70f3a0 100644
--- a/pandas/tests/series/test_reductions.py
+++ b/pandas/tests/series/test_reductions.py
@@ -7,7 +7,6 @@
Series,
)
import pandas._testing as tm
-from pandas.core.algorithms import mode
@pytest.mark.parametrize("as_period", [True, False])
@@ -24,12 +23,6 @@ def test_mode_extension_dtype(as_period):
assert res.dtype == ser.dtype
tm.assert_series_equal(res, ser)
- res = mode(ser._values)
- tm.assert_series_equal(res, ser)
-
- res = mode(pd.Index(ser))
- tm.assert_series_equal(res, ser)
-
def test_reductions_td64_with_nat():
# GH#8617
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index fcb50e463d9f9..0efe4a62c6152 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -2261,7 +2261,7 @@ def test_int64_add_overflow():
class TestMode:
def test_no_mode(self):
exp = Series([], dtype=np.float64, index=Index([], dtype=int))
- tm.assert_series_equal(algos.mode([]), exp)
+ tm.assert_numpy_array_equal(algos.mode([]), exp.values)
@pytest.mark.parametrize("dt", np.typecodes["AllInteger"] + np.typecodes["Float"])
def test_mode_single(self, dt):
@@ -2272,20 +2272,22 @@ def test_mode_single(self, dt):
exp_multi = [1]
data_multi = [1, 1]
- s = Series(data_single, dtype=dt)
+ ser = Series(data_single, dtype=dt)
exp = Series(exp_single, dtype=dt)
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
+ tm.assert_series_equal(ser.mode(), exp)
- s = Series(data_multi, dtype=dt)
+ ser = Series(data_multi, dtype=dt)
exp = Series(exp_multi, dtype=dt)
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
+ tm.assert_series_equal(ser.mode(), exp)
def test_mode_obj_int(self):
exp = Series([1], dtype=int)
- tm.assert_series_equal(algos.mode([1]), exp)
+ tm.assert_numpy_array_equal(algos.mode([1]), exp.values)
exp = Series(["a", "b", "c"], dtype=object)
- tm.assert_series_equal(algos.mode(["a", "b", "c"]), exp)
+ tm.assert_numpy_array_equal(algos.mode(["a", "b", "c"]), exp.values)
@pytest.mark.parametrize("dt", np.typecodes["AllInteger"] + np.typecodes["Float"])
def test_number_mode(self, dt):
@@ -2295,104 +2297,120 @@ def test_number_mode(self, dt):
exp_multi = [1, 3]
data_multi = [1] * 5 + [2] * 3 + [3] * 5
- s = Series(data_single, dtype=dt)
+ ser = Series(data_single, dtype=dt)
exp = Series(exp_single, dtype=dt)
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
+ tm.assert_series_equal(ser.mode(), exp)
- s = Series(data_multi, dtype=dt)
+ ser = Series(data_multi, dtype=dt)
exp = Series(exp_multi, dtype=dt)
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
+ tm.assert_series_equal(ser.mode(), exp)
def test_strobj_mode(self):
exp = ["b"]
data = ["a"] * 2 + ["b"] * 3
- s = Series(data, dtype="c")
+ ser = Series(data, dtype="c")
exp = Series(exp, dtype="c")
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
+ tm.assert_series_equal(ser.mode(), exp)
@pytest.mark.parametrize("dt", [str, object])
def test_strobj_multi_char(self, dt):
exp = ["bar"]
data = ["foo"] * 2 + ["bar"] * 3
- s = Series(data, dtype=dt)
+ ser = Series(data, dtype=dt)
exp = Series(exp, dtype=dt)
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
+ tm.assert_series_equal(ser.mode(), exp)
def test_datelike_mode(self):
exp = Series(["1900-05-03", "2011-01-03", "2013-01-02"], dtype="M8[ns]")
- s = Series(["2011-01-03", "2013-01-02", "1900-05-03"], dtype="M8[ns]")
- tm.assert_series_equal(algos.mode(s), exp)
+ ser = Series(["2011-01-03", "2013-01-02", "1900-05-03"], dtype="M8[ns]")
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
+ tm.assert_series_equal(ser.mode(), exp)
exp = Series(["2011-01-03", "2013-01-02"], dtype="M8[ns]")
- s = Series(
+ ser = Series(
["2011-01-03", "2013-01-02", "1900-05-03", "2011-01-03", "2013-01-02"],
dtype="M8[ns]",
)
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
+ tm.assert_series_equal(ser.mode(), exp)
def test_timedelta_mode(self):
exp = Series(["-1 days", "0 days", "1 days"], dtype="timedelta64[ns]")
- s = Series(["1 days", "-1 days", "0 days"], dtype="timedelta64[ns]")
- tm.assert_series_equal(algos.mode(s), exp)
+ ser = Series(["1 days", "-1 days", "0 days"], dtype="timedelta64[ns]")
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
+ tm.assert_series_equal(ser.mode(), exp)
exp = Series(["2 min", "1 day"], dtype="timedelta64[ns]")
- s = Series(
+ ser = Series(
["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"],
dtype="timedelta64[ns]",
)
- tm.assert_series_equal(algos.mode(s), exp)
+ tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
+ tm.assert_series_equal(ser.mode(), exp)
def test_mixed_dtype(self):
exp = Series(["foo"])
- s = Series([1, "foo", "foo"])
- tm.assert_series_equal(algos.mode(s), exp)
+ ser = Series([1, "foo", "foo"])
+ tm.assert_numpy_array_equal(algos.mode(ser.values), exp.values)
+ tm.assert_series_equal(ser.mode(), exp)
def test_uint64_overflow(self):
exp = Series([2 ** 63], dtype=np.uint64)
- s = Series([1, 2 ** 63, 2 ** 63], dtype=np.uint64)
- tm.assert_series_equal(algos.mode(s), exp)
+ 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)
- s = Series([1, 2 ** 63], dtype=np.uint64)
- tm.assert_series_equal(algos.mode(s), exp)
+ 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)
def test_categorical(self):
c = Categorical([1, 2])
exp = c
- tm.assert_categorical_equal(algos.mode(c), exp)
- tm.assert_categorical_equal(c.mode(), exp)
+ msg = "Categorical.mode is deprecated"
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = c.mode()
+ tm.assert_categorical_equal(res, exp)
c = Categorical([1, "a", "a"])
exp = Categorical(["a"], categories=[1, "a"])
- tm.assert_categorical_equal(algos.mode(c), exp)
- tm.assert_categorical_equal(c.mode(), exp)
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = c.mode()
+ tm.assert_categorical_equal(res, exp)
c = Categorical([1, 1, 2, 3, 3])
exp = Categorical([1, 3], categories=[1, 2, 3])
- tm.assert_categorical_equal(algos.mode(c), exp)
- tm.assert_categorical_equal(c.mode(), exp)
+ with tm.assert_produces_warning(FutureWarning, match=msg):
+ res = c.mode()
+ tm.assert_categorical_equal(res, exp)
def test_index(self):
idx = Index([1, 2, 3])
exp = Series([1, 2, 3], dtype=np.int64)
- tm.assert_series_equal(algos.mode(idx), exp)
+ tm.assert_numpy_array_equal(algos.mode(idx), exp.values)
idx = Index([1, "a", "a"])
exp = Series(["a"], dtype=object)
- tm.assert_series_equal(algos.mode(idx), exp)
+ tm.assert_numpy_array_equal(algos.mode(idx), exp.values)
idx = Index([1, 1, 2, 3, 3])
exp = Series([1, 3], dtype=np.int64)
- tm.assert_series_equal(algos.mode(idx), exp)
+ tm.assert_numpy_array_equal(algos.mode(idx), exp.values)
- exp = Series(["2 min", "1 day"], dtype="timedelta64[ns]")
idx = Index(
["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"],
dtype="timedelta64[ns]",
)
- tm.assert_series_equal(algos.mode(idx), exp)
+ with pytest.raises(AttributeError, match="TimedeltaIndex"):
+ # algos.mode expects Arraylike, does *not* unwrap TimedeltaIndex
+ algos.mode(idx)
class TestDiff:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45033 | 2021-12-23T20:38:49Z | 2021-12-28T14:09:43Z | 2021-12-28T14:09:43Z | 2021-12-28T17:15:37Z |
Error on bad lines pyarrow | diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index 76e3bd9825956..318dd659d46bf 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -77,52 +77,6 @@
)
from pandas.io.date_converters import generic_parser
-parser_defaults = {
- "delimiter": None,
- "escapechar": None,
- "quotechar": '"',
- "quoting": csv.QUOTE_MINIMAL,
- "doublequote": True,
- "skipinitialspace": False,
- "lineterminator": None,
- "header": "infer",
- "index_col": None,
- "names": None,
- "prefix": None,
- "skiprows": None,
- "skipfooter": 0,
- "nrows": None,
- "na_values": None,
- "keep_default_na": True,
- "true_values": None,
- "false_values": None,
- "converters": None,
- "dtype": None,
- "cache_dates": True,
- "thousands": None,
- "comment": None,
- "decimal": ".",
- # 'engine': 'c',
- "parse_dates": False,
- "keep_date_col": False,
- "dayfirst": False,
- "date_parser": None,
- "usecols": None,
- # 'iterator': False,
- "chunksize": None,
- "verbose": False,
- "encoding": None,
- "squeeze": None,
- "compression": None,
- "mangle_dupe_cols": True,
- "infer_datetime_format": False,
- "skip_blank_lines": True,
- "encoding_errors": "strict",
- "on_bad_lines": "error",
- "error_bad_lines": None,
- "warn_bad_lines": None,
-}
-
class ParserBase:
class BadLineHandleMethod(Enum):
@@ -1178,6 +1132,53 @@ def converter(*date_cols):
return converter
+parser_defaults = {
+ "delimiter": None,
+ "escapechar": None,
+ "quotechar": '"',
+ "quoting": csv.QUOTE_MINIMAL,
+ "doublequote": True,
+ "skipinitialspace": False,
+ "lineterminator": None,
+ "header": "infer",
+ "index_col": None,
+ "names": None,
+ "prefix": None,
+ "skiprows": None,
+ "skipfooter": 0,
+ "nrows": None,
+ "na_values": None,
+ "keep_default_na": True,
+ "true_values": None,
+ "false_values": None,
+ "converters": None,
+ "dtype": None,
+ "cache_dates": True,
+ "thousands": None,
+ "comment": None,
+ "decimal": ".",
+ # 'engine': 'c',
+ "parse_dates": False,
+ "keep_date_col": False,
+ "dayfirst": False,
+ "date_parser": None,
+ "usecols": None,
+ # 'iterator': False,
+ "chunksize": None,
+ "verbose": False,
+ "encoding": None,
+ "squeeze": None,
+ "compression": None,
+ "mangle_dupe_cols": True,
+ "infer_datetime_format": False,
+ "skip_blank_lines": True,
+ "encoding_errors": "strict",
+ "on_bad_lines": ParserBase.BadLineHandleMethod.ERROR,
+ "error_bad_lines": None,
+ "warn_bad_lines": None,
+}
+
+
def _process_date_conversion(
data_dict,
converter: Callable,
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index 468014cc2918e..464a9b0b9f88e 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -434,10 +434,7 @@
"dialect",
"warn_bad_lines",
"error_bad_lines",
- # TODO(1.4)
- # This doesn't error properly ATM, fix for release
- # but not blocker for initial PR
- # "on_bad_lines",
+ "on_bad_lines",
"delim_whitespace",
"quoting",
"lineterminator",
@@ -932,7 +929,18 @@ def _get_options_with_defaults(self, engine):
engine == "pyarrow"
and argname in _pyarrow_unsupported
and value != default
+ and value != getattr(value, "value", default)
):
+ if (
+ argname == "on_bad_lines"
+ and kwds.get("error_bad_lines") is not None
+ ):
+ argname = "error_bad_lines"
+ elif (
+ argname == "on_bad_lines" and kwds.get("warn_bad_lines") is not None
+ ):
+ argname = "warn_bad_lines"
+
raise ValueError(
f"The {repr(argname)} option is not supported with the "
f"'pyarrow' engine"
diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py
index 89d35499fd597..46ae629d09112 100644
--- a/pandas/tests/io/parser/test_unsupported.py
+++ b/pandas/tests/io/parser/test_unsupported.py
@@ -140,10 +140,12 @@ def test_pyarrow_engine(self):
f"supported with the 'pyarrow' engine"
)
kwargs = {default: object()}
- default_needs_bool = {"on_bad_lines", "error_bad_lines"}
+ default_needs_bool = {"warn_bad_lines", "error_bad_lines"}
if default == "dialect":
kwargs[default] = "excel" # test a random dialect
elif default in default_needs_bool:
kwargs[default] = True
+ elif default == "on_bad_lines":
+ kwargs[default] = "warn"
with pytest.raises(ValueError, match=msg):
read_csv(StringIO(data), engine="pyarrow", **kwargs)
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
cc @lithomas1 Not sure if that was what the TODO was referring to | https://api.github.com/repos/pandas-dev/pandas/pulls/45029 | 2021-12-23T13:35:58Z | 2021-12-29T15:19:24Z | 2021-12-29T15:19:24Z | 2023-07-26T09:54:48Z |
TYP: Fix wrong type annotations in pytables | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index bbdb88a4b04a7..fc15c846b1907 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2625,7 +2625,7 @@ def to_hdf(
min_itemsize: int | dict[str, int] | None = None,
nan_rep=None,
dropna: bool_t | None = None,
- data_columns: bool_t | list[str] | None = None,
+ data_columns: Literal[True] | list[str] | None = None,
errors: str = "strict",
encoding: str = "UTF-8",
) -> None:
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index ef9026a870423..3ce5cb31a127a 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -19,6 +19,7 @@
Any,
Callable,
Hashable,
+ Literal,
Sequence,
cast,
)
@@ -272,7 +273,7 @@ def to_hdf(
min_itemsize: int | dict[str, int] | None = None,
nan_rep=None,
dropna: bool | None = None,
- data_columns: bool | list[str] | None = None,
+ data_columns: Literal[True] | list[str] | None = None,
errors: str = "strict",
encoding: str = "UTF-8",
) -> None:
@@ -1078,7 +1079,7 @@ def put(
complevel: int | None = None,
min_itemsize: int | dict[str, int] | None = None,
nan_rep=None,
- data_columns: list[str] | None = None,
+ data_columns: Literal[True] | list[str] | None = None,
encoding=None,
errors: str = "strict",
track_times: bool = True,
@@ -1102,7 +1103,7 @@ def put(
subsets of the data.
append : bool, default False
This will force Table format, append the input data to the existing.
- data_columns : list, default None
+ data_columns : list of columns or True, default None
List of columns to create as data columns, or True to use all columns.
See `here
<https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#query-via-data-columns>`__.
@@ -1208,7 +1209,7 @@ def append(
chunksize=None,
expectedrows=None,
dropna: bool | None = None,
- data_columns: list[str] | None = None,
+ data_columns: Literal[True] | list[str] | None = None,
encoding=None,
errors: str = "strict",
):
@@ -3263,8 +3264,7 @@ class Table(Fixed):
values_axes : a list of the columns which comprise the data of this
table
data_columns : a list of the columns that we are allowing indexing
- (these become single columns in values_axes), or True to force all
- columns
+ (these become single columns in values_axes)
nan_rep : the string to use for nan representations for string
objects
levels : the names of levels
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45028 | 2021-12-23T12:23:31Z | 2021-12-23T14:52:56Z | 2021-12-23T14:52:56Z | 2021-12-23T14:53:39Z |
BUG: dropna changing index when nothing is dropped | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 040c424fb4127..588c04efed470 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -726,7 +726,7 @@ Missing
- Bug in constructing a :class:`DataFrame` with a dictionary ``np.datetime64`` as a value and ``dtype='timedelta64[ns]'``, or vice-versa, incorrectly casting instead of raising (:issue:`??`)
- Bug in :meth:`Series.interpolate` and :meth:`DataFrame.interpolate` with ``inplace=True`` not writing to the underlying array(s) in-place (:issue:`44749`)
- Bug in :meth:`Index.fillna` incorrectly returning an un-filled :class:`Index` when NA values are present and ``downcast`` argument is specified. This now raises ``NotImplementedError`` instead; do not pass ``downcast`` argument (:issue:`44873`)
--
+- Bug in :meth:`DataFrame.dropna` changing :class:`Index` even if no entries were dropped (:issue:`41965`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 34078d552e0b3..1245cbf289774 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5999,7 +5999,10 @@ def dropna(
else:
raise TypeError("must specify how or thresh")
- result = self.loc(axis=axis)[mask]
+ if np.all(mask):
+ result = self.copy()
+ else:
+ result = self.loc(axis=axis)[mask]
if inplace:
self._update_inplace(result)
diff --git a/pandas/tests/frame/methods/test_dropna.py b/pandas/tests/frame/methods/test_dropna.py
index 1207c2763db07..d0b9eebb31b93 100644
--- a/pandas/tests/frame/methods/test_dropna.py
+++ b/pandas/tests/frame/methods/test_dropna.py
@@ -267,3 +267,10 @@ def test_subset_is_nparray(self):
expected = DataFrame({"A": [1.0], "B": ["a"], "C": [4.0]})
result = df.dropna(subset=np.array(["A", "C"]))
tm.assert_frame_equal(result, expected)
+
+ def test_no_nans_in_frame(self, axis):
+ # GH#41965
+ df = DataFrame([[1, 2], [3, 4]], columns=pd.RangeIndex(0, 2))
+ expected = df.copy()
+ result = df.dropna(axis=axis)
+ tm.assert_frame_equal(result, expected, check_index_type=True)
| - [x] closes #41965
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
```
# With nan as last element
# before
# 1.63 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# after
# 1.68 ms ± 91.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# without nan
# before
# 1.6 ms ± 68.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# after
# 714 µs ± 63.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/45027 | 2021-12-23T11:05:56Z | 2021-12-23T14:55:04Z | 2021-12-23T14:55:04Z | 2021-12-23T14:56:03Z |
Fix Zstandard compression unit test | diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py
index 235f19d86a6b3..21cdf6f3274df 100644
--- a/pandas/tests/io/parser/test_network.py
+++ b/pandas/tests/io/parser/test_network.py
@@ -22,14 +22,11 @@
@pytest.mark.network
-@pytest.mark.parametrize(
- "compress_type, extension",
- icom._compression_to_extension.items(),
-)
@pytest.mark.parametrize("mode", ["explicit", "infer"])
@pytest.mark.parametrize("engine", ["python", "c"])
-def test_compressed_urls(salaries_table, compress_type, extension, mode, engine):
- check_compressed_urls(salaries_table, compress_type, extension, mode, engine)
+def test_compressed_urls(salaries_table, mode, engine, compression_only):
+ extension = icom._compression_to_extension[compression_only]
+ check_compressed_urls(salaries_table, compression_only, extension, mode, engine)
@tm.network
| Follow-up for #43925
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45026 | 2021-12-23T11:04:49Z | 2021-12-23T14:29:40Z | 2021-12-23T14:29:40Z | 2021-12-23T14:29:45Z |
CI: Add zstandard to env file | diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml
index 899913d6e8c70..78007e86a4848 100644
--- a/ci/deps/actions-38.yaml
+++ b/ci/deps/actions-38.yaml
@@ -18,3 +18,4 @@ dependencies:
- nomkl
- pytz
- tabulate==0.8.7
+ - zstandard
| - [ ] xref #43925
| https://api.github.com/repos/pandas-dev/pandas/pulls/45025 | 2021-12-23T10:25:52Z | 2021-12-23T14:29:59Z | null | 2021-12-23T14:59:06Z |
ENH: EA._hasnans, EADtype.empty | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 8bcdd42b9f795..fc915f5f84d8b 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -425,7 +425,7 @@ def __contains__(self, item: object) -> bool | np.bool_:
if not self._can_hold_na:
return False
elif item is self.dtype.na_value or isinstance(item, self.dtype.type):
- return self.isna().any()
+ return self._hasnans
else:
return False
else:
@@ -603,6 +603,16 @@ def isna(self) -> np.ndarray | ExtensionArraySupportsAnyAll:
"""
raise AbstractMethodError(self)
+ @property
+ def _hasnans(self) -> bool:
+ # GH#22680
+ """
+ Equivalent to `self.isna().any()`.
+
+ Some ExtensionArray subclasses may be able to optimize this check.
+ """
+ return bool(self.isna().any())
+
def _values_for_argsort(self) -> np.ndarray:
"""
Return values for sorting.
@@ -686,7 +696,7 @@ def argmin(self, skipna: bool = True) -> int:
ExtensionArray.argmax
"""
validate_bool_kwarg(skipna, "skipna")
- if not skipna and self.isna().any():
+ if not skipna and self._hasnans:
raise NotImplementedError
return nargminmax(self, "argmin")
@@ -710,7 +720,7 @@ def argmax(self, skipna: bool = True) -> int:
ExtensionArray.argmin
"""
validate_bool_kwarg(skipna, "skipna")
- if not skipna and self.isna().any():
+ if not skipna and self._hasnans:
raise NotImplementedError
return nargminmax(self, "argmax")
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index 372abee701b02..afd0d69e7e829 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -17,6 +17,7 @@
from pandas._libs.hashtable import object_hash
from pandas._typing import (
DtypeObj,
+ Shape,
npt,
type_t,
)
@@ -208,6 +209,19 @@ def construct_array_type(cls) -> type_t[ExtensionArray]:
"""
raise AbstractMethodError(cls)
+ def empty(self, shape: Shape) -> type_t[ExtensionArray]:
+ """
+ Construct an ExtensionArray of this dtype with the given shape.
+
+ Analogous to numpy.empty.
+
+ Returns
+ -------
+ ExtensionArray
+ """
+ cls = self.construct_array_type()
+ return cls._empty(shape, dtype=self)
+
@classmethod
def construct_from_string(
cls: type_t[ExtensionDtypeT], string: str
diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py
index 4ba315eeaeb15..c86054aed7e4d 100644
--- a/pandas/tests/extension/base/constructors.py
+++ b/pandas/tests/extension/base/constructors.py
@@ -126,6 +126,12 @@ def test_construct_empty_dataframe(self, dtype):
def test_empty(self, dtype):
cls = dtype.construct_array_type()
result = cls._empty((4,), dtype=dtype)
-
assert isinstance(result, cls)
assert result.dtype == dtype
+ assert result.shape == (4,)
+
+ # GH#19600 method on ExtensionDtype
+ result2 = dtype.empty((4,))
+ assert isinstance(result2, cls)
+ assert result2.dtype == dtype
+ assert result2.shape == (4,)
| - [x] closes #19600
- [x] closes #22680
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45024 | 2021-12-23T05:04:48Z | 2021-12-23T17:12:43Z | 2021-12-23T17:12:42Z | 2021-12-23T21:03:25Z |
BUG: Series.__getitem__ with CategoricalIndex[ints] listlike inconsistent with scalar | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 040c424fb4127..d02c0e38427ac 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -717,6 +717,7 @@ Indexing
- Bug in :meth:`IntervalIndex.get_indexer_non_unique` returning boolean mask instead of array of integers for a non unique and non monotonic index (:issue:`44084`)
- Bug in :meth:`IntervalIndex.get_indexer_non_unique` not handling targets of ``dtype`` 'object' with NaNs correctly (:issue:`44482`)
- Fixed regression where a single column ``np.matrix`` was no longer coerced to a 1d ``np.ndarray`` when added to a :class:`DataFrame` (:issue:`42376`)
+- Bug in :meth:`Series.__getitem__` with a :class:`CategoricalIndex` of integers treating lists of integers as positional indexers, inconsistent with the behavior with a single scalar integer (:issue:`15470`,:issue:`14865`)
-
Missing
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 9ef43c740d602..1cc15e9a5569f 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -16,7 +16,10 @@
DtypeObj,
npt,
)
-from pandas.util._decorators import doc
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
from pandas.util._exceptions import find_stack_level
from pandas.core.dtypes.common import (
@@ -180,6 +183,10 @@ class CategoricalIndex(NDArrayBackedExtensionIndex):
def _can_hold_strings(self):
return self.categories._can_hold_strings
+ @cache_readonly
+ def _should_fallback_to_positional(self) -> bool:
+ return self.categories._should_fallback_to_positional
+
codes: np.ndarray
categories: Index
ordered: bool | None
diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py
index 343cc21beb4b6..dabe3d480ff19 100644
--- a/pandas/tests/series/indexing/test_getitem.py
+++ b/pandas/tests/series/indexing/test_getitem.py
@@ -163,6 +163,27 @@ def test_getitem_scalar_categorical_index(self):
result = ser[cats[0]]
assert result == expected
+ def test_getitem_numeric_categorical_listlike_matches_scalar(self):
+ # GH#15470
+ ser = Series(["a", "b", "c"], index=pd.CategoricalIndex([2, 1, 0]))
+
+ # 0 is treated as a label
+ assert ser[0] == "c"
+
+ # the listlike analogue should also be treated as labels
+ res = ser[[0]]
+ expected = ser.iloc[-1:]
+ tm.assert_series_equal(res, expected)
+
+ res2 = ser[[0, 1, 2]]
+ tm.assert_series_equal(res2, ser.iloc[::-1])
+
+ def test_getitem_integer_categorical_not_positional(self):
+ # GH#14865
+ ser = Series(["a", "b", "c"], index=Index([1, 2, 3], dtype="category"))
+ assert ser.get(3) == "c"
+ assert ser[3] == "c"
+
def test_getitem_str_with_timedeltaindex(self):
rng = timedelta_range("1 day 10:11:12", freq="h", periods=500)
ser = Series(np.arange(len(rng)), index=rng)
| - [x] closes #15470
- [x] closes #14865
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45023 | 2021-12-23T04:43:31Z | 2021-12-23T16:18:29Z | 2021-12-23T16:18:28Z | 2021-12-23T16:24:18Z |
DOC: Run doctests for pandas/plotting | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 64c8368e06417..f3a8d6b12b970 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -75,6 +75,7 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
pandas/core \
pandas/errors/ \
pandas/io/ \
+ pandas/plotting/ \
pandas/tseries/ \
pandas/util/ \
pandas/_typing.py \
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 524a26b2d3fa6..5ad3e404b94a9 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -338,7 +338,7 @@ def hist_frame(
>>> np.random.seed(1234)
>>> df = pd.DataFrame(np.random.randn(10, 4),
... columns=['Col1', 'Col2', 'Col3', 'Col4'])
- >>> boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3'])
+ >>> boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3']) # doctest: +SKIP
Boxplots of variables distributions grouped by the values of a third
variable can be created using the option ``by``. For instance:
@@ -381,7 +381,7 @@ def hist_frame(
.. plot::
:context: close-figs
- >>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15)
+ >>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15) # doctest: +SKIP
The parameter ``return_type`` can be used to select the type of element
returned by `boxplot`. When ``return_type='axes'`` is selected,
@@ -591,14 +591,14 @@ def boxplot_frame_groupby(
>>> data = np.random.randn(len(index),4)
>>> df = pd.DataFrame(data, columns=list('ABCD'), index=index)
>>> grouped = df.groupby(level='lvl1')
- >>> grouped.boxplot(rot=45, fontsize=12, figsize=(8,10))
+ >>> grouped.boxplot(rot=45, fontsize=12, figsize=(8,10)) # doctest: +SKIP
The ``subplots=False`` option shows the boxplots in a single figure.
.. plot::
:context: close-figs
- >>> grouped.boxplot(subplots=False, rot=45, fontsize=12)
+ >>> grouped.boxplot(subplots=False, rot=45, fontsize=12) # doctest: +SKIP
"""
plot_backend = _get_plot_backend(backend)
return plot_backend.boxplot_frame_groupby(
@@ -987,6 +987,7 @@ def __call__(self, *args, **kwargs):
>>> s = pd.Series([1, 3, 2])
>>> s.plot.line()
+ <AxesSubplot:ylabel='Density'>
.. plot::
:context: close-figs
diff --git a/pandas/plotting/_matplotlib/groupby.py b/pandas/plotting/_matplotlib/groupby.py
index 37cc3186fe097..1b16eefb360ae 100644
--- a/pandas/plotting/_matplotlib/groupby.py
+++ b/pandas/plotting/_matplotlib/groupby.py
@@ -49,8 +49,15 @@ def create_iter_data_given_by(
... [3, 4, np.nan, np.nan], [np.nan, np.nan, 5, 6]]
>>> data = DataFrame(value, columns=mi)
>>> create_iter_data_given_by(data)
- {'h1': DataFrame({'a': [1, 3, np.nan], 'b': [3, 4, np.nan]}),
- 'h2': DataFrame({'a': [np.nan, np.nan, 5], 'b': [np.nan, np.nan, 6]})}
+ {'h1': h1
+ a b
+ 0 1.0 3.0
+ 1 3.0 4.0
+ 2 NaN NaN, 'h2': h2
+ a b
+ 0 NaN NaN
+ 1 NaN NaN
+ 2 5.0 6.0}
"""
# For `hist` plot, before transformation, the values in level 0 are values
@@ -96,10 +103,10 @@ def reconstruct_data_with_by(
>>> df = DataFrame(d)
>>> reconstruct_data_with_by(df, by='h', cols=['a', 'b'])
h1 h2
- a b a b
- 0 1 3 NaN NaN
- 1 3 4 NaN NaN
- 2 NaN NaN 5 6
+ a b a b
+ 0 1.0 3.0 NaN NaN
+ 1 3.0 4.0 NaN NaN
+ 2 NaN NaN 5.0 6.0
"""
grouped = data.groupby(by)
diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py
index e0a860b9d8709..ac7e467aa3d9f 100644
--- a/pandas/plotting/_misc.py
+++ b/pandas/plotting/_misc.py
@@ -123,6 +123,22 @@ def scatter_matrix(
>>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
>>> pd.plotting.scatter_matrix(df, alpha=0.2)
+ array([[<AxesSubplot:xlabel='A', ylabel='A'>,
+ <AxesSubplot:xlabel='B', ylabel='A'>,
+ <AxesSubplot:xlabel='C', ylabel='A'>,
+ <AxesSubplot:xlabel='D', ylabel='A'>],
+ [<AxesSubplot:xlabel='A', ylabel='B'>,
+ <AxesSubplot:xlabel='B', ylabel='B'>,
+ <AxesSubplot:xlabel='C', ylabel='B'>,
+ <AxesSubplot:xlabel='D', ylabel='B'>],
+ [<AxesSubplot:xlabel='A', ylabel='C'>,
+ <AxesSubplot:xlabel='B', ylabel='C'>,
+ <AxesSubplot:xlabel='C', ylabel='C'>,
+ <AxesSubplot:xlabel='D', ylabel='C'>],
+ [<AxesSubplot:xlabel='A', ylabel='D'>,
+ <AxesSubplot:xlabel='B', ylabel='D'>,
+ <AxesSubplot:xlabel='C', ylabel='D'>,
+ <AxesSubplot:xlabel='D', ylabel='D'>]], dtype=object)
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.scatter_matrix(
@@ -208,6 +224,7 @@ def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds):
... }
... )
>>> pd.plotting.radviz(df, 'Category')
+ <AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.radviz(
@@ -266,6 +283,7 @@ def andrews_curves(
... 'pandas/master/pandas/tests/io/data/csv/iris.csv'
... )
>>> pd.plotting.andrews_curves(df, 'Name')
+ <AxesSubplot:title={'center':'width'}>
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.andrews_curves(
@@ -325,6 +343,7 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
>>> s = pd.Series(np.random.uniform(size=100))
>>> pd.plotting.bootstrap_plot(s)
+ <Figure size 640x480 with 6 Axes>
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.bootstrap_plot(
@@ -392,6 +411,7 @@ def parallel_coordinates(
>>> pd.plotting.parallel_coordinates(
... df, 'Name', color=('#556270', '#4ECDC4', '#C7F464')
... )
+ <AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.parallel_coordinates(
@@ -440,6 +460,7 @@ def lag_plot(series, lag=1, ax=None, **kwds):
>>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50))
>>> s = pd.Series(x)
>>> s.plot()
+ <AxesSubplot:xlabel='Midrange'>
A lag plot with ``lag=1`` returns
@@ -447,6 +468,7 @@ def lag_plot(series, lag=1, ax=None, **kwds):
:context: close-figs
>>> pd.plotting.lag_plot(s, lag=1)
+ <AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.lag_plot(series=series, lag=lag, ax=ax, **kwds)
@@ -480,6 +502,7 @@ def autocorrelation_plot(series, ax=None, **kwargs):
>>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
>>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
>>> pd.plotting.autocorrelation_plot(s)
+ <AxesSubplot:title={'center':'width'}, xlabel='Lag', ylabel='Autocorrelation'>
"""
plot_backend = _get_plot_backend("matplotlib")
return plot_backend.autocorrelation_plot(series=series, ax=ax, **kwargs)
| - [x] closes #22459
| https://api.github.com/repos/pandas-dev/pandas/pulls/45019 | 2021-12-23T00:28:21Z | 2021-12-24T16:32:14Z | 2021-12-24T16:32:13Z | 2021-12-24T19:13:58Z |
BUG: DataFrame(dict_of_series) raising depending on order of dict | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 2c77b87f8efb6..2dec3b6bdebc7 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -609,6 +609,7 @@ Other Deprecations
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
+- Deprecated :meth:`DatetimeIndex.union_many`, use :meth:`DatetimeIndex.union` instead (:issue:`44091`)
- Deprecated :meth:`.Groupby.pad` in favor of :meth:`.Groupby.ffill` (:issue:`33396`)
- Deprecated :meth:`.Groupby.backfill` in favor of :meth:`.Groupby.bfill` (:issue:`33396`)
- Deprecated :meth:`.Resample.pad` in favor of :meth:`.Resample.ffill` (:issue:`33396`)
@@ -708,6 +709,7 @@ Datetimelike
- Bug in :meth:`Series.mode` with ``DatetimeTZDtype`` incorrectly returning timezone-naive and ``PeriodDtype`` incorrectly raising (:issue:`41927`)
- 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`)
-
Timedelta
diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py
index e497012f23b68..922c344510375 100644
--- a/pandas/core/indexes/api.py
+++ b/pandas/core/indexes/api.py
@@ -8,6 +8,8 @@
)
from pandas.errors import InvalidIndexError
+from pandas.core.dtypes.common import is_dtype_equal
+
from pandas.core.indexes.base import (
Index,
_new_Index,
@@ -213,14 +215,41 @@ def conv(i):
if kind == "special":
result = indexes[0]
+ first = result
+
+ dtis = [x for x in indexes if isinstance(x, DatetimeIndex)]
+ dti_tzs = [x for x in dtis if x.tz is not None]
+ if len(dti_tzs) not in [0, len(dtis)]:
+ # TODO: this behavior is not tested (so may not be desired),
+ # but is kept in order to keep behavior the same when
+ # deprecating union_many
+ # test_frame_from_dict_with_mixed_indexes
+ raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex")
+
+ if len(dtis) == len(indexes):
+ sort = True
+ if not all(is_dtype_equal(x.dtype, first.dtype) for x in indexes):
+ # i.e. timezones mismatch
+ # TODO(2.0): once deprecation is enforced, this union will
+ # cast to UTC automatically.
+ indexes = [x.tz_convert("UTC") for x in indexes]
+
+ result = indexes[0]
+
+ elif len(dtis) > 1:
+ # If we have mixed timezones, our casting behavior may depend on
+ # the order of indexes, which we don't want.
+ sort = False
+
+ # TODO: what about Categorical[dt64]?
+ # test_frame_from_dict_with_mixed_indexes
+ indexes = [x.astype(object, copy=False) for x in indexes]
+ result = indexes[0]
+
+ for other in indexes[1:]:
+ result = result.union(other, sort=None if sort else False)
+ return result
- if hasattr(result, "union_many"):
- # DatetimeIndex
- return result.union_many(indexes[1:])
- else:
- for other in indexes[1:]:
- result = result.union(other, sort=None if sort else False)
- return result
elif kind == "array":
index = indexes[0]
if not all(index.equals(other) for other in indexes[1:]):
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 187fa2f3aa1aa..5a3da9b65d03b 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -387,6 +387,13 @@ def union_many(self, others):
"""
A bit of a hack to accelerate unioning a collection of indexes.
"""
+ warnings.warn(
+ "DatetimeIndex.union_many is deprecated and will be removed in "
+ "a future version. Use obj.union instead.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
+
this = self
for other in others:
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index b7d553707a91b..8b677bde2f7e2 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -2666,6 +2666,50 @@ def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):
exp = pd.period_range("1/1/1980", "1/1/2012", freq="M")
tm.assert_index_equal(df.index, exp)
+ def test_frame_from_dict_with_mixed_tzaware_indexes(self):
+ # GH#44091
+ dti = date_range("2016-01-01", periods=3)
+
+ ser1 = Series(range(3), index=dti)
+ ser2 = Series(range(3), index=dti.tz_localize("UTC"))
+ ser3 = Series(range(3), index=dti.tz_localize("US/Central"))
+ ser4 = Series(range(3))
+
+ # no tz-naive, but we do have mixed tzs and a non-DTI
+ df1 = DataFrame({"A": ser2, "B": ser3, "C": ser4})
+ exp_index = Index(
+ list(ser2.index) + list(ser3.index) + list(ser4.index), dtype=object
+ )
+ tm.assert_index_equal(df1.index, exp_index)
+
+ df2 = DataFrame({"A": ser2, "C": ser4, "B": ser3})
+ exp_index3 = Index(
+ list(ser2.index) + list(ser4.index) + list(ser3.index), dtype=object
+ )
+ tm.assert_index_equal(df2.index, exp_index3)
+
+ df3 = DataFrame({"B": ser3, "A": ser2, "C": ser4})
+ exp_index3 = Index(
+ list(ser3.index) + list(ser2.index) + list(ser4.index), dtype=object
+ )
+ tm.assert_index_equal(df3.index, exp_index3)
+
+ df4 = DataFrame({"C": ser4, "B": ser3, "A": ser2})
+ exp_index4 = Index(
+ list(ser4.index) + list(ser3.index) + list(ser2.index), dtype=object
+ )
+ tm.assert_index_equal(df4.index, exp_index4)
+
+ # TODO: not clear if these raising is desired (no extant tests),
+ # but this is de facto behavior 2021-12-22
+ msg = "Cannot join tz-naive with tz-aware DatetimeIndex"
+ with pytest.raises(TypeError, match=msg):
+ DataFrame({"A": ser2, "B": ser3, "C": ser4, "D": ser1})
+ with pytest.raises(TypeError, match=msg):
+ DataFrame({"A": ser2, "B": ser3, "D": ser1})
+ with pytest.raises(TypeError, match=msg):
+ DataFrame({"D": ser1, "A": ser2, "B": ser3})
+
class TestDataFrameConstructorWithDtypeCoercion:
def test_floating_values_integer_dtype(self):
@@ -2911,7 +2955,7 @@ def test_construction_from_ndarray_with_eadtype_mismatched_columns(self):
DataFrame(arr2, columns=["foo", "bar"])
-def get1(obj):
+def get1(obj): # TODO: make a helper in tm?
if isinstance(obj, Series):
return obj.iloc[0]
else:
diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py
index ae4ed04f8adac..7c2b3b7f4482d 100644
--- a/pandas/tests/indexes/datetimes/test_setops.py
+++ b/pandas/tests/indexes/datetimes/test_setops.py
@@ -26,6 +26,13 @@
START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
+def test_union_many_deprecated():
+ dti = date_range("2016-01-01", periods=3)
+
+ with tm.assert_produces_warning(FutureWarning):
+ dti.union_many([dti, dti])
+
+
class TestDatetimeIndexSetOps:
tz = [
None,
| - [x] closes #44091
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45018 | 2021-12-22T22:11:35Z | 2021-12-29T16:15:19Z | 2021-12-29T16:15:18Z | 2021-12-29T16:27:07Z |
BUG: using dtype='int64' argument of Series causes ValueError: values cannot be losslessly cast to int64 for integer strings | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 929dfa5c12078..5f1c9c1889240 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1811,8 +1811,17 @@ def maybe_cast_to_integer_array(
# doesn't handle `uint64` correctly.
arr = np.asarray(arr)
- if is_unsigned_integer_dtype(dtype) and (arr < 0).any():
- raise OverflowError("Trying to coerce negative values to unsigned integers")
+ if is_unsigned_integer_dtype(dtype):
+ try:
+ if (arr < 0).any():
+ raise OverflowError(
+ "Trying to coerce negative values to unsigned integers"
+ )
+ except TypeError:
+ if (casted < 0).any():
+ raise OverflowError(
+ "Trying to coerce negative values to unsigned integers"
+ )
if is_float_dtype(arr.dtype):
if not np.isfinite(arr).all():
@@ -1823,7 +1832,7 @@ def maybe_cast_to_integer_array(
if is_object_dtype(arr.dtype):
raise ValueError("Trying to coerce float values to integers")
- if casted.dtype < arr.dtype:
+ if casted.dtype < arr.dtype or is_string_dtype(arr.dtype):
# GH#41734 e.g. [1, 200, 923442] and dtype="int8" -> overflows
warnings.warn(
f"Values are too large to be losslessly cast to {dtype}. "
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 3b7ae28be68fa..b33e3d88b7748 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1895,6 +1895,20 @@ def test_constructor_bool_dtype_missing_values(self):
expected = Series(True, index=[0], dtype="bool")
tm.assert_series_equal(result, expected)
+ def test_constructor_int64_dtype(self, any_int_dtype):
+ # GH-44923
+ result = Series(["0", "1", "2"], dtype=any_int_dtype)
+ expected = Series([0, 1, 2], dtype=any_int_dtype)
+ tm.assert_series_equal(result, expected)
+
+ def test_constructor_float64_dtype(self, any_float_dtype):
+ # GH-44923
+ if any_float_dtype in ["Float32", "Float64"]:
+ pytest.xfail(reason="Cannot be casted to FloatDtype Series")
+ result = Series(["-1", "0", "1", "2"], dtype=any_float_dtype)
+ expected = Series([-1.0, 0.0, 1.0, 2.0], dtype=any_float_dtype)
+ tm.assert_series_equal(result, expected)
+
@pytest.mark.filterwarnings(
"ignore:elementwise comparison failed:DeprecationWarning"
)
| - [x] closes #44923
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
Added extra check before returning ValueError. | https://api.github.com/repos/pandas-dev/pandas/pulls/45017 | 2021-12-22T19:59:38Z | 2022-05-07T02:52:21Z | null | 2022-05-07T02:52:22Z |
Typ parts of python parser | diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index 0b9d45a2efc59..7927439abb510 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -303,9 +303,7 @@ def _extract_multi_indexer_columns(
# clean the index_names
index_names = header.pop(-1)
- index_names, _, _ = self._clean_index_names(
- index_names, self.index_col, self.unnamed_cols
- )
+ index_names, _, _ = self._clean_index_names(index_names, self.index_col)
# extract the columns
field_count = len(header[0])
@@ -381,21 +379,24 @@ def _maybe_make_multi_index_columns(
return columns
@final
- def _make_index(self, data, alldata, columns, indexnamerow=False):
+ def _make_index(
+ self, data, alldata, columns, indexnamerow=False
+ ) -> tuple[Index | None, Sequence[Hashable] | MultiIndex]:
+ index: Index | None
if not is_index_col(self.index_col) or not self.index_col:
index = None
elif not self._has_complex_date_col:
- index = self._get_simple_index(alldata, columns)
- index = self._agg_index(index)
+ simple_index = self._get_simple_index(alldata, columns)
+ index = self._agg_index(simple_index)
elif self._has_complex_date_col:
if not self._name_processed:
(self.index_names, _, self.index_col) = self._clean_index_names(
- list(columns), self.index_col, self.unnamed_cols
+ list(columns), self.index_col
)
self._name_processed = True
- index = self._get_complex_date_index(data, columns)
- index = self._agg_index(index, try_parse_dates=False)
+ date_index = self._get_complex_date_index(data, columns)
+ index = self._agg_index(date_index, try_parse_dates=False)
# add names for the index
if indexnamerow:
@@ -966,7 +967,7 @@ def _validate_usecols_arg(self, usecols):
return usecols, usecols_dtype
return usecols, None
- def _clean_index_names(self, columns, index_col, unnamed_cols):
+ def _clean_index_names(self, columns, index_col):
if not is_index_col(index_col):
return None, columns, index_col
@@ -998,7 +999,7 @@ def _clean_index_names(self, columns, index_col, unnamed_cols):
# Only clean index names that were placeholders.
for i, name in enumerate(index_names):
- if isinstance(name, str) and name in unnamed_cols:
+ if isinstance(name, str) and name in self.unnamed_cols:
index_names[i] = None
return index_names, columns, index_col
diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py
index fc0f572c79e6b..e8909f542f335 100644
--- a/pandas/io/parsers/c_parser_wrapper.py
+++ b/pandas/io/parsers/c_parser_wrapper.py
@@ -172,7 +172,6 @@ def __init__(self, src: ReadCsvBuffer[str], **kwds):
self.names, # type: ignore[has-type]
# error: Cannot determine type of 'index_col'
self.index_col, # type: ignore[has-type]
- self.unnamed_cols,
)
if self.index_names is None:
@@ -220,6 +219,8 @@ def read(
Sequence[Hashable] | MultiIndex,
Mapping[Hashable, ArrayLike],
]:
+ index: Index | MultiIndex | None
+ column_names: Sequence[Hashable] | MultiIndex
try:
if self.low_memory:
chunks = self._reader.read_low_memory(nrows)
@@ -284,7 +285,12 @@ def read(
data_tups = sorted(data.items())
data = {k: v for k, (i, v) in zip(names, data_tups)}
- names, date_data = self._do_date_conversions(names, data)
+ column_names, date_data = self._do_date_conversions(names, data)
+
+ # maybe create a mi on the columns
+ column_names = self._maybe_make_multi_index_columns(
+ column_names, self.col_names
+ )
else:
# rename dict keys
@@ -308,12 +314,9 @@ def read(
data = {k: v for k, (i, v) in zip(names, data_tups)}
names, date_data = self._do_date_conversions(names, data)
- index, names = self._make_index(date_data, alldata, names)
-
- # maybe create a mi on the columns
- conv_names = self._maybe_make_multi_index_columns(names, self.col_names)
+ index, column_names = self._make_index(date_data, alldata, names)
- return index, conv_names, date_data
+ return index, column_names, date_data
def _filter_usecols(self, names: Sequence[Hashable]) -> Sequence[Hashable]:
# hackish
@@ -330,7 +333,7 @@ def _get_index_names(self):
if self._reader.leading_cols == 0 and self.index_col is not None:
(idx_names, names, self.index_col) = self._clean_index_names(
- names, self.index_col, self.unnamed_cols
+ names, self.index_col
)
return names, idx_names
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 52fa3be4ff418..68be818f4f3d4 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -13,6 +13,7 @@
DefaultDict,
Hashable,
Iterator,
+ List,
Literal,
Mapping,
Sequence,
@@ -37,6 +38,11 @@
from pandas.core.dtypes.common import is_integer
from pandas.core.dtypes.inference import is_dict_like
+from pandas import (
+ Index,
+ MultiIndex,
+)
+
from pandas.io.parsers.base_parser import (
ParserBase,
parser_defaults,
@@ -167,7 +173,7 @@ def __init__(self, f: ReadCsvBuffer[str] | list, **kwds):
)
self.num = re.compile(regex)
- def _make_reader(self, f) -> None:
+ def _make_reader(self, f: IO[str] | ReadCsvBuffer[str]) -> None:
sep = self.delimiter
if sep is None or len(sep) == 1:
@@ -198,10 +204,11 @@ class MyDialect(csv.Dialect):
self.pos += 1
line = f.readline()
lines = self._check_comments([[line]])[0]
+ lines_str = cast(List[str], lines)
# since `line` was a string, lines will be a list containing
# only a single string
- line = lines[0]
+ line = lines_str[0]
self.pos += 1
self.line_pos += 1
@@ -233,7 +240,11 @@ def _read():
# TextIOWrapper, mmap, None]")
self.data = reader # type: ignore[assignment]
- def read(self, rows: int | None = None):
+ def read(
+ self, rows: int | None = None
+ ) -> tuple[
+ Index | None, Sequence[Hashable] | MultiIndex, Mapping[Hashable, ArrayLike]
+ ]:
try:
content = self._get_lines(rows)
except StopIteration:
@@ -273,9 +284,11 @@ def read(self, rows: int | None = None):
conv_data = self._convert_data(data)
columns, conv_data = self._do_date_conversions(columns, conv_data)
- index, columns = self._make_index(conv_data, alldata, columns, indexnamerow)
+ index, result_columns = self._make_index(
+ conv_data, alldata, columns, indexnamerow
+ )
- return index, columns, conv_data
+ return index, result_columns, conv_data
def _exclude_implicit_index(
self,
@@ -586,7 +599,7 @@ def _handle_usecols(
self._col_indices = sorted(col_indices)
return columns
- def _buffered_line(self):
+ def _buffered_line(self) -> list[Scalar]:
"""
Return a line from buffer, filling buffer if required.
"""
@@ -876,7 +889,9 @@ def _clear_buffer(self) -> None:
_implicit_index = False
- def _get_index_name(self, columns: list[Hashable]):
+ def _get_index_name(
+ self, columns: list[Hashable]
+ ) -> tuple[list[Hashable] | None, list[Hashable], list[Hashable]]:
"""
Try several cases to get lines:
@@ -941,8 +956,8 @@ def _get_index_name(self, columns: list[Hashable]):
else:
# Case 2
- (index_name, columns_, self.index_col) = self._clean_index_names(
- columns, self.index_col, self.unnamed_cols
+ (index_name, _, self.index_col) = self._clean_index_names(
+ columns, self.index_col
)
return index_name, orig_names, columns
@@ -1034,7 +1049,7 @@ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]:
]
return zipped_content
- def _get_lines(self, rows: int | None = None):
+ def _get_lines(self, rows: int | None = None) -> list[list[Scalar]]:
lines = self.buf
new_rows = None
@@ -1131,7 +1146,7 @@ class FixedWidthReader(abc.Iterator):
def __init__(
self,
- f: IO[str],
+ f: IO[str] | ReadCsvBuffer[str],
colspecs: list[tuple[int, int]] | Literal["infer"],
delimiter: str | None,
comment: str | None,
@@ -1228,14 +1243,16 @@ def detect_colspecs(
return edge_pairs
def __next__(self) -> list[str]:
+ # Argument 1 to "next" has incompatible type "Union[IO[str],
+ # ReadCsvBuffer[str]]"; expected "SupportsNext[str]"
if self.buffer is not None:
try:
line = next(self.buffer)
except StopIteration:
self.buffer = None
- line = next(self.f)
+ line = next(self.f) # type: ignore[arg-type]
else:
- line = next(self.f)
+ line = next(self.f) # type: ignore[arg-type]
# Note: 'colspecs' is a sequence of half-open intervals.
return [line[fromm:to].strip(self.delimiter) for (fromm, to) in self.colspecs]
@@ -1252,7 +1269,7 @@ def __init__(self, f: ReadCsvBuffer[str], **kwds) -> None:
self.infer_nrows = kwds.pop("infer_nrows")
PythonParser.__init__(self, f, **kwds)
- def _make_reader(self, f: IO[str]) -> None:
+ def _make_reader(self, f: IO[str] | ReadCsvBuffer[str]) -> None:
self.data = FixedWidthReader(
f,
self.colspecs,
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45015 | 2021-12-22T16:14:46Z | 2022-02-06T22:45:00Z | 2022-02-06T22:45:00Z | 2022-08-17T20:03:03Z |
TYP: type excel util module | diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index a5db36cee4254..2ff3360d0b808 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -943,7 +943,7 @@ def supported_extensions(self):
@property
@abc.abstractmethod
- def engine(self):
+ def engine(self) -> str:
"""Name of engine."""
pass
diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py
index 66a66fbbcd78a..6be5ef0f64e16 100644
--- a/pandas/io/excel/_util.py
+++ b/pandas/io/excel/_util.py
@@ -1,8 +1,16 @@
from __future__ import annotations
from typing import (
+ TYPE_CHECKING,
Any,
+ Callable,
+ Hashable,
+ Iterable,
+ Literal,
MutableMapping,
+ Sequence,
+ TypeVar,
+ overload,
)
from pandas.compat._optional import import_optional_dependency
@@ -12,10 +20,16 @@
is_list_like,
)
-_writers: MutableMapping[str, str] = {}
+if TYPE_CHECKING:
+ from pandas.io.excel._base import ExcelWriter
+ ExcelWriter_t = type[ExcelWriter]
+ usecols_func = TypeVar("usecols_func", bound=Callable[[Hashable], object])
-def register_writer(klass):
+_writers: MutableMapping[str, ExcelWriter_t] = {}
+
+
+def register_writer(klass: ExcelWriter_t) -> None:
"""
Add engine to the excel writer registry.io.excel.
@@ -28,10 +42,12 @@ def register_writer(klass):
if not callable(klass):
raise ValueError("Can only register callables as engines")
engine_name = klass.engine
+ # for mypy
+ assert isinstance(engine_name, str)
_writers[engine_name] = klass
-def get_default_engine(ext, mode="reader"):
+def get_default_engine(ext: str, mode: Literal["reader", "writer"] = "reader") -> str:
"""
Return the default reader/writer for the given extension.
@@ -73,7 +89,7 @@ def get_default_engine(ext, mode="reader"):
return _default_readers[ext]
-def get_writer(engine_name):
+def get_writer(engine_name: str) -> ExcelWriter_t:
try:
return _writers[engine_name]
except KeyError as err:
@@ -145,7 +161,29 @@ def _range2cols(areas: str) -> list[int]:
return cols
-def maybe_convert_usecols(usecols):
+@overload
+def maybe_convert_usecols(usecols: str | list[int]) -> list[int]:
+ ...
+
+
+@overload
+def maybe_convert_usecols(usecols: list[str]) -> list[str]:
+ ...
+
+
+@overload
+def maybe_convert_usecols(usecols: usecols_func) -> usecols_func:
+ ...
+
+
+@overload
+def maybe_convert_usecols(usecols: None) -> None:
+ ...
+
+
+def maybe_convert_usecols(
+ usecols: str | list[int] | list[str] | usecols_func | None,
+) -> None | list[int] | list[str] | usecols_func:
"""
Convert `usecols` into a compatible format for parsing in `parsers.py`.
@@ -174,7 +212,17 @@ def maybe_convert_usecols(usecols):
return usecols
-def validate_freeze_panes(freeze_panes):
+@overload
+def validate_freeze_panes(freeze_panes: tuple[int, int]) -> Literal[True]:
+ ...
+
+
+@overload
+def validate_freeze_panes(freeze_panes: None) -> Literal[False]:
+ ...
+
+
+def validate_freeze_panes(freeze_panes: tuple[int, int] | None) -> bool:
if freeze_panes is not None:
if len(freeze_panes) == 2 and all(
isinstance(item, int) for item in freeze_panes
@@ -191,7 +239,9 @@ def validate_freeze_panes(freeze_panes):
return False
-def fill_mi_header(row, control_row):
+def fill_mi_header(
+ row: list[Hashable], control_row: list[bool]
+) -> tuple[list[Hashable], list[bool]]:
"""
Forward fill blank entries in row but only inside the same parent index.
@@ -224,7 +274,9 @@ def fill_mi_header(row, control_row):
return row, control_row
-def pop_header_name(row, index_col):
+def pop_header_name(
+ row: list[Hashable], index_col: int | Sequence[int]
+) -> tuple[Hashable | None, list[Hashable]]:
"""
Pop the header name for MultiIndex parsing.
@@ -243,7 +295,12 @@ def pop_header_name(row, index_col):
The original data row with the header name removed.
"""
# Pop out header name and fill w/blank.
- i = index_col if not is_list_like(index_col) else max(index_col)
+ if is_list_like(index_col):
+ assert isinstance(index_col, Iterable)
+ i = max(index_col)
+ else:
+ assert not isinstance(index_col, Iterable)
+ i = index_col
header_name = row[i]
header_name = None if header_name == "" else header_name
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45014 | 2021-12-22T11:43:20Z | 2021-12-28T15:31:32Z | 2021-12-28T15:31:32Z | 2021-12-28T16:45:16Z |
Set correct missing value indicator in astype for categorical | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 0ce7e0fbfb80a..c9a5b9e6cec67 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -108,7 +108,6 @@
)
import pandas.core.common as com
from pandas.core.construction import (
- ensure_wrapped_if_datetimelike,
extract_array,
sanitize_array,
)
@@ -539,14 +538,15 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
else:
# GH8628 (PERF): astype category codes instead of astyping array
- if is_datetime64_dtype(self.categories):
- new_cats = ensure_wrapped_if_datetimelike(self.categories._values)
- else:
- new_cats = np.asarray(self.categories)
+ new_cats = self.categories._values
try:
new_cats = new_cats.astype(dtype=dtype, copy=copy)
- fill_value = lib.item_from_zerodim(np.array(np.nan).astype(dtype))
+ fill_value = self.categories._na_value
+ if not is_valid_na_for_dtype(fill_value, dtype):
+ fill_value = lib.item_from_zerodim(
+ np.array(self.categories._na_value).astype(dtype)
+ )
except (
TypeError, # downstream error msg for CategoricalIndex is misleading
ValueError,
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 4e3306e84c1a1..c854eb1ea322a 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -56,6 +56,8 @@
nan_checker = np.isnan
INF_AS_NA = False
+_dtype_object = np.dtype("object")
+_dtype_str = np.dtype(str)
def isna(obj):
@@ -640,7 +642,11 @@ def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool:
# Numeric
return obj is not NaT and not isinstance(obj, (np.datetime64, np.timedelta64))
- elif dtype == np.dtype("object"):
+ elif dtype == _dtype_str:
+ # numpy string dtypes to avoid float np.nan
+ return not isinstance(obj, (np.datetime64, np.timedelta64, Decimal, float))
+
+ elif dtype == _dtype_object:
# This is needed for Categorical, but is kind of weird
return True
diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py
index 8733bfccd9f9d..38998d89593db 100644
--- a/pandas/tests/arrays/categorical/test_dtypes.py
+++ b/pandas/tests/arrays/categorical/test_dtypes.py
@@ -182,7 +182,7 @@ def test_astype_object_datetime_categories(self):
# GH#40754
cat = Categorical(to_datetime(["2021-03-27", NaT]))
result = cat.astype(object)
- expected = np.array([Timestamp("2021-03-27 00:00:00"), np.nan], dtype="object")
+ expected = np.array([Timestamp("2021-03-27 00:00:00"), NaT], dtype="object")
tm.assert_numpy_array_equal(result, expected)
def test_astype_object_timestamp_categories(self):
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/45012 | 2021-12-22T10:51:19Z | 2021-12-28T21:28:29Z | 2021-12-28T21:28:29Z | 2021-12-28T22:27:37Z |
CI: Remove unused asv-bot yml file | diff --git a/.github/workflows/asv-bot.yml b/.github/workflows/asv-bot.yml
deleted file mode 100644
index c2a49dd96c1c1..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 -l {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@v2
- 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
-
- - 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/master HEAD
- echo 'BENCH_OUTPUT<<EOF' >> $GITHUB_ENV
- asv compare -f 1.1 upstream/master HEAD >> $GITHUB_ENV
- echo 'EOF' >> $GITHUB_ENV
- echo "REGEX=$REGEX" >> $GITHUB_ENV
-
- - uses: actions/github-script@v4
- 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.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"]
- })
| I think we do not use this anymore. Runs get cancelled immediately | https://api.github.com/repos/pandas-dev/pandas/pulls/45011 | 2021-12-22T09:15:23Z | 2021-12-22T09:43:55Z | null | 2022-01-28T10:26:03Z |
REF: dont pass downcast=False to fillna from pytables | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 997a6bfc67dbc..e20618d9f996c 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3945,7 +3945,7 @@ def _create_axes(
new_name = name or f"values_block_{i}"
data_converted = _maybe_convert_for_string_atom(
new_name,
- blk,
+ blk.values,
existing_col=existing_col,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
@@ -4928,7 +4928,7 @@ def _unconvert_index(data, kind: str, encoding: str, errors: str) -> np.ndarray
def _maybe_convert_for_string_atom(
name: str,
- block: Block,
+ bvalues: ArrayLike,
existing_col,
min_itemsize,
nan_rep,
@@ -4936,11 +4936,12 @@ def _maybe_convert_for_string_atom(
errors,
columns: list[str],
):
- bvalues = block.values
if bvalues.dtype != object:
return bvalues
+ bvalues = cast(np.ndarray, bvalues)
+
dtype_name = bvalues.dtype.name
inferred_type = lib.infer_dtype(bvalues, skipna=False)
@@ -4956,13 +4957,9 @@ def _maybe_convert_for_string_atom(
elif not (inferred_type == "string" or dtype_name == "object"):
return bvalues
- blocks: list[Block] = block.fillna(nan_rep, downcast=False)
- # Note: because block is always object dtype, fillna goes
- # through a path such that the result is always a 1-element list
- assert len(blocks) == 1
- block = blocks[0]
-
- data = block.values
+ mask = isna(bvalues)
+ data = bvalues.copy()
+ data[mask] = nan_rep
# see if we have a valid string type
inferred_type = lib.infer_dtype(data, skipna=False)
@@ -4974,7 +4971,7 @@ def _maybe_convert_for_string_atom(
# expected behaviour:
# search block for a non-string object column by column
for i in range(data.shape[0]):
- col = block.iget(i)
+ col = data[i]
inferred_type = lib.infer_dtype(col, skipna=False)
if inferred_type != "string":
error_column_label = columns[i] if len(columns) > i else f"No.{i}"
@@ -4986,11 +4983,7 @@ def _maybe_convert_for_string_atom(
# itemsize is the maximum length of a string (along any dimension)
- # error: Argument 1 to "_convert_string_array" has incompatible type "Union[ndarray,
- # ExtensionArray]"; expected "ndarray"
- data_converted = _convert_string_array(
- data, encoding, errors # type: ignore[arg-type]
- ).reshape(data.shape)
+ data_converted = _convert_string_array(data, encoding, errors).reshape(data.shape)
itemsize = data_converted.itemsize
# specified min_itemsize?
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
That's the only place from which we pass downcast=False, so removing that makes it easier to deprecate downcast altogether #40988 (also just avoids using internals logic which is a goal anyway) | https://api.github.com/repos/pandas-dev/pandas/pulls/45010 | 2021-12-22T05:16:49Z | 2021-12-22T15:20:19Z | 2021-12-22T15:20:18Z | 2021-12-22T17:25:13Z |
DEPR: special-cased downcasting in DataFrame.where GH#44597 | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 9d788ffcfabe1..b7df9aa692655 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -545,6 +545,7 @@ Other Deprecations
- A deprecation warning is now shown for :meth:`DataFrame.to_latex` indicating the arguments signature may change and emulate more the arguments to :meth:`.Styler.to_latex` in future versions (:issue:`44411`)
- Deprecated :meth:`Categorical.replace`, use :meth:`Series.replace` instead (:issue:`44929`)
- Deprecated :meth:`Index.__getitem__` with a bool key; use ``index.values[key]`` to get the old behavior (:issue:`44051`)
+- Deprecated downcasting column-by-column in :meth:`DataFrame.where` with integer-dtypes (:issue:`44597`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 91c4946b64fe8..d9fc1a903009e 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1227,6 +1227,15 @@ def where(self, other, cond) -> list[Block]:
if m.any():
taken = result.take(m.nonzero()[0], axis=axis)
r = maybe_downcast_numeric(taken, self.dtype)
+ if r.dtype != taken.dtype:
+ warnings.warn(
+ "Downcasting integer-dtype results in .where is "
+ "deprecated and will change in a future version. "
+ "To retain the old behavior, explicitly cast the results "
+ "to the desired dtype.",
+ FutureWarning,
+ stacklevel=find_stack_level(),
+ )
nb = self.make_block(r.T, placement=self._mgr_locs[m])
result_blocks.append(nb)
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index 6ab0e2f718f8a..3d55ff5f98407 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -98,7 +98,7 @@ def test_where_upcasting(self):
tm.assert_series_equal(result, expected)
- def test_where_alignment(self, where_frame, float_string_frame):
+ def test_where_alignment(self, where_frame, float_string_frame, mixed_int_frame):
# aligning
def _check_align(df, cond, other, check_dtypes=True):
rs = df.where(cond, other)
@@ -141,7 +141,11 @@ def _check_align(df, cond, other, check_dtypes=True):
# check other is ndarray
cond = df > 0
- _check_align(df, cond, (_safe_add(df).values))
+ warn = None
+ if df is mixed_int_frame:
+ warn = FutureWarning
+ with tm.assert_produces_warning(warn, match="Downcasting integer-dtype"):
+ _check_align(df, cond, (_safe_add(df).values))
# integers are upcast, so don't check the dtypes
cond = df > 0
@@ -461,7 +465,7 @@ def test_where_complex(self):
df[df.abs() >= 5] = np.nan
tm.assert_frame_equal(df, expected)
- def test_where_axis(self):
+ def test_where_axis(self, using_array_manager):
# GH 9736
df = DataFrame(np.random.randn(2, 2))
mask = DataFrame([[False, False], [False, False]])
@@ -499,8 +503,10 @@ def test_where_axis(self):
assert return_value is None
tm.assert_frame_equal(result, expected)
+ warn = FutureWarning if using_array_manager else None
expected = DataFrame([[0, np.nan], [0, np.nan]])
- result = df.where(mask, s, axis="columns")
+ with tm.assert_produces_warning(warn, match="Downcasting integer-dtype"):
+ result = df.where(mask, s, axis="columns")
tm.assert_frame_equal(result, expected)
expected = DataFrame(
@@ -717,6 +723,23 @@ def test_where_try_cast_deprecated(frame_or_series):
obj.where(mask, -1, try_cast=False)
+def test_where_int_downcasting_deprecated(using_array_manager):
+ # GH#44597
+ arr = np.arange(6).astype(np.int16).reshape(3, 2)
+ df = DataFrame(arr)
+
+ mask = np.zeros(arr.shape, dtype=bool)
+ mask[:, 0] = True
+
+ 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)
+
+ expected = DataFrame({0: arr[:, 0], 1: np.array([2 ** 17] * 3, dtype=np.int32)})
+ tm.assert_frame_equal(res, expected)
+
+
def test_where_copies_with_noop(frame_or_series):
# GH-39595
result = frame_or_series([1, 2, 3, 4])
diff --git a/pandas/tests/frame/methods/test_clip.py b/pandas/tests/frame/methods/test_clip.py
index c851e65a7ad4f..e692948c92a26 100644
--- a/pandas/tests/frame/methods/test_clip.py
+++ b/pandas/tests/frame/methods/test_clip.py
@@ -136,7 +136,7 @@ def test_clip_against_unordered_columns(self):
tm.assert_frame_equal(result_lower, expected_lower)
tm.assert_frame_equal(result_lower_upper, expected_lower_upper)
- def test_clip_with_na_args(self, float_frame):
+ def test_clip_with_na_args(self, float_frame, using_array_manager):
"""Should process np.nan argument as None"""
# GH#17276
tm.assert_frame_equal(float_frame.clip(np.nan), float_frame)
@@ -151,7 +151,9 @@ def test_clip_with_na_args(self, float_frame):
)
tm.assert_frame_equal(result, expected)
- result = df.clip(lower=[4, 5, np.nan], axis=1)
+ warn = FutureWarning if using_array_manager else None
+ with tm.assert_produces_warning(warn, match="Downcasting integer-dtype"):
+ result = df.clip(lower=[4, 5, np.nan], axis=1)
expected = DataFrame(
{"col_0": [4, 4, 4], "col_1": [5, 5, 6], "col_2": [7, 8, 9]}
)
| - [x] closes #44597
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45009 | 2021-12-22T04:33:34Z | 2021-12-23T00:59:20Z | 2021-12-23T00:59:20Z | 2021-12-23T02:13:45Z |
BLD: remove MSVC workaround | diff --git a/pandas/_libs/src/headers/cmath b/pandas/_libs/src/headers/cmath
deleted file mode 100644
index 9e7540cfefc13..0000000000000
--- a/pandas/_libs/src/headers/cmath
+++ /dev/null
@@ -1,48 +0,0 @@
-#ifndef _PANDAS_MATH_H_
-#define _PANDAS_MATH_H_
-
-// MSVC 2017 has a bug where `x == x` can be true for NaNs.
-// MSC_VER from https://stackoverflow.com/a/70630/1889400
-// Place upper bound on this check once a fixed MSVC is released.
-#if defined(_MSC_VER) && (_MSC_VER < 1800)
-#include <cmath>
-// In older versions of Visual Studio there wasn't a std::signbit defined
-// This defines it using _copysign
-namespace std {
- __inline int isnan(double x) { return _isnan(x); }
- __inline int signbit(double num) { return _copysign(1.0, num) < 0; }
- __inline int notnan(double x) { return !isnan(x); }
-}
-#elif defined(_MSC_VER) && (_MSC_VER >= 1900)
-#include <cmath>
-namespace std {
- __inline int isnan(double x) { return _isnan(x); }
- __inline int notnan(double x) { return !isnan(x); }
-}
-#elif defined(_MSC_VER)
-#include <cmath>
-namespace std {
- __inline int isnan(double x) { return _isnan(x); }
- __inline int notnan(double x) { return x == x; }
-}
-#elif defined(__MVS__)
-#include <cmath>
-
-#define _signbit signbit
-#undef signbit
-#undef isnan
-
-namespace std {
- __inline int notnan(double x) { return x == x; }
- __inline int signbit(double num) { return _signbit(num); }
- __inline int isnan(double x) { return isnan(x); }
-}
-#else
-#include <cmath>
-
-namespace std {
- __inline int notnan(double x) { return x == x; }
-}
-
-#endif
-#endif
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index be8bb61092362..e64031d0703d8 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -2,7 +2,11 @@
import cython
-from libc.math cimport round
+from libc.math cimport (
+ round,
+ signbit,
+ sqrt,
+)
from libcpp.deque cimport deque
from pandas._libs.algos cimport TiebreakEnumType
@@ -19,14 +23,8 @@ from numpy cimport (
cnp.import_array()
-
-cdef extern from "../src/headers/cmath" namespace "std":
- bint isnan(float64_t) nogil
- bint notnan(float64_t) nogil
- int signbit(float64_t) nogil
- float64_t sqrt(float64_t x) nogil
-
from pandas._libs.algos import is_monotonic
+
from pandas._libs.dtypes cimport numeric_t
@@ -94,7 +92,7 @@ cdef inline void add_sum(float64_t val, int64_t *nobs, float64_t *sum_x,
float64_t y, t
# Not NaN
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] + 1
y = val - compensation[0]
t = sum_x[0] + y
@@ -110,7 +108,7 @@ cdef inline void remove_sum(float64_t val, int64_t *nobs, float64_t *sum_x,
float64_t y, t
# Not NaN
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] - 1
y = - val - compensation[0]
t = sum_x[0] + y
@@ -197,7 +195,7 @@ cdef inline void add_mean(float64_t val, Py_ssize_t *nobs, float64_t *sum_x,
float64_t y, t
# Not NaN
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] + 1
y = val - compensation[0]
t = sum_x[0] + y
@@ -213,7 +211,7 @@ cdef inline void remove_mean(float64_t val, Py_ssize_t *nobs, float64_t *sum_x,
cdef:
float64_t y, t
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] - 1
y = - val - compensation[0]
t = sum_x[0] + y
@@ -300,8 +298,8 @@ cdef inline void add_var(float64_t val, float64_t *nobs, float64_t *mean_x,
cdef:
float64_t delta, prev_mean, y, t
- # `isnan` instead of equality as fix for GH-21813, msvc 2017 bug
- if isnan(val):
+ # GH#21813, if msvc 2017 bug is resolved, we should be OK with != instead of `isnan`
+ if val != val:
return
nobs[0] = nobs[0] + 1
@@ -325,7 +323,7 @@ cdef inline void remove_var(float64_t val, float64_t *nobs, float64_t *mean_x,
""" remove a value from the var calc """
cdef:
float64_t delta, prev_mean, y, t
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] - 1
if nobs[0]:
# Welford's method for the online variance-calculation
@@ -450,7 +448,7 @@ cdef inline void add_skew(float64_t val, int64_t *nobs,
float64_t y, t
# Not NaN
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] + 1
y = val - compensation_x[0]
@@ -478,7 +476,7 @@ cdef inline void remove_skew(float64_t val, int64_t *nobs,
float64_t y, t
# Not NaN
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] - 1
y = - val - compensation_x[0]
@@ -520,7 +518,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
with nogil:
for i in range(0, N):
val = values_copy[i]
- if notnan(val):
+ if val == val:
nobs_mean += 1
sum_val += val
mean_val = sum_val / nobs_mean
@@ -623,7 +621,7 @@ cdef inline void add_kurt(float64_t val, int64_t *nobs,
float64_t y, t
# Not NaN
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] + 1
y = val - compensation_x[0]
@@ -656,7 +654,7 @@ cdef inline void remove_kurt(float64_t val, int64_t *nobs,
float64_t y, t
# Not NaN
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] - 1
y = - val - compensation_x[0]
@@ -702,7 +700,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
with nogil:
for i in range(0, N):
val = values_copy[i]
- if notnan(val):
+ if val == val:
nobs_mean += 1
sum_val += val
mean_val = sum_val / nobs_mean
@@ -796,7 +794,7 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start,
# setup
for j in range(s, e):
val = values[j]
- if notnan(val):
+ if val == val:
nobs += 1
err = skiplist_insert(sl, val) == -1
if err:
@@ -807,7 +805,7 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start,
# calculate adds
for j in range(end[i - 1], e):
val = values[j]
- if notnan(val):
+ if val == val:
nobs += 1
err = skiplist_insert(sl, val) == -1
if err:
@@ -816,7 +814,7 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start,
# calculate deletes
for j in range(start[i - 1], s):
val = values[j]
- if notnan(val):
+ if val == val:
skiplist_remove(sl, val)
nobs -= 1
if nobs >= minp:
@@ -1077,7 +1075,7 @@ def roll_quantile(const float64_t[:] values, ndarray[int64_t] start,
# setup
for j in range(s, e):
val = values[j]
- if notnan(val):
+ if val == val:
nobs += 1
skiplist_insert(skiplist, val)
@@ -1085,14 +1083,14 @@ def roll_quantile(const float64_t[:] values, ndarray[int64_t] start,
# calculate adds
for j in range(end[i - 1], e):
val = values[j]
- if notnan(val):
+ if val == val:
nobs += 1
skiplist_insert(skiplist, val)
# calculate deletes
for j in range(start[i - 1], s):
val = values[j]
- if notnan(val):
+ if val == val:
skiplist_remove(skiplist, val)
nobs -= 1
if nobs >= minp:
@@ -1202,7 +1200,7 @@ def roll_rank(const float64_t[:] values, ndarray[int64_t] start,
# setup
for j in range(s, e):
val = values[j] if ascending else -values[j]
- if notnan(val):
+ if val == val:
nobs += 1
rank = skiplist_insert(skiplist, val)
if rank == -1:
@@ -1229,14 +1227,14 @@ def roll_rank(const float64_t[:] values, ndarray[int64_t] start,
# calculate deletes
for j in range(start[i - 1], s):
val = values[j] if ascending else -values[j]
- if notnan(val):
+ if val == val:
skiplist_remove(skiplist, val)
nobs -= 1
# calculate adds
for j in range(end[i - 1], e):
val = values[j] if ascending else -values[j]
- if notnan(val):
+ if val == val:
nobs += 1
rank = skiplist_insert(skiplist, val)
if rank == -1:
@@ -1472,7 +1470,7 @@ cdef inline void add_weighted_var(float64_t val,
cdef:
float64_t temp, q, r
- if isnan(val):
+ if val != val:
return
nobs[0] = nobs[0] + 1
@@ -1518,7 +1516,7 @@ cdef inline void remove_weighted_var(float64_t val,
cdef:
float64_t temp, q, r
- if notnan(val):
+ if val == val:
nobs[0] = nobs[0] - 1
if nobs[0]:
@@ -1588,7 +1586,7 @@ def roll_weighted_var(const float64_t[:] values, const float64_t[:] weights,
w = weights[i % win_n]
pre_w = weights[(i - win_n) % win_n]
- if notnan(val):
+ if val == val:
if pre_val == pre_val:
remove_weighted_var(pre_val, pre_w, &t,
&sum_w, &mean, &nobs)
| - [x] closes #23209
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
Shot in the dark to see if the upstream problem behind #23209 is resolved. | https://api.github.com/repos/pandas-dev/pandas/pulls/45008 | 2021-12-22T03:06:37Z | 2022-01-30T18:51:27Z | 2022-01-30T18:51:26Z | 2022-01-30T18:53:42Z |
PERF: DataFrame(pytorch_tensor) | diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py
index 912971257490c..eace665ba0bac 100644
--- a/asv_bench/benchmarks/frame_ctor.py
+++ b/asv_bench/benchmarks/frame_ctor.py
@@ -182,4 +182,21 @@ def time_frame_from_arrays_sparse(self):
)
+class From3rdParty:
+ # GH#44616
+
+ def setup(self):
+ try:
+ import torch
+ except ImportError:
+ raise NotImplementedError
+
+ row = 700000
+ col = 64
+ self.val_tensor = torch.randn(row, col)
+
+ def time_from_torch(self):
+ DataFrame(self.val_tensor)
+
+
from .pandas_vb_common import setup # noqa: F401 isort:skip
diff --git a/ci/deps/actions-38-db.yaml b/ci/deps/actions-38-db.yaml
index 05b9eb8446af8..f445225a44dcb 100644
--- a/ci/deps/actions-38-db.yaml
+++ b/ci/deps/actions-38-db.yaml
@@ -33,6 +33,7 @@ dependencies:
- pyarrow>=1.0.1
- pymysql
- pytables
+ - pytorch
- python-snappy
- python-dateutil
- pytz
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index cdc0bbb1dfd6a..85442a876b988 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -601,6 +601,7 @@ Performance improvements
- Performance improvement in :func:`to_csv` when :class:`MultiIndex` contains a lot of unused levels (:issue:`37484`)
- Performance improvement in :func:`read_csv` when ``index_col`` was set with a numeric column (:issue:`44158`)
- Performance improvement in :func:`concat` (:issue:`43354`)
+- Performance improvement in constructing a :class:`DataFrame` from array-like objects like a ``Pytorch`` tensor (:issue:`44616`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 34078d552e0b3..2370b9ea16d94 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -702,11 +702,16 @@ def __init__(
# For data is list-like, or Iterable (will consume into list)
elif is_list_like(data):
if not isinstance(data, (abc.Sequence, ExtensionArray)):
- data = list(data)
+ if hasattr(data, "__array__"):
+ # GH#44616 big perf improvement for e.g. pytorch tensor
+ data = np.asarray(data)
+ else:
+ data = list(data)
if len(data) > 0:
if is_dataclass(data[0]):
data = dataclasses_to_dicts(data)
- if treat_as_nested(data):
+ if not isinstance(data, np.ndarray) and treat_as_nested(data):
+ # exclude ndarray as we may have cast it a few lines above
if columns is not None:
# error: Argument 1 to "ensure_index" has incompatible type
# "Collection[Any]"; expected "Union[Union[Union[ExtensionArray,
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index 1972fbbe0f414..3880b9ecd9da7 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -5,7 +5,7 @@
import subprocess
import sys
-import numpy as np # noqa:F401 needed in namespace for statsmodels
+import numpy as np
import pytest
import pandas.util._test_decorators as td
@@ -176,6 +176,20 @@ def test_pyarrow(df):
tm.assert_frame_equal(result, df)
+def test_torch_frame_construction(using_array_manager):
+ # GH#44616
+ torch = import_module("torch")
+ val_tensor = torch.randn(700, 64)
+
+ df = DataFrame(val_tensor)
+
+ if not using_array_manager:
+ assert np.shares_memory(df, val_tensor)
+
+ ser = pd.Series(val_tensor[0])
+ assert np.shares_memory(ser, val_tensor)
+
+
def test_yaml_dump(df):
# GH#42748
yaml = import_module("yaml")
| - [x] closes #44616
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
cc @YeahNew | https://api.github.com/repos/pandas-dev/pandas/pulls/45007 | 2021-12-21T23:29:57Z | 2021-12-23T16:35:50Z | 2021-12-23T16:35:50Z | 2021-12-23T16:40:47Z |
ENH: Implement Index.__invert__ | diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index be39ccd444865..2ac635ad4fb9c 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -1401,7 +1401,6 @@ class Timedelta(_Timedelta):
# Arithmetic Methods
# TODO: Can some of these be defined in the cython class?
- __inv__ = _op_unary_method(lambda x: -x, '__inv__')
__neg__ = _op_unary_method(lambda x: -x, '__neg__')
__pos__ = _op_unary_method(lambda x: x, '__pos__')
__abs__ = _op_unary_method(lambda x: abs(x), '__abs__')
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 263a046f59121..4c70b379ce1d8 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -6636,10 +6636,9 @@ def __neg__(self):
def __pos__(self):
return self._unary_method(operator.pos)
- def __inv__(self):
- # TODO: why not operator.inv?
- # TODO: __inv__ vs __invert__?
- return self._unary_method(lambda x: -x)
+ def __invert__(self):
+ # GH#8875
+ return self._unary_method(operator.inv)
# --------------------------------------------------------------------
# Reductions
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 86d7e20a551a1..bd79b4a50dcd0 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3802,7 +3802,7 @@ def drop_duplicates(self, keep: str | bool = "first") -> MultiIndex:
__neg__ = make_invalid_op("__neg__")
__pos__ = make_invalid_op("__pos__")
__abs__ = make_invalid_op("__abs__")
- __inv__ = make_invalid_op("__inv__")
+ __invert__ = make_invalid_op("__invert__")
def _lexsort_depth(codes: list[np.ndarray], nlevels: int) -> int:
diff --git a/pandas/tests/frame/test_unary.py b/pandas/tests/frame/test_unary.py
index 2129586455333..a69ca0fef7f8b 100644
--- a/pandas/tests/frame/test_unary.py
+++ b/pandas/tests/frame/test_unary.py
@@ -8,7 +8,7 @@
class TestDataFrameUnaryOperators:
- # __pos__, __neg__, __inv__
+ # __pos__, __neg__, __invert__
@pytest.mark.parametrize(
"df,expected",
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index c60c74479f8b6..6b6caf1f8affd 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -740,6 +740,30 @@ def test_append_preserves_dtype(self, simple_index):
alt = index.take(list(range(N)) * 2)
tm.assert_index_equal(result, alt, check_exact=True)
+ def test_inv(self, simple_index):
+ idx = simple_index
+
+ if idx.dtype.kind in ["i", "u"]:
+ res = ~idx
+ expected = Index(~idx.values, name=idx.name)
+ tm.assert_index_equal(res, expected)
+
+ # check that we are matching Series behavior
+ res2 = ~Series(idx)
+ # TODO(2.0): once we preserve dtype, check_dtype can be True
+ tm.assert_series_equal(res2, Series(expected), check_dtype=False)
+ else:
+ if idx.dtype.kind == "f":
+ msg = "ufunc 'invert' not supported for the input types"
+ else:
+ msg = "bad operand"
+ with pytest.raises(TypeError, match=msg):
+ ~idx
+
+ # check that we get the same behavior with Series
+ with pytest.raises(TypeError, match=msg):
+ ~Series(idx)
+
class NumericBase(Base):
"""
diff --git a/pandas/tests/indexes/multi/test_compat.py b/pandas/tests/indexes/multi/test_compat.py
index cbb4ae0b0d09b..d50a44057bd26 100644
--- a/pandas/tests/indexes/multi/test_compat.py
+++ b/pandas/tests/indexes/multi/test_compat.py
@@ -27,7 +27,7 @@ def test_numeric_compat(idx):
1 // idx
-@pytest.mark.parametrize("method", ["all", "any"])
+@pytest.mark.parametrize("method", ["all", "any", "__invert__"])
def test_logical_compat(idx, method):
msg = f"cannot perform {method}"
diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py
index 448ec4353d7e7..7a32c932aee77 100644
--- a/pandas/tests/scalar/timedelta/test_timedelta.py
+++ b/pandas/tests/scalar/timedelta/test_timedelta.py
@@ -25,6 +25,21 @@
class TestTimedeltaUnaryOps:
+ def test_invert(self):
+ td = Timedelta(10, unit="d")
+
+ msg = "bad operand type for unary ~"
+ with pytest.raises(TypeError, match=msg):
+ ~td
+
+ # check this matches pytimedelta and timedelta64
+ with pytest.raises(TypeError, match=msg):
+ ~(td.to_pytimedelta())
+
+ umsg = "ufunc 'invert' not supported for the input types"
+ with pytest.raises(TypeError, match=umsg):
+ ~(td.to_timedelta64())
+
def test_unary_ops(self):
td = Timedelta(10, unit="d")
diff --git a/pandas/tests/series/test_unary.py b/pandas/tests/series/test_unary.py
index 54fd467431489..ad0e344fa4420 100644
--- a/pandas/tests/series/test_unary.py
+++ b/pandas/tests/series/test_unary.py
@@ -5,7 +5,7 @@
class TestSeriesUnaryOps:
- # __neg__, __pos__, __inv__
+ # __neg__, __pos__, __invert__
def test_neg(self):
ser = tm.makeStringSeries()
| - [x] closes #8875
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
Could be considered a bugfix, as we have `__inv__`, which i think is a py2 leftover | https://api.github.com/repos/pandas-dev/pandas/pulls/45006 | 2021-12-21T20:24:42Z | 2021-12-23T00:57:27Z | 2021-12-23T00:57:27Z | 2021-12-23T00:59:02Z |
REGR: DataFrame.shift with periods>len(columns) GH#44978 | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 9d788ffcfabe1..9dca2761d0404 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -878,6 +878,7 @@ Other
- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` with ``value=None`` and ExtensionDtypes (:issue:`44270`,:issue:`37899`)
- Bug in :meth:`FloatingArray.equals` failing to consider two arrays equal if they contain ``np.nan`` values (:issue:`44382`)
- Bug in :meth:`DataFrame.shift` with ``axis=1`` and ``ExtensionDtype`` columns incorrectly raising when an incompatible ``fill_value`` is passed (:issue:`44564`)
+- Bug in :meth:`DataFrame.shift` with ``axis=1`` and ``periods`` larger than ``len(frame.columns)`` producing an invalid :class:`DataFrame` (:issue:`44978`)
- Bug in :meth:`DataFrame.diff` when passing a NumPy integer object instead of an ``int`` object (:issue:`44572`)
- Bug in :meth:`Series.replace` raising ``ValueError`` when using ``regex=True`` with a :class:`Series` containing ``np.nan`` values (:issue:`43344`)
- Bug in :meth:`DataFrame.to_records` where an incorrect ``n`` was used when missing names were replaced by ``level_n`` (:issue:`44818`)
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 5ebc0292f24b4..3e0b62da64f42 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -388,12 +388,13 @@ def shift(self: T, periods: int, axis: int, fill_value) -> T:
# GH#35488 we need to watch out for multi-block cases
# We only get here with fill_value not-lib.no_default
ncols = self.shape[0]
+ nper = abs(periods)
+ nper = min(nper, ncols)
if periods > 0:
indexer = np.array(
- [-1] * periods + list(range(ncols - periods)), dtype=np.intp
+ [-1] * nper + list(range(ncols - periods)), dtype=np.intp
)
else:
- nper = abs(periods)
indexer = np.array(
list(range(nper, ncols)) + [-1] * nper, dtype=np.intp
)
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index c92e3dbe27439..2463e81d78edd 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -664,3 +664,15 @@ def test_shift_axis1_categorical_columns(self):
columns=ci,
)
tm.assert_frame_equal(result, expected)
+
+ @td.skip_array_manager_not_yet_implemented
+ def test_shift_axis1_many_periods(self):
+ # GH#44978 periods > len(columns)
+ df = DataFrame(np.random.rand(5, 3))
+ shifted = df.shift(6, axis=1, fill_value=None)
+
+ expected = df * np.nan
+ tm.assert_frame_equal(shifted, expected)
+
+ shifted2 = df.shift(-6, axis=1, fill_value=None)
+ tm.assert_frame_equal(shifted2, expected)
| - [x] closes #44978
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45005 | 2021-12-21T20:15:22Z | 2021-12-22T22:53:10Z | 2021-12-22T22:53:10Z | 2021-12-22T23:44:01Z |
PERF/CLN: avoid potential copies in ravel | diff --git a/pandas/_libs/missing.pyi b/pandas/_libs/missing.pyi
index 1177e82906190..ab6841e7ddf35 100644
--- a/pandas/_libs/missing.pyi
+++ b/pandas/_libs/missing.pyi
@@ -12,4 +12,5 @@ def isposinf_scalar(val: object) -> bool: ...
def isneginf_scalar(val: object) -> bool: ...
def checknull(val: object, inf_as_na: bool = ...) -> bool: ...
def isnaobj(arr: np.ndarray, inf_as_na: bool = ...) -> npt.NDArray[np.bool_]: ...
+def isnaobj2d(arr: np.ndarray, inf_as_na: bool = ...) -> npt.NDArray[np.bool_]: ...
def is_numeric_na(values: np.ndarray) -> npt.NDArray[np.bool_]: ...
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 4e3306e84c1a1..5e810e7464d51 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -1,6 +1,8 @@
"""
missing types & inference
"""
+from __future__ import annotations
+
from decimal import Decimal
from functools import partial
@@ -17,6 +19,7 @@
from pandas._typing import (
ArrayLike,
DtypeObj,
+ npt,
)
from pandas.core.dtypes.common import (
@@ -259,18 +262,22 @@ def _isna_array(values: ArrayLike, inf_as_na: bool = False):
return result
-def _isna_string_dtype(values: np.ndarray, inf_as_na: bool) -> np.ndarray:
+def _isna_string_dtype(values: np.ndarray, inf_as_na: bool) -> npt.NDArray[np.bool_]:
# Working around NumPy ticket 1542
dtype = values.dtype
- shape = values.shape
if dtype.kind in ("S", "U"):
result = np.zeros(values.shape, dtype=bool)
else:
- result = np.empty(shape, dtype=bool)
- vec = libmissing.isnaobj(values.ravel(), inf_as_na=inf_as_na)
- result[...] = vec.reshape(shape)
+ if values.ndim == 1:
+ result = libmissing.isnaobj(values, inf_as_na=inf_as_na)
+ elif values.ndim == 2:
+ result = libmissing.isnaobj2d(values, inf_as_na=inf_as_na)
+ else:
+ # 0-D, reached via e.g. mask_missing
+ result = libmissing.isnaobj(values.ravel(), inf_as_na=inf_as_na)
+ result = result.reshape(values.shape)
return result
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index ba4a8ac202e36..5387061a0c13b 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1862,8 +1862,14 @@ def convert(
attempt to cast any object types to better types return a copy of
the block (if copy = True) by definition we ARE an ObjectBlock!!!!!
"""
+ values = self.values
+ if values.ndim == 2:
+ # maybe_split ensures we only get here with values.shape[0] == 1,
+ # avoid doing .ravel as that might make a copy
+ values = values[0]
+
res_values = soft_convert_objects(
- self.values.ravel(),
+ values,
datetime=datetime,
numeric=numeric,
timedelta=timedelta,
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 52d2322b11f42..61a81386b54a6 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -757,13 +757,10 @@ def get_median(x):
if mask is not None:
values[mask] = np.nan
- if axis is None:
- values = values.ravel("K")
-
notempty = values.size
# an array from a frame
- if values.ndim > 1:
+ if values.ndim > 1 and axis is not None:
# there's a non-empty array to apply over otherwise numpy raises
if notempty:
diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py
index 65725cbcf5a0c..8d5f7fb8de758 100644
--- a/pandas/core/ops/missing.py
+++ b/pandas/core/ops/missing.py
@@ -47,7 +47,7 @@ def _fill_zeros(result, x, y):
if is_float_dtype(result.dtype):
return result
- is_variable_type = hasattr(y, "dtype") or hasattr(y, "type")
+ is_variable_type = hasattr(y, "dtype")
is_scalar_type = is_scalar(y)
if not is_variable_type and not is_scalar_type:
@@ -58,19 +58,18 @@ def _fill_zeros(result, x, y):
if is_integer_dtype(y.dtype):
- if (y == 0).any():
+ ymask = y == 0
+ if ymask.any():
- # GH#7325, mask and nans must be broadcastable (also: GH#9308)
- # Raveling and then reshaping makes np.putmask faster
- mask = ((y == 0) & ~np.isnan(result)).ravel()
+ # GH#7325, mask and nans must be broadcastable
+ mask = ymask & ~np.isnan(result)
- shape = result.shape
- result = result.astype("float64", copy=False).ravel()
+ # GH#9308 doing ravel on result and mask can improve putmask perf,
+ # but can also make unwanted copies.
+ result = result.astype("float64", copy=False)
np.putmask(result, mask, np.nan)
- result = result.reshape(shape)
-
return result
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/45002 | 2021-12-21T19:30:27Z | 2021-12-22T16:06:15Z | 2021-12-22T16:06:15Z | 2021-12-22T16:06:16Z |
fix column_arrays for array manager | diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index 09f16a2ddab67..ec3a9e8b493e3 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -794,7 +794,8 @@ def column_arrays(self) -> list[ArrayLike]:
"""
Used in the JSON C code to access column arrays.
"""
- return self.arrays
+
+ return [np.asarray(arr) for arr in self.arrays]
def iset(
self, loc: int | slice | np.ndarray, value: ArrayLike, inplace: bool = False
diff --git a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
index 52e973aed4d4e..cd760854cb01e 100644
--- a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
+++ b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
@@ -131,9 +131,7 @@ def setup_method(self, method):
}
)
- def test_build_date_series(self, using_array_manager):
- if using_array_manager:
- pytest.skip("Segfault for array manager GH44994")
+ def test_build_date_series(self):
s = Series(self.da, name="a")
s.index.name = "id"
@@ -159,9 +157,7 @@ def test_build_date_series(self, using_array_manager):
assert result == expected
- def test_build_decimal_series(self, using_array_manager):
- if using_array_manager:
- pytest.skip("Segfault for array manager GH44994")
+ def test_build_decimal_series(self):
s = Series(self.dc, name="a")
s.index.name = "id"
@@ -237,9 +233,7 @@ def test_build_int64_series(self):
assert result == expected
- def test_to_json(self, using_array_manager):
- if using_array_manager:
- pytest.skip("Segfault for array manager GH44994")
+ def test_to_json(self):
df = self.df.copy()
df.index.name = "idx"
| - [x] closes #44994
- [ ] tests added / passed
- None - makes tests for JSON on array manager work
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
- Not needed - issue identified as result of another PR
Note - I was doing this in parallel with @phofl skipping the JSON tests for the array manager. So I undid those changes so that the JSON code tests with array manager are done. | https://api.github.com/repos/pandas-dev/pandas/pulls/45001 | 2021-12-21T18:42:59Z | 2021-12-28T19:54:34Z | 2021-12-28T19:54:34Z | 2023-02-13T20:56:17Z |
CI: Pin setuptools for sdist too | diff --git a/.github/workflows/sdist.yml b/.github/workflows/sdist.yml
index 5fc447a395aea..9ce3cc5d59208 100644
--- a/.github/workflows/sdist.yml
+++ b/.github/workflows/sdist.yml
@@ -39,9 +39,10 @@ jobs:
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 wheel
+ python -m pip install --upgrade pip "setuptools<60.0.0" wheel
# GH 39416
pip install numpy
@@ -57,8 +58,10 @@ jobs:
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
| Don't understand why this was green before | https://api.github.com/repos/pandas-dev/pandas/pulls/45000 | 2021-12-21T17:18:18Z | 2021-12-21T20:12:02Z | 2021-12-21T20:12:02Z | 2021-12-21T20:37:13Z |
CI: skip segfault tests for array manager | diff --git a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
index 3daac204aa730..52e973aed4d4e 100644
--- a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
+++ b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py
@@ -131,7 +131,10 @@ def setup_method(self, method):
}
)
- def test_build_date_series(self):
+ def test_build_date_series(self, using_array_manager):
+ if using_array_manager:
+ pytest.skip("Segfault for array manager GH44994")
+
s = Series(self.da, name="a")
s.index.name = "id"
result = s.to_json(orient="table", date_format="iso")
@@ -156,7 +159,10 @@ def test_build_date_series(self):
assert result == expected
- def test_build_decimal_series(self):
+ def test_build_decimal_series(self, using_array_manager):
+ if using_array_manager:
+ pytest.skip("Segfault for array manager GH44994")
+
s = Series(self.dc, name="a")
s.index.name = "id"
result = s.to_json(orient="table", date_format="iso")
@@ -231,7 +237,10 @@ def test_build_int64_series(self):
assert result == expected
- def test_to_json(self):
+ def test_to_json(self, using_array_manager):
+ if using_array_manager:
+ pytest.skip("Segfault for array manager GH44994")
+
df = self.df.copy()
df.index.name = "idx"
result = df.to_json(orient="table", date_format="iso")
| - [x] xref #44994
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/44999 | 2021-12-21T16:59:20Z | 2021-12-21T18:36:19Z | 2021-12-21T18:36:18Z | 2021-12-21T18:36:21Z |
CLN: follow-ups, whatsnew notes, use tm.get_obj | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 7d117d6822071..076a8e1a890c5 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -633,7 +633,7 @@ Datetimelike
- Bug in adding a ``np.timedelta64`` object to a :class:`BusinessDay` or :class:`CustomBusinessDay` object incorrectly raising (:issue:`44532`)
- Bug in :meth:`Index.insert` for inserting ``np.datetime64``, ``np.timedelta64`` or ``tuple`` into :class:`Index` with ``dtype='object'`` with negative loc adding ``None`` and replacing existing value (:issue:`44509`)
- Bug in :meth:`Series.mode` with ``DatetimeTZDtype`` incorrectly returning timezone-naive and ``PeriodDtype`` incorrectly raising (:issue:`41927`)
-- Bug in :class:`DateOffset`` addition with :class:`Timestamp` where ``offset.nanoseconds`` would not be included in the result. (:issue:`43968`)
+- Bug in :class:`DateOffset`` addition with :class:`Timestamp` where ``offset.nanoseconds`` would not be included in the result. (:issue:`43968`,:issue:`36589`)
-
Timedelta
@@ -841,7 +841,7 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
- Bug in :func:`array` failing to preserve :class:`PandasArray` (:issue:`43887`)
-- NumPy ufuncs ``np.abs``, ``np.positive``, ``np.negative`` now correctly preserve dtype when called on ExtensionArrays that implement ``__abs__, __pos__, __neg__``, respectively. In particular this is fixed for :class:`TimedeltaArray` (:issue:`43899`)
+- NumPy ufuncs ``np.abs``, ``np.positive``, ``np.negative`` now correctly preserve dtype when called on ExtensionArrays that implement ``__abs__, __pos__, __neg__``, respectively. In particular this is fixed for :class:`TimedeltaArray` (:issue:`43899`,:issue:`23316`)
- NumPy ufuncs ``np.minimum.reduce`` and ``np.maximum.reduce`` now work correctly instead of raising ``NotImplementedError`` on :class:`Series` with ``IntegerDtype`` or ``FloatDtype`` (:issue:`43923`)
- Avoid raising ``PerformanceWarning`` about fragmented DataFrame when using many columns with an extension dtype (:issue:`44098`)
- Bug in :class:`IntegerArray` and :class:`FloatingArray` construction incorrectly coercing mismatched NA values (e.g. ``np.timedelta64("NaT")``) to numeric NA (:issue:`44514`)
@@ -849,7 +849,8 @@ ExtensionArray
- Bug in :func:`array` incorrectly raising when passed a ``ndarray`` with ``float16`` dtype (:issue:`44715`)
- Bug in calling ``np.sqrt`` on :class:`BooleanArray` returning a malformed :class:`FloatingArray` (:issue:`44715`)
- Bug in :meth:`Series.where` with ``ExtensionDtype`` when ``other`` is a NA scalar incompatible with the series dtype (e.g. ``NaT`` with a numeric dtype) incorrectly casting to a compatible NA value (:issue:`44697`)
-- Fixed bug in :meth:`Series.replace` with ``FloatDtype``, ``string[python]``, or ``string[pyarrow]`` dtype not being preserved when possible (:issue:`33484`)
+- Fixed bug in :meth:`Series.replace` with ``FloatDtype``, ``string[python]``, or ``string[pyarrow]`` dtype not being preserved when possible (:issue:`33484`,:issue:`40732`,:issue:`31644`,:issue:`41215`,:issue:`25438`)
+-
Styler
^^^^^^
@@ -870,7 +871,7 @@ Other
- Bug in :meth:`RangeIndex.union` with another ``RangeIndex`` with matching (even) ``step`` and starts differing by strictly less than ``step / 2`` (:issue:`44019`)
- Bug in :meth:`RangeIndex.difference` with ``sort=None`` and ``step<0`` failing to sort (:issue:`44085`)
- Bug in :meth:`Series.to_frame` and :meth:`Index.to_frame` ignoring the ``name`` argument when ``name=None`` is explicitly passed (:issue:`44212`)
-- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` with ``value=None`` and ExtensionDtypes (:issue:`44270`)
+- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` with ``value=None`` and ExtensionDtypes (:issue:`44270`,:issue:`37899`)
- Bug in :meth:`FloatingArray.equals` failing to consider two arrays equal if they contain ``np.nan`` values (:issue:`44382`)
- Bug in :meth:`DataFrame.shift` with ``axis=1`` and ``ExtensionDtype`` columns incorrectly raising when an incompatible ``fill_value`` is passed (:issue:`44564`)
- Bug in :meth:`DataFrame.diff` when passing a NumPy integer object instead of an ``int`` object (:issue:`44572`)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 1b3c217f1293b..60c8426ff3c6c 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -128,10 +128,12 @@ def ensure_python_int(value: int | np.integer) -> int:
------
TypeError: if the value isn't an int or can't be converted to one.
"""
- if not is_scalar(value):
- raise TypeError(
- f"Value needs to be a scalar value, was type {type(value).__name__}"
- )
+ if not (is_integer(value) or is_float(value)):
+ if not is_scalar(value):
+ raise TypeError(
+ f"Value needs to be a scalar value, was type {type(value).__name__}"
+ )
+ raise TypeError(f"Wrong type {type(value)} for value {value}")
try:
new_value = int(value)
assert new_value == value
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index 887c8da6305dd..fdb1ee754a7e6 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -1041,11 +1041,7 @@ def _arith_method(self, other, op):
rstop = op(left.stop, right)
res_name = ops.get_op_result_name(self, other)
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
- # The constructor validation can lead to a DeprecationWarning
- # from numpy, e.g. with RangeIndex + np.datetime64("now")
- result = type(self)(rstart, rstop, rstep, name=res_name)
+ result = type(self)(rstart, rstop, rstep, name=res_name)
# for compat with numpy / Int64Index
# even if we can represent as a RangeIndex, return
diff --git a/pandas/tests/apply/test_frame_transform.py b/pandas/tests/apply/test_frame_transform.py
index 7434a7df37629..3384f9d46029a 100644
--- a/pandas/tests/apply/test_frame_transform.py
+++ b/pandas/tests/apply/test_frame_transform.py
@@ -141,8 +141,7 @@ def test_transform_bad_dtype(op, frame_or_series, request):
)
obj = DataFrame({"A": 3 * [object]}) # DataFrame that will fail on most transforms
- if frame_or_series is not DataFrame:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
# tshift is deprecated
warn = None if op != "tshift" else FutureWarning
diff --git a/pandas/tests/apply/test_invalid_arg.py b/pandas/tests/apply/test_invalid_arg.py
index b0faeba23a479..410a8f6bf3965 100644
--- a/pandas/tests/apply/test_invalid_arg.py
+++ b/pandas/tests/apply/test_invalid_arg.py
@@ -352,8 +352,7 @@ def test_transform_reducer_raises(all_reductions, frame_or_series, op_wrapper):
op = op_wrapper(all_reductions)
obj = DataFrame({"A": [1, 2, 3]})
- if frame_or_series is not DataFrame:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
msg = "Function did not transform"
with pytest.raises(ValueError, match=msg):
diff --git a/pandas/tests/frame/indexing/test_mask.py b/pandas/tests/frame/indexing/test_mask.py
index dd75e232051fa..bd7ffe9a8e770 100644
--- a/pandas/tests/frame/indexing/test_mask.py
+++ b/pandas/tests/frame/indexing/test_mask.py
@@ -96,9 +96,8 @@ def test_mask_pos_args_deprecation(self, frame_or_series):
# https://github.com/pandas-dev/pandas/issues/41485
obj = DataFrame({"a": range(5)})
expected = DataFrame({"a": [-1, 1, -1, 3, -1]})
- if frame_or_series is Series:
- obj = obj["a"]
- expected = expected["a"]
+ obj = tm.get_obj(obj, frame_or_series)
+ expected = tm.get_obj(expected, frame_or_series)
cond = obj % 2 == 0
msg = (
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index e668e77644082..6ab0e2f718f8a 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -708,8 +708,7 @@ def test_where_interval_noop(self):
def test_where_try_cast_deprecated(frame_or_series):
obj = DataFrame(np.random.randn(4, 3))
- if frame_or_series is not DataFrame:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
mask = obj > 0
diff --git a/pandas/tests/frame/methods/test_append.py b/pandas/tests/frame/methods/test_append.py
index c29b247cc6e17..c5b7a7ff69a53 100644
--- a/pandas/tests/frame/methods/test_append.py
+++ b/pandas/tests/frame/methods/test_append.py
@@ -15,8 +15,7 @@
class TestDataFrameAppend:
def test_append_multiindex(self, multiindex_dataframe_random_data, frame_or_series):
obj = multiindex_dataframe_random_data
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
a = obj[:5]
b = obj[5:]
diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py
index 0a8d7c43adffe..07eacb5e89e3a 100644
--- a/pandas/tests/frame/methods/test_asfreq.py
+++ b/pandas/tests/frame/methods/test_asfreq.py
@@ -88,8 +88,7 @@ def test_asfreq_keep_index_name(self, frame_or_series):
index_name = "bar"
index = date_range("20130101", periods=20, name=index_name)
obj = DataFrame(list(range(20)), columns=["foo"], index=index)
- if frame_or_series is Series:
- obj = obj["foo"]
+ obj = tm.get_obj(obj, frame_or_series)
assert index_name == obj.index.name
assert index_name == obj.asfreq("10D").index.name
@@ -97,8 +96,7 @@ def test_asfreq_keep_index_name(self, frame_or_series):
def test_asfreq_ts(self, frame_or_series):
index = period_range(freq="A", start="1/1/2001", end="12/31/2010")
obj = DataFrame(np.random.randn(len(index), 3), index=index)
- if frame_or_series is Series:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
result = obj.asfreq("D", how="end")
exp_index = index.asfreq("D", how="end")
@@ -115,8 +113,7 @@ def test_asfreq_resample_set_correct_freq(self, frame_or_series):
# we test if .asfreq() and .resample() set the correct value for .freq
dti = to_datetime(["2012-01-01", "2012-01-02", "2012-01-03"])
obj = DataFrame({"col": [1, 2, 3]}, index=dti)
- if frame_or_series is Series:
- obj = obj["col"]
+ obj = tm.get_obj(obj, frame_or_series)
# testing the settings before calling .asfreq() and .resample()
assert obj.index.freq is None
diff --git a/pandas/tests/frame/methods/test_at_time.py b/pandas/tests/frame/methods/test_at_time.py
index 2d05176d20f5f..8537c32c24e3a 100644
--- a/pandas/tests/frame/methods/test_at_time.py
+++ b/pandas/tests/frame/methods/test_at_time.py
@@ -31,8 +31,7 @@ def test_localized_at_time(self, tzstr, frame_or_series):
def test_at_time(self, frame_or_series):
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
- if frame_or_series is not DataFrame:
- ts = ts[0]
+ ts = tm.get_obj(ts, frame_or_series)
rs = ts.at_time(rng[1])
assert (rs.index.hour == rng[1].hour).all()
assert (rs.index.minute == rng[1].minute).all()
@@ -46,8 +45,7 @@ def test_at_time_midnight(self, frame_or_series):
# midnight, everything
rng = date_range("1/1/2000", "1/31/2000")
ts = DataFrame(np.random.randn(len(rng), 3), index=rng)
- if frame_or_series is not DataFrame:
- ts = ts[0]
+ ts = tm.get_obj(ts, frame_or_series)
result = ts.at_time(time(0, 0))
tm.assert_equal(result, ts)
@@ -56,8 +54,7 @@ def test_at_time_nonexistent(self, frame_or_series):
# time doesn't exist
rng = date_range("1/1/2012", freq="23Min", periods=384)
ts = DataFrame(np.random.randn(len(rng)), rng)
- if frame_or_series is not DataFrame:
- ts = ts[0]
+ ts = tm.get_obj(ts, frame_or_series)
rs = ts.at_time("16:00")
assert len(rs) == 0
@@ -87,8 +84,7 @@ def test_at_time_tz(self):
def test_at_time_raises(self, frame_or_series):
# GH#20725
obj = DataFrame([[1, 2, 3], [4, 5, 6]])
- if frame_or_series is not DataFrame:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
msg = "Index must be DatetimeIndex"
with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
obj.at_time("00:00")
diff --git a/pandas/tests/frame/methods/test_between_time.py b/pandas/tests/frame/methods/test_between_time.py
index 51f60aa2b9d76..d8a742c644e9e 100644
--- a/pandas/tests/frame/methods/test_between_time.py
+++ b/pandas/tests/frame/methods/test_between_time.py
@@ -23,8 +23,7 @@ def test_between_time_formats(self, frame_or_series):
# GH#11818
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
- if frame_or_series is Series:
- ts = ts[0]
+ ts = tm.get_obj(ts, frame_or_series)
strings = [
("2:00", "2:30"),
@@ -62,8 +61,7 @@ def test_between_time_types(self, frame_or_series):
# GH11818
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
obj = DataFrame({"A": 0}, index=rng)
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
msg = r"Cannot convert arg \[datetime\.datetime\(2010, 1, 2, 1, 0\)\] to a time"
with pytest.raises(ValueError, match=msg):
@@ -72,8 +70,7 @@ def test_between_time_types(self, frame_or_series):
def test_between_time(self, inclusive_endpoints_fixture, frame_or_series):
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
- if frame_or_series is not DataFrame:
- ts = ts[0]
+ ts = tm.get_obj(ts, frame_or_series)
stime = time(0, 0)
etime = time(1, 0)
@@ -107,8 +104,7 @@ def test_between_time(self, inclusive_endpoints_fixture, frame_or_series):
# across midnight
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
- if frame_or_series is not DataFrame:
- ts = ts[0]
+ ts = tm.get_obj(ts, frame_or_series)
stime = time(22, 0)
etime = time(9, 0)
@@ -135,8 +131,7 @@ def test_between_time(self, inclusive_endpoints_fixture, frame_or_series):
def test_between_time_raises(self, frame_or_series):
# GH#20725
obj = DataFrame([[1, 2, 3], [4, 5, 6]])
- if frame_or_series is not DataFrame:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
msg = "Index must be DatetimeIndex"
with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
@@ -215,8 +210,7 @@ def test_between_time_warn(self, include_start, include_end, frame_or_series):
# GH40245
rng = date_range("1/1/2000", "1/5/2000", freq="5min")
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
- if frame_or_series is not DataFrame:
- ts = ts[0]
+ ts = tm.get_obj(ts, frame_or_series)
stime = time(0, 0)
etime = time(1, 0)
diff --git a/pandas/tests/frame/methods/test_first_and_last.py b/pandas/tests/frame/methods/test_first_and_last.py
index 70b9af358c1b9..6b11211526960 100644
--- a/pandas/tests/frame/methods/test_first_and_last.py
+++ b/pandas/tests/frame/methods/test_first_and_last.py
@@ -13,14 +13,12 @@
class TestFirst:
def test_first_subset(self, frame_or_series):
ts = tm.makeTimeDataFrame(freq="12h")
- if frame_or_series is not DataFrame:
- ts = ts["A"]
+ ts = tm.get_obj(ts, frame_or_series)
result = ts.first("10d")
assert len(result) == 20
ts = tm.makeTimeDataFrame(freq="D")
- if frame_or_series is not DataFrame:
- ts = ts["A"]
+ ts = tm.get_obj(ts, frame_or_series)
result = ts.first("10d")
assert len(result) == 10
@@ -38,8 +36,7 @@ def test_first_subset(self, frame_or_series):
def test_first_last_raises(self, frame_or_series):
# GH#20725
obj = DataFrame([[1, 2, 3], [4, 5, 6]])
- if frame_or_series is not DataFrame:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
msg = "'first' only supports a DatetimeIndex index"
with pytest.raises(TypeError, match=msg): # index is not a DatetimeIndex
@@ -51,14 +48,12 @@ def test_first_last_raises(self, frame_or_series):
def test_last_subset(self, frame_or_series):
ts = tm.makeTimeDataFrame(freq="12h")
- if frame_or_series is not DataFrame:
- ts = ts["A"]
+ ts = tm.get_obj(ts, frame_or_series)
result = ts.last("10d")
assert len(result) == 20
ts = tm.makeTimeDataFrame(nper=30, freq="D")
- if frame_or_series is not DataFrame:
- ts = ts["A"]
+ ts = tm.get_obj(ts, frame_or_series)
result = ts.last("10d")
assert len(result) == 10
diff --git a/pandas/tests/frame/methods/test_pipe.py b/pandas/tests/frame/methods/test_pipe.py
index 26ea904260a65..1d7cc16f49280 100644
--- a/pandas/tests/frame/methods/test_pipe.py
+++ b/pandas/tests/frame/methods/test_pipe.py
@@ -21,8 +21,7 @@ def test_pipe(self, frame_or_series):
def test_pipe_tuple(self, frame_or_series):
obj = DataFrame({"A": [1, 2, 3]})
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
f = lambda x, y: y
result = obj.pipe((f, "y"), 0)
@@ -30,8 +29,7 @@ def test_pipe_tuple(self, frame_or_series):
def test_pipe_tuple_error(self, frame_or_series):
obj = DataFrame({"A": [1, 2, 3]})
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
f = lambda x, y: y
diff --git a/pandas/tests/frame/methods/test_reorder_levels.py b/pandas/tests/frame/methods/test_reorder_levels.py
index fd20c662229c1..9080bdbee0e3d 100644
--- a/pandas/tests/frame/methods/test_reorder_levels.py
+++ b/pandas/tests/frame/methods/test_reorder_levels.py
@@ -16,7 +16,7 @@ def test_reorder_levels(self, frame_or_series):
names=["L0", "L1", "L2"],
)
df = DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=index)
- obj = df if frame_or_series is DataFrame else df["A"]
+ obj = tm.get_obj(df, frame_or_series)
# no change, position
result = obj.reorder_levels([0, 1, 2])
@@ -34,7 +34,7 @@ def test_reorder_levels(self, frame_or_series):
names=["L1", "L2", "L0"],
)
expected = DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=e_idx)
- expected = expected if frame_or_series is DataFrame else expected["A"]
+ expected = tm.get_obj(expected, frame_or_series)
tm.assert_equal(result, expected)
result = obj.reorder_levels([0, 0, 0])
@@ -44,7 +44,7 @@ def test_reorder_levels(self, frame_or_series):
names=["L0", "L0", "L0"],
)
expected = DataFrame({"A": np.arange(6), "B": np.arange(6)}, index=e_idx)
- expected = expected if frame_or_series is DataFrame else expected["A"]
+ expected = tm.get_obj(expected, frame_or_series)
tm.assert_equal(result, expected)
result = obj.reorder_levels(["L0", "L0", "L0"])
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py
index 1bfc00f8d31ac..db356799ee13d 100644
--- a/pandas/tests/frame/methods/test_replace.py
+++ b/pandas/tests/frame/methods/test_replace.py
@@ -483,8 +483,7 @@ def test_replace_with_empty_list(self, frame_or_series):
# GH 21977
ser = Series([["a", "b"], [], np.nan, [1]])
obj = DataFrame({"col": ser})
- if frame_or_series is Series:
- obj = ser
+ obj = tm.get_obj(obj, frame_or_series)
expected = obj
result = obj.replace([], np.nan)
tm.assert_equal(result, expected)
@@ -1332,8 +1331,7 @@ def test_replace_with_duplicate_columns(self, replacement):
def test_replace_ea_ignore_float(self, frame_or_series, value):
# GH#34871
obj = DataFrame({"Per": [value] * 3})
- if frame_or_series is not DataFrame:
- obj = obj["Per"]
+ obj = tm.get_obj(obj, frame_or_series)
expected = obj.copy()
result = obj.replace(1.0, 0.0)
diff --git a/pandas/tests/frame/methods/test_sample.py b/pandas/tests/frame/methods/test_sample.py
index be85d6a186fcc..901987a953d82 100644
--- a/pandas/tests/frame/methods/test_sample.py
+++ b/pandas/tests/frame/methods/test_sample.py
@@ -166,8 +166,7 @@ def test_sample_none_weights(self, obj):
def test_sample_random_state(self, func_str, arg, frame_or_series):
# GH#32503
obj = DataFrame({"col1": range(10, 20), "col2": range(20, 30)})
- if frame_or_series is Series:
- obj = obj["col1"]
+ obj = tm.get_obj(obj, frame_or_series)
result = obj.sample(n=3, random_state=eval(func_str)(arg))
expected = obj.sample(n=3, random_state=com.random_state(eval(func_str)(arg)))
tm.assert_equal(result, expected)
@@ -192,8 +191,7 @@ def test_sample_upsampling_without_replacement(self, frame_or_series):
# GH#27451
obj = DataFrame({"A": list("abc")})
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
msg = (
"Replace has to be set to `True` when "
diff --git a/pandas/tests/frame/methods/test_to_period.py b/pandas/tests/frame/methods/test_to_period.py
index e3f3fe9f697a9..cd1b4b61ec033 100644
--- a/pandas/tests/frame/methods/test_to_period.py
+++ b/pandas/tests/frame/methods/test_to_period.py
@@ -21,8 +21,7 @@ def test_to_period(self, frame_or_series):
np.random.randn(len(dr), K), index=dr, columns=["A", "B", "C", "D", "E"]
)
obj["mix"] = "a"
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
pts = obj.to_period()
exp = obj.copy()
@@ -41,8 +40,7 @@ def test_to_period_without_freq(self, frame_or_series):
)
obj = DataFrame(np.random.randn(4, 4), index=idx, columns=idx)
- if frame_or_series is Series:
- obj = obj[idx[0]]
+ obj = tm.get_obj(obj, frame_or_series)
expected = obj.copy()
expected.index = exp_idx
tm.assert_equal(obj.to_period(), expected)
diff --git a/pandas/tests/frame/methods/test_to_timestamp.py b/pandas/tests/frame/methods/test_to_timestamp.py
index e23d12b691b4a..acbb51fe79643 100644
--- a/pandas/tests/frame/methods/test_to_timestamp.py
+++ b/pandas/tests/frame/methods/test_to_timestamp.py
@@ -34,8 +34,7 @@ def test_to_timestamp(self, frame_or_series):
columns=["A", "B", "C", "D", "E"],
)
obj["mix"] = "a"
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
exp_index = date_range("1/1/2001", end="12/31/2009", freq="A-DEC")
exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns")
diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py
index 33ba29c65cebb..bfee3edc085d8 100644
--- a/pandas/tests/frame/methods/test_truncate.py
+++ b/pandas/tests/frame/methods/test_truncate.py
@@ -15,8 +15,7 @@
class TestDataFrameTruncate:
def test_truncate(self, datetime_frame, frame_or_series):
ts = datetime_frame[::3]
- if frame_or_series is Series:
- ts = ts.iloc[:, 0]
+ ts = tm.get_obj(ts, frame_or_series)
start, end = datetime_frame.index[3], datetime_frame.index[6]
@@ -77,8 +76,7 @@ def test_truncate_nonsortedindex(self, frame_or_series):
# GH#17935
obj = DataFrame({"A": ["a", "b", "c", "d", "e"]}, index=[5, 3, 2, 9, 0])
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
msg = "truncate requires a sorted index"
with pytest.raises(ValueError, match=msg):
@@ -135,8 +133,7 @@ def test_truncate_multiindex(self, frame_or_series):
# GH 34564
mi = pd.MultiIndex.from_product([[1, 2, 3, 4], ["A", "B"]], names=["L1", "L2"])
s1 = DataFrame(range(mi.shape[0]), index=mi, columns=["col"])
- if frame_or_series is Series:
- s1 = s1["col"]
+ s1 = tm.get_obj(s1, frame_or_series)
result = s1.truncate(before=2, after=3)
@@ -144,8 +141,7 @@ def test_truncate_multiindex(self, frame_or_series):
{"L1": [2, 2, 3, 3], "L2": ["A", "B", "A", "B"], "col": [2, 3, 4, 5]}
)
expected = df.set_index(["L1", "L2"])
- if frame_or_series is Series:
- expected = expected["col"]
+ expected = tm.get_obj(expected, frame_or_series)
tm.assert_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py
index 046f7a4f9e1c3..bb9ea64d5f326 100644
--- a/pandas/tests/frame/methods/test_tz_convert.py
+++ b/pandas/tests/frame/methods/test_tz_convert.py
@@ -16,13 +16,11 @@ def test_tz_convert(self, frame_or_series):
rng = date_range("1/1/2011", periods=200, freq="D", tz="US/Eastern")
obj = DataFrame({"a": 1}, index=rng)
- if frame_or_series is not DataFrame:
- obj = obj["a"]
+ obj = tm.get_obj(obj, frame_or_series)
result = obj.tz_convert("Europe/Berlin")
expected = DataFrame({"a": 1}, rng.tz_convert("Europe/Berlin"))
- if frame_or_series is not DataFrame:
- expected = expected["a"]
+ expected = tm.get_obj(expected, frame_or_series)
assert result.index.tz.zone == "Europe/Berlin"
tm.assert_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_tz_localize.py b/pandas/tests/frame/methods/test_tz_localize.py
index 425ec4335455e..43c6eb4594f28 100644
--- a/pandas/tests/frame/methods/test_tz_localize.py
+++ b/pandas/tests/frame/methods/test_tz_localize.py
@@ -17,13 +17,11 @@ def test_tz_localize(self, frame_or_series):
rng = date_range("1/1/2011", periods=100, freq="H")
obj = DataFrame({"a": 1}, index=rng)
- if frame_or_series is not DataFrame:
- obj = obj["a"]
+ obj = tm.get_obj(obj, frame_or_series)
result = obj.tz_localize("utc")
expected = DataFrame({"a": 1}, rng.tz_localize("UTC"))
- if frame_or_series is not DataFrame:
- expected = expected["a"]
+ expected = tm.get_obj(expected, frame_or_series)
assert result.index.tz.zone == "UTC"
tm.assert_equal(result, expected)
diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py
index bb80bd12c1958..e71f625a6ead6 100644
--- a/pandas/tests/frame/test_repr_info.py
+++ b/pandas/tests/frame/test_repr_info.py
@@ -44,8 +44,7 @@ def test_repr_unicode_level_names(self, frame_or_series):
index = MultiIndex.from_tuples([(0, 0), (1, 1)], names=["\u0394", "i1"])
obj = DataFrame(np.random.randn(2, 4), index=index)
- if frame_or_series is Series:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
repr(obj)
def test_assign_index_sequences(self):
diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py
index 186135f598235..0eaf5fc6d6e1a 100644
--- a/pandas/tests/generic/test_generic.py
+++ b/pandas/tests/generic/test_generic.py
@@ -382,8 +382,7 @@ def test_transpose(self):
def test_numpy_transpose(self, frame_or_series):
obj = tm.makeTimeDataFrame()
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
if frame_or_series is Series:
# 1D -> np.transpose is no-op
@@ -417,8 +416,7 @@ def test_take_invalid_kwargs(self, frame_or_series):
indices = [-3, 2, 0, 1]
obj = tm.makeTimeDataFrame()
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
msg = r"take\(\) got an unexpected keyword argument 'foo'"
with pytest.raises(TypeError, match=msg):
@@ -436,8 +434,7 @@ def test_take_invalid_kwargs(self, frame_or_series):
def test_depr_take_kwarg_is_copy(self, is_copy, frame_or_series):
# GH 27357
obj = DataFrame({"A": [1, 2, 3]})
- if frame_or_series is Series:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
msg = (
"is_copy is deprecated and will be removed in a future version. "
@@ -485,8 +482,7 @@ def test_flags_identity(self, frame_or_series):
def test_slice_shift_deprecated(self, frame_or_series):
# GH 37601
obj = DataFrame({"A": [1, 2, 3, 4]})
- if frame_or_series is DataFrame:
- obj = obj["A"]
+ obj = tm.get_obj(obj, frame_or_series)
with tm.assert_produces_warning(FutureWarning):
obj.slice_shift()
diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py
index c565902d080c3..72e7e458b4e1f 100644
--- a/pandas/tests/indexes/period/test_partial_slicing.py
+++ b/pandas/tests/indexes/period/test_partial_slicing.py
@@ -126,8 +126,7 @@ def test_maybe_cast_slice_bound(self, make_range, frame_or_series):
idx = make_range(start="2013/10/01", freq="D", periods=10)
obj = DataFrame({"units": [100 + i for i in range(10)]}, index=idx)
- if frame_or_series is not DataFrame:
- obj = obj["units"]
+ obj = tm.get_obj(obj, frame_or_series)
msg = (
f"cannot do slice indexing on {type(idx).__name__} with "
diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py
index 2a12d690ff0bd..47868779c7ef7 100644
--- a/pandas/tests/indexing/multiindex/test_setitem.py
+++ b/pandas/tests/indexing/multiindex/test_setitem.py
@@ -387,8 +387,7 @@ def test_loc_getitem_setitem_slice_integers(self, frame_or_series):
obj = DataFrame(
np.random.randn(len(index), 4), index=index, columns=["a", "b", "c", "d"]
)
- if frame_or_series is not DataFrame:
- obj = obj["a"]
+ obj = tm.get_obj(obj, frame_or_series)
res = obj.loc[1:2]
exp = obj.reindex(obj.index[2:])
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index e088f1ce87a6a..c110130fe52ea 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -269,8 +269,7 @@ def test_iloc_getitem_invalid_scalar(self, frame_or_series):
# GH 21982
obj = DataFrame(np.arange(100).reshape(10, 10))
- if frame_or_series is Series:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
with pytest.raises(TypeError, match="Cannot index by location index"):
obj.iloc["a"]
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 91d3709325f7c..b215aee4ea1c6 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1214,8 +1214,7 @@ def test_loc_getitem_time_object(self, frame_or_series):
mask = (rng.hour == 9) & (rng.minute == 30)
obj = DataFrame(np.random.randn(len(rng), 3), index=rng)
- if frame_or_series is Series:
- obj = obj[0]
+ obj = tm.get_obj(obj, frame_or_series)
result = obj.loc[time(9, 30)]
exp = obj.loc[mask]
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index 1926dbbd35372..1bff5b4cc82a6 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -256,8 +256,7 @@ def test_agg_multiple_levels(
self, multiindex_year_month_day_dataframe_random_data, frame_or_series
):
ymd = multiindex_year_month_day_dataframe_random_data
- if frame_or_series is Series:
- ymd = ymd["A"]
+ ymd = tm.get_obj(ymd, frame_or_series)
with tm.assert_produces_warning(FutureWarning):
result = ymd.sum(level=["year", "month"])
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/44998 | 2021-12-21T16:33:03Z | 2021-12-22T16:06:02Z | 2021-12-22T16:06:02Z | 2021-12-22T17:18:14Z |
BUG: convert_dtypes lose columns.names GH#41435 | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 2592be9c4a350..9f391f36e2d7d 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -667,6 +667,7 @@ Conversion
- Bug in :func:`to_datetime` with ``arg:xr.DataArray`` and ``unit="ns"`` specified raises TypeError (:issue:`44053`)
- Bug in :meth:`DataFrame.convert_dtypes` not returning the correct type when a subclass does not overload :meth:`_constructor_sliced` (:issue:`43201`)
- Bug in :meth:`DataFrame.astype` not propagating ``attrs`` from the original :class:`DataFrame` (:issue:`44414`)
+- Bug in :meth:`DataFrame.convert_dtypes` result losing ``columns.names`` (:issue:`41435`)
Strings
^^^^^^^
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index f9d066f1e694d..f8fecb6505ede 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -367,7 +367,7 @@ def __init__(
categories=None,
ordered=None,
dtype: Dtype | None = None,
- fastpath=False,
+ fastpath: bool = False,
copy: bool = True,
):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index e66086faf53af..a683599e20b77 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6254,7 +6254,7 @@ def convert_dtypes(
for col_name, col in self.items()
]
if len(results) > 0:
- result = concat(results, axis=1, copy=False)
+ result = concat(results, axis=1, copy=False, keys=self.columns)
cons = cast(Type["DataFrame"], self._constructor)
result = cons(result)
result = result.__finalize__(self, method="convert_dtypes")
diff --git a/pandas/tests/frame/methods/test_convert_dtypes.py b/pandas/tests/frame/methods/test_convert_dtypes.py
index a2d539d784d3c..ec639ed7132a4 100644
--- a/pandas/tests/frame/methods/test_convert_dtypes.py
+++ b/pandas/tests/frame/methods/test_convert_dtypes.py
@@ -32,3 +32,12 @@ def test_convert_empty(self):
# Empty DataFrame can pass convert_dtypes, see GH#40393
empty_df = pd.DataFrame()
tm.assert_frame_equal(empty_df, empty_df.convert_dtypes())
+
+ def test_convert_dtypes_retain_column_names(self):
+ # GH#41435
+ df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
+ df.columns.name = "cols"
+
+ result = df.convert_dtypes()
+ tm.assert_index_equal(result.columns, df.columns)
+ assert result.columns.name == "cols"
| - [x] closes #41435
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/44997 | 2021-12-21T16:31:47Z | 2021-12-22T02:45:49Z | 2021-12-22T02:45:48Z | 2021-12-22T02:47:04Z |
DOC: Enable doctests for _config, _testing, utils, io, misc files | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 6335eb4b14007..64c8368e06417 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -66,22 +66,21 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
MSG='Doctests' ; echo $MSG
python -m pytest --doctest-modules \
+ pandas/_config/ \
pandas/_libs/ \
+ pandas/_testing/ \
pandas/api/ \
pandas/arrays/ \
pandas/compat/ \
pandas/core \
pandas/errors/ \
- pandas/io/clipboard/ \
- pandas/io/json/ \
- pandas/io/excel/ \
- pandas/io/parsers/ \
- pandas/io/sas/ \
- pandas/io/sql.py \
- pandas/io/formats/format.py \
- pandas/io/formats/style.py \
- pandas/io/stata.py \
- pandas/tseries/
+ pandas/io/ \
+ pandas/tseries/ \
+ pandas/util/ \
+ pandas/_typing.py \
+ pandas/_version.py \
+ pandas/conftest.py \
+ pandas/testing.py
RET=$(($RET + $?)) ; echo $MSG "DONE"
MSG='Cython Doctests' ; echo $MSG
diff --git a/pandas/_config/config.py b/pandas/_config/config.py
index d8b1829840a4d..5a0f58266c203 100644
--- a/pandas/_config/config.py
+++ b/pandas/_config/config.py
@@ -411,7 +411,7 @@ class option_context(ContextDecorator):
Examples
--------
>>> with option_context('display.max_rows', 10, 'display.max_columns', 5):
- ... ...
+ ... pass
"""
def __init__(self, *args):
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index 66503ac81b4d1..5154626dc3c7c 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -431,7 +431,7 @@ def _make_timeseries(start="2000-01-01", end="2000-12-31", freq="1D", seed=None)
Examples
--------
- >>> _make_timeseries()
+ >>> _make_timeseries() # doctest: +SKIP
id name x y
timestamp
2000-01-01 982 Frank 0.031261 0.986727
diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py
index 2c8e1b0daaeaa..8fe78fdd499ae 100644
--- a/pandas/_testing/_io.py
+++ b/pandas/_testing/_io.py
@@ -167,7 +167,7 @@ def network(
... def test_network():
... with pd.io.common.urlopen("rabbit://bonanza.com"):
... pass
- >>> test_network()
+ >>> test_network() # doctest: +SKIP
Traceback
...
URLError: <urlopen error unknown url type: rabbit>
@@ -189,7 +189,7 @@ def network(
... def test_something():
... print("I ran!")
... raise ValueError("Failure")
- >>> test_something()
+ >>> test_something() # doctest: +SKIP
Traceback (most recent call last):
...
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 08f92698ed9a0..d59ad72d74d73 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -193,16 +193,15 @@ def _get_tol_from_less_precise(check_less_precise: bool | int) -> float:
--------
>>> # Using check_less_precise as a bool:
>>> _get_tol_from_less_precise(False)
- 0.5e-5
+ 5e-06
>>> _get_tol_from_less_precise(True)
- 0.5e-3
+ 0.0005
>>> # Using check_less_precise as an int representing the decimal
>>> # tolerance intended:
>>> _get_tol_from_less_precise(2)
- 0.5e-2
+ 0.005
>>> _get_tol_from_less_precise(8)
- 0.5e-8
-
+ 5e-09
"""
if isinstance(check_less_precise, bool):
if check_less_precise:
diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py
index db35b2e7b4cab..aff3e9e5471de 100644
--- a/pandas/_testing/contexts.py
+++ b/pandas/_testing/contexts.py
@@ -54,13 +54,13 @@ def set_timezone(tz: str):
--------
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
- >>> tzlocal().tzname(datetime.now())
+ >>> tzlocal().tzname(datetime(2021, 1, 1)) # doctest: +SKIP
'IST'
>>> with set_timezone('US/Eastern'):
- ... tzlocal().tzname(datetime.now())
+ ... tzlocal().tzname(datetime(2021, 1, 1))
...
- 'EDT'
+ 'EST'
"""
import os
import time
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index de475d145f3a0..dcb1f9a2a70dc 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -1062,7 +1062,7 @@ def format_index(
--------
Using ``na_rep`` and ``precision`` with the default ``formatter``
- >>> df = pd.DataFrame([[1, 2, 3]], columns=[2.0, np.nan, 4.0]])
+ >>> df = pd.DataFrame([[1, 2, 3]], columns=[2.0, np.nan, 4.0])
>>> df.style.format_index(axis=1, na_rep='MISS', precision=3) # doctest: +SKIP
2.000 MISS 4.000
0 1 2 3
@@ -1096,6 +1096,7 @@ def format_index(
>>> df = pd.DataFrame([[1, 2, 3]], columns=['"A"', 'A&B', None])
>>> s = df.style.format_index('$ {0}', axis=1, escape="html", na_rep="NA")
+ ... # doctest: +SKIP
<th .. >$ "A"</th>
<th .. >$ A&B</th>
<th .. >NA</td>
@@ -1811,7 +1812,7 @@ def _parse_latex_header_span(
Examples
--------
- >>> cell = {'display_value':'text', 'attributes': 'colspan="3"'}
+ >>> cell = {'cellstyle': '', 'display_value':'text', 'attributes': 'colspan="3"'}
>>> _parse_latex_header_span(cell, 't', 'c')
'\\multicolumn{3}{c}{text}'
"""
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py
index a936b8d1f585c..39a729bc51f35 100644
--- a/pandas/util/_decorators.py
+++ b/pandas/util/_decorators.py
@@ -122,19 +122,19 @@ def deprecate_kwarg(
>>> f(columns='should work ok')
should work ok
- >>> f(cols='should raise warning')
+ >>> f(cols='should raise warning') # doctest: +SKIP
FutureWarning: cols is deprecated, use columns instead
warnings.warn(msg, FutureWarning)
should raise warning
- >>> f(cols='should error', columns="can\'t pass do both")
+ >>> f(cols='should error', columns="can\'t pass do both") # doctest: +SKIP
TypeError: Can only specify 'cols' or 'columns', not both
>>> @deprecate_kwarg('old', 'new', {'yes': True, 'no': False})
... def f(new=False):
... print('yes!' if new else 'no!')
...
- >>> f(old='yes')
+ >>> f(old='yes') # doctest: +SKIP
FutureWarning: old='yes' is deprecated, use new=True instead
warnings.warn(msg, FutureWarning)
yes!
@@ -145,14 +145,14 @@ def deprecate_kwarg(
... def f(cols='', another_param=''):
... print(cols)
...
- >>> f(cols='should raise warning')
+ >>> f(cols='should raise warning') # doctest: +SKIP
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning
- >>> f(another_param='should not raise warning')
+ >>> f(another_param='should not raise warning') # doctest: +SKIP
should not raise warning
- >>> f(cols='should raise warning', another_param='')
+ >>> f(cols='should raise warning', another_param='') # doctest: +SKIP
FutureWarning: the 'cols' keyword is deprecated and will be removed in a
future version please takes steps to stop use of 'cols'
should raise warning
diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py
index ee54b1b2074cb..8e3de9404fbee 100644
--- a/pandas/util/_validators.py
+++ b/pandas/util/_validators.py
@@ -281,14 +281,15 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
Examples
--------
- >>> df._validate_axis_style_args((str.upper,), {'columns': id},
- ... 'mapper', 'rename')
- {'columns': <function id>, 'index': <method 'upper' of 'str' objects>}
+ >>> df = pd.DataFrame(range(2))
+ >>> validate_axis_style_args(df, (str.upper,), {'columns': id},
+ ... 'mapper', 'rename')
+ {'columns': <built-in function id>, 'index': <method 'upper' of 'str' objects>}
This emits a warning
- >>> df._validate_axis_style_args((str.upper, id), {},
- ... 'mapper', 'rename')
- {'columns': <function id>, 'index': <method 'upper' of 'str' objects>}
+ >>> validate_axis_style_args(df, (str.upper, id), {},
+ ... 'mapper', 'rename')
+ {'index': <method 'upper' of 'str' objects>, 'columns': <built-in function id>}
"""
# TODO: Change to keyword-only args and remove all this
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/44990 | 2021-12-21T04:03:11Z | 2021-12-21T17:45:55Z | 2021-12-21T17:45:55Z | 2021-12-21T17:45:58Z |
CI: Pin setuptools for python dev | diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml
index 8b3a5a23d7a97..a7c7f3b739f65 100644
--- a/.github/workflows/python-dev.yml
+++ b/.github/workflows/python-dev.yml
@@ -45,10 +45,11 @@ jobs:
with:
python-version: '3.10-dev'
+ # TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
- name: Install dependencies
shell: bash
run: |
- python -m pip install --upgrade pip setuptools wheel
+ 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
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 6c685d09ab55a..ac91dcac4d2d8 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -36,13 +36,14 @@ jobs:
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 && \
+ 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 && \
python setup.py build_ext -q -j2 && \
python -m pip install --no-build-isolation -e . && \
diff --git a/ci/setup_env.sh b/ci/setup_env.sh
index 2e16bc6545161..4a3e103ea0310 100755
--- a/ci/setup_env.sh
+++ b/ci/setup_env.sh
@@ -106,7 +106,8 @@ echo "[Build extensions]"
python setup.py build_ext -q -j2
echo "[Updating pip]"
-python -m pip install --no-deps -U pip wheel setuptools
+# TODO: GH#44980 https://github.com/pypa/setuptools/issues/2941
+python -m pip install --no-deps -U pip wheel "setuptools<60.0.0"
echo "[Install pandas]"
python -m pip install --no-build-isolation -e .
| Lets see if this works
- [x] xref #44980 | https://api.github.com/repos/pandas-dev/pandas/pulls/44989 | 2021-12-20T20:33:10Z | 2021-12-21T16:52:57Z | 2021-12-21T16:52:57Z | 2021-12-21T17:01:07Z |
TYP: Return int instead of changing result type in nanops.py | diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 52d2322b11f42..dea6fb33e09fe 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -1391,14 +1391,10 @@ def _maybe_arg_null_out(
if axis is None or not getattr(result, "ndim", False):
if skipna:
if mask.all():
- # error: Incompatible types in assignment (expression has type
- # "int", variable has type "ndarray")
- result = -1 # type: ignore[assignment]
+ return -1
else:
if mask.any():
- # error: Incompatible types in assignment (expression has type
- # "int", variable has type "ndarray")
- result = -1 # type: ignore[assignment]
+ return -1
else:
if skipna:
na_mask = mask.all(axis)
| xref #37715
The error was about the lines that set ````result = -1````, which changed the type of result from np.ndarray to int. Changed it to return -1 from the if block since everywhere else its dealing with an np.ndarray | https://api.github.com/repos/pandas-dev/pandas/pulls/44988 | 2021-12-20T17:58:48Z | 2021-12-22T02:37:56Z | 2021-12-22T02:37:56Z | 2021-12-22T14:54:54Z |
DOC: Removed overview CONTRIBUTING file and its link from the README. | diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
deleted file mode 100644
index 49200523df40f..0000000000000
--- a/.github/CONTRIBUTING.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# Contributing to pandas
-
-Whether you are a novice or experienced software developer, all contributions and suggestions are welcome!
-
-Our main contributing guide can be found [in this repo](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst) or [on the website](https://pandas.pydata.org/docs/dev/development/contributing.html). If you do not want to read it in its entirety, we will summarize the main ways in which you can contribute and point to relevant sections of that document for further information.
-
-## Getting Started
-
-If you are looking to contribute to the *pandas* codebase, the best place to start is the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues). This is also a great place for filing bug reports and making suggestions for ways in which we can improve the code and documentation.
-
-If you have additional questions, feel free to ask them on the [mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata) or on [Gitter](https://gitter.im/pydata/pandas). Further information can also be found in the "[Where to start?](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#where-to-start)" section.
-
-## Filing Issues
-
-If you notice a bug in the code or documentation, or have suggestions for how we can improve either, feel free to create an issue on the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues) using [GitHub's "issue" form](https://github.com/pandas-dev/pandas/issues/new). The form contains some questions that will help us best address your issue. For more information regarding how to file issues against *pandas*, please refer to the "[Bug reports and enhancement requests](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#bug-reports-and-enhancement-requests)" section.
-
-## Contributing to the Codebase
-
-The code is hosted on [GitHub](https://www.github.com/pandas-dev/pandas), so you will need to use [Git](https://git-scm.com/) to clone the project and make changes to the codebase. Once you have obtained a copy of the code, you should create a development environment that is separate from your existing Python environment so that you can make and test changes without compromising your own work environment. For more information, please refer to the "[Working with the code](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#working-with-the-code)" section.
-
-Before submitting your changes for review, make sure to check that your changes do not break any tests. You can find more information about our test suites in the "[Test-driven development/code writing](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#test-driven-development-code-writing)" section. We also have guidelines regarding coding style that will be enforced during testing, which can be found in the "[Code standards](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#code-standards)" section.
-
-Once your changes are ready to be submitted, make sure to push your changes to GitHub before creating a pull request. Details about how to do that can be found in the "[Contributing your changes to pandas](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#contributing-your-changes-to-pandas)" section. We will review your changes, and you will most likely be asked to make additional changes before it is finally ready to merge. However, once it's ready, we will merge it, and you will have successfully contributed to the codebase!
diff --git a/README.md b/README.md
index 7bb77c70ab682..bde815939239d 100644
--- a/README.md
+++ b/README.md
@@ -160,7 +160,7 @@ Most development discussions take place on GitHub in this repo. Further, the [pa
All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome.
-A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**. There is also an [overview](.github/CONTRIBUTING.md) on GitHub.
+A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**.
If you are simply looking to start working with the pandas codebase, navigate to the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues) and start looking through interesting issues. There are a number of issues listed under [Docs](https://github.com/pandas-dev/pandas/issues?labels=Docs&sort=updated&state=open) and [good first issue](https://github.com/pandas-dev/pandas/issues?labels=good+first+issue&sort=updated&state=open) where you could start out.
| This is to prevent documentation duplicates.
- [x] closes #44985
| https://api.github.com/repos/pandas-dev/pandas/pulls/44987 | 2021-12-20T16:41:01Z | 2021-12-27T15:02:29Z | null | 2021-12-27T15:02:29Z |
DOC: Fixed broken links in the CONTRIBUTING file. | diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 49200523df40f..b8f9b2b83d7f8 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -18,6 +18,6 @@ If you notice a bug in the code or documentation, or have suggestions for how we
The code is hosted on [GitHub](https://www.github.com/pandas-dev/pandas), so you will need to use [Git](https://git-scm.com/) to clone the project and make changes to the codebase. Once you have obtained a copy of the code, you should create a development environment that is separate from your existing Python environment so that you can make and test changes without compromising your own work environment. For more information, please refer to the "[Working with the code](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#working-with-the-code)" section.
-Before submitting your changes for review, make sure to check that your changes do not break any tests. You can find more information about our test suites in the "[Test-driven development/code writing](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#test-driven-development-code-writing)" section. We also have guidelines regarding coding style that will be enforced during testing, which can be found in the "[Code standards](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#code-standards)" section.
+Before submitting your changes for review, make sure to check that your changes do not break any tests. You can find more information about our test suites in the "[Test-driven development/code writing](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing_codebase.rst#test-driven-development-code-writing)" section. We also have guidelines regarding coding style that will be enforced during testing, which can be found in the "[Code standards](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing_codebase.rst#code-standards)" section.
Once your changes are ready to be submitted, make sure to push your changes to GitHub before creating a pull request. Details about how to do that can be found in the "[Contributing your changes to pandas](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#contributing-your-changes-to-pandas)" section. We will review your changes, and you will most likely be asked to make additional changes before it is finally ready to merge. However, once it's ready, we will merge it, and you will have successfully contributed to the codebase!
| - [x] closes #44985
| https://api.github.com/repos/pandas-dev/pandas/pulls/44986 | 2021-12-20T16:22:05Z | 2021-12-20T17:46:22Z | null | 2021-12-25T00:28:37Z |
DOC fix typo in describe_option | diff --git a/pandas/_config/config.py b/pandas/_config/config.py
index b22a6840644ec..d8b1829840a4d 100644
--- a/pandas/_config/config.py
+++ b/pandas/_config/config.py
@@ -333,7 +333,7 @@ def __doc__(self):
Prints the description for one or more registered options.
-Call with not arguments to get a listing for all registered options.
+Call with no arguments to get a listing for all registered options.
Available options:
| I updated pandas/_config/config.py fixing a typo -
Call with not arguments to get a listing for all registered options to Call with no arguments to get a listing for all registered options.
closes #44970 | https://api.github.com/repos/pandas-dev/pandas/pulls/44984 | 2021-12-20T14:35:45Z | 2021-12-20T14:40:31Z | 2021-12-20T14:40:31Z | 2021-12-23T14:02:02Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.