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
DOC: how to revert MultiIndex.to_flat_index
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index c80dadcc42022..ad10b41093f27 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1787,6 +1787,10 @@ def to_flat_index(self): pd.Index Index with the MultiIndex data represented in Tuples. + See Also + -------- + MultiIndex.from_tuples : Convert flat index back to MultiIndex. + Notes ----- This method will simply return the caller if called by anything other
Took me way too long to figure this out. Hopefully this benefits someone else!
https://api.github.com/repos/pandas-dev/pandas/pulls/38911
2021-01-02T23:28:30Z
2021-01-04T01:12:07Z
2021-01-04T01:12:07Z
2021-01-04T01:12:59Z
REF: simplify Index.__new__
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b0c89000a53a9..2db803e5c1b19 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6,6 +6,7 @@ TYPE_CHECKING, Any, Callable, + Dict, FrozenSet, Hashable, List, @@ -131,6 +132,11 @@ _Identity = NewType("_Identity", object) +def disallow_kwargs(kwargs: Dict[str, Any]): + if kwargs: + raise TypeError(f"Unexpected keyword arguments {repr(set(kwargs))}") + + def _new_Index(cls, d): """ This is called upon unpickling, rather than the default which doesn't @@ -296,13 +302,19 @@ def __new__( return result.astype(dtype, copy=False) return result - if is_ea_or_datetimelike_dtype(dtype): + elif is_ea_or_datetimelike_dtype(dtype): # non-EA dtype indexes have special casting logic, so we punt here klass = cls._dtype_to_subclass(dtype) if klass is not Index: return klass(data, dtype=dtype, copy=copy, name=name, **kwargs) - if is_ea_or_datetimelike_dtype(data_dtype): + ea_cls = dtype.construct_array_type() + data = ea_cls._from_sequence(data, dtype=dtype, copy=copy) + data = np.asarray(data, dtype=object) + disallow_kwargs(kwargs) + return Index._simple_new(data, name=name) + + elif is_ea_or_datetimelike_dtype(data_dtype): klass = cls._dtype_to_subclass(data_dtype) if klass is not Index: result = klass(data, copy=copy, name=name, **kwargs) @@ -310,18 +322,9 @@ def __new__( return result.astype(dtype, copy=False) return result - # extension dtype - if is_extension_array_dtype(data_dtype) or is_extension_array_dtype(dtype): - if not (dtype is None or is_object_dtype(dtype)): - # coerce to the provided dtype - ea_cls = dtype.construct_array_type() - data = ea_cls._from_sequence(data, dtype=dtype, copy=False) - else: - data = np.asarray(data, dtype=object) - - # coerce to the object dtype - data = data.astype(object) - return Index(data, dtype=object, copy=copy, name=name, **kwargs) + data = np.array(data, dtype=object, copy=copy) + disallow_kwargs(kwargs) + return Index._simple_new(data, name=name) # index-like elif isinstance(data, (np.ndarray, Index, ABCSeries)): @@ -333,7 +336,7 @@ def __new__( # should not be coerced # GH 11836 data = _maybe_cast_with_dtype(data, dtype, copy) - dtype = data.dtype # TODO: maybe not for object? + dtype = data.dtype if data.dtype.kind in ["i", "u", "f"]: # maybe coerce to a sub-class @@ -342,16 +345,15 @@ def __new__( arr = com.asarray_tuplesafe(data, dtype=object) if dtype is None: - new_data = _maybe_cast_data_without_dtype(arr) - new_dtype = new_data.dtype - return cls( - new_data, dtype=new_dtype, copy=copy, name=name, **kwargs - ) + arr = _maybe_cast_data_without_dtype(arr) + dtype = arr.dtype + + if kwargs: + return cls(arr, dtype, copy=copy, name=name, **kwargs) klass = cls._dtype_to_subclass(arr.dtype) arr = klass._ensure_array(arr, dtype, copy) - if kwargs: - raise TypeError(f"Unexpected keyword arguments {repr(set(kwargs))}") + disallow_kwargs(kwargs) return klass._simple_new(arr, name) elif is_scalar(data): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 249e9707be328..7d214829b1871 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -623,7 +623,7 @@ def _convert_arr_indexer(self, keyarr): return com.asarray_tuplesafe(keyarr) -class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): +class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin): """ Mixin class for methods shared by DatetimeIndex and TimedeltaIndex, but not PeriodIndex @@ -816,11 +816,7 @@ def _union(self, other, sort): i8self = Int64Index._simple_new(self.asi8) i8other = Int64Index._simple_new(other.asi8) i8result = i8self._union(i8other, sort=sort) - # pandas\core\indexes\datetimelike.py:887: error: Unexpected - # keyword argument "freq" for "DatetimeTimedeltaMixin" [call-arg] - result = type(self)( - i8result, dtype=self.dtype, freq="infer" # type: ignore[call-arg] - ) + result = type(self)(i8result, dtype=self.dtype, freq="infer") return result # --------------------------------------------------------------------
Avoid recursing where possible.
https://api.github.com/repos/pandas-dev/pandas/pulls/38910
2021-01-02T23:10:19Z
2021-01-03T17:03:03Z
2021-01-03T17:03:03Z
2021-01-03T18:04:46Z
BUG: Fixed regression in rolling.skew and rolling.kurt modifying object
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index b1f8389420cd9..c07d82432f45e 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -37,7 +37,7 @@ Fixed regressions - Fixed regression in :meth:`.GroupBy.sem` where the presence of non-numeric columns would cause an error instead of being dropped (:issue:`38774`) - Fixed regression in :func:`read_excel` with non-rawbyte file handles (:issue:`38788`) - Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`) -- +- Fixed regression in :meth:`Rolling.skew` and :meth:`Rolling.kurt` modifying the object inplace (:issue:`38908`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index c21e71c407630..3c00ff092422b 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -495,7 +495,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, float64_t x = 0, xx = 0, xxx = 0 int64_t nobs = 0, i, j, N = len(values), nobs_mean = 0 int64_t s, e - ndarray[float64_t] output, mean_array + ndarray[float64_t] output, mean_array, values_copy bint is_monotonic_increasing_bounds minp = max(minp, 3) @@ -504,10 +504,11 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, ) output = np.empty(N, dtype=float) min_val = np.nanmin(values) + values_copy = np.copy(values) with nogil: for i in range(0, N): - val = values[i] + val = values_copy[i] if notnan(val): nobs_mean += 1 sum_val += val @@ -516,7 +517,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, if min_val - mean_val > -1e5: mean_val = round(mean_val) for i in range(0, N): - values[i] = values[i] - mean_val + values_copy[i] = values_copy[i] - mean_val for i in range(0, N): @@ -528,7 +529,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, if i == 0 or not is_monotonic_increasing_bounds: for j in range(s, e): - val = values[j] + val = values_copy[j] add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add, &compensation_xx_add, &compensation_xxx_add) @@ -538,13 +539,13 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, # and removed # calculate deletes for j in range(start[i - 1], s): - val = values[j] + val = values_copy[j] remove_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_remove, &compensation_xx_remove, &compensation_xxx_remove) # calculate adds for j in range(end[i - 1], e): - val = values[j] + val = values_copy[j] add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add, &compensation_xx_add, &compensation_xxx_add) @@ -675,7 +676,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, float64_t compensation_x_remove = 0, compensation_x_add = 0 float64_t x = 0, xx = 0, xxx = 0, xxxx = 0 int64_t nobs = 0, i, j, s, e, N = len(values), nobs_mean = 0 - ndarray[float64_t] output + ndarray[float64_t] output, values_copy bint is_monotonic_increasing_bounds minp = max(minp, 4) @@ -683,11 +684,12 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, start, end ) output = np.empty(N, dtype=float) + values_copy = np.copy(values) min_val = np.nanmin(values) with nogil: for i in range(0, N): - val = values[i] + val = values_copy[i] if notnan(val): nobs_mean += 1 sum_val += val @@ -696,7 +698,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, if min_val - mean_val > -1e4: mean_val = round(mean_val) for i in range(0, N): - values[i] = values[i] - mean_val + values_copy[i] = values_copy[i] - mean_val for i in range(0, N): @@ -708,7 +710,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, if i == 0 or not is_monotonic_increasing_bounds: for j in range(s, e): - add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx, + add_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx, &compensation_x_add, &compensation_xx_add, &compensation_xxx_add, &compensation_xxxx_add) @@ -718,13 +720,13 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, # and removed # calculate deletes for j in range(start[i - 1], s): - remove_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx, + remove_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx, &compensation_x_remove, &compensation_xx_remove, &compensation_xxx_remove, &compensation_xxxx_remove) # calculate adds for j in range(end[i - 1], e): - add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx, + add_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx, &compensation_x_add, &compensation_xx_add, &compensation_xxx_add, &compensation_xxxx_add) diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 84056299093cf..b275b64ff706b 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -1102,11 +1102,13 @@ def test_groupby_rolling_nan_included(): @pytest.mark.parametrize("method", ["skew", "kurt"]) def test_rolling_skew_kurt_numerical_stability(method): - # GH: 6929 - s = Series(np.random.rand(10)) - expected = getattr(s.rolling(3), method)() - s = s + 50000 - result = getattr(s.rolling(3), method)() + # GH#6929 + ser = Series(np.random.rand(10)) + ser_copy = ser.copy() + expected = getattr(ser.rolling(3), method)() + tm.assert_series_equal(ser, ser_copy) + ser = ser + 50000 + result = getattr(ser.rolling(3), method)() tm.assert_series_equal(result, expected)
- [x] closes #38908 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Alternative would be np.copy before releasing gil. In this case we would have to touch values_copy twice in case of ``min_val - mean_val > -1e5``
https://api.github.com/repos/pandas-dev/pandas/pulls/38909
2021-01-02T23:07:19Z
2021-01-04T13:37:14Z
2021-01-04T13:37:14Z
2021-01-04T14:04:50Z
BUG: casting on concat with empties
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 5e84947cd42f1..b4a31635687e1 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -294,7 +294,7 @@ Groupby/resample/rolling Reshaping ^^^^^^^^^ - Bug in :meth:`DataFrame.unstack` with missing levels led to incorrect index names (:issue:`37510`) -- Bug in :func:`concat` incorrectly casting to ``object`` dtype in some cases when one or more of the operands is empty (:issue:`38843`) +- Bug in :func:`concat` incorrectly casting to ``object`` dtype in some cases when one or more of the operands is empty (:issue:`38843`, :issue:`38907`) - diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 013e52248f5c4..a45933714ee96 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -318,6 +318,12 @@ def _concatenate_join_units( # Concatenating join units along ax0 is handled in _merge_blocks. raise AssertionError("Concatenating join units along axis0") + nonempties = [ + x for x in join_units if x.block is None or x.block.shape[concat_axis] > 0 + ] + if nonempties: + join_units = nonempties + empty_dtype, upcasted_na = _get_empty_dtype_and_na(join_units) to_concat = [ diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index d8dd08ea13341..f2d628c70ae62 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -154,7 +154,8 @@ def test_partial_setting_mixed_dtype(self): # columns will align df = DataFrame(columns=["A", "B"]) df.loc[0] = Series(1, index=range(4)) - tm.assert_frame_equal(df, DataFrame(columns=["A", "B"], index=[0])) + expected = DataFrame(columns=["A", "B"], index=[0], dtype=int) + tm.assert_frame_equal(df, expected) # columns will align df = DataFrame(columns=["A", "B"]) diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py index ffeda703cd890..1a895aee98f0a 100644 --- a/pandas/tests/reshape/concat/test_append.py +++ b/pandas/tests/reshape/concat/test_append.py @@ -82,6 +82,7 @@ def test_append_length0_frame(self, sort): df5 = df.append(df3, sort=sort) expected = DataFrame(index=[0, 1], columns=["A", "B", "C"]) + expected["C"] = expected["C"].astype(np.float64) tm.assert_frame_equal(df5, expected) def test_append_records(self): @@ -340,16 +341,11 @@ def test_append_empty_frame_to_series_with_dateutil_tz(self): expected = DataFrame( [[np.nan, np.nan, 1.0, 2.0, date]], columns=["c", "d", "a", "b", "date"] ) - # These columns get cast to object after append - expected["c"] = expected["c"].astype(object) - expected["d"] = expected["d"].astype(object) tm.assert_frame_equal(result_a, expected) expected = DataFrame( [[np.nan, np.nan, 1.0, 2.0, date]] * 2, columns=["c", "d", "a", "b", "date"] ) - expected["c"] = expected["c"].astype(object) - expected["d"] = expected["d"].astype(object) result_b = result_a.append(s, ignore_index=True) tm.assert_frame_equal(result_b, expected) diff --git a/pandas/tests/reshape/concat/test_empty.py b/pandas/tests/reshape/concat/test_empty.py index dea04e98088e8..075785120677a 100644 --- a/pandas/tests/reshape/concat/test_empty.py +++ b/pandas/tests/reshape/concat/test_empty.py @@ -210,7 +210,6 @@ def test_concat_empty_df_object_dtype(self, dtype): df_2 = DataFrame(columns=df_1.columns) result = pd.concat([df_1, df_2], axis=0) expected = df_1.copy() - expected["EmptyCol"] = expected["EmptyCol"].astype(object) # TODO: why? tm.assert_frame_equal(result, expected) def test_concat_empty_dataframe_dtypes(self):
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Covers the case missed by #38843
https://api.github.com/repos/pandas-dev/pandas/pulls/38907
2021-01-02T19:38:03Z
2021-01-03T16:58:04Z
2021-01-03T16:58:04Z
2021-01-03T18:08:41Z
ENH: Use Kahan summation to calculate groupby.sum()
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 9d1b3eaebdf8b..94a12fec6adcb 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -289,7 +289,7 @@ Groupby/resample/rolling - Bug in :meth:`SeriesGroupBy.value_counts` where unobserved categories in a grouped categorical series were not tallied (:issue:`38672`) - Bug in :meth:`.GroupBy.indices` would contain non-existent indices when null values were present in the groupby keys (:issue:`9304`) -- +- Fixed bug in :meth:`DataFrameGroupBy.sum` and :meth:`SeriesGroupBy.sum` causing loss of precision through using Kahan summation (:issue:`38778`) Reshaping ^^^^^^^^^ diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index ffb75401013dc..ac8f22263f787 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -467,12 +467,12 @@ def _group_add(complexfloating_t[:, :] out, const int64_t[:] labels, Py_ssize_t min_count=0): """ - Only aggregates on axis=0 + Only aggregates on axis=0 using Kahan summation """ cdef: Py_ssize_t i, j, N, K, lab, ncounts = len(counts) - complexfloating_t val, count - complexfloating_t[:, :] sumx + complexfloating_t val, count, t, y + complexfloating_t[:, :] sumx, compensation int64_t[:, :] nobs Py_ssize_t len_values = len(values), len_labels = len(labels) @@ -481,6 +481,7 @@ def _group_add(complexfloating_t[:, :] out, nobs = np.zeros((<object>out).shape, dtype=np.int64) sumx = np.zeros_like(out) + compensation = np.zeros_like(out) N, K = (<object>values).shape @@ -497,12 +498,10 @@ def _group_add(complexfloating_t[:, :] out, # not nan if val == val: nobs[lab, j] += 1 - if (complexfloating_t is complex64_t or - complexfloating_t is complex128_t): - # clang errors if we use += with these dtypes - sumx[lab, j] = sumx[lab, j] + val - else: - sumx[lab, j] += val + y = val - compensation[lab, j] + t = sumx[lab, j] + y + compensation[lab, j] = t - sumx[lab, j] - y + sumx[lab, j] = t for i in range(ncounts): for j in range(K): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index e5021b7b4dd5f..4e085a7608e31 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -5,6 +5,7 @@ import numpy as np import pytest +from pandas.compat import IS64 from pandas.errors import PerformanceWarning import pandas as pd @@ -2174,3 +2175,15 @@ def test_groupby_series_with_tuple_name(): expected = Series([2, 4], index=[1, 2], name=("a", "a")) expected.index.name = ("b", "b") tm.assert_series_equal(result, expected) + + +@pytest.mark.xfail(not IS64, reason="GH#38778: fail on 32-bit system") +def test_groupby_numerical_stability_sum(): + # GH#38778 + data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] + df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) + result = df.groupby("group").sum() + expected = DataFrame( + {"a": [97.0, 98.0], "b": [97.0, 98.0]}, index=Index([1, 2], name="group") + ) + tm.assert_frame_equal(result, expected)
- [x] closes #38778 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This simplifies the op example. I think ``` series = Series([1e16, 99, -5e15, -5e15]) series.sum() ``` is dispatched to numpy? The result is wrong too. ``100.0`` Mean doesn't work either. I will look through the functions to determine which need Kahan summation too and open an issue to track these.
https://api.github.com/repos/pandas-dev/pandas/pulls/38903
2021-01-02T15:58:45Z
2021-01-03T23:25:09Z
2021-01-03T23:25:09Z
2021-01-03T23:29:09Z
TST: strictly xfail
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index 493cb979494c8..e38de67071f15 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -117,8 +117,9 @@ class TestConstructors(base.BaseConstructorsTests): class TestReshaping(base.BaseReshapingTests): + @pytest.mark.xfail(reason="Deliberately upcast to object?") def test_concat_with_reindex(self, data): - pytest.xfail(reason="Deliberately upcast to object?") + super().test_concat_with_reindex(data) class TestGetitem(base.BaseGetitemTests): diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 196d4a0b3bb76..1c397d6a6a1b5 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -1229,13 +1229,15 @@ def test_min_max_dt64_with_NaT(self): exp = Series([pd.NaT], index=["foo"]) tm.assert_series_equal(res, exp) - def test_min_max_dt64_with_NaT_skipna_false(self, tz_naive_fixture): + def test_min_max_dt64_with_NaT_skipna_false(self, request, tz_naive_fixture): # GH#36907 tz = tz_naive_fixture if isinstance(tz, tzlocal) and is_platform_windows(): - pytest.xfail( - reason="GH#37659 OSError raised within tzlocal bc Windows " - "chokes in times before 1970-01-01" + request.node.add_marker( + pytest.mark.xfail( + reason="GH#37659 OSError raised within tzlocal bc Windows " + "chokes in times before 1970-01-01" + ) ) df = DataFrame( diff --git a/pandas/tests/frame/test_ufunc.py b/pandas/tests/frame/test_ufunc.py index 81c0dc65b4e97..8a29c2f2f89a1 100644 --- a/pandas/tests/frame/test_ufunc.py +++ b/pandas/tests/frame/test_ufunc.py @@ -24,10 +24,14 @@ def test_unary_unary(dtype): @pytest.mark.parametrize("dtype", dtypes) -def test_unary_binary(dtype): +def test_unary_binary(request, dtype): # unary input, binary output if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): - pytest.xfail(reason="Extension / mixed with multiple outuputs not implemented.") + request.node.add_marker( + pytest.mark.xfail( + reason="Extension / mixed with multiple outputs not implemented." + ) + ) values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) @@ -55,14 +59,18 @@ def test_binary_input_dispatch_binop(dtype): @pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_b", dtypes) -def test_binary_input_aligns_columns(dtype_a, dtype_b): +def test_binary_input_aligns_columns(request, dtype_a, dtype_b): if ( pd.api.types.is_extension_array_dtype(dtype_a) or isinstance(dtype_a, dict) or pd.api.types.is_extension_array_dtype(dtype_b) or isinstance(dtype_b, dict) ): - pytest.xfail(reason="Extension / mixed with multiple inputs not implemented.") + request.node.add_marker( + pytest.mark.xfail( + reason="Extension / mixed with multiple inputs not implemented." + ) + ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}).astype(dtype_a) @@ -80,9 +88,13 @@ def test_binary_input_aligns_columns(dtype_a, dtype_b): @pytest.mark.parametrize("dtype", dtypes) -def test_binary_input_aligns_index(dtype): +def test_binary_input_aligns_index(request, dtype): if pd.api.types.is_extension_array_dtype(dtype) or isinstance(dtype, dict): - pytest.xfail(reason="Extension / mixed with multiple inputs not implemented.") + request.node.add_marker( + pytest.mark.xfail( + reason="Extension / mixed with multiple inputs not implemented." + ) + ) df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "b"]).astype(dtype) df2 = pd.DataFrame({"A": [1, 2], "B": [3, 4]}, index=["a", "c"]).astype(dtype) result = np.heaviside(df1, df2) diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 4974d3fff1df4..73a68e8508644 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -547,14 +547,14 @@ def test_finalize_called_eval_numexpr(): (pd.DataFrame({"A": [1]}), pd.Series([1])), ], ) -def test_binops(args, annotate, all_arithmetic_functions): +def test_binops(request, args, annotate, all_arithmetic_functions): # This generates 326 tests... Is that needed? left, right = args if annotate == "both" and isinstance(left, int) or isinstance(right, int): return if isinstance(left, pd.DataFrame) or isinstance(right, pd.DataFrame): - pytest.xfail(reason="not implemented") + request.node.add_marker(pytest.mark.xfail(reason="not implemented")) if annotate in {"left", "both"} and not isinstance(left, int): left.attrs = {"a": 1} diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 72637400ff023..216d37a381c32 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -158,10 +158,10 @@ def test_transform_broadcast(tsframe, ts): assert_fp_equal(res.xs(idx), agged[idx]) -def test_transform_axis_1(transformation_func): +def test_transform_axis_1(request, transformation_func): # GH 36308 if transformation_func == "tshift": - pytest.xfail("tshift is deprecated") + request.node.add_marker(pytest.mark.xfail(reason="tshift is deprecated")) args = ("ffill",) if transformation_func == "fillna" else () df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"]) @@ -333,7 +333,7 @@ def test_dispatch_transform(tsframe): tm.assert_frame_equal(filled, expected) -def test_transform_transformation_func(transformation_func): +def test_transform_transformation_func(request, transformation_func): # GH 30918 df = DataFrame( { @@ -354,7 +354,7 @@ def test_transform_transformation_func(transformation_func): "Current behavior of groupby.tshift is inconsistent with other " "transformations. See GH34452 for more details" ) - pytest.xfail(msg) + request.node.add_marker(pytest.mark.xfail(reason=msg)) else: test_op = lambda x: x.transform(transformation_func) mock_op = lambda x: getattr(x, transformation_func)() @@ -1038,16 +1038,22 @@ def test_transform_invalid_name_raises(): Series([0, 0, 0, 1, 1, 1], index=["A", "B", "C", "D", "E", "F"]), ], ) -def test_transform_agg_by_name(reduction_func, obj): +def test_transform_agg_by_name(request, reduction_func, obj): func = reduction_func g = obj.groupby(np.repeat([0, 1], 3)) if func == "ngroup": # GH#27468 - pytest.xfail("TODO: g.transform('ngroup') doesn't work") - if func == "size": # GH#27469 - pytest.xfail("TODO: g.transform('size') doesn't work") + request.node.add_marker( + pytest.mark.xfail(reason="TODO: g.transform('ngroup') doesn't work") + ) + if func == "size" and obj.ndim == 2: # GH#27469 + request.node.add_marker( + pytest.mark.xfail(reason="TODO: g.transform('size') doesn't work") + ) if func == "corrwith" and isinstance(obj, Series): # GH#32293 - pytest.xfail("TODO: implement SeriesGroupBy.corrwith") + request.node.add_marker( + pytest.mark.xfail(reason="TODO: implement SeriesGroupBy.corrwith") + ) args = {"nth": [0], "quantile": [0.5], "corrwith": [obj]}.get(func, []) diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 0352759e7381b..a24c8e252d234 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -123,10 +123,12 @@ def test_repeat(self, tz_naive_fixture): ("U", "microsecond"), ], ) - def test_resolution(self, tz_naive_fixture, freq, expected): + def test_resolution(self, request, tz_naive_fixture, freq, expected): tz = tz_naive_fixture if freq == "A" and not IS64 and isinstance(tz, tzlocal): - pytest.xfail(reason="OverflowError inside tzlocal past 2038") + request.node.add_marker( + pytest.mark.xfail(reason="OverflowError inside tzlocal past 2038") + ) idx = date_range(start="2013-04-01", periods=30, freq=freq, tz=tz) assert idx.resolution == expected diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index e5bb78604207f..1eca7f7a5d261 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1596,13 +1596,15 @@ def test_isin_nan_common_object(self, nulls_fixture, nulls_fixture2): np.array([False, False]), ) - def test_isin_nan_common_float64(self, nulls_fixture): + def test_isin_nan_common_float64(self, request, nulls_fixture): if nulls_fixture is pd.NaT: pytest.skip("pd.NaT not compatible with Float64Index") # Float64Index overrides isin, so must be checked separately if nulls_fixture is pd.NA: - pytest.xfail("Float64Index cannot contain pd.NA") + request.node.add_marker( + pytest.mark.xfail(reason="Float64Index cannot contain pd.NA") + ) tm.assert_numpy_array_equal( Float64Index([1.0, nulls_fixture]).isin([np.nan]), np.array([False, True]) diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 912743e45975a..64b08c6058b81 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -38,19 +38,21 @@ def test_union_same_types(index): assert idx1.union(idx2).dtype == idx1.dtype -def test_union_different_types(index, index_fixture2): +def test_union_different_types(request, index, index_fixture2): # This test only considers combinations of indices # GH 23525 idx1, idx2 = index, index_fixture2 type_pair = tuple(sorted([type(idx1), type(idx2)], key=lambda x: str(x))) if type_pair in COMPATIBLE_INCONSISTENT_PAIRS: - pytest.xfail("This test only considers non compatible indexes.") + request.node.add_marker( + pytest.mark.xfail(reason="This test only considers non compatible indexes.") + ) if any(isinstance(idx, pd.MultiIndex) for idx in (idx1, idx2)): pytest.xfail("This test doesn't consider multiindixes.") if is_dtype_equal(idx1.dtype, idx2.dtype): - pytest.xfail("This test only considers non matching dtypes.") + pytest.skip("This test only considers non matching dtypes.") # A union with a CategoricalIndex (even as dtype('O')) and a # non-CategoricalIndex can only be made if both indices are monotonic. diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 41f967ce32796..8735e2a09920d 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -339,26 +339,33 @@ def test_setitem_index_float64(self, val, exp_dtype, request): exp_index = pd.Index([1.1, 2.1, 3.1, 4.1, val]) self._assert_setitem_index_conversion(obj, val, exp_index, exp_dtype) + @pytest.mark.xfail(reason="Test not implemented") def test_setitem_series_period(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_setitem_index_complex128(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_setitem_index_bool(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_setitem_index_datetime64(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_setitem_index_datetime64tz(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_setitem_index_timedelta64(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_setitem_index_period(self): - pytest.xfail("Test not implemented") + raise NotImplementedError class TestInsertIndexCoercion(CoercionBase): @@ -511,11 +518,13 @@ def test_insert_index_period(self, insert, coerced_val, coerced_dtype): # passing keywords to pd.Index pd.Index(data, freq="M") + @pytest.mark.xfail(reason="Test not implemented") def test_insert_index_complex128(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_insert_index_bool(self): - pytest.xfail("Test not implemented") + raise NotImplementedError class TestWhereCoercion(CoercionBase): @@ -760,17 +769,21 @@ def test_where_index_datetime64tz(self): self._assert_where_conversion(obj, cond, values, exp, exp_dtype) + @pytest.mark.xfail(reason="Test not implemented") def test_where_index_complex128(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_where_index_bool(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_where_series_timedelta64(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_where_series_period(self): - pytest.xfail("Test not implemented") + raise NotImplementedError @pytest.mark.parametrize( "value", [pd.Timedelta(days=9), timedelta(days=9), np.timedelta64(9, "D")] @@ -822,8 +835,9 @@ class TestFillnaSeriesCoercion(CoercionBase): method = "fillna" + @pytest.mark.xfail(reason="Test not implemented") def test_has_comprehensive_tests(self): - pytest.xfail("Test not implemented") + raise NotImplementedError def _assert_fillna_conversion(self, original, value, expected, expected_dtype): """ test coercion triggered by fillna """ @@ -942,29 +956,37 @@ def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype): ) self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype) + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_series_int64(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_index_int64(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_series_bool(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_index_bool(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_series_timedelta64(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_series_period(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_index_timedelta64(self): - pytest.xfail("Test not implemented") + raise NotImplementedError + @pytest.mark.xfail(reason="Test not implemented") def test_fillna_index_period(self): - pytest.xfail("Test not implemented") + raise NotImplementedError class TestReplaceSeriesCoercion(CoercionBase): @@ -1120,5 +1142,6 @@ def test_replace_series_datetime_datetime(self, how, to_key, from_key): tm.assert_series_equal(result, exp) + @pytest.mark.xfail(reason="Test not implemented") def test_replace_series_period(self): - pytest.xfail("Test not implemented") + raise NotImplementedError diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index f472e24ac9498..1b80b6429c8b5 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -136,9 +136,13 @@ def test_usecols_int(self, read_ext, df_ref): usecols=3, ) - def test_usecols_list(self, read_ext, df_ref): + def test_usecols_list(self, request, read_ext, df_ref): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) df_ref = df_ref.reindex(columns=["B", "C"]) df1 = pd.read_excel( @@ -156,9 +160,13 @@ def test_usecols_list(self, read_ext, df_ref): tm.assert_frame_equal(df1, df_ref, check_names=False) tm.assert_frame_equal(df2, df_ref, check_names=False) - def test_usecols_str(self, read_ext, df_ref): + def test_usecols_str(self, request, read_ext, df_ref): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) df1 = df_ref.reindex(columns=["A", "B", "C"]) df2 = pd.read_excel( @@ -208,9 +216,15 @@ def test_usecols_str(self, read_ext, df_ref): @pytest.mark.parametrize( "usecols", [[0, 1, 3], [0, 3, 1], [1, 0, 3], [1, 3, 0], [3, 0, 1], [3, 1, 0]] ) - def test_usecols_diff_positional_int_columns_order(self, read_ext, usecols, df_ref): + def test_usecols_diff_positional_int_columns_order( + self, request, read_ext, usecols, df_ref + ): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) expected = df_ref[["A", "C"]] result = pd.read_excel( @@ -226,17 +240,25 @@ def test_usecols_diff_positional_str_columns_order(self, read_ext, usecols, df_r result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols=usecols) tm.assert_frame_equal(result, expected, check_names=False) - def test_read_excel_without_slicing(self, read_ext, df_ref): + def test_read_excel_without_slicing(self, request, read_ext, df_ref): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) expected = df_ref result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0) tm.assert_frame_equal(result, expected, check_names=False) - def test_usecols_excel_range_str(self, read_ext, df_ref): + def test_usecols_excel_range_str(self, request, read_ext, df_ref): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) expected = df_ref[["C", "D"]] result = pd.read_excel( @@ -310,17 +332,25 @@ def test_excel_stop_iterator(self, read_ext): expected = DataFrame([["aaaa", "bbbbb"]], columns=["Test", "Test1"]) tm.assert_frame_equal(parsed, expected) - def test_excel_cell_error_na(self, read_ext): + def test_excel_cell_error_na(self, request, read_ext): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) parsed = pd.read_excel("test3" + read_ext, sheet_name="Sheet1") expected = DataFrame([[np.nan]], columns=["Test"]) tm.assert_frame_equal(parsed, expected) - def test_excel_table(self, read_ext, df_ref): + def test_excel_table(self, request, read_ext, df_ref): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) df1 = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0) df2 = pd.read_excel( @@ -335,9 +365,13 @@ def test_excel_table(self, read_ext, df_ref): ) tm.assert_frame_equal(df3, df1.iloc[:-1]) - def test_reader_special_dtypes(self, read_ext): + def test_reader_special_dtypes(self, request, read_ext): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) expected = DataFrame.from_dict( { @@ -568,10 +602,14 @@ def test_read_excel_blank_with_header(self, read_ext): actual = pd.read_excel("blank_with_header" + read_ext, sheet_name="Sheet1") tm.assert_frame_equal(actual, expected) - def test_date_conversion_overflow(self, read_ext): + def test_date_conversion_overflow(self, request, read_ext): # GH 10001 : pandas.ExcelFile ignore parse_dates=False if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) expected = DataFrame( [ @@ -583,24 +621,29 @@ def test_date_conversion_overflow(self, read_ext): ) if pd.read_excel.keywords["engine"] == "openpyxl": - pytest.xfail("Maybe not supported by openpyxl") + request.node.add_marker( + pytest.mark.xfail(reason="Maybe not supported by openpyxl") + ) - if pd.read_excel.keywords["engine"] is None: + if pd.read_excel.keywords["engine"] is None and read_ext in (".xlsx", ".xlsm"): # GH 35029 - pytest.xfail("Defaults to openpyxl, maybe not supported") + request.node.add_marker( + pytest.mark.xfail(reason="Defaults to openpyxl, maybe not supported") + ) result = pd.read_excel("testdateoverflow" + read_ext) tm.assert_frame_equal(result, expected) - def test_sheet_name(self, read_ext, df_ref): + def test_sheet_name(self, request, read_ext, df_ref): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) filename = "test1" sheet_name = "Sheet1" - if pd.read_excel.keywords["engine"] == "openpyxl": - pytest.xfail("Maybe not supported by openpyxl") - df1 = pd.read_excel( filename + read_ext, sheet_name=sheet_name, index_col=0 ) # doc @@ -730,9 +773,13 @@ def test_close_from_py_localpath(self, read_ext): # should not throw an exception because the passed file was closed f.read() - def test_reader_seconds(self, read_ext): + def test_reader_seconds(self, request, read_ext): if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) # Test reading times with and without milliseconds. GH5945. expected = DataFrame.from_dict( @@ -759,10 +806,14 @@ def test_reader_seconds(self, read_ext): actual = pd.read_excel("times_1904" + read_ext, sheet_name="Sheet1") tm.assert_frame_equal(actual, expected) - def test_read_excel_multiindex(self, read_ext): + def test_read_excel_multiindex(self, request, read_ext): # see gh-4679 if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]]) mi_file = "testmultiindex" + read_ext @@ -849,11 +900,15 @@ def test_read_excel_multiindex(self, read_ext): ], ) def test_read_excel_multiindex_blank_after_name( - self, read_ext, sheet_name, idx_lvl2 + self, request, read_ext, sheet_name, idx_lvl2 ): # GH34673 if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb (GH4679") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb (GH4679" + ) + ) mi_file = "testmultiindex" + read_ext mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]], names=["c1", "c2"]) @@ -968,10 +1023,14 @@ def test_read_excel_bool_header_arg(self, read_ext): with pytest.raises(TypeError, match=msg): pd.read_excel("test1" + read_ext, header=arg) - def test_read_excel_skiprows(self, read_ext): + def test_read_excel_skiprows(self, request, read_ext): # GH 4903 if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) actual = pd.read_excel( "testskiprows" + read_ext, sheet_name="skiprows_list", skiprows=[0, 2] @@ -1151,11 +1210,15 @@ def test_excel_passes_na_filter(self, read_ext, na_filter): expected = DataFrame(expected, columns=["Test"]) tm.assert_frame_equal(parsed, expected) - def test_excel_table_sheet_by_index(self, read_ext, df_ref): + def test_excel_table_sheet_by_index(self, request, read_ext, df_ref): # For some reason pd.read_excel has no attribute 'keywords' here. # Skipping based on read_ext instead. if read_ext == ".xlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) with pd.ExcelFile("test1" + read_ext) as excel: df1 = pd.read_excel(excel, sheet_name=0, index_col=0) @@ -1178,11 +1241,15 @@ def test_excel_table_sheet_by_index(self, read_ext, df_ref): tm.assert_frame_equal(df3, df1.iloc[:-1]) - def test_sheet_name(self, read_ext, df_ref): + def test_sheet_name(self, request, read_ext, df_ref): # For some reason pd.read_excel has no attribute 'keywords' here. # Skipping based on read_ext instead. if read_ext == ".xlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) filename = "test1" sheet_name = "Sheet1" @@ -1262,10 +1329,14 @@ def test_header_with_index_col(self, engine, filename): ) tm.assert_frame_equal(expected, result) - def test_read_datetime_multiindex(self, engine, read_ext): + def test_read_datetime_multiindex(self, request, engine, read_ext): # GH 34748 if engine == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) f = "test_datetime_mi" + read_ext with pd.ExcelFile(f) as excel: diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index 6b1abebe0506a..ed996d32cf2fb 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -21,7 +21,7 @@ "openpyxl", ], ) -def test_styler_to_excel(engine): +def test_styler_to_excel(request, engine): def style(df): # TODO: RGB colors not supported in xlwt return DataFrame( @@ -44,8 +44,12 @@ def style(df): def assert_equal_style(cell1, cell2, engine): if engine in ["xlsxwriter", "openpyxl"]: - pytest.xfail( - reason=(f"GH25351: failing on some attribute comparisons in {engine}") + request.node.add_marker( + pytest.mark.xfail( + reason=( + f"GH25351: failing on some attribute comparisons in {engine}" + ) + ) ) # TODO: should find a better way to check equality assert cell1.alignment.__dict__ == cell2.alignment.__dict__ diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 851e64a3f2478..eaf35c845ab9a 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -165,7 +165,7 @@ def test_roundtrip_intframe(self, orient, convert_axes, numpy, dtype, int_frame) @pytest.mark.parametrize("dtype", [None, np.float64, int, "U3"]) @pytest.mark.parametrize("convert_axes", [True, False]) @pytest.mark.parametrize("numpy", [True, False]) - def test_roundtrip_str_axes(self, orient, convert_axes, numpy, dtype): + def test_roundtrip_str_axes(self, request, orient, convert_axes, numpy, dtype): df = DataFrame( np.zeros((200, 4)), columns=[str(i) for i in range(4)], @@ -175,7 +175,9 @@ def test_roundtrip_str_axes(self, orient, convert_axes, numpy, dtype): # TODO: do we even need to support U3 dtypes? if numpy and dtype == "U3" and orient != "split": - pytest.xfail("Can't decode directly to array") + request.node.add_marker( + pytest.mark.xfail(reason="Can't decode directly to array") + ) data = df.to_json(orient=orient) result = pd.read_json( @@ -202,14 +204,20 @@ def test_roundtrip_str_axes(self, orient, convert_axes, numpy, dtype): @pytest.mark.parametrize("convert_axes", [True, False]) @pytest.mark.parametrize("numpy", [True, False]) - def test_roundtrip_categorical(self, orient, convert_axes, numpy): + def test_roundtrip_categorical(self, request, orient, convert_axes, numpy): # TODO: create a better frame to test with and improve coverage if orient in ("index", "columns"): - pytest.xfail(f"Can't have duplicate index values for orient '{orient}')") + request.node.add_marker( + pytest.mark.xfail( + reason=f"Can't have duplicate index values for orient '{orient}')" + ) + ) data = self.categorical.to_json(orient=orient) if numpy and orient in ("records", "values"): - pytest.xfail(f"Orient {orient} is broken with numpy=True") + request.node.add_marker( + pytest.mark.xfail(reason=f"Orient {orient} is broken with numpy=True") + ) result = pd.read_json( data, orient=orient, convert_axes=convert_axes, numpy=numpy @@ -264,9 +272,11 @@ def test_roundtrip_timestamp(self, orient, convert_axes, numpy, datetime_frame): @pytest.mark.parametrize("convert_axes", [True, False]) @pytest.mark.parametrize("numpy", [True, False]) - def test_roundtrip_mixed(self, orient, convert_axes, numpy): + def test_roundtrip_mixed(self, request, orient, convert_axes, numpy): if numpy and orient != "split": - pytest.xfail("Can't decode directly to array") + request.node.add_marker( + pytest.mark.xfail(reason="Can't decode directly to array") + ) index = pd.Index(["a", "b", "c", "d", "e"]) values = { diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 822b412916726..c6969fd5bbb74 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -309,16 +309,18 @@ def test_cross_engine_pa_fp(df_cross_compat, pa, fp): tm.assert_frame_equal(result, df[["a", "d"]]) -def test_cross_engine_fp_pa(df_cross_compat, pa, fp): +def test_cross_engine_fp_pa(request, df_cross_compat, pa, fp): # cross-compat with differing reading/writing engines if ( LooseVersion(pyarrow.__version__) < "0.15" and LooseVersion(pyarrow.__version__) >= "0.13" ): - pytest.xfail( - "Reading fastparquet with pyarrow in 0.14 fails: " - "https://issues.apache.org/jira/browse/ARROW-6492" + request.node.add_marker( + pytest.mark.xfail( + "Reading fastparquet with pyarrow in 0.14 fails: " + "https://issues.apache.org/jira/browse/ARROW-6492" + ) ) df = df_cross_compat diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index c12111e20a4b1..c669cf39c9a61 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -117,10 +117,12 @@ def test_aaa_group_order(): tm.assert_frame_equal(grouped.get_group(datetime(2013, 1, 5)), df[4::5]) -def test_aggregate_normal(resample_method): +def test_aggregate_normal(request, resample_method): """Check TimeGrouper's aggregation is identical as normal groupby.""" if resample_method == "ohlc": - pytest.xfail(reason="DataError: No numeric types to aggregate") + request.node.add_marker( + pytest.mark.xfail(reason="DataError: No numeric types to aggregate") + ) data = np.random.randn(20, 4) normal_df = DataFrame(data, columns=["A", "B", "C", "D"])
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Continuation of #38881. This handles cases where replacing pytest.xfail is clear, opened #38902 for the handful of remaining cases. In the case where `pytest.xfail` is used for a test which has been yet to be implemented, I've added ~~`assert False` to maintain the current behavior of counting it as an xfail. Maybe there is a better alternative here.~~ `raise NotImplementedError`.
https://api.github.com/repos/pandas-dev/pandas/pulls/38901
2021-01-02T15:40:36Z
2021-01-03T19:43:59Z
2021-01-03T19:43:59Z
2021-01-03T20:35:30Z
Validate axis args
diff --git a/pandas/core/series.py b/pandas/core/series.py index 7f2039c998f53..274801431661f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2076,7 +2076,7 @@ def idxmin(self, axis=0, skipna=True, *args, **kwargs): >>> s.idxmin(skipna=False) nan """ - i = self.argmin(None, skipna=skipna) + i = self.argmin(axis, skipna, *args, **kwargs) if i == -1: return np.nan return self.index[i] @@ -2146,7 +2146,7 @@ def idxmax(self, axis=0, skipna=True, *args, **kwargs): >>> s.idxmax(skipna=False) nan """ - i = self.argmax(None, skipna=skipna) + i = self.argmax(axis, skipna, *args, **kwargs) if i == -1: return np.nan return self.index[i]
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This is a follow up PR on #37924 @jreback cheers
https://api.github.com/repos/pandas-dev/pandas/pulls/38899
2021-01-02T13:21:07Z
2021-01-03T17:14:40Z
2021-01-03T17:14:40Z
2021-01-03T17:14:44Z
TST/REF: split io/parsers/test_common into multiple files
diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py new file mode 100644 index 0000000000000..8c1475025b442 --- /dev/null +++ b/pandas/tests/io/parser/common/test_chunksize.py @@ -0,0 +1,221 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import StringIO + +import numpy as np +import pytest + +from pandas.errors import DtypeWarning + +from pandas import DataFrame, concat +import pandas._testing as tm + + +@pytest.mark.parametrize("index_col", [0, "index"]) +def test_read_chunksize_with_index(all_parsers, index_col): + parser = all_parsers + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + + expected = DataFrame( + [ + ["foo", 2, 3, 4, 5], + ["bar", 7, 8, 9, 10], + ["baz", 12, 13, 14, 15], + ["qux", 12, 13, 14, 15], + ["foo2", 12, 13, 14, 15], + ["bar2", 12, 13, 14, 15], + ], + columns=["index", "A", "B", "C", "D"], + ) + expected = expected.set_index("index") + + with parser.read_csv(StringIO(data), index_col=0, chunksize=2) as reader: + chunks = list(reader) + tm.assert_frame_equal(chunks[0], expected[:2]) + tm.assert_frame_equal(chunks[1], expected[2:4]) + tm.assert_frame_equal(chunks[2], expected[4:]) + + +@pytest.mark.parametrize("chunksize", [1.3, "foo", 0]) +def test_read_chunksize_bad(all_parsers, chunksize): + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + parser = all_parsers + msg = r"'chunksize' must be an integer >=1" + + with pytest.raises(ValueError, match=msg): + with parser.read_csv(StringIO(data), chunksize=chunksize) as _: + pass + + +@pytest.mark.parametrize("chunksize", [2, 8]) +def test_read_chunksize_and_nrows(all_parsers, chunksize): + # see gh-15755 + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + parser = all_parsers + kwargs = {"index_col": 0, "nrows": 5} + + expected = parser.read_csv(StringIO(data), **kwargs) + with parser.read_csv(StringIO(data), chunksize=chunksize, **kwargs) as reader: + tm.assert_frame_equal(concat(reader), expected) + + +def test_read_chunksize_and_nrows_changing_size(all_parsers): + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + parser = all_parsers + kwargs = {"index_col": 0, "nrows": 5} + + expected = parser.read_csv(StringIO(data), **kwargs) + with parser.read_csv(StringIO(data), chunksize=8, **kwargs) as reader: + tm.assert_frame_equal(reader.get_chunk(size=2), expected.iloc[:2]) + tm.assert_frame_equal(reader.get_chunk(size=4), expected.iloc[2:5]) + + with pytest.raises(StopIteration, match=""): + reader.get_chunk(size=3) + + +def test_get_chunk_passed_chunksize(all_parsers): + parser = all_parsers + data = """A,B,C +1,2,3 +4,5,6 +7,8,9 +1,2,3""" + + with parser.read_csv(StringIO(data), chunksize=2) as reader: + result = reader.get_chunk() + + expected = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("kwargs", [{}, {"index_col": 0}]) +def test_read_chunksize_compat(all_parsers, kwargs): + # see gh-12185 + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + parser = all_parsers + result = parser.read_csv(StringIO(data), **kwargs) + with parser.read_csv(StringIO(data), chunksize=2, **kwargs) as reader: + tm.assert_frame_equal(concat(reader), result) + + +def test_read_chunksize_jagged_names(all_parsers): + # see gh-23509 + parser = all_parsers + data = "\n".join(["0"] * 7 + [",".join(["0"] * 10)]) + + expected = DataFrame([[0] + [np.nan] * 9] * 7 + [[0] * 10]) + with parser.read_csv(StringIO(data), names=range(10), chunksize=4) as reader: + result = concat(reader) + tm.assert_frame_equal(result, expected) + + +def test_chunk_begins_with_newline_whitespace(all_parsers): + # see gh-10022 + parser = all_parsers + data = "\n hello\nworld\n" + + result = parser.read_csv(StringIO(data), header=None) + expected = DataFrame([" hello", "world"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.xfail(reason="GH38630, sometimes gives ResourceWarning", strict=False) +def test_chunks_have_consistent_numerical_type(all_parsers): + parser = all_parsers + integers = [str(i) for i in range(499999)] + data = "a\n" + "\n".join(integers + ["1.0", "2.0"] + integers) + + # Coercions should work without warnings. + with tm.assert_produces_warning(None): + result = parser.read_csv(StringIO(data)) + + assert type(result.a[0]) is np.float64 + assert result.a.dtype == float + + +def test_warn_if_chunks_have_mismatched_type(all_parsers): + warning_type = None + parser = all_parsers + integers = [str(i) for i in range(499999)] + data = "a\n" + "\n".join(integers + ["a", "b"] + integers) + + # see gh-3866: if chunks are different types and can't + # be coerced using numerical types, then issue warning. + if parser.engine == "c" and parser.low_memory: + warning_type = DtypeWarning + + with tm.assert_produces_warning(warning_type): + df = parser.read_csv(StringIO(data)) + assert df.a.dtype == object + + +@pytest.mark.parametrize("iterator", [True, False]) +def test_empty_with_nrows_chunksize(all_parsers, iterator): + # see gh-9535 + parser = all_parsers + expected = DataFrame(columns=["foo", "bar"]) + + nrows = 10 + data = StringIO("foo,bar\n") + + if iterator: + with parser.read_csv(data, chunksize=nrows) as reader: + result = next(iter(reader)) + else: + result = parser.read_csv(data, nrows=nrows) + + tm.assert_frame_equal(result, expected) + + +def test_read_csv_memory_growth_chunksize(all_parsers): + # see gh-24805 + # + # Let's just make sure that we don't crash + # as we iteratively process all chunks. + parser = all_parsers + + with tm.ensure_clean() as path: + with open(path, "w") as f: + for i in range(1000): + f.write(str(i) + "\n") + + with parser.read_csv(path, chunksize=20) as result: + for _ in result: + pass diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py new file mode 100644 index 0000000000000..4fd754bf79ba2 --- /dev/null +++ b/pandas/tests/io/parser/common/test_common_basic.py @@ -0,0 +1,727 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from datetime import datetime +from inspect import signature +from io import StringIO +import os + +import numpy as np +import pytest + +from pandas._libs.tslib import Timestamp +from pandas.errors import EmptyDataError, ParserError + +from pandas import DataFrame, Index, Series, compat +import pandas._testing as tm + +from pandas.io.parsers import CParserWrapper, TextFileReader + + +def test_override_set_noconvert_columns(): + # see gh-17351 + # + # Usecols needs to be sorted in _set_noconvert_columns based + # on the test_usecols_with_parse_dates test from test_usecols.py + class MyTextFileReader(TextFileReader): + def __init__(self): + self._currow = 0 + self.squeeze = False + + class MyCParserWrapper(CParserWrapper): + def _set_noconvert_columns(self): + if self.usecols_dtype == "integer": + # self.usecols is a set, which is documented as unordered + # but in practice, a CPython set of integers is sorted. + # In other implementations this assumption does not hold. + # The following code simulates a different order, which + # before GH 17351 would cause the wrong columns to be + # converted via the parse_dates parameter + self.usecols = list(self.usecols) + self.usecols.reverse() + return CParserWrapper._set_noconvert_columns(self) + + data = """a,b,c,d,e +0,1,20140101,0900,4 +0,1,20140102,1000,4""" + + parse_dates = [[1, 2]] + cols = { + "a": [0, 0], + "c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")], + } + expected = DataFrame(cols, columns=["c_d", "a"]) + + parser = MyTextFileReader() + parser.options = { + "usecols": [0, 2, 3], + "parse_dates": parse_dates, + "delimiter": ",", + } + parser.engine = "c" + parser._engine = MyCParserWrapper(StringIO(data), **parser.options) + + result = parser.read() + tm.assert_frame_equal(result, expected) + + +def test_read_csv_local(all_parsers, csv1): + prefix = "file:///" if compat.is_platform_windows() else "file://" + parser = all_parsers + + fname = prefix + str(os.path.abspath(csv1)) + result = parser.read_csv(fname, index_col=0, parse_dates=True) + + expected = DataFrame( + [ + [0.980269, 3.685731, -0.364216805298, -1.159738], + [1.047916, -0.041232, -0.16181208307, 0.212549], + [0.498581, 0.731168, -0.537677223318, 1.346270], + [1.120202, 1.567621, 0.00364077397681, 0.675253], + [-0.487094, 0.571455, -1.6116394093, 0.103469], + [0.836649, 0.246462, 0.588542635376, 1.062782], + [-0.157161, 1.340307, 1.1957779562, -1.097007], + ], + columns=["A", "B", "C", "D"], + index=Index( + [ + datetime(2000, 1, 3), + datetime(2000, 1, 4), + datetime(2000, 1, 5), + datetime(2000, 1, 6), + datetime(2000, 1, 7), + datetime(2000, 1, 10), + datetime(2000, 1, 11), + ], + name="index", + ), + ) + tm.assert_frame_equal(result, expected) + + +def test_1000_sep(all_parsers): + parser = all_parsers + data = """A|B|C +1|2,334|5 +10|13|10. +""" + expected = DataFrame({"A": [1, 10], "B": [2334, 13], "C": [5, 10.0]}) + + result = parser.read_csv(StringIO(data), sep="|", thousands=",") + tm.assert_frame_equal(result, expected) + + +def test_squeeze(all_parsers): + data = """\ +a,1 +b,2 +c,3 +""" + parser = all_parsers + index = Index(["a", "b", "c"], name=0) + expected = Series([1, 2, 3], name=1, index=index) + + result = parser.read_csv(StringIO(data), index_col=0, header=None, squeeze=True) + tm.assert_series_equal(result, expected) + + # see gh-8217 + # + # Series should not be a view. + assert not result._is_view + + +def test_unnamed_columns(all_parsers): + data = """A,B,C,, +1,2,3,4,5 +6,7,8,9,10 +11,12,13,14,15 +""" + parser = all_parsers + expected = DataFrame( + [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], + dtype=np.int64, + columns=["A", "B", "C", "Unnamed: 3", "Unnamed: 4"], + ) + result = parser.read_csv(StringIO(data)) + tm.assert_frame_equal(result, expected) + + +def test_csv_mixed_type(all_parsers): + data = """A,B,C +a,1,2 +b,3,4 +c,4,5 +""" + parser = all_parsers + expected = DataFrame({"A": ["a", "b", "c"], "B": [1, 3, 4], "C": [2, 4, 5]}) + result = parser.read_csv(StringIO(data)) + tm.assert_frame_equal(result, expected) + + +def test_read_csv_low_memory_no_rows_with_index(all_parsers): + # see gh-21141 + parser = all_parsers + + if not parser.low_memory: + pytest.skip("This is a low-memory specific test") + + data = """A,B,C +1,1,1,2 +2,2,3,4 +3,3,4,5 +""" + result = parser.read_csv(StringIO(data), low_memory=True, index_col=0, nrows=0) + expected = DataFrame(columns=["A", "B", "C"]) + tm.assert_frame_equal(result, expected) + + +def test_read_csv_dataframe(all_parsers, csv1): + parser = all_parsers + result = parser.read_csv(csv1, index_col=0, parse_dates=True) + + expected = DataFrame( + [ + [0.980269, 3.685731, -0.364216805298, -1.159738], + [1.047916, -0.041232, -0.16181208307, 0.212549], + [0.498581, 0.731168, -0.537677223318, 1.346270], + [1.120202, 1.567621, 0.00364077397681, 0.675253], + [-0.487094, 0.571455, -1.6116394093, 0.103469], + [0.836649, 0.246462, 0.588542635376, 1.062782], + [-0.157161, 1.340307, 1.1957779562, -1.097007], + ], + columns=["A", "B", "C", "D"], + index=Index( + [ + datetime(2000, 1, 3), + datetime(2000, 1, 4), + datetime(2000, 1, 5), + datetime(2000, 1, 6), + datetime(2000, 1, 7), + datetime(2000, 1, 10), + datetime(2000, 1, 11), + ], + name="index", + ), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("nrows", [3, 3.0]) +def test_read_nrows(all_parsers, nrows): + # see gh-10476 + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + expected = DataFrame( + [["foo", 2, 3, 4, 5], ["bar", 7, 8, 9, 10], ["baz", 12, 13, 14, 15]], + columns=["index", "A", "B", "C", "D"], + ) + parser = all_parsers + + result = parser.read_csv(StringIO(data), nrows=nrows) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("nrows", [1.2, "foo", -1]) +def test_read_nrows_bad(all_parsers, nrows): + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + msg = r"'nrows' must be an integer >=0" + parser = all_parsers + + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), nrows=nrows) + + +def test_nrows_skipfooter_errors(all_parsers): + msg = "'skipfooter' not supported with 'nrows'" + data = "a\n1\n2\n3\n4\n5\n6" + parser = all_parsers + + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), skipfooter=1, nrows=5) + + +def test_missing_trailing_delimiters(all_parsers): + parser = all_parsers + data = """A,B,C,D +1,2,3,4 +1,3,3, +1,4,5""" + + result = parser.read_csv(StringIO(data)) + expected = DataFrame( + [[1, 2, 3, 4], [1, 3, 3, np.nan], [1, 4, 5, np.nan]], + columns=["A", "B", "C", "D"], + ) + tm.assert_frame_equal(result, expected) + + +def test_skip_initial_space(all_parsers): + data = ( + '"09-Apr-2012", "01:10:18.300", 2456026.548822908, 12849, ' + "1.00361, 1.12551, 330.65659, 0355626618.16711, 73.48821, " + "314.11625, 1917.09447, 179.71425, 80.000, 240.000, -350, " + "70.06056, 344.98370, 1, 1, -0.689265, -0.692787, " + "0.212036, 14.7674, 41.605, -9999.0, -9999.0, " + "-9999.0, -9999.0, -9999.0, -9999.0, 000, 012, 128" + ) + parser = all_parsers + + result = parser.read_csv( + StringIO(data), + names=list(range(33)), + header=None, + na_values=["-9999.0"], + skipinitialspace=True, + ) + expected = DataFrame( + [ + [ + "09-Apr-2012", + "01:10:18.300", + 2456026.548822908, + 12849, + 1.00361, + 1.12551, + 330.65659, + 355626618.16711, + 73.48821, + 314.11625, + 1917.09447, + 179.71425, + 80.0, + 240.0, + -350, + 70.06056, + 344.9837, + 1, + 1, + -0.689265, + -0.692787, + 0.212036, + 14.7674, + 41.605, + np.nan, + np.nan, + np.nan, + np.nan, + np.nan, + np.nan, + 0, + 12, + 128, + ] + ] + ) + tm.assert_frame_equal(result, expected) + + +def test_trailing_delimiters(all_parsers): + # see gh-2442 + data = """A,B,C +1,2,3, +4,5,6, +7,8,9,""" + parser = all_parsers + result = parser.read_csv(StringIO(data), index_col=False) + + expected = DataFrame({"A": [1, 4, 7], "B": [2, 5, 8], "C": [3, 6, 9]}) + tm.assert_frame_equal(result, expected) + + +def test_escapechar(all_parsers): + # https://stackoverflow.com/questions/13824840/feature-request-for- + # pandas-read-csv + data = '''SEARCH_TERM,ACTUAL_URL +"bra tv bord","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord" +"tv p\xc3\xa5 hjul","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord" +"SLAGBORD, \\"Bergslagen\\", IKEA:s 1700-tals series","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"''' # noqa + + parser = all_parsers + result = parser.read_csv( + StringIO(data), escapechar="\\", quotechar='"', encoding="utf-8" + ) + + assert result["SEARCH_TERM"][2] == 'SLAGBORD, "Bergslagen", IKEA:s 1700-tals series' + + tm.assert_index_equal(result.columns, Index(["SEARCH_TERM", "ACTUAL_URL"])) + + +def test_ignore_leading_whitespace(all_parsers): + # see gh-3374, gh-6607 + parser = all_parsers + data = " a b c\n 1 2 3\n 4 5 6\n 7 8 9" + result = parser.read_csv(StringIO(data), sep=r"\s+") + + expected = DataFrame({"a": [1, 4, 7], "b": [2, 5, 8], "c": [3, 6, 9]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("usecols", [None, [0, 1], ["a", "b"]]) +def test_uneven_lines_with_usecols(all_parsers, usecols): + # see gh-12203 + parser = all_parsers + data = r"""a,b,c +0,1,2 +3,4,5,6,7 +8,9,10""" + + if usecols is None: + # Make sure that an error is still raised + # when the "usecols" parameter is not provided. + msg = r"Expected \d+ fields in line \d+, saw \d+" + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data)) + else: + expected = DataFrame({"a": [0, 3, 8], "b": [1, 4, 9]}) + + result = parser.read_csv(StringIO(data), usecols=usecols) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data,kwargs,expected", + [ + # First, check to see that the response of parser when faced with no + # provided columns raises the correct error, with or without usecols. + ("", {}, None), + ("", {"usecols": ["X"]}, None), + ( + ",,", + {"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]}, + DataFrame(columns=["X"], index=[0], dtype=np.float64), + ), + ( + "", + {"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]}, + DataFrame(columns=["X"]), + ), + ], +) +def test_read_empty_with_usecols(all_parsers, data, kwargs, expected): + # see gh-12493 + parser = all_parsers + + if expected is None: + msg = "No columns to parse from file" + with pytest.raises(EmptyDataError, match=msg): + parser.read_csv(StringIO(data), **kwargs) + else: + result = parser.read_csv(StringIO(data), **kwargs) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "kwargs,expected", + [ + # gh-8661, gh-8679: this should ignore six lines, including + # lines with trailing whitespace and blank lines. + ( + { + "header": None, + "delim_whitespace": True, + "skiprows": [0, 1, 2, 3, 5, 6], + "skip_blank_lines": True, + }, + DataFrame([[1.0, 2.0, 4.0], [5.1, np.nan, 10.0]]), + ), + # gh-8983: test skipping set of rows after a row with trailing spaces. + ( + { + "delim_whitespace": True, + "skiprows": [1, 2, 3, 5, 6], + "skip_blank_lines": True, + }, + DataFrame({"A": [1.0, 5.1], "B": [2.0, np.nan], "C": [4.0, 10]}), + ), + ], +) +def test_trailing_spaces(all_parsers, kwargs, expected): + data = "A B C \nrandom line with trailing spaces \nskip\n1,2,3\n1,2.,4.\nrandom line with trailing tabs\t\t\t\n \n5.1,NaN,10.0\n" # noqa + parser = all_parsers + + result = parser.read_csv(StringIO(data.replace(",", " ")), **kwargs) + tm.assert_frame_equal(result, expected) + + +def test_raise_on_sep_with_delim_whitespace(all_parsers): + # see gh-6607 + data = "a b c\n1 2 3" + parser = all_parsers + + with pytest.raises(ValueError, match="you can only specify one"): + parser.read_csv(StringIO(data), sep=r"\s", delim_whitespace=True) + + +@pytest.mark.parametrize("delim_whitespace", [True, False]) +def test_single_char_leading_whitespace(all_parsers, delim_whitespace): + # see gh-9710 + parser = all_parsers + data = """\ +MyColumn +a +b +a +b\n""" + + expected = DataFrame({"MyColumn": list("abab")}) + result = parser.read_csv( + StringIO(data), skipinitialspace=True, delim_whitespace=delim_whitespace + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "sep,skip_blank_lines,exp_data", + [ + (",", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]), + (r"\s+", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]), + ( + ",", + False, + [ + [1.0, 2.0, 4.0], + [np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan], + [5.0, np.nan, 10.0], + [np.nan, np.nan, np.nan], + [-70.0, 0.4, 1.0], + ], + ), + ], +) +def test_empty_lines(all_parsers, sep, skip_blank_lines, exp_data): + parser = all_parsers + data = """\ +A,B,C +1,2.,4. + + +5.,NaN,10.0 + +-70,.4,1 +""" + + if sep == r"\s+": + data = data.replace(",", " ") + + result = parser.read_csv(StringIO(data), sep=sep, skip_blank_lines=skip_blank_lines) + expected = DataFrame(exp_data, columns=["A", "B", "C"]) + tm.assert_frame_equal(result, expected) + + +def test_whitespace_lines(all_parsers): + parser = all_parsers + data = """ + +\t \t\t +\t +A,B,C +\t 1,2.,4. +5.,NaN,10.0 +""" + expected = DataFrame([[1, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"]) + result = parser.read_csv(StringIO(data)) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data,expected", + [ + ( + """ A B C D +a 1 2 3 4 +b 1 2 3 4 +c 1 2 3 4 +""", + DataFrame( + [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], + columns=["A", "B", "C", "D"], + index=["a", "b", "c"], + ), + ), + ( + " a b c\n1 2 3 \n4 5 6\n 7 8 9", + DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"]), + ), + ], +) +def test_whitespace_regex_separator(all_parsers, data, expected): + # see gh-6607 + parser = all_parsers + result = parser.read_csv(StringIO(data), sep=r"\s+") + tm.assert_frame_equal(result, expected) + + +def test_sub_character(all_parsers, csv_dir_path): + # see gh-16893 + filename = os.path.join(csv_dir_path, "sub_char.csv") + expected = DataFrame([[1, 2, 3]], columns=["a", "\x1ab", "c"]) + + parser = all_parsers + result = parser.read_csv(filename) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("filename", ["sé-es-vé.csv", "ru-sй.csv", "中文文件名.csv"]) +def test_filename_with_special_chars(all_parsers, filename): + # see gh-15086. + parser = all_parsers + df = DataFrame({"a": [1, 2, 3]}) + + with tm.ensure_clean(filename) as path: + df.to_csv(path, index=False) + + result = parser.read_csv(path) + tm.assert_frame_equal(result, df) + + +def test_read_table_same_signature_as_read_csv(all_parsers): + # GH-34976 + parser = all_parsers + + table_sign = signature(parser.read_table) + csv_sign = signature(parser.read_csv) + + assert table_sign.parameters.keys() == csv_sign.parameters.keys() + assert table_sign.return_annotation == csv_sign.return_annotation + + for key, csv_param in csv_sign.parameters.items(): + table_param = table_sign.parameters[key] + if key == "sep": + assert csv_param.default == "," + assert table_param.default == "\t" + assert table_param.annotation == csv_param.annotation + assert table_param.kind == csv_param.kind + continue + else: + assert table_param == csv_param + + +def test_read_table_equivalency_to_read_csv(all_parsers): + # see gh-21948 + # As of 0.25.0, read_table is undeprecated + parser = all_parsers + data = "a\tb\n1\t2\n3\t4" + expected = parser.read_csv(StringIO(data), sep="\t") + result = parser.read_table(StringIO(data)) + tm.assert_frame_equal(result, expected) + + +def test_first_row_bom(all_parsers): + # see gh-26545 + parser = all_parsers + data = '''\ufeff"Head1" "Head2" "Head3"''' + + result = parser.read_csv(StringIO(data), delimiter="\t") + expected = DataFrame(columns=["Head1", "Head2", "Head3"]) + tm.assert_frame_equal(result, expected) + + +def test_first_row_bom_unquoted(all_parsers): + # see gh-36343 + parser = all_parsers + data = """\ufeffHead1 Head2 Head3""" + + result = parser.read_csv(StringIO(data), delimiter="\t") + expected = DataFrame(columns=["Head1", "Head2", "Head3"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("nrows", range(1, 6)) +def test_blank_lines_between_header_and_data_rows(all_parsers, nrows): + # GH 28071 + ref = DataFrame( + [[np.nan, np.nan], [np.nan, np.nan], [1, 2], [np.nan, np.nan], [3, 4]], + columns=list("ab"), + ) + csv = "\nheader\n\na,b\n\n\n1,2\n\n3,4" + parser = all_parsers + df = parser.read_csv(StringIO(csv), header=3, nrows=nrows, skip_blank_lines=False) + tm.assert_frame_equal(df, ref[:nrows]) + + +def test_no_header_two_extra_columns(all_parsers): + # GH 26218 + column_names = ["one", "two", "three"] + ref = DataFrame([["foo", "bar", "baz"]], columns=column_names) + stream = StringIO("foo,bar,baz,bam,blah") + parser = all_parsers + df = parser.read_csv(stream, header=None, names=column_names, index_col=False) + tm.assert_frame_equal(df, ref) + + +def test_read_csv_names_not_accepting_sets(all_parsers): + # GH 34946 + data = """\ + 1,2,3 + 4,5,6\n""" + parser = all_parsers + with pytest.raises(ValueError, match="Names should be an ordered collection."): + parser.read_csv(StringIO(data), names=set("QAZ")) + + +def test_read_table_delim_whitespace_default_sep(all_parsers): + # GH: 35958 + f = StringIO("a b c\n1 -2 -3\n4 5 6") + parser = all_parsers + result = parser.read_table(f, delim_whitespace=True) + expected = DataFrame({"a": [1, 4], "b": [-2, 5], "c": [-3, 6]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("delimiter", [",", "\t"]) +def test_read_csv_delim_whitespace_non_default_sep(all_parsers, delimiter): + # GH: 35958 + f = StringIO("a b c\n1 -2 -3\n4 5 6") + parser = all_parsers + msg = ( + "Specified a delimiter with both sep and " + "delim_whitespace=True; you can only specify one." + ) + with pytest.raises(ValueError, match=msg): + parser.read_csv(f, delim_whitespace=True, sep=delimiter) + + with pytest.raises(ValueError, match=msg): + parser.read_csv(f, delim_whitespace=True, delimiter=delimiter) + + +@pytest.mark.parametrize("delimiter", [",", "\t"]) +def test_read_table_delim_whitespace_non_default_sep(all_parsers, delimiter): + # GH: 35958 + f = StringIO("a b c\n1 -2 -3\n4 5 6") + parser = all_parsers + msg = ( + "Specified a delimiter with both sep and " + "delim_whitespace=True; you can only specify one." + ) + with pytest.raises(ValueError, match=msg): + parser.read_table(f, delim_whitespace=True, sep=delimiter) + + with pytest.raises(ValueError, match=msg): + parser.read_table(f, delim_whitespace=True, delimiter=delimiter) + + +def test_dict_keys_as_names(all_parsers): + # GH: 36928 + data = "1,2" + + keys = {"a": int, "b": int}.keys() + parser = all_parsers + + result = parser.read_csv(StringIO(data), names=keys) + expected = DataFrame({"a": [1], "b": [2]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_data_list.py b/pandas/tests/io/parser/common/test_data_list.py new file mode 100644 index 0000000000000..92b8c864f1619 --- /dev/null +++ b/pandas/tests/io/parser/common/test_data_list.py @@ -0,0 +1,82 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +import csv +from io import StringIO + +from pandas import DataFrame +import pandas._testing as tm + +from pandas.io.parsers import TextParser + + +def test_read_data_list(all_parsers): + parser = all_parsers + kwargs = {"index_col": 0} + data = "A,B,C\nfoo,1,2,3\nbar,4,5,6" + + data_list = [["A", "B", "C"], ["foo", "1", "2", "3"], ["bar", "4", "5", "6"]] + expected = parser.read_csv(StringIO(data), **kwargs) + + with TextParser(data_list, chunksize=2, **kwargs) as parser: + result = parser.read() + + tm.assert_frame_equal(result, expected) + + +def test_reader_list(all_parsers): + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + parser = all_parsers + kwargs = {"index_col": 0} + + lines = list(csv.reader(StringIO(data))) + with TextParser(lines, chunksize=2, **kwargs) as reader: + chunks = list(reader) + + expected = parser.read_csv(StringIO(data), **kwargs) + + tm.assert_frame_equal(chunks[0], expected[:2]) + tm.assert_frame_equal(chunks[1], expected[2:4]) + tm.assert_frame_equal(chunks[2], expected[4:]) + + +def test_reader_list_skiprows(all_parsers): + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + parser = all_parsers + kwargs = {"index_col": 0} + + lines = list(csv.reader(StringIO(data))) + with TextParser(lines, chunksize=2, skiprows=[1], **kwargs) as reader: + chunks = list(reader) + + expected = parser.read_csv(StringIO(data), **kwargs) + + tm.assert_frame_equal(chunks[0], expected[1:3]) + + +def test_read_csv_parse_simple_list(all_parsers): + parser = all_parsers + data = """foo +bar baz +qux foo +foo +bar""" + + result = parser.read_csv(StringIO(data), header=None) + expected = DataFrame(["foo", "bar baz", "qux foo", "foo", "bar"]) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_decimal.py b/pandas/tests/io/parser/common/test_decimal.py new file mode 100644 index 0000000000000..7ca9f253bd501 --- /dev/null +++ b/pandas/tests/io/parser/common/test_decimal.py @@ -0,0 +1,60 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import StringIO + +import pytest + +from pandas import DataFrame +import pandas._testing as tm + + +@pytest.mark.parametrize( + "data,thousands,decimal", + [ + ( + """A|B|C +1|2,334.01|5 +10|13|10. +""", + ",", + ".", + ), + ( + """A|B|C +1|2.334,01|5 +10|13|10, +""", + ".", + ",", + ), + ], +) +def test_1000_sep_with_decimal(all_parsers, data, thousands, decimal): + parser = all_parsers + expected = DataFrame({"A": [1, 10], "B": [2334.01, 13], "C": [5, 10.0]}) + + result = parser.read_csv( + StringIO(data), sep="|", thousands=thousands, decimal=decimal + ) + tm.assert_frame_equal(result, expected) + + +def test_euro_decimal_format(all_parsers): + parser = all_parsers + data = """Id;Number1;Number2;Text1;Text2;Number3 +1;1521,1541;187101,9543;ABC;poi;4,738797819 +2;121,12;14897,76;DEF;uyt;0,377320872 +3;878,158;108013,434;GHI;rez;2,735694704""" + + result = parser.read_csv(StringIO(data), sep=";", decimal=",") + expected = DataFrame( + [ + [1, 1521.1541, 187101.9543, "ABC", "poi", 4.738797819], + [2, 121.12, 14897.76, "DEF", "uyt", 0.377320872], + [3, 878.158, 108013.434, "GHI", "rez", 2.735694704], + ], + columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"], + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py new file mode 100644 index 0000000000000..d0f1d63f88b3e --- /dev/null +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -0,0 +1,434 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import BytesIO, StringIO +import os +import platform +from urllib.error import URLError + +import pytest + +from pandas.errors import EmptyDataError, ParserError +import pandas.util._test_decorators as td + +from pandas import DataFrame +import pandas._testing as tm + + +@tm.network +def test_url(all_parsers, csv_dir_path): + # TODO: FTP testing + parser = all_parsers + kwargs = {"sep": "\t"} + + url = ( + "https://raw.github.com/pandas-dev/pandas/master/" + "pandas/tests/io/parser/data/salaries.csv" + ) + url_result = parser.read_csv(url, **kwargs) + + local_path = os.path.join(csv_dir_path, "salaries.csv") + local_result = parser.read_csv(local_path, **kwargs) + tm.assert_frame_equal(url_result, local_result) + + +@pytest.mark.slow +def test_local_file(all_parsers, csv_dir_path): + parser = all_parsers + kwargs = {"sep": "\t"} + + local_path = os.path.join(csv_dir_path, "salaries.csv") + local_result = parser.read_csv(local_path, **kwargs) + url = "file://localhost/" + local_path + + try: + url_result = parser.read_csv(url, **kwargs) + tm.assert_frame_equal(url_result, local_result) + except URLError: + # Fails on some systems. + pytest.skip("Failing on: " + " ".join(platform.uname())) + + +def test_path_path_lib(all_parsers): + parser = all_parsers + df = tm.makeDataFrame() + result = tm.round_trip_pathlib(df.to_csv, lambda p: parser.read_csv(p, index_col=0)) + tm.assert_frame_equal(df, result) + + +def test_path_local_path(all_parsers): + parser = all_parsers + df = tm.makeDataFrame() + result = tm.round_trip_localpath( + df.to_csv, lambda p: parser.read_csv(p, index_col=0) + ) + tm.assert_frame_equal(df, result) + + +def test_nonexistent_path(all_parsers): + # gh-2428: pls no segfault + # gh-14086: raise more helpful FileNotFoundError + # GH#29233 "File foo" instead of "File b'foo'" + parser = all_parsers + path = f"{tm.rands(10)}.csv" + + msg = r"\[Errno 2\]" + with pytest.raises(FileNotFoundError, match=msg) as e: + parser.read_csv(path) + assert path == e.value.filename + + +@td.skip_if_windows # os.chmod does not work in windows +def test_no_permission(all_parsers): + # GH 23784 + parser = all_parsers + + msg = r"\[Errno 13\]" + with tm.ensure_clean() as path: + os.chmod(path, 0) # make file unreadable + + # verify that this process cannot open the file (not running as sudo) + try: + with open(path): + pass + pytest.skip("Running as sudo.") + except PermissionError: + pass + + with pytest.raises(PermissionError, match=msg) as e: + parser.read_csv(path) + assert path == e.value.filename + + +@pytest.mark.parametrize( + "data,kwargs,expected,msg", + [ + # gh-10728: WHITESPACE_LINE + ( + "a,b,c\n4,5,6\n ", + {}, + DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), + None, + ), + # gh-10548: EAT_LINE_COMMENT + ( + "a,b,c\n4,5,6\n#comment", + {"comment": "#"}, + DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), + None, + ), + # EAT_CRNL_NOP + ( + "a,b,c\n4,5,6\n\r", + {}, + DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), + None, + ), + # EAT_COMMENT + ( + "a,b,c\n4,5,6#comment", + {"comment": "#"}, + DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), + None, + ), + # SKIP_LINE + ( + "a,b,c\n4,5,6\nskipme", + {"skiprows": [2]}, + DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), + None, + ), + # EAT_LINE_COMMENT + ( + "a,b,c\n4,5,6\n#comment", + {"comment": "#", "skip_blank_lines": False}, + DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), + None, + ), + # IN_FIELD + ( + "a,b,c\n4,5,6\n ", + {"skip_blank_lines": False}, + DataFrame([["4", 5, 6], [" ", None, None]], columns=["a", "b", "c"]), + None, + ), + # EAT_CRNL + ( + "a,b,c\n4,5,6\n\r", + {"skip_blank_lines": False}, + DataFrame([[4, 5, 6], [None, None, None]], columns=["a", "b", "c"]), + None, + ), + # ESCAPED_CHAR + ( + "a,b,c\n4,5,6\n\\", + {"escapechar": "\\"}, + None, + "(EOF following escape character)|(unexpected end of data)", + ), + # ESCAPE_IN_QUOTED_FIELD + ( + 'a,b,c\n4,5,6\n"\\', + {"escapechar": "\\"}, + None, + "(EOF inside string starting at row 2)|(unexpected end of data)", + ), + # IN_QUOTED_FIELD + ( + 'a,b,c\n4,5,6\n"', + {"escapechar": "\\"}, + None, + "(EOF inside string starting at row 2)|(unexpected end of data)", + ), + ], + ids=[ + "whitespace-line", + "eat-line-comment", + "eat-crnl-nop", + "eat-comment", + "skip-line", + "eat-line-comment", + "in-field", + "eat-crnl", + "escaped-char", + "escape-in-quoted-field", + "in-quoted-field", + ], +) +def test_eof_states(all_parsers, data, kwargs, expected, msg): + # see gh-10728, gh-10548 + parser = all_parsers + + if expected is None: + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data), **kwargs) + else: + result = parser.read_csv(StringIO(data), **kwargs) + tm.assert_frame_equal(result, expected) + + +def test_temporary_file(all_parsers): + # see gh-13398 + parser = all_parsers + data = "0 0" + + with tm.ensure_clean(mode="w+", return_filelike=True) as new_file: + new_file.write(data) + new_file.flush() + new_file.seek(0) + + result = parser.read_csv(new_file, sep=r"\s+", header=None) + + expected = DataFrame([[0, 0]]) + tm.assert_frame_equal(result, expected) + + +def test_internal_eof_byte(all_parsers): + # see gh-5500 + parser = all_parsers + data = "a,b\n1\x1a,2" + + expected = DataFrame([["1\x1a", 2]], columns=["a", "b"]) + result = parser.read_csv(StringIO(data)) + tm.assert_frame_equal(result, expected) + + +def test_internal_eof_byte_to_file(all_parsers): + # see gh-16559 + parser = all_parsers + data = b'c1,c2\r\n"test \x1a test", test\r\n' + expected = DataFrame([["test \x1a test", " test"]], columns=["c1", "c2"]) + path = f"__{tm.rands(10)}__.csv" + + with tm.ensure_clean(path) as path: + with open(path, "wb") as f: + f.write(data) + + result = parser.read_csv(path) + tm.assert_frame_equal(result, expected) + + +def test_file_handle_string_io(all_parsers): + # gh-14418 + # + # Don't close user provided file handles. + parser = all_parsers + data = "a,b\n1,2" + + fh = StringIO(data) + parser.read_csv(fh) + assert not fh.closed + + +def test_file_handles_with_open(all_parsers, csv1): + # gh-14418 + # + # Don't close user provided file handles. + parser = all_parsers + + for mode in ["r", "rb"]: + with open(csv1, mode) as f: + parser.read_csv(f) + assert not f.closed + + +def test_invalid_file_buffer_class(all_parsers): + # see gh-15337 + class InvalidBuffer: + pass + + parser = all_parsers + msg = "Invalid file path or buffer object type" + + with pytest.raises(ValueError, match=msg): + parser.read_csv(InvalidBuffer()) + + +def test_invalid_file_buffer_mock(all_parsers): + # see gh-15337 + parser = all_parsers + msg = "Invalid file path or buffer object type" + + class Foo: + pass + + with pytest.raises(ValueError, match=msg): + parser.read_csv(Foo()) + + +def test_valid_file_buffer_seems_invalid(all_parsers): + # gh-16135: we want to ensure that "tell" and "seek" + # aren't actually being used when we call `read_csv` + # + # Thus, while the object may look "invalid" (these + # methods are attributes of the `StringIO` class), + # it is still a valid file-object for our purposes. + class NoSeekTellBuffer(StringIO): + def tell(self): + raise AttributeError("No tell method") + + def seek(self, pos, whence=0): + raise AttributeError("No seek method") + + data = "a\n1" + parser = all_parsers + expected = DataFrame({"a": [1]}) + + result = parser.read_csv(NoSeekTellBuffer(data)) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("io_class", [StringIO, BytesIO]) +@pytest.mark.parametrize("encoding", [None, "utf-8"]) +def test_read_csv_file_handle(all_parsers, io_class, encoding): + """ + Test whether read_csv does not close user-provided file handles. + + GH 36980 + """ + parser = all_parsers + expected = DataFrame({"a": [1], "b": [2]}) + + content = "a,b\n1,2" + if io_class == BytesIO: + content = content.encode("utf-8") + handle = io_class(content) + + tm.assert_frame_equal(parser.read_csv(handle, encoding=encoding), expected) + assert not handle.closed + + +def test_memory_map_file_handle_silent_fallback(all_parsers, compression): + """ + Do not fail for buffers with memory_map=True (cannot memory map BytesIO). + + GH 37621 + """ + parser = all_parsers + expected = DataFrame({"a": [1], "b": [2]}) + + handle = BytesIO() + expected.to_csv(handle, index=False, compression=compression, mode="wb") + handle.seek(0) + + tm.assert_frame_equal( + parser.read_csv(handle, memory_map=True, compression=compression), + expected, + ) + + +def test_memory_map_compression(all_parsers, compression): + """ + Support memory map for compressed files. + + GH 37621 + """ + parser = all_parsers + expected = DataFrame({"a": [1], "b": [2]}) + + with tm.ensure_clean() as path: + expected.to_csv(path, index=False, compression=compression) + + tm.assert_frame_equal( + parser.read_csv(path, memory_map=True, compression=compression), + expected, + ) + + +def test_context_manager(all_parsers, datapath): + # make sure that opened files are closed + parser = all_parsers + + path = datapath("io", "data", "csv", "iris.csv") + + reader = parser.read_csv(path, chunksize=1) + assert not reader._engine.handles.handle.closed + try: + with reader: + next(reader) + assert False + except AssertionError: + assert reader._engine.handles.handle.closed + + +def test_context_manageri_user_provided(all_parsers, datapath): + # make sure that user-provided handles are not closed + parser = all_parsers + + with open(datapath("io", "data", "csv", "iris.csv"), mode="r") as path: + + reader = parser.read_csv(path, chunksize=1) + assert not reader._engine.handles.handle.closed + try: + with reader: + next(reader) + assert False + except AssertionError: + assert not reader._engine.handles.handle.closed + + +def test_file_descriptor_leak(all_parsers): + # GH 31488 + + parser = all_parsers + with tm.ensure_clean() as path: + + def test(): + with pytest.raises(EmptyDataError, match="No columns to parse from file"): + parser.read_csv(path) + + td.check_file_leaks(test)() + + +@td.check_file_leaks +def test_memory_map(all_parsers, csv_dir_path): + mmap_file = os.path.join(csv_dir_path, "test_mmap.csv") + parser = all_parsers + + expected = DataFrame( + {"a": [1, 2, 3], "b": ["one", "two", "three"], "c": ["I", "II", "III"]} + ) + + result = parser.read_csv(mmap_file, memory_map=True) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_float.py b/pandas/tests/io/parser/common/test_float.py new file mode 100644 index 0000000000000..29aa387e2b045 --- /dev/null +++ b/pandas/tests/io/parser/common/test_float.py @@ -0,0 +1,66 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import StringIO + +import numpy as np +import pytest + +from pandas.compat import is_platform_linux + +from pandas import DataFrame +import pandas._testing as tm + + +def test_float_parser(all_parsers): + # see gh-9565 + parser = all_parsers + data = "45e-1,4.5,45.,inf,-inf" + result = parser.read_csv(StringIO(data), header=None) + + expected = DataFrame([[float(s) for s in data.split(",")]]) + tm.assert_frame_equal(result, expected) + + +def test_scientific_no_exponent(all_parsers_all_precisions): + # see gh-12215 + df = DataFrame.from_dict({"w": ["2e"], "x": ["3E"], "y": ["42e"], "z": ["632E"]}) + data = df.to_csv(index=False) + parser, precision = all_parsers_all_precisions + if parser == "pyarrow": + pytest.skip() + + df_roundtrip = parser.read_csv(StringIO(data), float_precision=precision) + tm.assert_frame_equal(df_roundtrip, df) + + +@pytest.mark.parametrize("neg_exp", [-617, -100000, -99999999999999999]) +def test_very_negative_exponent(all_parsers_all_precisions, neg_exp): + # GH#38753 + parser, precision = all_parsers_all_precisions + if parser == "pyarrow": + pytest.skip() + data = f"data\n10E{neg_exp}" + result = parser.read_csv(StringIO(data), float_precision=precision) + expected = DataFrame({"data": [0.0]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("exp", [999999999999999999, -999999999999999999]) +def test_too_many_exponent_digits(all_parsers_all_precisions, exp, request): + # GH#38753 + parser, precision = all_parsers_all_precisions + data = f"data\n10E{exp}" + result = parser.read_csv(StringIO(data), float_precision=precision) + if precision == "round_trip": + if exp == 999999999999999999 and is_platform_linux(): + mark = pytest.mark.xfail(reason="GH38794, on Linux gives object result") + request.node.add_marker(mark) + + value = np.inf if exp > 0 else 0.0 + expected = DataFrame({"data": [value]}) + else: + expected = DataFrame({"data": [f"10E{exp}"]}) + + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_index.py b/pandas/tests/io/parser/common/test_index.py new file mode 100644 index 0000000000000..a133e1be49946 --- /dev/null +++ b/pandas/tests/io/parser/common/test_index.py @@ -0,0 +1,281 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from datetime import datetime +from io import StringIO +import os + +import pytest + +from pandas import DataFrame, Index, MultiIndex +import pandas._testing as tm + + +@pytest.mark.parametrize( + "data,kwargs,expected", + [ + ( + """foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""", + {"index_col": 0, "names": ["index", "A", "B", "C", "D"]}, + DataFrame( + [ + [2, 3, 4, 5], + [7, 8, 9, 10], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + ], + index=Index(["foo", "bar", "baz", "qux", "foo2", "bar2"], name="index"), + columns=["A", "B", "C", "D"], + ), + ), + ( + """foo,one,2,3,4,5 +foo,two,7,8,9,10 +foo,three,12,13,14,15 +bar,one,12,13,14,15 +bar,two,12,13,14,15 +""", + {"index_col": [0, 1], "names": ["index1", "index2", "A", "B", "C", "D"]}, + DataFrame( + [ + [2, 3, 4, 5], + [7, 8, 9, 10], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + ], + index=MultiIndex.from_tuples( + [ + ("foo", "one"), + ("foo", "two"), + ("foo", "three"), + ("bar", "one"), + ("bar", "two"), + ], + names=["index1", "index2"], + ), + columns=["A", "B", "C", "D"], + ), + ), + ], +) +def test_pass_names_with_index(all_parsers, data, kwargs, expected): + parser = all_parsers + result = parser.read_csv(StringIO(data), **kwargs) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("index_col", [[0, 1], [1, 0]]) +def test_multi_index_no_level_names(all_parsers, index_col): + data = """index1,index2,A,B,C,D +foo,one,2,3,4,5 +foo,two,7,8,9,10 +foo,three,12,13,14,15 +bar,one,12,13,14,15 +bar,two,12,13,14,15 +""" + headless_data = "\n".join(data.split("\n")[1:]) + + names = ["A", "B", "C", "D"] + parser = all_parsers + + result = parser.read_csv( + StringIO(headless_data), index_col=index_col, header=None, names=names + ) + expected = parser.read_csv(StringIO(data), index_col=index_col) + + # No index names in headless data. + expected.index.names = [None] * 2 + tm.assert_frame_equal(result, expected) + + +def test_multi_index_no_level_names_implicit(all_parsers): + parser = all_parsers + data = """A,B,C,D +foo,one,2,3,4,5 +foo,two,7,8,9,10 +foo,three,12,13,14,15 +bar,one,12,13,14,15 +bar,two,12,13,14,15 +""" + + result = parser.read_csv(StringIO(data)) + expected = DataFrame( + [ + [2, 3, 4, 5], + [7, 8, 9, 10], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + ], + columns=["A", "B", "C", "D"], + index=MultiIndex.from_tuples( + [ + ("foo", "one"), + ("foo", "two"), + ("foo", "three"), + ("bar", "one"), + ("bar", "two"), + ] + ), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data,expected,header", + [ + ("a,b", DataFrame(columns=["a", "b"]), [0]), + ( + "a,b\nc,d", + DataFrame(columns=MultiIndex.from_tuples([("a", "c"), ("b", "d")])), + [0, 1], + ), + ], +) +@pytest.mark.parametrize("round_trip", [True, False]) +def test_multi_index_blank_df(all_parsers, data, expected, header, round_trip): + # see gh-14545 + parser = all_parsers + data = expected.to_csv(index=False) if round_trip else data + + result = parser.read_csv(StringIO(data), header=header) + tm.assert_frame_equal(result, expected) + + +def test_no_unnamed_index(all_parsers): + parser = all_parsers + data = """ id c0 c1 c2 +0 1 0 a b +1 2 0 c d +2 2 2 e f +""" + result = parser.read_csv(StringIO(data), sep=" ") + expected = DataFrame( + [[0, 1, 0, "a", "b"], [1, 2, 0, "c", "d"], [2, 2, 2, "e", "f"]], + columns=["Unnamed: 0", "id", "c0", "c1", "c2"], + ) + tm.assert_frame_equal(result, expected) + + +def test_read_duplicate_index_explicit(all_parsers): + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo,12,13,14,15 +bar,12,13,14,15 +""" + parser = all_parsers + result = parser.read_csv(StringIO(data), index_col=0) + + expected = DataFrame( + [ + [2, 3, 4, 5], + [7, 8, 9, 10], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + ], + columns=["A", "B", "C", "D"], + index=Index(["foo", "bar", "baz", "qux", "foo", "bar"], name="index"), + ) + tm.assert_frame_equal(result, expected) + + +def test_read_duplicate_index_implicit(all_parsers): + data = """A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo,12,13,14,15 +bar,12,13,14,15 +""" + parser = all_parsers + result = parser.read_csv(StringIO(data)) + + expected = DataFrame( + [ + [2, 3, 4, 5], + [7, 8, 9, 10], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + [12, 13, 14, 15], + ], + columns=["A", "B", "C", "D"], + index=Index(["foo", "bar", "baz", "qux", "foo", "bar"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_read_csv_no_index_name(all_parsers, csv_dir_path): + parser = all_parsers + csv2 = os.path.join(csv_dir_path, "test2.csv") + result = parser.read_csv(csv2, index_col=0, parse_dates=True) + + expected = DataFrame( + [ + [0.980269, 3.685731, -0.364216805298, -1.159738, "foo"], + [1.047916, -0.041232, -0.16181208307, 0.212549, "bar"], + [0.498581, 0.731168, -0.537677223318, 1.346270, "baz"], + [1.120202, 1.567621, 0.00364077397681, 0.675253, "qux"], + [-0.487094, 0.571455, -1.6116394093, 0.103469, "foo2"], + ], + columns=["A", "B", "C", "D", "E"], + index=Index( + [ + datetime(2000, 1, 3), + datetime(2000, 1, 4), + datetime(2000, 1, 5), + datetime(2000, 1, 6), + datetime(2000, 1, 7), + ] + ), + ) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_index(all_parsers): + # see gh-10184 + data = "x,y" + parser = all_parsers + result = parser.read_csv(StringIO(data), index_col=0) + + expected = DataFrame(columns=["y"], index=Index([], name="x")) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_multi_index(all_parsers): + # see gh-10467 + data = "x,y,z" + parser = all_parsers + result = parser.read_csv(StringIO(data), index_col=["x", "y"]) + + expected = DataFrame( + columns=["z"], index=MultiIndex.from_arrays([[]] * 2, names=["x", "y"]) + ) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_reversed_multi_index(all_parsers): + data = "x,y,z" + parser = all_parsers + result = parser.read_csv(StringIO(data), index_col=[1, 0]) + + expected = DataFrame( + columns=["z"], index=MultiIndex.from_arrays([[]] * 2, names=["y", "x"]) + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_inf.py b/pandas/tests/io/parser/common/test_inf.py new file mode 100644 index 0000000000000..fca4aaaba6675 --- /dev/null +++ b/pandas/tests/io/parser/common/test_inf.py @@ -0,0 +1,61 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import StringIO + +import numpy as np +import pytest + +from pandas import DataFrame, option_context +import pandas._testing as tm + + +@pytest.mark.parametrize("na_filter", [True, False]) +def test_inf_parsing(all_parsers, na_filter): + parser = all_parsers + data = """\ +,A +a,inf +b,-inf +c,+Inf +d,-Inf +e,INF +f,-INF +g,+INf +h,-INf +i,inF +j,-inF""" + expected = DataFrame( + {"A": [float("inf"), float("-inf")] * 5}, + index=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"], + ) + result = parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("na_filter", [True, False]) +def test_infinity_parsing(all_parsers, na_filter): + parser = all_parsers + data = """\ +,A +a,Infinity +b,-Infinity +c,+Infinity +""" + expected = DataFrame( + {"A": [float("infinity"), float("-infinity"), float("+infinity")]}, + index=["a", "b", "c"], + ) + result = parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter) + tm.assert_frame_equal(result, expected) + + +def test_read_csv_with_use_inf_as_na(all_parsers): + # https://github.com/pandas-dev/pandas/issues/35493 + parser = all_parsers + data = "1.0\nNaN\n3.0" + with option_context("use_inf_as_na", True): + result = parser.read_csv(StringIO(data), header=None) + expected = DataFrame([1.0, np.nan, 3.0]) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_ints.py b/pandas/tests/io/parser/common/test_ints.py new file mode 100644 index 0000000000000..a8f5c43ea15c7 --- /dev/null +++ b/pandas/tests/io/parser/common/test_ints.py @@ -0,0 +1,203 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import StringIO + +import numpy as np +import pytest + +from pandas import DataFrame, Series +import pandas._testing as tm + + +def test_int_conversion(all_parsers): + data = """A,B +1.0,1 +2.0,2 +3.0,3 +""" + parser = all_parsers + result = parser.read_csv(StringIO(data)) + + expected = DataFrame([[1.0, 1], [2.0, 2], [3.0, 3]], columns=["A", "B"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data,kwargs,expected", + [ + ( + "A,B\nTrue,1\nFalse,2\nTrue,3", + {}, + DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]), + ), + ( + "A,B\nYES,1\nno,2\nyes,3\nNo,3\nYes,3", + {"true_values": ["yes", "Yes", "YES"], "false_values": ["no", "NO", "No"]}, + DataFrame( + [[True, 1], [False, 2], [True, 3], [False, 3], [True, 3]], + columns=["A", "B"], + ), + ), + ( + "A,B\nTRUE,1\nFALSE,2\nTRUE,3", + {}, + DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]), + ), + ( + "A,B\nfoo,bar\nbar,foo", + {"true_values": ["foo"], "false_values": ["bar"]}, + DataFrame([[True, False], [False, True]], columns=["A", "B"]), + ), + ], +) +def test_parse_bool(all_parsers, data, kwargs, expected): + parser = all_parsers + result = parser.read_csv(StringIO(data), **kwargs) + tm.assert_frame_equal(result, expected) + + +def test_parse_integers_above_fp_precision(all_parsers): + data = """Numbers +17007000002000191 +17007000002000191 +17007000002000191 +17007000002000191 +17007000002000192 +17007000002000192 +17007000002000192 +17007000002000192 +17007000002000192 +17007000002000194""" + parser = all_parsers + result = parser.read_csv(StringIO(data)) + expected = DataFrame( + { + "Numbers": [ + 17007000002000191, + 17007000002000191, + 17007000002000191, + 17007000002000191, + 17007000002000192, + 17007000002000192, + 17007000002000192, + 17007000002000192, + 17007000002000192, + 17007000002000194, + ] + } + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("sep", [" ", r"\s+"]) +def test_integer_overflow_bug(all_parsers, sep): + # see gh-2601 + data = "65248E10 11\n55555E55 22\n" + parser = all_parsers + + result = parser.read_csv(StringIO(data), header=None, sep=sep) + expected = DataFrame([[6.5248e14, 11], [5.5555e59, 22]]) + tm.assert_frame_equal(result, expected) + + +def test_int64_min_issues(all_parsers): + # see gh-2599 + parser = all_parsers + data = "A,B\n0,0\n0," + result = parser.read_csv(StringIO(data)) + + expected = DataFrame({"A": [0, 0], "B": [0, np.nan]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("conv", [None, np.int64, np.uint64]) +def test_int64_overflow(all_parsers, conv): + data = """ID +00013007854817840016671868 +00013007854817840016749251 +00013007854817840016754630 +00013007854817840016781876 +00013007854817840017028824 +00013007854817840017963235 +00013007854817840018860166""" + parser = all_parsers + + if conv is None: + # 13007854817840016671868 > UINT64_MAX, so this + # will overflow and return object as the dtype. + result = parser.read_csv(StringIO(data)) + expected = DataFrame( + [ + "00013007854817840016671868", + "00013007854817840016749251", + "00013007854817840016754630", + "00013007854817840016781876", + "00013007854817840017028824", + "00013007854817840017963235", + "00013007854817840018860166", + ], + columns=["ID"], + ) + tm.assert_frame_equal(result, expected) + else: + # 13007854817840016671868 > UINT64_MAX, so attempts + # to cast to either int64 or uint64 will result in + # an OverflowError being raised. + msg = ( + "(Python int too large to convert to C long)|" + "(long too big to convert)|" + "(int too big to convert)" + ) + + with pytest.raises(OverflowError, match=msg): + parser.read_csv(StringIO(data), converters={"ID": conv}) + + +@pytest.mark.parametrize( + "val", [np.iinfo(np.uint64).max, np.iinfo(np.int64).max, np.iinfo(np.int64).min] +) +def test_int64_uint64_range(all_parsers, val): + # These numbers fall right inside the int64-uint64 + # range, so they should be parsed as string. + parser = all_parsers + result = parser.read_csv(StringIO(str(val)), header=None) + + expected = DataFrame([val]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "val", [np.iinfo(np.uint64).max + 1, np.iinfo(np.int64).min - 1] +) +def test_outside_int64_uint64_range(all_parsers, val): + # These numbers fall just outside the int64-uint64 + # range, so they should be parsed as string. + parser = all_parsers + result = parser.read_csv(StringIO(str(val)), header=None) + + expected = DataFrame([str(val)]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("exp_data", [[str(-1), str(2 ** 63)], [str(2 ** 63), str(-1)]]) +def test_numeric_range_too_wide(all_parsers, exp_data): + # No numerical dtype can hold both negative and uint64 + # values, so they should be cast as string. + parser = all_parsers + data = "\n".join(exp_data) + expected = DataFrame(exp_data) + + result = parser.read_csv(StringIO(data), header=None) + tm.assert_frame_equal(result, expected) + + +def test_integer_precision(all_parsers): + # Gh 7072 + s = """1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765 +5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389""" + parser = all_parsers + result = parser.read_csv(StringIO(s), header=None)[4] + expected = Series([4321583677327450765, 4321113141090630389], name=4) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_iterator.py b/pandas/tests/io/parser/common/test_iterator.py new file mode 100644 index 0000000000000..3cc30b0ab4029 --- /dev/null +++ b/pandas/tests/io/parser/common/test_iterator.py @@ -0,0 +1,104 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import StringIO + +import pytest + +from pandas import DataFrame, Series, concat +import pandas._testing as tm + + +def test_iterator(all_parsers): + # see gh-6607 + data = """index,A,B,C,D +foo,2,3,4,5 +bar,7,8,9,10 +baz,12,13,14,15 +qux,12,13,14,15 +foo2,12,13,14,15 +bar2,12,13,14,15 +""" + parser = all_parsers + kwargs = {"index_col": 0} + + expected = parser.read_csv(StringIO(data), **kwargs) + with parser.read_csv(StringIO(data), iterator=True, **kwargs) as reader: + + first_chunk = reader.read(3) + tm.assert_frame_equal(first_chunk, expected[:3]) + + last_chunk = reader.read(5) + tm.assert_frame_equal(last_chunk, expected[3:]) + + +def test_iterator2(all_parsers): + parser = all_parsers + data = """A,B,C +foo,1,2,3 +bar,4,5,6 +baz,7,8,9 +""" + + with parser.read_csv(StringIO(data), iterator=True) as reader: + result = list(reader) + + expected = DataFrame( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], + index=["foo", "bar", "baz"], + columns=["A", "B", "C"], + ) + tm.assert_frame_equal(result[0], expected) + + +def test_iterator_stop_on_chunksize(all_parsers): + # gh-3967: stopping iteration when chunksize is specified + parser = all_parsers + data = """A,B,C +foo,1,2,3 +bar,4,5,6 +baz,7,8,9 +""" + + with parser.read_csv(StringIO(data), chunksize=1) as reader: + result = list(reader) + + assert len(result) == 3 + expected = DataFrame( + [[1, 2, 3], [4, 5, 6], [7, 8, 9]], + index=["foo", "bar", "baz"], + columns=["A", "B", "C"], + ) + tm.assert_frame_equal(concat(result), expected) + + +@pytest.mark.parametrize( + "kwargs", [{"iterator": True, "chunksize": 1}, {"iterator": True}, {"chunksize": 1}] +) +def test_iterator_skipfooter_errors(all_parsers, kwargs): + msg = "'skipfooter' not supported for iteration" + parser = all_parsers + data = "a\n1\n2" + + with pytest.raises(ValueError, match=msg): + with parser.read_csv(StringIO(data), skipfooter=1, **kwargs) as _: + pass + + +def test_iteration_open_handle(all_parsers): + parser = all_parsers + kwargs = {"squeeze": True, "header": None} + + with tm.ensure_clean() as path: + with open(path, "w") as f: + f.write("AAA\nBBB\nCCC\nDDD\nEEE\nFFF\nGGG") + + with open(path) as f: + for line in f: + if "CCC" in line: + break + + result = parser.read_csv(f, **kwargs) + expected = Series(["DDD", "EEE", "FFF", "GGG"], name=0) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py new file mode 100644 index 0000000000000..a2787ddad3683 --- /dev/null +++ b/pandas/tests/io/parser/common/test_read_errors.py @@ -0,0 +1,210 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +import codecs +from io import StringIO +import os + +import numpy as np +import pytest + +from pandas.errors import EmptyDataError, ParserError + +from pandas import DataFrame +import pandas._testing as tm + + +def test_empty_decimal_marker(all_parsers): + data = """A|B|C +1|2,334|5 +10|13|10. +""" + # Parsers support only length-1 decimals + msg = "Only length-1 decimal markers supported" + parser = all_parsers + + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), decimal="") + + +def test_bad_stream_exception(all_parsers, csv_dir_path): + # see gh-13652 + # + # This test validates that both the Python engine and C engine will + # raise UnicodeDecodeError instead of C engine raising ParserError + # and swallowing the exception that caused read to fail. + path = os.path.join(csv_dir_path, "sauron.SHIFT_JIS.csv") + codec = codecs.lookup("utf-8") + utf8 = codecs.lookup("utf-8") + parser = all_parsers + msg = "'utf-8' codec can't decode byte" + + # Stream must be binary UTF8. + with open(path, "rb") as handle, codecs.StreamRecoder( + handle, utf8.encode, utf8.decode, codec.streamreader, codec.streamwriter + ) as stream: + + with pytest.raises(UnicodeDecodeError, match=msg): + parser.read_csv(stream) + + +def test_malformed(all_parsers): + # see gh-6607 + parser = all_parsers + data = """ignore +A,B,C +1,2,3 # comment +1,2,3,4,5 +2,3,4 +""" + msg = "Expected 3 fields in line 4, saw 5" + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data), header=1, comment="#") + + +@pytest.mark.parametrize("nrows", [5, 3, None]) +def test_malformed_chunks(all_parsers, nrows): + data = """ignore +A,B,C +skip +1,2,3 +3,5,10 # comment +1,2,3,4,5 +2,3,4 +""" + parser = all_parsers + msg = "Expected 3 fields in line 6, saw 5" + with parser.read_csv( + StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2] + ) as reader: + with pytest.raises(ParserError, match=msg): + reader.read(nrows) + + +def test_catch_too_many_names(all_parsers): + # see gh-5156 + data = """\ +1,2,3 +4,,6 +7,8,9 +10,11,12\n""" + parser = all_parsers + msg = ( + "Too many columns specified: expected 4 and found 3" + if parser.engine == "c" + else "Number of passed names did not match " + "number of header fields in the file" + ) + + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), header=0, names=["a", "b", "c", "d"]) + + +@pytest.mark.parametrize("nrows", [0, 1, 2, 3, 4, 5]) +def test_raise_on_no_columns(all_parsers, nrows): + parser = all_parsers + data = "\n" * nrows + + msg = "No columns to parse from file" + with pytest.raises(EmptyDataError, match=msg): + parser.read_csv(StringIO(data)) + + +def test_read_csv_raises_on_header_prefix(all_parsers): + # gh-27394 + parser = all_parsers + msg = "Argument prefix must be None if argument header is not None" + + s = StringIO("0,1\n2,3") + + with pytest.raises(ValueError, match=msg): + parser.read_csv(s, header=0, prefix="_X") + + +def test_unexpected_keyword_parameter_exception(all_parsers): + # GH-34976 + parser = all_parsers + + msg = "{}\\(\\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg.format("read_csv")): + parser.read_csv("foo.csv", foo=1) + with pytest.raises(TypeError, match=msg.format("read_table")): + parser.read_table("foo.tsv", foo=1) + + +def test_suppress_error_output(all_parsers, capsys): + # see gh-15925 + parser = all_parsers + data = "a\n1\n1,2,3\n4\n5,6,7" + expected = DataFrame({"a": [1, 4]}) + + result = parser.read_csv( + StringIO(data), error_bad_lines=False, warn_bad_lines=False + ) + tm.assert_frame_equal(result, expected) + + captured = capsys.readouterr() + assert captured.err == "" + + +@pytest.mark.parametrize( + "kwargs", + [{}, {"error_bad_lines": True}], # Default is True. # Explicitly pass in. +) +@pytest.mark.parametrize( + "warn_kwargs", [{}, {"warn_bad_lines": True}, {"warn_bad_lines": False}] +) +def test_error_bad_lines(all_parsers, kwargs, warn_kwargs): + # see gh-15925 + parser = all_parsers + kwargs.update(**warn_kwargs) + data = "a\n1\n1,2,3\n4\n5,6,7" + + msg = "Expected 1 fields in line 3, saw 3" + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data), **kwargs) + + +def test_warn_bad_lines(all_parsers, capsys): + # see gh-15925 + parser = all_parsers + data = "a\n1\n1,2,3\n4\n5,6,7" + expected = DataFrame({"a": [1, 4]}) + + result = parser.read_csv(StringIO(data), error_bad_lines=False, warn_bad_lines=True) + tm.assert_frame_equal(result, expected) + + captured = capsys.readouterr() + assert "Skipping line 3" in captured.err + assert "Skipping line 5" in captured.err + + +def test_read_csv_wrong_num_columns(all_parsers): + # Too few columns. + data = """A,B,C,D,E,F +1,2,3,4,5,6 +6,7,8,9,10,11,12 +11,12,13,14,15,16 +""" + parser = all_parsers + msg = "Expected 6 fields in line 3, saw 7" + + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data)) + + +def test_null_byte_char(all_parsers): + # see gh-2741 + data = "\x00,foo" + names = ["a", "b"] + parser = all_parsers + + if parser.engine == "c": + expected = DataFrame([[np.nan, "foo"]], columns=names) + out = parser.read_csv(StringIO(data), names=names) + tm.assert_frame_equal(out, expected) + else: + msg = "NULL byte detected" + with pytest.raises(ParserError, match=msg): + parser.read_csv(StringIO(data), names=names) diff --git a/pandas/tests/io/parser/common/test_verbose.py b/pandas/tests/io/parser/common/test_verbose.py new file mode 100644 index 0000000000000..fdd905b48ea1e --- /dev/null +++ b/pandas/tests/io/parser/common/test_verbose.py @@ -0,0 +1,51 @@ +""" +Tests that work on both the Python and C engines but do not have a +specific classification into the other test modules. +""" +from io import StringIO + + +def test_verbose_read(all_parsers, capsys): + parser = all_parsers + data = """a,b,c,d +one,1,2,3 +one,1,2,3 +,1,2,3 +one,1,2,3 +,1,2,3 +,1,2,3 +one,1,2,3 +two,1,2,3""" + + # Engines are verbose in different ways. + parser.read_csv(StringIO(data), verbose=True) + captured = capsys.readouterr() + + if parser.engine == "c": + assert "Tokenization took:" in captured.out + assert "Parser memory cleanup took:" in captured.out + else: # Python engine + assert captured.out == "Filled 3 NA values in column a\n" + + +def test_verbose_read2(all_parsers, capsys): + parser = all_parsers + data = """a,b,c,d +one,1,2,3 +two,1,2,3 +three,1,2,3 +four,1,2,3 +five,1,2,3 +,1,2,3 +seven,1,2,3 +eight,1,2,3""" + + parser.read_csv(StringIO(data), verbose=True, index_col=0) + captured = capsys.readouterr() + + # Engines are verbose in different ways. + if parser.engine == "c": + assert "Tokenization took:" in captured.out + assert "Parser memory cleanup took:" in captured.out + else: # Python engine + assert captured.out == "Filled 1 NA values in column a\n" diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py deleted file mode 100644 index 31f1581a6184b..0000000000000 --- a/pandas/tests/io/parser/test_common.py +++ /dev/null @@ -1,2374 +0,0 @@ -""" -Tests that work on both the Python and C engines but do not have a -specific classification into the other test modules. -""" -import codecs -import csv -from datetime import datetime -from inspect import signature -from io import BytesIO, StringIO -import os -import platform -from urllib.error import URLError - -import numpy as np -import pytest - -from pandas._libs.tslib import Timestamp -from pandas.compat import is_platform_linux -from pandas.errors import DtypeWarning, EmptyDataError, ParserError -import pandas.util._test_decorators as td - -from pandas import DataFrame, Index, MultiIndex, Series, compat, concat, option_context -import pandas._testing as tm - -from pandas.io.parsers import CParserWrapper, TextFileReader, TextParser - - -def test_override_set_noconvert_columns(): - # see gh-17351 - # - # Usecols needs to be sorted in _set_noconvert_columns based - # on the test_usecols_with_parse_dates test from test_usecols.py - class MyTextFileReader(TextFileReader): - def __init__(self): - self._currow = 0 - self.squeeze = False - - class MyCParserWrapper(CParserWrapper): - def _set_noconvert_columns(self): - if self.usecols_dtype == "integer": - # self.usecols is a set, which is documented as unordered - # but in practice, a CPython set of integers is sorted. - # In other implementations this assumption does not hold. - # The following code simulates a different order, which - # before GH 17351 would cause the wrong columns to be - # converted via the parse_dates parameter - self.usecols = list(self.usecols) - self.usecols.reverse() - return CParserWrapper._set_noconvert_columns(self) - - data = """a,b,c,d,e -0,1,20140101,0900,4 -0,1,20140102,1000,4""" - - parse_dates = [[1, 2]] - cols = { - "a": [0, 0], - "c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")], - } - expected = DataFrame(cols, columns=["c_d", "a"]) - - parser = MyTextFileReader() - parser.options = { - "usecols": [0, 2, 3], - "parse_dates": parse_dates, - "delimiter": ",", - } - parser._engine = MyCParserWrapper(StringIO(data), **parser.options) - - result = parser.read() - tm.assert_frame_equal(result, expected) - - -def test_empty_decimal_marker(all_parsers): - data = """A|B|C -1|2,334|5 -10|13|10. -""" - # Parsers support only length-1 decimals - msg = "Only length-1 decimal markers supported" - parser = all_parsers - - with pytest.raises(ValueError, match=msg): - parser.read_csv(StringIO(data), decimal="") - - -def test_bad_stream_exception(all_parsers, csv_dir_path): - # see gh-13652 - # - # This test validates that both the Python engine and C engine will - # raise UnicodeDecodeError instead of C engine raising ParserError - # and swallowing the exception that caused read to fail. - path = os.path.join(csv_dir_path, "sauron.SHIFT_JIS.csv") - codec = codecs.lookup("utf-8") - utf8 = codecs.lookup("utf-8") - parser = all_parsers - msg = "'utf-8' codec can't decode byte" - - # Stream must be binary UTF8. - with open(path, "rb") as handle, codecs.StreamRecoder( - handle, utf8.encode, utf8.decode, codec.streamreader, codec.streamwriter - ) as stream: - - with pytest.raises(UnicodeDecodeError, match=msg): - parser.read_csv(stream) - - -def test_read_csv_local(all_parsers, csv1): - prefix = "file:///" if compat.is_platform_windows() else "file://" - parser = all_parsers - - fname = prefix + str(os.path.abspath(csv1)) - result = parser.read_csv(fname, index_col=0, parse_dates=True) - - expected = DataFrame( - [ - [0.980269, 3.685731, -0.364216805298, -1.159738], - [1.047916, -0.041232, -0.16181208307, 0.212549], - [0.498581, 0.731168, -0.537677223318, 1.346270], - [1.120202, 1.567621, 0.00364077397681, 0.675253], - [-0.487094, 0.571455, -1.6116394093, 0.103469], - [0.836649, 0.246462, 0.588542635376, 1.062782], - [-0.157161, 1.340307, 1.1957779562, -1.097007], - ], - columns=["A", "B", "C", "D"], - index=Index( - [ - datetime(2000, 1, 3), - datetime(2000, 1, 4), - datetime(2000, 1, 5), - datetime(2000, 1, 6), - datetime(2000, 1, 7), - datetime(2000, 1, 10), - datetime(2000, 1, 11), - ], - name="index", - ), - ) - tm.assert_frame_equal(result, expected) - - -def test_1000_sep(all_parsers): - parser = all_parsers - data = """A|B|C -1|2,334|5 -10|13|10. -""" - expected = DataFrame({"A": [1, 10], "B": [2334, 13], "C": [5, 10.0]}) - - result = parser.read_csv(StringIO(data), sep="|", thousands=",") - tm.assert_frame_equal(result, expected) - - -def test_squeeze(all_parsers): - data = """\ -a,1 -b,2 -c,3 -""" - parser = all_parsers - index = Index(["a", "b", "c"], name=0) - expected = Series([1, 2, 3], name=1, index=index) - - result = parser.read_csv(StringIO(data), index_col=0, header=None, squeeze=True) - tm.assert_series_equal(result, expected) - - # see gh-8217 - # - # Series should not be a view. - assert not result._is_view - - -def test_malformed(all_parsers): - # see gh-6607 - parser = all_parsers - data = """ignore -A,B,C -1,2,3 # comment -1,2,3,4,5 -2,3,4 -""" - msg = "Expected 3 fields in line 4, saw 5" - with pytest.raises(ParserError, match=msg): - parser.read_csv(StringIO(data), header=1, comment="#") - - -@pytest.mark.parametrize("nrows", [5, 3, None]) -def test_malformed_chunks(all_parsers, nrows): - data = """ignore -A,B,C -skip -1,2,3 -3,5,10 # comment -1,2,3,4,5 -2,3,4 -""" - parser = all_parsers - msg = "Expected 3 fields in line 6, saw 5" - with parser.read_csv( - StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2] - ) as reader: - with pytest.raises(ParserError, match=msg): - reader.read(nrows) - - -def test_unnamed_columns(all_parsers): - data = """A,B,C,, -1,2,3,4,5 -6,7,8,9,10 -11,12,13,14,15 -""" - parser = all_parsers - expected = DataFrame( - [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], - dtype=np.int64, - columns=["A", "B", "C", "Unnamed: 3", "Unnamed: 4"], - ) - result = parser.read_csv(StringIO(data)) - tm.assert_frame_equal(result, expected) - - -def test_csv_mixed_type(all_parsers): - data = """A,B,C -a,1,2 -b,3,4 -c,4,5 -""" - parser = all_parsers - expected = DataFrame({"A": ["a", "b", "c"], "B": [1, 3, 4], "C": [2, 4, 5]}) - result = parser.read_csv(StringIO(data)) - tm.assert_frame_equal(result, expected) - - -def test_read_csv_low_memory_no_rows_with_index(all_parsers): - # see gh-21141 - parser = all_parsers - - if not parser.low_memory: - pytest.skip("This is a low-memory specific test") - - data = """A,B,C -1,1,1,2 -2,2,3,4 -3,3,4,5 -""" - result = parser.read_csv(StringIO(data), low_memory=True, index_col=0, nrows=0) - expected = DataFrame(columns=["A", "B", "C"]) - tm.assert_frame_equal(result, expected) - - -def test_read_csv_dataframe(all_parsers, csv1): - parser = all_parsers - result = parser.read_csv(csv1, index_col=0, parse_dates=True) - - expected = DataFrame( - [ - [0.980269, 3.685731, -0.364216805298, -1.159738], - [1.047916, -0.041232, -0.16181208307, 0.212549], - [0.498581, 0.731168, -0.537677223318, 1.346270], - [1.120202, 1.567621, 0.00364077397681, 0.675253], - [-0.487094, 0.571455, -1.6116394093, 0.103469], - [0.836649, 0.246462, 0.588542635376, 1.062782], - [-0.157161, 1.340307, 1.1957779562, -1.097007], - ], - columns=["A", "B", "C", "D"], - index=Index( - [ - datetime(2000, 1, 3), - datetime(2000, 1, 4), - datetime(2000, 1, 5), - datetime(2000, 1, 6), - datetime(2000, 1, 7), - datetime(2000, 1, 10), - datetime(2000, 1, 11), - ], - name="index", - ), - ) - tm.assert_frame_equal(result, expected) - - -def test_read_csv_no_index_name(all_parsers, csv_dir_path): - parser = all_parsers - csv2 = os.path.join(csv_dir_path, "test2.csv") - result = parser.read_csv(csv2, index_col=0, parse_dates=True) - - expected = DataFrame( - [ - [0.980269, 3.685731, -0.364216805298, -1.159738, "foo"], - [1.047916, -0.041232, -0.16181208307, 0.212549, "bar"], - [0.498581, 0.731168, -0.537677223318, 1.346270, "baz"], - [1.120202, 1.567621, 0.00364077397681, 0.675253, "qux"], - [-0.487094, 0.571455, -1.6116394093, 0.103469, "foo2"], - ], - columns=["A", "B", "C", "D", "E"], - index=Index( - [ - datetime(2000, 1, 3), - datetime(2000, 1, 4), - datetime(2000, 1, 5), - datetime(2000, 1, 6), - datetime(2000, 1, 7), - ] - ), - ) - tm.assert_frame_equal(result, expected) - - -def test_read_csv_wrong_num_columns(all_parsers): - # Too few columns. - data = """A,B,C,D,E,F -1,2,3,4,5,6 -6,7,8,9,10,11,12 -11,12,13,14,15,16 -""" - parser = all_parsers - msg = "Expected 6 fields in line 3, saw 7" - - with pytest.raises(ParserError, match=msg): - parser.read_csv(StringIO(data)) - - -def test_read_duplicate_index_explicit(all_parsers): - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo,12,13,14,15 -bar,12,13,14,15 -""" - parser = all_parsers - result = parser.read_csv(StringIO(data), index_col=0) - - expected = DataFrame( - [ - [2, 3, 4, 5], - [7, 8, 9, 10], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - ], - columns=["A", "B", "C", "D"], - index=Index(["foo", "bar", "baz", "qux", "foo", "bar"], name="index"), - ) - tm.assert_frame_equal(result, expected) - - -def test_read_duplicate_index_implicit(all_parsers): - data = """A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo,12,13,14,15 -bar,12,13,14,15 -""" - parser = all_parsers - result = parser.read_csv(StringIO(data)) - - expected = DataFrame( - [ - [2, 3, 4, 5], - [7, 8, 9, 10], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - ], - columns=["A", "B", "C", "D"], - index=Index(["foo", "bar", "baz", "qux", "foo", "bar"]), - ) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "data,kwargs,expected", - [ - ( - "A,B\nTrue,1\nFalse,2\nTrue,3", - {}, - DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]), - ), - ( - "A,B\nYES,1\nno,2\nyes,3\nNo,3\nYes,3", - {"true_values": ["yes", "Yes", "YES"], "false_values": ["no", "NO", "No"]}, - DataFrame( - [[True, 1], [False, 2], [True, 3], [False, 3], [True, 3]], - columns=["A", "B"], - ), - ), - ( - "A,B\nTRUE,1\nFALSE,2\nTRUE,3", - {}, - DataFrame([[True, 1], [False, 2], [True, 3]], columns=["A", "B"]), - ), - ( - "A,B\nfoo,bar\nbar,foo", - {"true_values": ["foo"], "false_values": ["bar"]}, - DataFrame([[True, False], [False, True]], columns=["A", "B"]), - ), - ], -) -def test_parse_bool(all_parsers, data, kwargs, expected): - parser = all_parsers - result = parser.read_csv(StringIO(data), **kwargs) - tm.assert_frame_equal(result, expected) - - -def test_int_conversion(all_parsers): - data = """A,B -1.0,1 -2.0,2 -3.0,3 -""" - parser = all_parsers - result = parser.read_csv(StringIO(data)) - - expected = DataFrame([[1.0, 1], [2.0, 2], [3.0, 3]], columns=["A", "B"]) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("nrows", [3, 3.0]) -def test_read_nrows(all_parsers, nrows): - # see gh-10476 - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - expected = DataFrame( - [["foo", 2, 3, 4, 5], ["bar", 7, 8, 9, 10], ["baz", 12, 13, 14, 15]], - columns=["index", "A", "B", "C", "D"], - ) - parser = all_parsers - - result = parser.read_csv(StringIO(data), nrows=nrows) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("nrows", [1.2, "foo", -1]) -def test_read_nrows_bad(all_parsers, nrows): - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - msg = r"'nrows' must be an integer >=0" - parser = all_parsers - - with pytest.raises(ValueError, match=msg): - parser.read_csv(StringIO(data), nrows=nrows) - - -@pytest.mark.parametrize("index_col", [0, "index"]) -def test_read_chunksize_with_index(all_parsers, index_col): - parser = all_parsers - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - - expected = DataFrame( - [ - ["foo", 2, 3, 4, 5], - ["bar", 7, 8, 9, 10], - ["baz", 12, 13, 14, 15], - ["qux", 12, 13, 14, 15], - ["foo2", 12, 13, 14, 15], - ["bar2", 12, 13, 14, 15], - ], - columns=["index", "A", "B", "C", "D"], - ) - expected = expected.set_index("index") - - with parser.read_csv(StringIO(data), index_col=0, chunksize=2) as reader: - chunks = list(reader) - tm.assert_frame_equal(chunks[0], expected[:2]) - tm.assert_frame_equal(chunks[1], expected[2:4]) - tm.assert_frame_equal(chunks[2], expected[4:]) - - -@pytest.mark.parametrize("chunksize", [1.3, "foo", 0]) -def test_read_chunksize_bad(all_parsers, chunksize): - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - parser = all_parsers - msg = r"'chunksize' must be an integer >=1" - - with pytest.raises(ValueError, match=msg): - with parser.read_csv(StringIO(data), chunksize=chunksize) as _: - pass - - -@pytest.mark.parametrize("chunksize", [2, 8]) -def test_read_chunksize_and_nrows(all_parsers, chunksize): - # see gh-15755 - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - parser = all_parsers - kwargs = {"index_col": 0, "nrows": 5} - - expected = parser.read_csv(StringIO(data), **kwargs) - with parser.read_csv(StringIO(data), chunksize=chunksize, **kwargs) as reader: - tm.assert_frame_equal(concat(reader), expected) - - -def test_read_chunksize_and_nrows_changing_size(all_parsers): - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - parser = all_parsers - kwargs = {"index_col": 0, "nrows": 5} - - expected = parser.read_csv(StringIO(data), **kwargs) - with parser.read_csv(StringIO(data), chunksize=8, **kwargs) as reader: - tm.assert_frame_equal(reader.get_chunk(size=2), expected.iloc[:2]) - tm.assert_frame_equal(reader.get_chunk(size=4), expected.iloc[2:5]) - - with pytest.raises(StopIteration, match=""): - reader.get_chunk(size=3) - - -def test_get_chunk_passed_chunksize(all_parsers): - parser = all_parsers - data = """A,B,C -1,2,3 -4,5,6 -7,8,9 -1,2,3""" - - with parser.read_csv(StringIO(data), chunksize=2) as reader: - result = reader.get_chunk() - - expected = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"]) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("kwargs", [{}, {"index_col": 0}]) -def test_read_chunksize_compat(all_parsers, kwargs): - # see gh-12185 - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - parser = all_parsers - result = parser.read_csv(StringIO(data), **kwargs) - with parser.read_csv(StringIO(data), chunksize=2, **kwargs) as reader: - tm.assert_frame_equal(concat(reader), result) - - -def test_read_chunksize_jagged_names(all_parsers): - # see gh-23509 - parser = all_parsers - data = "\n".join(["0"] * 7 + [",".join(["0"] * 10)]) - - expected = DataFrame([[0] + [np.nan] * 9] * 7 + [[0] * 10]) - with parser.read_csv(StringIO(data), names=range(10), chunksize=4) as reader: - result = concat(reader) - tm.assert_frame_equal(result, expected) - - -def test_read_data_list(all_parsers): - parser = all_parsers - kwargs = {"index_col": 0} - data = "A,B,C\nfoo,1,2,3\nbar,4,5,6" - - data_list = [["A", "B", "C"], ["foo", "1", "2", "3"], ["bar", "4", "5", "6"]] - expected = parser.read_csv(StringIO(data), **kwargs) - - with TextParser(data_list, chunksize=2, **kwargs) as parser: - result = parser.read() - - tm.assert_frame_equal(result, expected) - - -def test_iterator(all_parsers): - # see gh-6607 - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - parser = all_parsers - kwargs = {"index_col": 0} - - expected = parser.read_csv(StringIO(data), **kwargs) - with parser.read_csv(StringIO(data), iterator=True, **kwargs) as reader: - - first_chunk = reader.read(3) - tm.assert_frame_equal(first_chunk, expected[:3]) - - last_chunk = reader.read(5) - tm.assert_frame_equal(last_chunk, expected[3:]) - - -def test_iterator2(all_parsers): - parser = all_parsers - data = """A,B,C -foo,1,2,3 -bar,4,5,6 -baz,7,8,9 -""" - - with parser.read_csv(StringIO(data), iterator=True) as reader: - result = list(reader) - - expected = DataFrame( - [[1, 2, 3], [4, 5, 6], [7, 8, 9]], - index=["foo", "bar", "baz"], - columns=["A", "B", "C"], - ) - tm.assert_frame_equal(result[0], expected) - - -def test_reader_list(all_parsers): - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - parser = all_parsers - kwargs = {"index_col": 0} - - lines = list(csv.reader(StringIO(data))) - with TextParser(lines, chunksize=2, **kwargs) as reader: - chunks = list(reader) - - expected = parser.read_csv(StringIO(data), **kwargs) - - tm.assert_frame_equal(chunks[0], expected[:2]) - tm.assert_frame_equal(chunks[1], expected[2:4]) - tm.assert_frame_equal(chunks[2], expected[4:]) - - -def test_reader_list_skiprows(all_parsers): - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - parser = all_parsers - kwargs = {"index_col": 0} - - lines = list(csv.reader(StringIO(data))) - with TextParser(lines, chunksize=2, skiprows=[1], **kwargs) as reader: - chunks = list(reader) - - expected = parser.read_csv(StringIO(data), **kwargs) - - tm.assert_frame_equal(chunks[0], expected[1:3]) - - -def test_iterator_stop_on_chunksize(all_parsers): - # gh-3967: stopping iteration when chunksize is specified - parser = all_parsers - data = """A,B,C -foo,1,2,3 -bar,4,5,6 -baz,7,8,9 -""" - - with parser.read_csv(StringIO(data), chunksize=1) as reader: - result = list(reader) - - assert len(result) == 3 - expected = DataFrame( - [[1, 2, 3], [4, 5, 6], [7, 8, 9]], - index=["foo", "bar", "baz"], - columns=["A", "B", "C"], - ) - tm.assert_frame_equal(concat(result), expected) - - -@pytest.mark.parametrize( - "kwargs", [{"iterator": True, "chunksize": 1}, {"iterator": True}, {"chunksize": 1}] -) -def test_iterator_skipfooter_errors(all_parsers, kwargs): - msg = "'skipfooter' not supported for iteration" - parser = all_parsers - data = "a\n1\n2" - - with pytest.raises(ValueError, match=msg): - with parser.read_csv(StringIO(data), skipfooter=1, **kwargs) as _: - pass - - -def test_nrows_skipfooter_errors(all_parsers): - msg = "'skipfooter' not supported with 'nrows'" - data = "a\n1\n2\n3\n4\n5\n6" - parser = all_parsers - - with pytest.raises(ValueError, match=msg): - parser.read_csv(StringIO(data), skipfooter=1, nrows=5) - - -@pytest.mark.parametrize( - "data,kwargs,expected", - [ - ( - """foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""", - {"index_col": 0, "names": ["index", "A", "B", "C", "D"]}, - DataFrame( - [ - [2, 3, 4, 5], - [7, 8, 9, 10], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - ], - index=Index(["foo", "bar", "baz", "qux", "foo2", "bar2"], name="index"), - columns=["A", "B", "C", "D"], - ), - ), - ( - """foo,one,2,3,4,5 -foo,two,7,8,9,10 -foo,three,12,13,14,15 -bar,one,12,13,14,15 -bar,two,12,13,14,15 -""", - {"index_col": [0, 1], "names": ["index1", "index2", "A", "B", "C", "D"]}, - DataFrame( - [ - [2, 3, 4, 5], - [7, 8, 9, 10], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - ], - index=MultiIndex.from_tuples( - [ - ("foo", "one"), - ("foo", "two"), - ("foo", "three"), - ("bar", "one"), - ("bar", "two"), - ], - names=["index1", "index2"], - ), - columns=["A", "B", "C", "D"], - ), - ), - ], -) -def test_pass_names_with_index(all_parsers, data, kwargs, expected): - parser = all_parsers - result = parser.read_csv(StringIO(data), **kwargs) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("index_col", [[0, 1], [1, 0]]) -def test_multi_index_no_level_names(all_parsers, index_col): - data = """index1,index2,A,B,C,D -foo,one,2,3,4,5 -foo,two,7,8,9,10 -foo,three,12,13,14,15 -bar,one,12,13,14,15 -bar,two,12,13,14,15 -""" - headless_data = "\n".join(data.split("\n")[1:]) - - names = ["A", "B", "C", "D"] - parser = all_parsers - - result = parser.read_csv( - StringIO(headless_data), index_col=index_col, header=None, names=names - ) - expected = parser.read_csv(StringIO(data), index_col=index_col) - - # No index names in headless data. - expected.index.names = [None] * 2 - tm.assert_frame_equal(result, expected) - - -def test_multi_index_no_level_names_implicit(all_parsers): - parser = all_parsers - data = """A,B,C,D -foo,one,2,3,4,5 -foo,two,7,8,9,10 -foo,three,12,13,14,15 -bar,one,12,13,14,15 -bar,two,12,13,14,15 -""" - - result = parser.read_csv(StringIO(data)) - expected = DataFrame( - [ - [2, 3, 4, 5], - [7, 8, 9, 10], - [12, 13, 14, 15], - [12, 13, 14, 15], - [12, 13, 14, 15], - ], - columns=["A", "B", "C", "D"], - index=MultiIndex.from_tuples( - [ - ("foo", "one"), - ("foo", "two"), - ("foo", "three"), - ("bar", "one"), - ("bar", "two"), - ] - ), - ) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "data,expected,header", - [ - ("a,b", DataFrame(columns=["a", "b"]), [0]), - ( - "a,b\nc,d", - DataFrame(columns=MultiIndex.from_tuples([("a", "c"), ("b", "d")])), - [0, 1], - ), - ], -) -@pytest.mark.parametrize("round_trip", [True, False]) -def test_multi_index_blank_df(all_parsers, data, expected, header, round_trip): - # see gh-14545 - parser = all_parsers - data = expected.to_csv(index=False) if round_trip else data - - result = parser.read_csv(StringIO(data), header=header) - tm.assert_frame_equal(result, expected) - - -def test_no_unnamed_index(all_parsers): - parser = all_parsers - data = """ id c0 c1 c2 -0 1 0 a b -1 2 0 c d -2 2 2 e f -""" - result = parser.read_csv(StringIO(data), sep=" ") - expected = DataFrame( - [[0, 1, 0, "a", "b"], [1, 2, 0, "c", "d"], [2, 2, 2, "e", "f"]], - columns=["Unnamed: 0", "id", "c0", "c1", "c2"], - ) - tm.assert_frame_equal(result, expected) - - -def test_read_csv_parse_simple_list(all_parsers): - parser = all_parsers - data = """foo -bar baz -qux foo -foo -bar""" - - result = parser.read_csv(StringIO(data), header=None) - expected = DataFrame(["foo", "bar baz", "qux foo", "foo", "bar"]) - tm.assert_frame_equal(result, expected) - - -@tm.network -def test_url(all_parsers, csv_dir_path): - # TODO: FTP testing - parser = all_parsers - kwargs = {"sep": "\t"} - - url = ( - "https://raw.github.com/pandas-dev/pandas/master/" - "pandas/tests/io/parser/data/salaries.csv" - ) - url_result = parser.read_csv(url, **kwargs) - - local_path = os.path.join(csv_dir_path, "salaries.csv") - local_result = parser.read_csv(local_path, **kwargs) - tm.assert_frame_equal(url_result, local_result) - - -@pytest.mark.slow -def test_local_file(all_parsers, csv_dir_path): - parser = all_parsers - kwargs = {"sep": "\t"} - - local_path = os.path.join(csv_dir_path, "salaries.csv") - local_result = parser.read_csv(local_path, **kwargs) - url = "file://localhost/" + local_path - - try: - url_result = parser.read_csv(url, **kwargs) - tm.assert_frame_equal(url_result, local_result) - except URLError: - # Fails on some systems. - pytest.skip("Failing on: " + " ".join(platform.uname())) - - -def test_path_path_lib(all_parsers): - parser = all_parsers - df = tm.makeDataFrame() - result = tm.round_trip_pathlib(df.to_csv, lambda p: parser.read_csv(p, index_col=0)) - tm.assert_frame_equal(df, result) - - -def test_path_local_path(all_parsers): - parser = all_parsers - df = tm.makeDataFrame() - result = tm.round_trip_localpath( - df.to_csv, lambda p: parser.read_csv(p, index_col=0) - ) - tm.assert_frame_equal(df, result) - - -def test_nonexistent_path(all_parsers): - # gh-2428: pls no segfault - # gh-14086: raise more helpful FileNotFoundError - # GH#29233 "File foo" instead of "File b'foo'" - parser = all_parsers - path = f"{tm.rands(10)}.csv" - - msg = r"\[Errno 2\]" - with pytest.raises(FileNotFoundError, match=msg) as e: - parser.read_csv(path) - assert path == e.value.filename - - -@td.skip_if_windows # os.chmod does not work in windows -def test_no_permission(all_parsers): - # GH 23784 - parser = all_parsers - - msg = r"\[Errno 13\]" - with tm.ensure_clean() as path: - os.chmod(path, 0) # make file unreadable - - # verify that this process cannot open the file (not running as sudo) - try: - with open(path): - pass - pytest.skip("Running as sudo.") - except PermissionError: - pass - - with pytest.raises(PermissionError, match=msg) as e: - parser.read_csv(path) - assert path == e.value.filename - - -def test_missing_trailing_delimiters(all_parsers): - parser = all_parsers - data = """A,B,C,D -1,2,3,4 -1,3,3, -1,4,5""" - - result = parser.read_csv(StringIO(data)) - expected = DataFrame( - [[1, 2, 3, 4], [1, 3, 3, np.nan], [1, 4, 5, np.nan]], - columns=["A", "B", "C", "D"], - ) - tm.assert_frame_equal(result, expected) - - -def test_skip_initial_space(all_parsers): - data = ( - '"09-Apr-2012", "01:10:18.300", 2456026.548822908, 12849, ' - "1.00361, 1.12551, 330.65659, 0355626618.16711, 73.48821, " - "314.11625, 1917.09447, 179.71425, 80.000, 240.000, -350, " - "70.06056, 344.98370, 1, 1, -0.689265, -0.692787, " - "0.212036, 14.7674, 41.605, -9999.0, -9999.0, " - "-9999.0, -9999.0, -9999.0, -9999.0, 000, 012, 128" - ) - parser = all_parsers - - result = parser.read_csv( - StringIO(data), - names=list(range(33)), - header=None, - na_values=["-9999.0"], - skipinitialspace=True, - ) - expected = DataFrame( - [ - [ - "09-Apr-2012", - "01:10:18.300", - 2456026.548822908, - 12849, - 1.00361, - 1.12551, - 330.65659, - 355626618.16711, - 73.48821, - 314.11625, - 1917.09447, - 179.71425, - 80.0, - 240.0, - -350, - 70.06056, - 344.9837, - 1, - 1, - -0.689265, - -0.692787, - 0.212036, - 14.7674, - 41.605, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - 0, - 12, - 128, - ] - ] - ) - tm.assert_frame_equal(result, expected) - - -def test_trailing_delimiters(all_parsers): - # see gh-2442 - data = """A,B,C -1,2,3, -4,5,6, -7,8,9,""" - parser = all_parsers - result = parser.read_csv(StringIO(data), index_col=False) - - expected = DataFrame({"A": [1, 4, 7], "B": [2, 5, 8], "C": [3, 6, 9]}) - tm.assert_frame_equal(result, expected) - - -def test_escapechar(all_parsers): - # https://stackoverflow.com/questions/13824840/feature-request-for- - # pandas-read-csv - data = '''SEARCH_TERM,ACTUAL_URL -"bra tv bord","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord" -"tv p\xc3\xa5 hjul","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord" -"SLAGBORD, \\"Bergslagen\\", IKEA:s 1700-tals series","http://www.ikea.com/se/sv/catalog/categories/departments/living_room/10475/?se%7cps%7cnonbranded%7cvardagsrum%7cgoogle%7ctv_bord"''' # noqa - - parser = all_parsers - result = parser.read_csv( - StringIO(data), escapechar="\\", quotechar='"', encoding="utf-8" - ) - - assert result["SEARCH_TERM"][2] == 'SLAGBORD, "Bergslagen", IKEA:s 1700-tals series' - - tm.assert_index_equal(result.columns, Index(["SEARCH_TERM", "ACTUAL_URL"])) - - -def test_int64_min_issues(all_parsers): - # see gh-2599 - parser = all_parsers - data = "A,B\n0,0\n0," - result = parser.read_csv(StringIO(data)) - - expected = DataFrame({"A": [0, 0], "B": [0, np.nan]}) - tm.assert_frame_equal(result, expected) - - -def test_parse_integers_above_fp_precision(all_parsers): - data = """Numbers -17007000002000191 -17007000002000191 -17007000002000191 -17007000002000191 -17007000002000192 -17007000002000192 -17007000002000192 -17007000002000192 -17007000002000192 -17007000002000194""" - parser = all_parsers - result = parser.read_csv(StringIO(data)) - expected = DataFrame( - { - "Numbers": [ - 17007000002000191, - 17007000002000191, - 17007000002000191, - 17007000002000191, - 17007000002000192, - 17007000002000192, - 17007000002000192, - 17007000002000192, - 17007000002000192, - 17007000002000194, - ] - } - ) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.xfail(reason="GH38630, sometimes gives ResourceWarning", strict=False) -def test_chunks_have_consistent_numerical_type(all_parsers): - parser = all_parsers - integers = [str(i) for i in range(499999)] - data = "a\n" + "\n".join(integers + ["1.0", "2.0"] + integers) - - # Coercions should work without warnings. - with tm.assert_produces_warning(None): - result = parser.read_csv(StringIO(data)) - - assert type(result.a[0]) is np.float64 - assert result.a.dtype == float - - -def test_warn_if_chunks_have_mismatched_type(all_parsers): - warning_type = None - parser = all_parsers - integers = [str(i) for i in range(499999)] - data = "a\n" + "\n".join(integers + ["a", "b"] + integers) - - # see gh-3866: if chunks are different types and can't - # be coerced using numerical types, then issue warning. - if parser.engine == "c" and parser.low_memory: - warning_type = DtypeWarning - - with tm.assert_produces_warning(warning_type): - df = parser.read_csv(StringIO(data)) - assert df.a.dtype == object - - -@pytest.mark.parametrize("sep", [" ", r"\s+"]) -def test_integer_overflow_bug(all_parsers, sep): - # see gh-2601 - data = "65248E10 11\n55555E55 22\n" - parser = all_parsers - - result = parser.read_csv(StringIO(data), header=None, sep=sep) - expected = DataFrame([[6.5248e14, 11], [5.5555e59, 22]]) - tm.assert_frame_equal(result, expected) - - -def test_catch_too_many_names(all_parsers): - # see gh-5156 - data = """\ -1,2,3 -4,,6 -7,8,9 -10,11,12\n""" - parser = all_parsers - msg = ( - "Too many columns specified: expected 4 and found 3" - if parser.engine == "c" - else "Number of passed names did not match " - "number of header fields in the file" - ) - - with pytest.raises(ValueError, match=msg): - parser.read_csv(StringIO(data), header=0, names=["a", "b", "c", "d"]) - - -def test_ignore_leading_whitespace(all_parsers): - # see gh-3374, gh-6607 - parser = all_parsers - data = " a b c\n 1 2 3\n 4 5 6\n 7 8 9" - result = parser.read_csv(StringIO(data), sep=r"\s+") - - expected = DataFrame({"a": [1, 4, 7], "b": [2, 5, 8], "c": [3, 6, 9]}) - tm.assert_frame_equal(result, expected) - - -def test_chunk_begins_with_newline_whitespace(all_parsers): - # see gh-10022 - parser = all_parsers - data = "\n hello\nworld\n" - - result = parser.read_csv(StringIO(data), header=None) - expected = DataFrame([" hello", "world"]) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_index(all_parsers): - # see gh-10184 - data = "x,y" - parser = all_parsers - result = parser.read_csv(StringIO(data), index_col=0) - - expected = DataFrame(columns=["y"], index=Index([], name="x")) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_multi_index(all_parsers): - # see gh-10467 - data = "x,y,z" - parser = all_parsers - result = parser.read_csv(StringIO(data), index_col=["x", "y"]) - - expected = DataFrame( - columns=["z"], index=MultiIndex.from_arrays([[]] * 2, names=["x", "y"]) - ) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_reversed_multi_index(all_parsers): - data = "x,y,z" - parser = all_parsers - result = parser.read_csv(StringIO(data), index_col=[1, 0]) - - expected = DataFrame( - columns=["z"], index=MultiIndex.from_arrays([[]] * 2, names=["y", "x"]) - ) - tm.assert_frame_equal(result, expected) - - -def test_float_parser(all_parsers): - # see gh-9565 - parser = all_parsers - data = "45e-1,4.5,45.,inf,-inf" - result = parser.read_csv(StringIO(data), header=None) - - expected = DataFrame([[float(s) for s in data.split(",")]]) - tm.assert_frame_equal(result, expected) - - -def test_scientific_no_exponent(all_parsers_all_precisions): - # see gh-12215 - df = DataFrame.from_dict({"w": ["2e"], "x": ["3E"], "y": ["42e"], "z": ["632E"]}) - data = df.to_csv(index=False) - parser, precision = all_parsers_all_precisions - - df_roundtrip = parser.read_csv(StringIO(data), float_precision=precision) - tm.assert_frame_equal(df_roundtrip, df) - - -@pytest.mark.parametrize("conv", [None, np.int64, np.uint64]) -def test_int64_overflow(all_parsers, conv): - data = """ID -00013007854817840016671868 -00013007854817840016749251 -00013007854817840016754630 -00013007854817840016781876 -00013007854817840017028824 -00013007854817840017963235 -00013007854817840018860166""" - parser = all_parsers - - if conv is None: - # 13007854817840016671868 > UINT64_MAX, so this - # will overflow and return object as the dtype. - result = parser.read_csv(StringIO(data)) - expected = DataFrame( - [ - "00013007854817840016671868", - "00013007854817840016749251", - "00013007854817840016754630", - "00013007854817840016781876", - "00013007854817840017028824", - "00013007854817840017963235", - "00013007854817840018860166", - ], - columns=["ID"], - ) - tm.assert_frame_equal(result, expected) - else: - # 13007854817840016671868 > UINT64_MAX, so attempts - # to cast to either int64 or uint64 will result in - # an OverflowError being raised. - msg = ( - "(Python int too large to convert to C long)|" - "(long too big to convert)|" - "(int too big to convert)" - ) - - with pytest.raises(OverflowError, match=msg): - parser.read_csv(StringIO(data), converters={"ID": conv}) - - -@pytest.mark.parametrize( - "val", [np.iinfo(np.uint64).max, np.iinfo(np.int64).max, np.iinfo(np.int64).min] -) -def test_int64_uint64_range(all_parsers, val): - # These numbers fall right inside the int64-uint64 - # range, so they should be parsed as string. - parser = all_parsers - result = parser.read_csv(StringIO(str(val)), header=None) - - expected = DataFrame([val]) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "val", [np.iinfo(np.uint64).max + 1, np.iinfo(np.int64).min - 1] -) -def test_outside_int64_uint64_range(all_parsers, val): - # These numbers fall just outside the int64-uint64 - # range, so they should be parsed as string. - parser = all_parsers - result = parser.read_csv(StringIO(str(val)), header=None) - - expected = DataFrame([str(val)]) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("exp_data", [[str(-1), str(2 ** 63)], [str(2 ** 63), str(-1)]]) -def test_numeric_range_too_wide(all_parsers, exp_data): - # No numerical dtype can hold both negative and uint64 - # values, so they should be cast as string. - parser = all_parsers - data = "\n".join(exp_data) - expected = DataFrame(exp_data) - - result = parser.read_csv(StringIO(data), header=None) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("neg_exp", [-617, -100000, -99999999999999999]) -def test_very_negative_exponent(all_parsers_all_precisions, neg_exp): - # GH#38753 - parser, precision = all_parsers_all_precisions - data = f"data\n10E{neg_exp}" - result = parser.read_csv(StringIO(data), float_precision=precision) - expected = DataFrame({"data": [0.0]}) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("exp", [999999999999999999, -999999999999999999]) -def test_too_many_exponent_digits(all_parsers_all_precisions, exp, request): - # GH#38753 - parser, precision = all_parsers_all_precisions - data = f"data\n10E{exp}" - result = parser.read_csv(StringIO(data), float_precision=precision) - if precision == "round_trip": - if exp == 999999999999999999 and is_platform_linux(): - mark = pytest.mark.xfail(reason="GH38794, on Linux gives object result") - request.node.add_marker(mark) - - value = np.inf if exp > 0 else 0.0 - expected = DataFrame({"data": [value]}) - else: - expected = DataFrame({"data": [f"10E{exp}"]}) - - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("iterator", [True, False]) -def test_empty_with_nrows_chunksize(all_parsers, iterator): - # see gh-9535 - parser = all_parsers - expected = DataFrame(columns=["foo", "bar"]) - - nrows = 10 - data = StringIO("foo,bar\n") - - if iterator: - with parser.read_csv(data, chunksize=nrows) as reader: - result = next(iter(reader)) - else: - result = parser.read_csv(data, nrows=nrows) - - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "data,kwargs,expected,msg", - [ - # gh-10728: WHITESPACE_LINE - ( - "a,b,c\n4,5,6\n ", - {}, - DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), - None, - ), - # gh-10548: EAT_LINE_COMMENT - ( - "a,b,c\n4,5,6\n#comment", - {"comment": "#"}, - DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), - None, - ), - # EAT_CRNL_NOP - ( - "a,b,c\n4,5,6\n\r", - {}, - DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), - None, - ), - # EAT_COMMENT - ( - "a,b,c\n4,5,6#comment", - {"comment": "#"}, - DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), - None, - ), - # SKIP_LINE - ( - "a,b,c\n4,5,6\nskipme", - {"skiprows": [2]}, - DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), - None, - ), - # EAT_LINE_COMMENT - ( - "a,b,c\n4,5,6\n#comment", - {"comment": "#", "skip_blank_lines": False}, - DataFrame([[4, 5, 6]], columns=["a", "b", "c"]), - None, - ), - # IN_FIELD - ( - "a,b,c\n4,5,6\n ", - {"skip_blank_lines": False}, - DataFrame([["4", 5, 6], [" ", None, None]], columns=["a", "b", "c"]), - None, - ), - # EAT_CRNL - ( - "a,b,c\n4,5,6\n\r", - {"skip_blank_lines": False}, - DataFrame([[4, 5, 6], [None, None, None]], columns=["a", "b", "c"]), - None, - ), - # ESCAPED_CHAR - ( - "a,b,c\n4,5,6\n\\", - {"escapechar": "\\"}, - None, - "(EOF following escape character)|(unexpected end of data)", - ), - # ESCAPE_IN_QUOTED_FIELD - ( - 'a,b,c\n4,5,6\n"\\', - {"escapechar": "\\"}, - None, - "(EOF inside string starting at row 2)|(unexpected end of data)", - ), - # IN_QUOTED_FIELD - ( - 'a,b,c\n4,5,6\n"', - {"escapechar": "\\"}, - None, - "(EOF inside string starting at row 2)|(unexpected end of data)", - ), - ], - ids=[ - "whitespace-line", - "eat-line-comment", - "eat-crnl-nop", - "eat-comment", - "skip-line", - "eat-line-comment", - "in-field", - "eat-crnl", - "escaped-char", - "escape-in-quoted-field", - "in-quoted-field", - ], -) -def test_eof_states(all_parsers, data, kwargs, expected, msg): - # see gh-10728, gh-10548 - parser = all_parsers - - if expected is None: - with pytest.raises(ParserError, match=msg): - parser.read_csv(StringIO(data), **kwargs) - else: - result = parser.read_csv(StringIO(data), **kwargs) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("usecols", [None, [0, 1], ["a", "b"]]) -def test_uneven_lines_with_usecols(all_parsers, usecols): - # see gh-12203 - parser = all_parsers - data = r"""a,b,c -0,1,2 -3,4,5,6,7 -8,9,10""" - - if usecols is None: - # Make sure that an error is still raised - # when the "usecols" parameter is not provided. - msg = r"Expected \d+ fields in line \d+, saw \d+" - with pytest.raises(ParserError, match=msg): - parser.read_csv(StringIO(data)) - else: - expected = DataFrame({"a": [0, 3, 8], "b": [1, 4, 9]}) - - result = parser.read_csv(StringIO(data), usecols=usecols) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "data,kwargs,expected", - [ - # First, check to see that the response of parser when faced with no - # provided columns raises the correct error, with or without usecols. - ("", {}, None), - ("", {"usecols": ["X"]}, None), - ( - ",,", - {"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]}, - DataFrame(columns=["X"], index=[0], dtype=np.float64), - ), - ( - "", - {"names": ["Dummy", "X", "Dummy_2"], "usecols": ["X"]}, - DataFrame(columns=["X"]), - ), - ], -) -def test_read_empty_with_usecols(all_parsers, data, kwargs, expected): - # see gh-12493 - parser = all_parsers - - if expected is None: - msg = "No columns to parse from file" - with pytest.raises(EmptyDataError, match=msg): - parser.read_csv(StringIO(data), **kwargs) - else: - result = parser.read_csv(StringIO(data), **kwargs) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "kwargs,expected", - [ - # gh-8661, gh-8679: this should ignore six lines, including - # lines with trailing whitespace and blank lines. - ( - { - "header": None, - "delim_whitespace": True, - "skiprows": [0, 1, 2, 3, 5, 6], - "skip_blank_lines": True, - }, - DataFrame([[1.0, 2.0, 4.0], [5.1, np.nan, 10.0]]), - ), - # gh-8983: test skipping set of rows after a row with trailing spaces. - ( - { - "delim_whitespace": True, - "skiprows": [1, 2, 3, 5, 6], - "skip_blank_lines": True, - }, - DataFrame({"A": [1.0, 5.1], "B": [2.0, np.nan], "C": [4.0, 10]}), - ), - ], -) -def test_trailing_spaces(all_parsers, kwargs, expected): - data = "A B C \nrandom line with trailing spaces \nskip\n1,2,3\n1,2.,4.\nrandom line with trailing tabs\t\t\t\n \n5.1,NaN,10.0\n" # noqa - parser = all_parsers - - result = parser.read_csv(StringIO(data.replace(",", " ")), **kwargs) - tm.assert_frame_equal(result, expected) - - -def test_raise_on_sep_with_delim_whitespace(all_parsers): - # see gh-6607 - data = "a b c\n1 2 3" - parser = all_parsers - - with pytest.raises(ValueError, match="you can only specify one"): - parser.read_csv(StringIO(data), sep=r"\s", delim_whitespace=True) - - -@pytest.mark.parametrize("delim_whitespace", [True, False]) -def test_single_char_leading_whitespace(all_parsers, delim_whitespace): - # see gh-9710 - parser = all_parsers - data = """\ -MyColumn -a -b -a -b\n""" - - expected = DataFrame({"MyColumn": list("abab")}) - result = parser.read_csv( - StringIO(data), skipinitialspace=True, delim_whitespace=delim_whitespace - ) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "sep,skip_blank_lines,exp_data", - [ - (",", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]), - (r"\s+", True, [[1.0, 2.0, 4.0], [5.0, np.nan, 10.0], [-70.0, 0.4, 1.0]]), - ( - ",", - False, - [ - [1.0, 2.0, 4.0], - [np.nan, np.nan, np.nan], - [np.nan, np.nan, np.nan], - [5.0, np.nan, 10.0], - [np.nan, np.nan, np.nan], - [-70.0, 0.4, 1.0], - ], - ), - ], -) -def test_empty_lines(all_parsers, sep, skip_blank_lines, exp_data): - parser = all_parsers - data = """\ -A,B,C -1,2.,4. - - -5.,NaN,10.0 - --70,.4,1 -""" - - if sep == r"\s+": - data = data.replace(",", " ") - - result = parser.read_csv(StringIO(data), sep=sep, skip_blank_lines=skip_blank_lines) - expected = DataFrame(exp_data, columns=["A", "B", "C"]) - tm.assert_frame_equal(result, expected) - - -def test_whitespace_lines(all_parsers): - parser = all_parsers - data = """ - -\t \t\t -\t -A,B,C -\t 1,2.,4. -5.,NaN,10.0 -""" - expected = DataFrame([[1, 2.0, 4.0], [5.0, np.nan, 10.0]], columns=["A", "B", "C"]) - result = parser.read_csv(StringIO(data)) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "data,expected", - [ - ( - """ A B C D -a 1 2 3 4 -b 1 2 3 4 -c 1 2 3 4 -""", - DataFrame( - [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], - columns=["A", "B", "C", "D"], - index=["a", "b", "c"], - ), - ), - ( - " a b c\n1 2 3 \n4 5 6\n 7 8 9", - DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"]), - ), - ], -) -def test_whitespace_regex_separator(all_parsers, data, expected): - # see gh-6607 - parser = all_parsers - result = parser.read_csv(StringIO(data), sep=r"\s+") - tm.assert_frame_equal(result, expected) - - -def test_verbose_read(all_parsers, capsys): - parser = all_parsers - data = """a,b,c,d -one,1,2,3 -one,1,2,3 -,1,2,3 -one,1,2,3 -,1,2,3 -,1,2,3 -one,1,2,3 -two,1,2,3""" - - # Engines are verbose in different ways. - parser.read_csv(StringIO(data), verbose=True) - captured = capsys.readouterr() - - if parser.engine == "c": - assert "Tokenization took:" in captured.out - assert "Parser memory cleanup took:" in captured.out - else: # Python engine - assert captured.out == "Filled 3 NA values in column a\n" - - -def test_verbose_read2(all_parsers, capsys): - parser = all_parsers - data = """a,b,c,d -one,1,2,3 -two,1,2,3 -three,1,2,3 -four,1,2,3 -five,1,2,3 -,1,2,3 -seven,1,2,3 -eight,1,2,3""" - - parser.read_csv(StringIO(data), verbose=True, index_col=0) - captured = capsys.readouterr() - - # Engines are verbose in different ways. - if parser.engine == "c": - assert "Tokenization took:" in captured.out - assert "Parser memory cleanup took:" in captured.out - else: # Python engine - assert captured.out == "Filled 1 NA values in column a\n" - - -def test_iteration_open_handle(all_parsers): - parser = all_parsers - kwargs = {"squeeze": True, "header": None} - - with tm.ensure_clean() as path: - with open(path, "w") as f: - f.write("AAA\nBBB\nCCC\nDDD\nEEE\nFFF\nGGG") - - with open(path) as f: - for line in f: - if "CCC" in line: - break - - result = parser.read_csv(f, **kwargs) - expected = Series(["DDD", "EEE", "FFF", "GGG"], name=0) - tm.assert_series_equal(result, expected) - - -@pytest.mark.parametrize( - "data,thousands,decimal", - [ - ( - """A|B|C -1|2,334.01|5 -10|13|10. -""", - ",", - ".", - ), - ( - """A|B|C -1|2.334,01|5 -10|13|10, -""", - ".", - ",", - ), - ], -) -def test_1000_sep_with_decimal(all_parsers, data, thousands, decimal): - parser = all_parsers - expected = DataFrame({"A": [1, 10], "B": [2334.01, 13], "C": [5, 10.0]}) - - result = parser.read_csv( - StringIO(data), sep="|", thousands=thousands, decimal=decimal - ) - tm.assert_frame_equal(result, expected) - - -def test_euro_decimal_format(all_parsers): - parser = all_parsers - data = """Id;Number1;Number2;Text1;Text2;Number3 -1;1521,1541;187101,9543;ABC;poi;4,738797819 -2;121,12;14897,76;DEF;uyt;0,377320872 -3;878,158;108013,434;GHI;rez;2,735694704""" - - result = parser.read_csv(StringIO(data), sep=";", decimal=",") - expected = DataFrame( - [ - [1, 1521.1541, 187101.9543, "ABC", "poi", 4.738797819], - [2, 121.12, 14897.76, "DEF", "uyt", 0.377320872], - [3, 878.158, 108013.434, "GHI", "rez", 2.735694704], - ], - columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"], - ) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("na_filter", [True, False]) -def test_inf_parsing(all_parsers, na_filter): - parser = all_parsers - data = """\ -,A -a,inf -b,-inf -c,+Inf -d,-Inf -e,INF -f,-INF -g,+INf -h,-INf -i,inF -j,-inF""" - expected = DataFrame( - {"A": [float("inf"), float("-inf")] * 5}, - index=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"], - ) - result = parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("na_filter", [True, False]) -def test_infinity_parsing(all_parsers, na_filter): - parser = all_parsers - data = """\ -,A -a,Infinity -b,-Infinity -c,+Infinity -""" - expected = DataFrame( - {"A": [float("infinity"), float("-infinity"), float("+infinity")]}, - index=["a", "b", "c"], - ) - result = parser.read_csv(StringIO(data), index_col=0, na_filter=na_filter) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("nrows", [0, 1, 2, 3, 4, 5]) -def test_raise_on_no_columns(all_parsers, nrows): - parser = all_parsers - data = "\n" * nrows - - msg = "No columns to parse from file" - with pytest.raises(EmptyDataError, match=msg): - parser.read_csv(StringIO(data)) - - -@td.check_file_leaks -def test_memory_map(all_parsers, csv_dir_path): - mmap_file = os.path.join(csv_dir_path, "test_mmap.csv") - parser = all_parsers - - expected = DataFrame( - {"a": [1, 2, 3], "b": ["one", "two", "three"], "c": ["I", "II", "III"]} - ) - - result = parser.read_csv(mmap_file, memory_map=True) - tm.assert_frame_equal(result, expected) - - -def test_null_byte_char(all_parsers): - # see gh-2741 - data = "\x00,foo" - names = ["a", "b"] - parser = all_parsers - - if parser.engine == "c": - expected = DataFrame([[np.nan, "foo"]], columns=names) - out = parser.read_csv(StringIO(data), names=names) - tm.assert_frame_equal(out, expected) - else: - msg = "NULL byte detected" - with pytest.raises(ParserError, match=msg): - parser.read_csv(StringIO(data), names=names) - - -def test_temporary_file(all_parsers): - # see gh-13398 - parser = all_parsers - data = "0 0" - - with tm.ensure_clean(mode="w+", return_filelike=True) as new_file: - new_file.write(data) - new_file.flush() - new_file.seek(0) - - result = parser.read_csv(new_file, sep=r"\s+", header=None) - - expected = DataFrame([[0, 0]]) - tm.assert_frame_equal(result, expected) - - -def test_internal_eof_byte(all_parsers): - # see gh-5500 - parser = all_parsers - data = "a,b\n1\x1a,2" - - expected = DataFrame([["1\x1a", 2]], columns=["a", "b"]) - result = parser.read_csv(StringIO(data)) - tm.assert_frame_equal(result, expected) - - -def test_internal_eof_byte_to_file(all_parsers): - # see gh-16559 - parser = all_parsers - data = b'c1,c2\r\n"test \x1a test", test\r\n' - expected = DataFrame([["test \x1a test", " test"]], columns=["c1", "c2"]) - path = f"__{tm.rands(10)}__.csv" - - with tm.ensure_clean(path) as path: - with open(path, "wb") as f: - f.write(data) - - result = parser.read_csv(path) - tm.assert_frame_equal(result, expected) - - -def test_sub_character(all_parsers, csv_dir_path): - # see gh-16893 - filename = os.path.join(csv_dir_path, "sub_char.csv") - expected = DataFrame([[1, 2, 3]], columns=["a", "\x1ab", "c"]) - - parser = all_parsers - result = parser.read_csv(filename) - tm.assert_frame_equal(result, expected) - - -def test_file_handle_string_io(all_parsers): - # gh-14418 - # - # Don't close user provided file handles. - parser = all_parsers - data = "a,b\n1,2" - - fh = StringIO(data) - parser.read_csv(fh) - assert not fh.closed - - -def test_file_handles_with_open(all_parsers, csv1): - # gh-14418 - # - # Don't close user provided file handles. - parser = all_parsers - - for mode in ["r", "rb"]: - with open(csv1, mode) as f: - parser.read_csv(f) - assert not f.closed - - -def test_invalid_file_buffer_class(all_parsers): - # see gh-15337 - class InvalidBuffer: - pass - - parser = all_parsers - msg = "Invalid file path or buffer object type" - - with pytest.raises(ValueError, match=msg): - parser.read_csv(InvalidBuffer()) - - -def test_invalid_file_buffer_mock(all_parsers): - # see gh-15337 - parser = all_parsers - msg = "Invalid file path or buffer object type" - - class Foo: - pass - - with pytest.raises(ValueError, match=msg): - parser.read_csv(Foo()) - - -def test_valid_file_buffer_seems_invalid(all_parsers): - # gh-16135: we want to ensure that "tell" and "seek" - # aren't actually being used when we call `read_csv` - # - # Thus, while the object may look "invalid" (these - # methods are attributes of the `StringIO` class), - # it is still a valid file-object for our purposes. - class NoSeekTellBuffer(StringIO): - def tell(self): - raise AttributeError("No tell method") - - def seek(self, pos, whence=0): - raise AttributeError("No seek method") - - data = "a\n1" - parser = all_parsers - expected = DataFrame({"a": [1]}) - - result = parser.read_csv(NoSeekTellBuffer(data)) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "kwargs", - [{}, {"error_bad_lines": True}], # Default is True. # Explicitly pass in. -) -@pytest.mark.parametrize( - "warn_kwargs", [{}, {"warn_bad_lines": True}, {"warn_bad_lines": False}] -) -def test_error_bad_lines(all_parsers, kwargs, warn_kwargs): - # see gh-15925 - parser = all_parsers - kwargs.update(**warn_kwargs) - data = "a\n1\n1,2,3\n4\n5,6,7" - - msg = "Expected 1 fields in line 3, saw 3" - with pytest.raises(ParserError, match=msg): - parser.read_csv(StringIO(data), **kwargs) - - -def test_warn_bad_lines(all_parsers, capsys): - # see gh-15925 - parser = all_parsers - data = "a\n1\n1,2,3\n4\n5,6,7" - expected = DataFrame({"a": [1, 4]}) - - result = parser.read_csv(StringIO(data), error_bad_lines=False, warn_bad_lines=True) - tm.assert_frame_equal(result, expected) - - captured = capsys.readouterr() - assert "Skipping line 3" in captured.err - assert "Skipping line 5" in captured.err - - -def test_suppress_error_output(all_parsers, capsys): - # see gh-15925 - parser = all_parsers - data = "a\n1\n1,2,3\n4\n5,6,7" - expected = DataFrame({"a": [1, 4]}) - - result = parser.read_csv( - StringIO(data), error_bad_lines=False, warn_bad_lines=False - ) - tm.assert_frame_equal(result, expected) - - captured = capsys.readouterr() - assert captured.err == "" - - -@pytest.mark.parametrize("filename", ["sé-es-vé.csv", "ru-sй.csv", "中文文件名.csv"]) -def test_filename_with_special_chars(all_parsers, filename): - # see gh-15086. - parser = all_parsers - df = DataFrame({"a": [1, 2, 3]}) - - with tm.ensure_clean(filename) as path: - df.to_csv(path, index=False) - - result = parser.read_csv(path) - tm.assert_frame_equal(result, df) - - -def test_read_csv_memory_growth_chunksize(all_parsers): - # see gh-24805 - # - # Let's just make sure that we don't crash - # as we iteratively process all chunks. - parser = all_parsers - - with tm.ensure_clean() as path: - with open(path, "w") as f: - for i in range(1000): - f.write(str(i) + "\n") - - with parser.read_csv(path, chunksize=20) as result: - for _ in result: - pass - - -def test_read_csv_raises_on_header_prefix(all_parsers): - # gh-27394 - parser = all_parsers - msg = "Argument prefix must be None if argument header is not None" - - s = StringIO("0,1\n2,3") - - with pytest.raises(ValueError, match=msg): - parser.read_csv(s, header=0, prefix="_X") - - -def test_unexpected_keyword_parameter_exception(all_parsers): - # GH-34976 - parser = all_parsers - - msg = "{}\\(\\) got an unexpected keyword argument 'foo'" - with pytest.raises(TypeError, match=msg.format("read_csv")): - parser.read_csv("foo.csv", foo=1) - with pytest.raises(TypeError, match=msg.format("read_table")): - parser.read_table("foo.tsv", foo=1) - - -def test_read_table_same_signature_as_read_csv(all_parsers): - # GH-34976 - parser = all_parsers - - table_sign = signature(parser.read_table) - csv_sign = signature(parser.read_csv) - - assert table_sign.parameters.keys() == csv_sign.parameters.keys() - assert table_sign.return_annotation == csv_sign.return_annotation - - for key, csv_param in csv_sign.parameters.items(): - table_param = table_sign.parameters[key] - if key == "sep": - assert csv_param.default == "," - assert table_param.default == "\t" - assert table_param.annotation == csv_param.annotation - assert table_param.kind == csv_param.kind - continue - else: - assert table_param == csv_param - - -def test_read_table_equivalency_to_read_csv(all_parsers): - # see gh-21948 - # As of 0.25.0, read_table is undeprecated - parser = all_parsers - data = "a\tb\n1\t2\n3\t4" - expected = parser.read_csv(StringIO(data), sep="\t") - result = parser.read_table(StringIO(data)) - tm.assert_frame_equal(result, expected) - - -def test_first_row_bom(all_parsers): - # see gh-26545 - parser = all_parsers - data = '''\ufeff"Head1" "Head2" "Head3"''' - - result = parser.read_csv(StringIO(data), delimiter="\t") - expected = DataFrame(columns=["Head1", "Head2", "Head3"]) - tm.assert_frame_equal(result, expected) - - -def test_first_row_bom_unquoted(all_parsers): - # see gh-36343 - parser = all_parsers - data = """\ufeffHead1 Head2 Head3""" - - result = parser.read_csv(StringIO(data), delimiter="\t") - expected = DataFrame(columns=["Head1", "Head2", "Head3"]) - tm.assert_frame_equal(result, expected) - - -def test_integer_precision(all_parsers): - # Gh 7072 - s = """1,1;0;0;0;1;1;3844;3844;3844;1;1;1;1;1;1;0;0;1;1;0;0,,,4321583677327450765 -5,1;0;0;0;1;1;843;843;843;1;1;1;1;1;1;0;0;1;1;0;0,64.0,;,4321113141090630389""" - parser = all_parsers - result = parser.read_csv(StringIO(s), header=None)[4] - expected = Series([4321583677327450765, 4321113141090630389], name=4) - tm.assert_series_equal(result, expected) - - -def test_file_descriptor_leak(all_parsers): - # GH 31488 - - parser = all_parsers - with tm.ensure_clean() as path: - - def test(): - with pytest.raises(EmptyDataError, match="No columns to parse from file"): - parser.read_csv(path) - - td.check_file_leaks(test)() - - -@pytest.mark.parametrize("nrows", range(1, 6)) -def test_blank_lines_between_header_and_data_rows(all_parsers, nrows): - # GH 28071 - ref = DataFrame( - [[np.nan, np.nan], [np.nan, np.nan], [1, 2], [np.nan, np.nan], [3, 4]], - columns=list("ab"), - ) - csv = "\nheader\n\na,b\n\n\n1,2\n\n3,4" - parser = all_parsers - df = parser.read_csv(StringIO(csv), header=3, nrows=nrows, skip_blank_lines=False) - tm.assert_frame_equal(df, ref[:nrows]) - - -def test_no_header_two_extra_columns(all_parsers): - # GH 26218 - column_names = ["one", "two", "three"] - ref = DataFrame([["foo", "bar", "baz"]], columns=column_names) - stream = StringIO("foo,bar,baz,bam,blah") - parser = all_parsers - df = parser.read_csv(stream, header=None, names=column_names, index_col=False) - tm.assert_frame_equal(df, ref) - - -def test_read_csv_names_not_accepting_sets(all_parsers): - # GH 34946 - data = """\ - 1,2,3 - 4,5,6\n""" - parser = all_parsers - with pytest.raises(ValueError, match="Names should be an ordered collection."): - parser.read_csv(StringIO(data), names=set("QAZ")) - - -def test_read_csv_with_use_inf_as_na(all_parsers): - # https://github.com/pandas-dev/pandas/issues/35493 - parser = all_parsers - data = "1.0\nNaN\n3.0" - with option_context("use_inf_as_na", True): - result = parser.read_csv(StringIO(data), header=None) - expected = DataFrame([1.0, np.nan, 3.0]) - tm.assert_frame_equal(result, expected) - - -def test_read_table_delim_whitespace_default_sep(all_parsers): - # GH: 35958 - f = StringIO("a b c\n1 -2 -3\n4 5 6") - parser = all_parsers - result = parser.read_table(f, delim_whitespace=True) - expected = DataFrame({"a": [1, 4], "b": [-2, 5], "c": [-3, 6]}) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("delimiter", [",", "\t"]) -def test_read_csv_delim_whitespace_non_default_sep(all_parsers, delimiter): - # GH: 35958 - f = StringIO("a b c\n1 -2 -3\n4 5 6") - parser = all_parsers - msg = ( - "Specified a delimiter with both sep and " - "delim_whitespace=True; you can only specify one." - ) - with pytest.raises(ValueError, match=msg): - parser.read_csv(f, delim_whitespace=True, sep=delimiter) - - with pytest.raises(ValueError, match=msg): - parser.read_csv(f, delim_whitespace=True, delimiter=delimiter) - - -@pytest.mark.parametrize("delimiter", [",", "\t"]) -def test_read_table_delim_whitespace_non_default_sep(all_parsers, delimiter): - # GH: 35958 - f = StringIO("a b c\n1 -2 -3\n4 5 6") - parser = all_parsers - msg = ( - "Specified a delimiter with both sep and " - "delim_whitespace=True; you can only specify one." - ) - with pytest.raises(ValueError, match=msg): - parser.read_table(f, delim_whitespace=True, sep=delimiter) - - with pytest.raises(ValueError, match=msg): - parser.read_table(f, delim_whitespace=True, delimiter=delimiter) - - -def test_dict_keys_as_names(all_parsers): - # GH: 36928 - data = "1,2" - - keys = {"a": int, "b": int}.keys() - parser = all_parsers - - result = parser.read_csv(StringIO(data), names=keys) - expected = DataFrame({"a": [1], "b": [2]}) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("io_class", [StringIO, BytesIO]) -@pytest.mark.parametrize("encoding", [None, "utf-8"]) -def test_read_csv_file_handle(all_parsers, io_class, encoding): - """ - Test whether read_csv does not close user-provided file handles. - - GH 36980 - """ - parser = all_parsers - expected = DataFrame({"a": [1], "b": [2]}) - - content = "a,b\n1,2" - if io_class == BytesIO: - content = content.encode("utf-8") - handle = io_class(content) - - tm.assert_frame_equal(parser.read_csv(handle, encoding=encoding), expected) - assert not handle.closed - - -def test_memory_map_file_handle_silent_fallback(all_parsers, compression): - """ - Do not fail for buffers with memory_map=True (cannot memory map BytesIO). - - GH 37621 - """ - parser = all_parsers - expected = DataFrame({"a": [1], "b": [2]}) - - handle = BytesIO() - expected.to_csv(handle, index=False, compression=compression, mode="wb") - handle.seek(0) - - tm.assert_frame_equal( - parser.read_csv(handle, memory_map=True, compression=compression), - expected, - ) - - -def test_memory_map_compression(all_parsers, compression): - """ - Support memory map for compressed files. - - GH 37621 - """ - parser = all_parsers - expected = DataFrame({"a": [1], "b": [2]}) - - with tm.ensure_clean() as path: - expected.to_csv(path, index=False, compression=compression) - - tm.assert_frame_equal( - parser.read_csv(path, memory_map=True, compression=compression), - expected, - ) - - -def test_context_manager(all_parsers, datapath): - # make sure that opened files are closed - parser = all_parsers - - path = datapath("io", "data", "csv", "iris.csv") - - reader = parser.read_csv(path, chunksize=1) - assert not reader._engine.handles.handle.closed - try: - with reader: - next(reader) - assert False - except AssertionError: - assert reader._engine.handles.handle.closed - - -def test_context_manageri_user_provided(all_parsers, datapath): - # make sure that user-provided handles are not closed - parser = all_parsers - - with open(datapath("io", "data", "csv", "iris.csv"), mode="r") as path: - - reader = parser.read_csv(path, chunksize=1) - assert not reader._engine.handles.handle.closed - try: - with reader: - next(reader) - assert False - except AssertionError: - assert not reader._engine.handles.handle.closed
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Another precursor to #38370
https://api.github.com/repos/pandas-dev/pandas/pulls/38897
2021-01-02T08:35:39Z
2021-01-04T00:50:12Z
2021-01-04T00:50:12Z
2021-01-04T00:50:18Z
ENH: Add numba engine to several rolling aggregations
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index 306083e9c22b2..5f8cdb2a0bdac 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -50,20 +50,24 @@ class Engine: ["int", "float"], [np.sum, lambda x: np.sum(x) + 5], ["cython", "numba"], + ["sum", "max", "min", "median", "mean"], ) - param_names = ["constructor", "dtype", "function", "engine"] + param_names = ["constructor", "dtype", "function", "engine", "method"] - def setup(self, constructor, dtype, function, engine): + def setup(self, constructor, dtype, function, engine, method): N = 10 ** 3 arr = (100 * np.random.random(N)).astype(dtype) self.data = getattr(pd, constructor)(arr) - def time_rolling_apply(self, constructor, dtype, function, engine): + def time_rolling_apply(self, constructor, dtype, function, engine, method): self.data.rolling(10).apply(function, raw=True, engine=engine) - def time_expanding_apply(self, constructor, dtype, function, engine): + def time_expanding_apply(self, constructor, dtype, function, engine, method): self.data.expanding().apply(function, raw=True, engine=engine) + def time_rolling_methods(self, constructor, dtype, function, engine, method): + getattr(self.data.rolling(10), method)(engine=engine) + class ExpandingMethods: diff --git a/doc/source/user_guide/window.rst b/doc/source/user_guide/window.rst index 08641bc5b17ae..9db4a4bb873bd 100644 --- a/doc/source/user_guide/window.rst +++ b/doc/source/user_guide/window.rst @@ -321,6 +321,10 @@ Numba will be applied in potentially two routines: #. If ``func`` is a standard Python function, the engine will `JIT <https://numba.pydata.org/numba-doc/latest/user/overview.html>`__ the passed function. ``func`` can also be a JITed function in which case the engine will not JIT the function again. #. The engine will JIT the for loop where the apply function is applied to each window. +.. versionadded:: 1.3 + +``mean``, ``median``, ``max``, ``min``, and ``sum`` also support the ``engine`` and ``engine_kwargs`` arguments. + The ``engine_kwargs`` argument is a dictionary of keyword arguments that will be passed into the `numba.jit decorator <https://numba.pydata.org/numba-doc/latest/reference/jit-compilation.html#numba.jit>`__. These keyword arguments will be applied to *both* the passed function (if a standard Python function) diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index b4b98ec0403a8..1760e773c7b93 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -52,6 +52,7 @@ Other enhancements - Improved integer type mapping from pandas to SQLAlchemy when using :meth:`DataFrame.to_sql` (:issue:`35076`) - :func:`to_numeric` now supports downcasting of nullable ``ExtensionDtype`` objects (:issue:`33013`) - :func:`pandas.read_excel` can now auto detect .xlsb files (:issue:`35416`) +- :meth:`.Rolling.sum`, :meth:`.Expanding.sum`, :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.Rolling.median`, :meth:`.Expanding.median`, :meth:`.Rolling.max`, :meth:`.Expanding.max`, :meth:`.Rolling.min`, and :meth:`.Expanding.min` now support ``Numba`` execution with the ``engine`` keyword (:issue:`38895`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 81aa6699c3c61..1f0c16fb5aa8f 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -172,33 +172,33 @@ def apply( @Substitution(name="expanding") @Appender(_shared_docs["sum"]) - def sum(self, *args, **kwargs): + def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_expanding_func("sum", args, kwargs) - return super().sum(*args, **kwargs) + return super().sum(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="expanding", func_name="max") @Appender(_doc_template) @Appender(_shared_docs["max"]) - def max(self, *args, **kwargs): + def max(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_expanding_func("max", args, kwargs) - return super().max(*args, **kwargs) + return super().max(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="expanding") @Appender(_shared_docs["min"]) - def min(self, *args, **kwargs): + def min(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_expanding_func("min", args, kwargs) - return super().min(*args, **kwargs) + return super().min(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="expanding") @Appender(_shared_docs["mean"]) - def mean(self, *args, **kwargs): + def mean(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_expanding_func("mean", args, kwargs) - return super().mean(*args, **kwargs) + return super().mean(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="expanding") @Appender(_shared_docs["median"]) - def median(self, **kwargs): - return super().median(**kwargs) + def median(self, engine=None, engine_kwargs=None, **kwargs): + return super().median(engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="expanding", versionadded="") @Appender(_shared_docs["std"]) @@ -256,9 +256,16 @@ def kurt(self, **kwargs): @Substitution(name="expanding") @Appender(_shared_docs["quantile"]) - def quantile(self, quantile, interpolation="linear", **kwargs): + def quantile( + self, + quantile, + interpolation="linear", + **kwargs, + ): return super().quantile( - quantile=quantile, interpolation=interpolation, **kwargs + quantile=quantile, + interpolation=interpolation, + **kwargs, ) @Substitution(name="expanding", func_name="cov") diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index db8a48300206b..7ae1e61d426b9 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1241,6 +1241,7 @@ def count(self): objects instead. If you are just applying a NumPy reduction function this will achieve much better performance. + engine : str, default None * ``'cython'`` : Runs rolling apply through C-extensions from cython. * ``'numba'`` : Runs rolling apply through JIT compiled code from numba. @@ -1351,8 +1352,21 @@ def apply_func(values, begin, end, min_periods, raw=raw): return apply_func - def sum(self, *args, **kwargs): + def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_window_func("sum", args, kwargs) + if maybe_use_numba(engine): + if self.method == "table": + raise NotImplementedError("method='table' is not supported.") + # Once numba supports np.nansum with axis, args will be relevant. + # https://github.com/numba/numba/issues/6610 + args = () if self.method == "single" else (0,) + return self.apply( + np.nansum, + raw=True, + engine=engine, + engine_kwargs=engine_kwargs, + args=args, + ) window_func = window_aggregations.roll_sum return self._apply(window_func, name="sum", **kwargs) @@ -1362,13 +1376,43 @@ def sum(self, *args, **kwargs): Parameters ---------- - *args, **kwargs - Arguments and keyword arguments to be passed into func. + engine : str, default None + * ``'cython'`` : Runs rolling max through C-extensions from cython. + * ``'numba'`` : Runs rolling max through JIT compiled code from numba. + * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` + + .. versionadded:: 1.3.0 + + engine_kwargs : dict, default None + * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` + * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` + and ``parallel`` dictionary keys. The values must either be ``True`` or + ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is + ``{'nopython': True, 'nogil': False, 'parallel': False}`` + + .. versionadded:: 1.3.0 + + **kwargs + For compatibility with other %(name)s methods. Has no effect on + the result. """ ) - def max(self, *args, **kwargs): + def max(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_window_func("max", args, kwargs) + if maybe_use_numba(engine): + if self.method == "table": + raise NotImplementedError("method='table' is not supported.") + # Once numba supports np.nanmax with axis, args will be relevant. + # https://github.com/numba/numba/issues/6610 + args = () if self.method == "single" else (0,) + return self.apply( + np.nanmax, + raw=True, + engine=engine, + engine_kwargs=engine_kwargs, + args=args, + ) window_func = window_aggregations.roll_max return self._apply(window_func, name="max", **kwargs) @@ -1378,8 +1422,25 @@ def max(self, *args, **kwargs): Parameters ---------- + engine : str, default None + * ``'cython'`` : Runs rolling min through C-extensions from cython. + * ``'numba'`` : Runs rolling min through JIT compiled code from numba. + * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` + + .. versionadded:: 1.3.0 + + engine_kwargs : dict, default None + * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` + * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` + and ``parallel`` dictionary keys. The values must either be ``True`` or + ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is + ``{'nopython': True, 'nogil': False, 'parallel': False}`` + + .. versionadded:: 1.3.0 + **kwargs - Under Review. + For compatibility with other %(name)s methods. Has no effect on + the result. Returns ------- @@ -1409,13 +1470,39 @@ def max(self, *args, **kwargs): """ ) - def min(self, *args, **kwargs): + def min(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_window_func("min", args, kwargs) + if maybe_use_numba(engine): + if self.method == "table": + raise NotImplementedError("method='table' is not supported.") + # Once numba supports np.nanmin with axis, args will be relevant. + # https://github.com/numba/numba/issues/6610 + args = () if self.method == "single" else (0,) + return self.apply( + np.nanmin, + raw=True, + engine=engine, + engine_kwargs=engine_kwargs, + args=args, + ) window_func = window_aggregations.roll_min return self._apply(window_func, name="min", **kwargs) - def mean(self, *args, **kwargs): + def mean(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_window_func("mean", args, kwargs) + if maybe_use_numba(engine): + if self.method == "table": + raise NotImplementedError("method='table' is not supported.") + # Once numba supports np.nanmean with axis, args will be relevant. + # https://github.com/numba/numba/issues/6610 + args = () if self.method == "single" else (0,) + return self.apply( + np.nanmean, + raw=True, + engine=engine, + engine_kwargs=engine_kwargs, + args=args, + ) window_func = window_aggregations.roll_mean return self._apply(window_func, name="mean", **kwargs) @@ -1425,9 +1512,25 @@ def mean(self, *args, **kwargs): Parameters ---------- + engine : str, default None + * ``'cython'`` : Runs rolling median through C-extensions from cython. + * ``'numba'`` : Runs rolling median through JIT compiled code from numba. + * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` + + .. versionadded:: 1.3.0 + + engine_kwargs : dict, default None + * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` + * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` + and ``parallel`` dictionary keys. The values must either be ``True`` or + ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is + ``{'nopython': True, 'nogil': False, 'parallel': False}`` + + .. versionadded:: 1.3.0 + **kwargs For compatibility with other %(name)s methods. Has no effect - on the computed median. + on the computed result. Returns ------- @@ -1456,10 +1559,21 @@ def mean(self, *args, **kwargs): """ ) - def median(self, **kwargs): + def median(self, engine=None, engine_kwargs=None, **kwargs): + if maybe_use_numba(engine): + if self.method == "table": + raise NotImplementedError("method='table' is not supported.") + # Once numba supports np.nanmedian with axis, args will be relevant. + # https://github.com/numba/numba/issues/6610 + args = () if self.method == "single" else (0,) + return self.apply( + np.nanmedian, + raw=True, + engine=engine, + engine_kwargs=engine_kwargs, + args=args, + ) window_func = window_aggregations.roll_median_c - # GH 32865. Move max window size calculation to - # the median function implementation return self._apply(window_func, name="median", **kwargs) def std(self, ddof: int = 1, *args, **kwargs): @@ -1492,7 +1606,8 @@ def var(self, ddof: int = 1, *args, **kwargs): Parameters ---------- **kwargs - Keyword arguments to be passed into func. + For compatibility with other %(name)s methods. Has no effect on + the result. """ def skew(self, **kwargs): @@ -1512,7 +1627,8 @@ def skew(self, **kwargs): Parameters ---------- **kwargs - Under Review. + For compatibility with other %(name)s methods. Has no effect on + the result. Returns ------- @@ -1604,6 +1720,7 @@ def kurt(self, **kwargs): ---------- quantile : float Quantile to compute. 0 <= quantile <= 1. + interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points `i` and `j`: @@ -1614,6 +1731,23 @@ def kurt(self, **kwargs): * higher: `j`. * nearest: `i` or `j` whichever is nearest. * midpoint: (`i` + `j`) / 2. + + engine : str, default None + * ``'cython'`` : Runs rolling quantile through C-extensions from cython. + * ``'numba'`` : Runs rolling quantile through JIT compiled code from numba. + * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` + + .. versionadded:: 1.3.0 + + engine_kwargs : dict, default None + * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` + * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` + and ``parallel`` dictionary keys. The values must either be ``True`` or + ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is + ``{'nopython': True, 'nogil': False, 'parallel': False}`` + + .. versionadded:: 1.3.0 + **kwargs For compatibility with other %(name)s methods. Has no effect on the result. @@ -1995,33 +2129,33 @@ def apply( @Substitution(name="rolling") @Appender(_shared_docs["sum"]) - def sum(self, *args, **kwargs): + def sum(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_rolling_func("sum", args, kwargs) - return super().sum(*args, **kwargs) + return super().sum(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="rolling", func_name="max") @Appender(_doc_template) @Appender(_shared_docs["max"]) - def max(self, *args, **kwargs): + def max(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_rolling_func("max", args, kwargs) - return super().max(*args, **kwargs) + return super().max(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="rolling") @Appender(_shared_docs["min"]) - def min(self, *args, **kwargs): + def min(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_rolling_func("min", args, kwargs) - return super().min(*args, **kwargs) + return super().min(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="rolling") @Appender(_shared_docs["mean"]) - def mean(self, *args, **kwargs): + def mean(self, *args, engine=None, engine_kwargs=None, **kwargs): nv.validate_rolling_func("mean", args, kwargs) - return super().mean(*args, **kwargs) + return super().mean(*args, engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="rolling") @Appender(_shared_docs["median"]) - def median(self, **kwargs): - return super().median(**kwargs) + def median(self, engine=None, engine_kwargs=None, **kwargs): + return super().median(engine=engine, engine_kwargs=engine_kwargs, **kwargs) @Substitution(name="rolling", versionadded="") @Appender(_shared_docs["std"]) @@ -2081,7 +2215,9 @@ def kurt(self, **kwargs): @Appender(_shared_docs["quantile"]) def quantile(self, quantile, interpolation="linear", **kwargs): return super().quantile( - quantile=quantile, interpolation=interpolation, **kwargs + quantile=quantile, + interpolation=interpolation, + **kwargs, ) @Substitution(name="rolling", func_name="cov") diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py index a765f268cfb07..70bead489d2c6 100644 --- a/pandas/tests/window/conftest.py +++ b/pandas/tests/window/conftest.py @@ -47,12 +47,26 @@ def win_types_special(request): "kurt", "skew", "count", + "sem", ] ) def arithmetic_win_operators(request): return request.param +@pytest.fixture( + params=[ + "sum", + "mean", + "median", + "max", + "min", + ] +) +def arithmetic_numba_supported_operators(request): + return request.param + + @pytest.fixture(params=["right", "left", "both", "neither"]) def closed(request): return request.param diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index 4d22495e6c69a..9d9c216801d73 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -12,9 +12,9 @@ @td.skip_if_no("numba", "0.46.0") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba -class TestRollingApply: +class TestEngine: @pytest.mark.parametrize("jit", [True, False]) - def test_numba_vs_cython(self, jit, nogil, parallel, nopython, center): + def test_numba_vs_cython_apply(self, jit, nogil, parallel, nopython, center): def f(x, *args): arg_sum = 0 for arg in args: @@ -38,8 +38,47 @@ def f(x, *args): ) tm.assert_series_equal(result, expected) + def test_numba_vs_cython_rolling_methods( + self, nogil, parallel, nopython, arithmetic_numba_supported_operators + ): + + method = arithmetic_numba_supported_operators + + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + + df = DataFrame(np.eye(5)) + roll = df.rolling(2) + result = getattr(roll, method)(engine="numba", engine_kwargs=engine_kwargs) + expected = getattr(roll, method)(engine="cython") + + # Check the cache + assert (getattr(np, f"nan{method}"), "Rolling_apply_single") in NUMBA_FUNC_CACHE + + tm.assert_frame_equal(result, expected) + + def test_numba_vs_cython_expanding_methods( + self, nogil, parallel, nopython, arithmetic_numba_supported_operators + ): + + method = arithmetic_numba_supported_operators + + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + + df = DataFrame(np.eye(5)) + expand = df.expanding() + result = getattr(expand, method)(engine="numba", engine_kwargs=engine_kwargs) + expected = getattr(expand, method)(engine="cython") + + # Check the cache + assert ( + getattr(np, f"nan{method}"), + "Expanding_apply_single", + ) in NUMBA_FUNC_CACHE + + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize("jit", [True, False]) - def test_cache(self, jit, nogil, parallel, nopython): + def test_cache_apply(self, jit, nogil, parallel, nopython): # Test that the functions are cached correctly if we switch functions def func_1(x): return np.mean(x) + 4 @@ -138,7 +177,27 @@ def f(x): f, engine="numba", raw=True ) - def test_table_method_rolling(self, axis, nogil, parallel, nopython): + @pytest.mark.xfail( + raises=NotImplementedError, reason="method='table' is not supported." + ) + def test_table_method_rolling_methods( + self, axis, nogil, parallel, nopython, arithmetic_numba_supported_operators + ): + method = arithmetic_numba_supported_operators + + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + + df = DataFrame(np.eye(3)) + + result = getattr( + df.rolling(2, method="table", axis=axis, min_periods=0), method + )(engine_kwargs=engine_kwargs, engine="numba") + expected = getattr( + df.rolling(2, method="single", axis=axis, min_periods=0), method + )(engine_kwargs=engine_kwargs, engine="numba") + tm.assert_frame_equal(result, expected) + + def test_table_method_rolling_apply(self, axis, nogil, parallel, nopython): engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} def f(x): @@ -173,7 +232,7 @@ def weighted_mean(x): ) tm.assert_frame_equal(result, expected) - def test_table_method_expanding(self, axis, nogil, parallel, nopython): + def test_table_method_expanding_apply(self, axis, nogil, parallel, nopython): engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} def f(x): @@ -187,3 +246,23 @@ def f(x): f, raw=True, engine_kwargs=engine_kwargs, engine="numba" ) tm.assert_frame_equal(result, expected) + + @pytest.mark.xfail( + raises=NotImplementedError, reason="method='table' is not supported." + ) + def test_table_method_expanding_methods( + self, axis, nogil, parallel, nopython, arithmetic_numba_supported_operators + ): + method = arithmetic_numba_supported_operators + + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + + df = DataFrame(np.eye(3)) + + result = getattr(df.expanding(method="table", axis=axis), method)( + engine_kwargs=engine_kwargs, engine="numba" + ) + expected = getattr(df.expanding(method="single", axis=axis), method)( + engine_kwargs=engine_kwargs, engine="numba" + ) + tm.assert_frame_equal(result, expected)
- [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Adds `engine ` and `engine_kwargs` argument to `mean`, `median`, `sum`, `min`, `max`
https://api.github.com/repos/pandas-dev/pandas/pulls/38895
2021-01-02T02:06:51Z
2021-01-04T21:10:56Z
2021-01-04T21:10:56Z
2021-06-14T20:11:38Z
TST/CLN: deduplicate troublesome rank values
diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py index 991a91275ae1d..6ad1b475e28a2 100644 --- a/pandas/tests/frame/methods/test_rank.py +++ b/pandas/tests/frame/methods/test_rank.py @@ -392,7 +392,7 @@ def test_pct_max_many_rows(self): ([NegInfinity(), "1", "A", "BA", "Ba", "C", Infinity()], "object"), ], ) - def test_rank_inf_and_nan(self, contents, dtype): + def test_rank_inf_and_nan(self, contents, dtype, frame_or_series): dtype_na_map = { "float64": np.nan, "float32": np.nan, @@ -410,12 +410,13 @@ def test_rank_inf_and_nan(self, contents, dtype): nan_indices = np.random.choice(range(len(values)), 5) values = np.insert(values, nan_indices, na_value) exp_order = np.insert(exp_order, nan_indices, np.nan) - # shuffle the testing array and expected results in the same way + + # Shuffle the testing array and expected results in the same way random_order = np.random.permutation(len(values)) - df = DataFrame({"a": values[random_order]}) - expected = DataFrame({"a": exp_order[random_order]}, dtype="float64") - result = df.rank() - tm.assert_frame_equal(result, expected) + obj = frame_or_series(values[random_order]) + expected = frame_or_series(exp_order[random_order], dtype="float64") + result = obj.rank() + tm.assert_equal(result, expected) def test_df_series_inf_nan_consistency(self): # GH#32593 diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py index 6d3c37659f5c4..9d052e2236aae 100644 --- a/pandas/tests/series/methods/test_rank.py +++ b/pandas/tests/series/methods/test_rank.py @@ -3,7 +3,6 @@ import numpy as np import pytest -from pandas._libs import iNaT from pandas._libs.algos import Infinity, NegInfinity import pandas.util._test_decorators as td @@ -206,91 +205,6 @@ def test_rank_signature(self): with pytest.raises(ValueError, match=msg): s.rank("average") - @pytest.mark.parametrize( - "contents,dtype", - [ - ( - [ - -np.inf, - -50, - -1, - -1e-20, - -1e-25, - -1e-50, - 0, - 1e-40, - 1e-20, - 1e-10, - 2, - 40, - np.inf, - ], - "float64", - ), - ( - [ - -np.inf, - -50, - -1, - -1e-20, - -1e-25, - -1e-45, - 0, - 1e-40, - 1e-20, - 1e-10, - 2, - 40, - np.inf, - ], - "float32", - ), - ([np.iinfo(np.uint8).min, 1, 2, 100, np.iinfo(np.uint8).max], "uint8"), - pytest.param( - [ - np.iinfo(np.int64).min, - -100, - 0, - 1, - 9999, - 100000, - 1e10, - np.iinfo(np.int64).max, - ], - "int64", - marks=pytest.mark.xfail( - reason="iNaT is equivalent to minimum value of dtype" - "int64 pending issue GH#16674" - ), - ), - ([NegInfinity(), "1", "A", "BA", "Ba", "C", Infinity()], "object"), - ], - ) - def test_rank_inf(self, contents, dtype): - dtype_na_map = { - "float64": np.nan, - "float32": np.nan, - "int64": iNaT, - "object": None, - } - # Insert nans at random positions if underlying dtype has missing - # value. Then adjust the expected order by adding nans accordingly - # This is for testing whether rank calculation is affected - # when values are interwined with nan values. - values = np.array(contents, dtype=dtype) - exp_order = np.array(range(len(values)), dtype="float64") + 1.0 - if dtype in dtype_na_map: - na_value = dtype_na_map[dtype] - nan_indices = np.random.choice(range(len(values)), 5) - values = np.insert(values, nan_indices, na_value) - exp_order = np.insert(exp_order, nan_indices, np.nan) - # shuffle the testing array and expected results in the same way - random_order = np.random.permutation(len(values)) - iseries = Series(values[random_order]) - exp = Series(exp_order[random_order], dtype="float64") - iranks = iseries.rank() - tm.assert_series_equal(iranks, exp) - def test_rank_tie_methods(self): s = self.s
xref https://github.com/pandas-dev/pandas/pull/38681#discussion_r548554225
https://api.github.com/repos/pandas-dev/pandas/pulls/38894
2021-01-02T01:11:31Z
2021-01-04T03:35:48Z
2021-01-04T03:35:48Z
2021-01-04T03:55:08Z
doc fix for testing.assert_series_equal check_freq arg
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index b1f8389420cd9..4102bdd07aa8f 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -15,12 +15,12 @@ including other versions of pandas. Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. _whatsnew_121.api_breaking.testing.assert_frame_equal: +.. _whatsnew_121.api_breaking.testing.check_freq: -Added ``check_freq`` argument to ``testing.assert_frame_equal`` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Added ``check_freq`` argument to ``testing.assert_frame_equal`` and ``testing.assert_series_equal`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The ``check_freq`` argument was added to :func:`testing.assert_frame_equal` in pandas 1.1.0 and defaults to ``True``. :func:`testing.assert_frame_equal` now raises ``AssertionError`` if the indexes do not have the same frequency. Before pandas 1.1.0, the index frequency was not checked by :func:`testing.assert_frame_equal`. +The ``check_freq`` argument was added to :func:`testing.assert_frame_equal` and :func:`testing.assert_series_equal` in pandas 1.1.0 and defaults to ``True``. :func:`testing.assert_frame_equal` and :func:`testing.assert_series_equal` now raise ``AssertionError`` if the indexes do not have the same frequency. Before pandas 1.1.0, the index frequency was not checked. .. --------------------------------------------------------------------------- diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 13115d6b959d9..69e17199c9a90 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -878,6 +878,8 @@ def assert_series_equal( .. versionadded:: 1.0.2 check_freq : bool, default True Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex. + + .. versionadded:: 1.1.0 check_flags : bool, default True Whether to check the `flags` attribute.
This fixes `check_freq` arg docs for `assert_series_equal` like #38471 did for `assert_frame_equal`. - [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38893
2021-01-02T00:46:40Z
2021-01-03T17:01:53Z
2021-01-03T17:01:53Z
2021-01-04T16:50:08Z
ASV: Add asv for groupby.indices
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index bf210352bcb5d..b4d9db95af163 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -126,6 +126,9 @@ def setup(self, data, key): def time_series_groups(self, data, key): self.ser.groupby(self.ser).groups + def time_series_indices(self, data, key): + self.ser.groupby(self.ser).indices + class GroupManyLabels:
- [x] closes #38495 Asv for the indices performance regression
https://api.github.com/repos/pandas-dev/pandas/pulls/38892
2021-01-01T23:56:57Z
2021-01-03T18:44:22Z
2021-01-03T18:44:22Z
2021-01-03T18:44:59Z
Backport PR #38471 on branch 1.2.x (DOC: fixes for assert_frame_equal check_freq argument)
diff --git a/doc/source/whatsnew/v1.2.1.rst b/doc/source/whatsnew/v1.2.1.rst index a1612117072a5..b1f8389420cd9 100644 --- a/doc/source/whatsnew/v1.2.1.rst +++ b/doc/source/whatsnew/v1.2.1.rst @@ -10,6 +10,20 @@ including other versions of pandas. .. --------------------------------------------------------------------------- +.. _whatsnew_121.api_breaking: + +Backwards incompatible API changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. _whatsnew_121.api_breaking.testing.assert_frame_equal: + +Added ``check_freq`` argument to ``testing.assert_frame_equal`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``check_freq`` argument was added to :func:`testing.assert_frame_equal` in pandas 1.1.0 and defaults to ``True``. :func:`testing.assert_frame_equal` now raises ``AssertionError`` if the indexes do not have the same frequency. Before pandas 1.1.0, the index frequency was not checked by :func:`testing.assert_frame_equal`. + +.. --------------------------------------------------------------------------- + .. _whatsnew_121.regressions: Fixed regressions diff --git a/pandas/_testing.py b/pandas/_testing.py index 73b1dcf31979f..0b0778f3d3e5c 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -1578,6 +1578,8 @@ def assert_frame_equal( (same as in columns) - same labels must be with the same data. check_freq : bool, default True Whether to check the `freq` attribute on a DatetimeIndex or TimedeltaIndex. + + .. versionadded:: 1.1.0 check_flags : bool, default True Whether to check the `flags` attribute. rtol : float, default 1e-5
Backport PR #38471
https://api.github.com/repos/pandas-dev/pandas/pulls/38891
2021-01-01T23:29:45Z
2021-01-02T11:11:58Z
2021-01-02T11:11:58Z
2021-01-04T16:49:22Z
CLN: add typing for dtype arg in directories core/indexes and core/strings (GH38808)
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 9062667298d7c..24920e9b5faa7 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -7,7 +7,7 @@ from pandas._libs import index as libindex from pandas._libs.lib import no_default -from pandas._typing import ArrayLike, Label +from pandas._typing import ArrayLike, Dtype, Label from pandas.util._decorators import Appender, doc from pandas.core.dtypes.common import ( @@ -180,7 +180,13 @@ def _engine_type(self): # Constructors def __new__( - cls, data=None, categories=None, ordered=None, dtype=None, copy=False, name=None + cls, + data=None, + categories=None, + ordered=None, + dtype: Optional[Dtype] = None, + copy=False, + name=None, ): name = maybe_extract_name(name, data, cls) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index d176b6a5d8e6d..f82ee27aef534 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -14,7 +14,7 @@ to_offset, ) from pandas._libs.tslibs.offsets import prefix_mapping -from pandas._typing import DtypeObj +from pandas._typing import Dtype, DtypeObj from pandas.errors import InvalidIndexError from pandas.util._decorators import cache_readonly, doc @@ -289,7 +289,7 @@ def __new__( ambiguous="raise", dayfirst=False, yearfirst=False, - dtype=None, + dtype: Optional[Dtype] = None, copy=False, name=None, ): diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 054b21d2857ff..aabc3e741641f 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -11,7 +11,7 @@ from pandas._libs import lib from pandas._libs.interval import Interval, IntervalMixin, IntervalTree from pandas._libs.tslibs import BaseOffset, Timedelta, Timestamp, to_offset -from pandas._typing import DtypeObj, Label +from pandas._typing import Dtype, DtypeObj, Label from pandas.errors import InvalidIndexError from pandas.util._decorators import Appender, cache_readonly from pandas.util._exceptions import rewrite_exception @@ -192,7 +192,7 @@ def __new__( cls, data, closed=None, - dtype=None, + dtype: Optional[Dtype] = None, copy: bool = False, name=None, verify_integrity: bool = True, @@ -249,7 +249,12 @@ def _simple_new(cls, array: IntervalArray, name: Label = None): } ) def from_breaks( - cls, breaks, closed: str = "right", name=None, copy: bool = False, dtype=None + cls, + breaks, + closed: str = "right", + name=None, + copy: bool = False, + dtype: Optional[Dtype] = None, ): with rewrite_exception("IntervalArray", cls.__name__): array = IntervalArray.from_breaks( @@ -281,7 +286,7 @@ def from_arrays( closed: str = "right", name=None, copy: bool = False, - dtype=None, + dtype: Optional[Dtype] = None, ): with rewrite_exception("IntervalArray", cls.__name__): array = IntervalArray.from_arrays( @@ -307,7 +312,12 @@ def from_arrays( } ) def from_tuples( - cls, data, closed: str = "right", name=None, copy: bool = False, dtype=None + cls, + data, + closed: str = "right", + name=None, + copy: bool = False, + dtype: Optional[Dtype] = None, ): with rewrite_exception("IntervalArray", cls.__name__): arr = IntervalArray.from_tuples(data, closed=closed, copy=copy, dtype=dtype) diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 2c2888e1c6f72..59793d1a63813 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -1,4 +1,4 @@ -from typing import Any +from typing import Any, Optional import warnings import numpy as np @@ -45,7 +45,7 @@ class NumericIndex(Index): _is_numeric_dtype = True _can_hold_strings = False - def __new__(cls, data=None, dtype=None, copy=False, name=None): + def __new__(cls, data=None, dtype: Optional[Dtype] = None, copy=False, name=None): name = maybe_extract_name(name, data, cls) subarr = cls._ensure_array(data, dtype, copy) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 7746d7e617f8b..7762198246603 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,5 +1,5 @@ from datetime import datetime, timedelta -from typing import Any +from typing import Any, Optional import warnings import numpy as np @@ -7,7 +7,7 @@ from pandas._libs import index as libindex, lib from pandas._libs.tslibs import BaseOffset, Period, Resolution, Tick from pandas._libs.tslibs.parsing import DateParseError, parse_time_string -from pandas._typing import DtypeObj +from pandas._typing import Dtype, DtypeObj from pandas.errors import InvalidIndexError from pandas.util._decorators import cache_readonly, doc @@ -190,7 +190,7 @@ def __new__( data=None, ordinal=None, freq=None, - dtype=None, + dtype: Optional[Dtype] = None, copy=False, name=None, **fields, diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 029c4a30a6b22..4256ad93695e9 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -8,7 +8,7 @@ from pandas._libs import index as libindex from pandas._libs.lib import no_default -from pandas._typing import Label +from pandas._typing import Dtype, Label from pandas.compat.numpy import function as nv from pandas.util._decorators import cache_readonly, doc @@ -83,7 +83,13 @@ class RangeIndex(Int64Index): # Constructors def __new__( - cls, start=None, stop=None, step=None, dtype=None, copy=False, name=None + cls, + start=None, + stop=None, + step=None, + dtype: Optional[Dtype] = None, + copy=False, + name=None, ): cls._validate_dtype(dtype) @@ -113,7 +119,9 @@ def __new__( return cls._simple_new(rng, name=name) @classmethod - def from_range(cls, data: range, name=None, dtype=None) -> "RangeIndex": + def from_range( + cls, data: range, name=None, dtype: Optional[Dtype] = None + ) -> "RangeIndex": """ Create RangeIndex from a range object. @@ -405,7 +413,7 @@ def _shallow_copy(self, values=None, name: Label = no_default): return result @doc(Int64Index.copy) - def copy(self, name=None, deep=False, dtype=None, names=None): + def copy(self, name=None, deep=False, dtype: Optional[Dtype] = None, names=None): name = self._validate_names(name=name, names=names, deep=deep)[0] new_index = self._shallow_copy(name=name) diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index a29d84edd3a77..471f1e521b991 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -1,6 +1,6 @@ import re import textwrap -from typing import Pattern, Set, Union, cast +from typing import Optional, Pattern, Set, Union, cast import unicodedata import warnings @@ -9,7 +9,7 @@ import pandas._libs.lib as lib import pandas._libs.missing as libmissing import pandas._libs.ops as libops -from pandas._typing import Scalar +from pandas._typing import Dtype, Scalar from pandas.core.dtypes.common import is_re, is_scalar from pandas.core.dtypes.missing import isna @@ -28,7 +28,7 @@ def __len__(self): # For typing, _str_map relies on the object being sized. raise NotImplementedError - def _str_map(self, f, na_value=None, dtype=None): + def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None): """ Map a callable over valid element of the array.
Follow on PR for #38808 - [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38890
2021-01-01T23:22:05Z
2021-01-04T01:11:37Z
2021-01-04T01:11:37Z
2021-01-04T01:11:41Z
DOC: create shared includes for comparison docs, take III
diff --git a/doc/source/getting_started/comparison/comparison_with_sas.rst b/doc/source/getting_started/comparison/comparison_with_sas.rst index c6f508aae0e21..eb11b75027909 100644 --- a/doc/source/getting_started/comparison/comparison_with_sas.rst +++ b/doc/source/getting_started/comparison/comparison_with_sas.rst @@ -8,7 +8,7 @@ For potential users coming from `SAS <https://en.wikipedia.org/wiki/SAS_(softwar this page is meant to demonstrate how different SAS operations would be performed in pandas. -.. include:: comparison_boilerplate.rst +.. include:: includes/introduction.rst .. note:: @@ -93,16 +93,7 @@ specifying the column names. ; run; -A pandas ``DataFrame`` can be constructed in many different ways, -but for a small number of values, it is often convenient to specify it as -a Python dictionary, where the keys are the column names -and the values are the data. - -.. ipython:: python - - df = pd.DataFrame({"x": [1, 3, 5], "y": [2, 4, 6]}) - df - +.. include:: includes/construct_dataframe.rst Reading external data ~~~~~~~~~~~~~~~~~~~~~ @@ -217,12 +208,7 @@ or more columns. DATA step begins and can also be used in PROC statements */ run; -DataFrames can be filtered in multiple ways; the most intuitive of which is using -:ref:`boolean indexing <indexing.boolean>` - -.. ipython:: python - - tips[tips["total_bill"] > 10].head() +.. include:: includes/filtering.rst If/then logic ~~~~~~~~~~~~~ @@ -239,18 +225,7 @@ In SAS, if/then logic can be used to create new columns. else bucket = 'high'; run; -The same operation in pandas can be accomplished using -the ``where`` method from ``numpy``. - -.. ipython:: python - - tips["bucket"] = np.where(tips["total_bill"] < 10, "low", "high") - tips.head() - -.. ipython:: python - :suppress: - - tips = tips.drop("bucket", axis=1) +.. include:: includes/if_then.rst Date functionality ~~~~~~~~~~~~~~~~~~ @@ -278,28 +253,7 @@ functions pandas supports other Time Series features not available in Base SAS (such as resampling and custom offsets) - see the :ref:`timeseries documentation<timeseries>` for more details. -.. ipython:: python - - tips["date1"] = pd.Timestamp("2013-01-15") - tips["date2"] = pd.Timestamp("2015-02-15") - tips["date1_year"] = tips["date1"].dt.year - tips["date2_month"] = tips["date2"].dt.month - tips["date1_next"] = tips["date1"] + pd.offsets.MonthBegin() - tips["months_between"] = tips["date2"].dt.to_period("M") - tips[ - "date1" - ].dt.to_period("M") - - tips[ - ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"] - ].head() - -.. ipython:: python - :suppress: - - tips = tips.drop( - ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"], - axis=1, - ) +.. include:: includes/time_date.rst Selection of columns ~~~~~~~~~~~~~~~~~~~~ @@ -349,14 +303,7 @@ Sorting in SAS is accomplished via ``PROC SORT`` by sex total_bill; run; -pandas objects have a :meth:`~DataFrame.sort_values` method, which -takes a list of columns to sort by. - -.. ipython:: python - - tips = tips.sort_values(["sex", "total_bill"]) - tips.head() - +.. include:: includes/sorting.rst String processing ----------------- @@ -377,14 +324,7 @@ functions. ``LENGTHN`` excludes trailing blanks and ``LENGTHC`` includes trailin put(LENGTHC(time)); run; -Python determines the length of a character string with the ``len`` function. -``len`` includes trailing blanks. Use ``len`` and ``rstrip`` to exclude -trailing blanks. - -.. ipython:: python - - tips["time"].str.len().head() - tips["time"].str.rstrip().str.len().head() +.. include:: includes/length.rst Find diff --git a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst index 73645d429cc66..7b779b02e20f8 100644 --- a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst +++ b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst @@ -14,7 +14,7 @@ terminology and link to documentation for Excel, but much will be the same/simil `Apple Numbers <https://www.apple.com/mac/numbers/compatibility/functions.html>`_, and other Excel-compatible spreadsheet software. -.. include:: comparison_boilerplate.rst +.. include:: includes/introduction.rst Data structures --------------- diff --git a/doc/source/getting_started/comparison/comparison_with_sql.rst b/doc/source/getting_started/comparison/comparison_with_sql.rst index 4fe7b7e96cf50..52799442d6118 100644 --- a/doc/source/getting_started/comparison/comparison_with_sql.rst +++ b/doc/source/getting_started/comparison/comparison_with_sql.rst @@ -8,7 +8,7 @@ Since many potential pandas users have some familiarity with `SQL <https://en.wikipedia.org/wiki/SQL>`_, this page is meant to provide some examples of how various SQL operations would be performed using pandas. -.. include:: comparison_boilerplate.rst +.. include:: includes/introduction.rst Most of the examples will utilize the ``tips`` dataset found within pandas tests. We'll read the data into a DataFrame called ``tips`` and assume we have a database table of the same name and @@ -65,24 +65,9 @@ Filtering in SQL is done via a WHERE clause. SELECT * FROM tips - WHERE time = 'Dinner' - LIMIT 5; - -DataFrames can be filtered in multiple ways; the most intuitive of which is using -:ref:`boolean indexing <indexing.boolean>` - -.. ipython:: python - - tips[tips["time"] == "Dinner"].head(5) - -The above statement is simply passing a ``Series`` of True/False objects to the DataFrame, -returning all rows with True. - -.. ipython:: python + WHERE time = 'Dinner'; - is_dinner = tips["time"] == "Dinner" - is_dinner.value_counts() - tips[is_dinner].head(5) +.. include:: includes/filtering.rst Just like SQL's OR and AND, multiple conditions can be passed to a DataFrame using | (OR) and & (AND). diff --git a/doc/source/getting_started/comparison/comparison_with_stata.rst b/doc/source/getting_started/comparison/comparison_with_stata.rst index b3ed9b1ba630f..d1ad18bddb0a7 100644 --- a/doc/source/getting_started/comparison/comparison_with_stata.rst +++ b/doc/source/getting_started/comparison/comparison_with_stata.rst @@ -8,7 +8,7 @@ For potential users coming from `Stata <https://en.wikipedia.org/wiki/Stata>`__ this page is meant to demonstrate how different Stata operations would be performed in pandas. -.. include:: comparison_boilerplate.rst +.. include:: includes/introduction.rst .. note:: @@ -89,16 +89,7 @@ specifying the column names. 5 6 end -A pandas ``DataFrame`` can be constructed in many different ways, -but for a small number of values, it is often convenient to specify it as -a Python dictionary, where the keys are the column names -and the values are the data. - -.. ipython:: python - - df = pd.DataFrame({"x": [1, 3, 5], "y": [2, 4, 6]}) - df - +.. include:: includes/construct_dataframe.rst Reading external data ~~~~~~~~~~~~~~~~~~~~~ @@ -210,12 +201,7 @@ Filtering in Stata is done with an ``if`` clause on one or more columns. list if total_bill > 10 -DataFrames can be filtered in multiple ways; the most intuitive of which is using -:ref:`boolean indexing <indexing.boolean>`. - -.. ipython:: python - - tips[tips["total_bill"] > 10].head() +.. include:: includes/filtering.rst If/then logic ~~~~~~~~~~~~~ @@ -227,18 +213,7 @@ In Stata, an ``if`` clause can also be used to create new columns. generate bucket = "low" if total_bill < 10 replace bucket = "high" if total_bill >= 10 -The same operation in pandas can be accomplished using -the ``where`` method from ``numpy``. - -.. ipython:: python - - tips["bucket"] = np.where(tips["total_bill"] < 10, "low", "high") - tips.head() - -.. ipython:: python - :suppress: - - tips = tips.drop("bucket", axis=1) +.. include:: includes/if_then.rst Date functionality ~~~~~~~~~~~~~~~~~~ @@ -266,28 +241,7 @@ functions, pandas supports other Time Series features not available in Stata (such as time zone handling and custom offsets) -- see the :ref:`timeseries documentation<timeseries>` for more details. -.. ipython:: python - - tips["date1"] = pd.Timestamp("2013-01-15") - tips["date2"] = pd.Timestamp("2015-02-15") - tips["date1_year"] = tips["date1"].dt.year - tips["date2_month"] = tips["date2"].dt.month - tips["date1_next"] = tips["date1"] + pd.offsets.MonthBegin() - tips["months_between"] = tips["date2"].dt.to_period("M") - tips[ - "date1" - ].dt.to_period("M") - - tips[ - ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"] - ].head() - -.. ipython:: python - :suppress: - - tips = tips.drop( - ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"], - axis=1, - ) +.. include:: includes/time_date.rst Selection of columns ~~~~~~~~~~~~~~~~~~~~ @@ -327,14 +281,7 @@ Sorting in Stata is accomplished via ``sort`` sort sex total_bill -pandas objects have a :meth:`DataFrame.sort_values` method, which -takes a list of columns to sort by. - -.. ipython:: python - - tips = tips.sort_values(["sex", "total_bill"]) - tips.head() - +.. include:: includes/sorting.rst String processing ----------------- @@ -350,14 +297,7 @@ Stata determines the length of a character string with the :func:`strlen` and generate strlen_time = strlen(time) generate ustrlen_time = ustrlen(time) -Python determines the length of a character string with the ``len`` function. -In Python 3, all strings are Unicode strings. ``len`` includes trailing blanks. -Use ``len`` and ``rstrip`` to exclude trailing blanks. - -.. ipython:: python - - tips["time"].str.len().head() - tips["time"].str.rstrip().str.len().head() +.. include:: includes/length.rst Finding position of substring diff --git a/doc/source/getting_started/comparison/includes/construct_dataframe.rst b/doc/source/getting_started/comparison/includes/construct_dataframe.rst new file mode 100644 index 0000000000000..4d066c7962d98 --- /dev/null +++ b/doc/source/getting_started/comparison/includes/construct_dataframe.rst @@ -0,0 +1,9 @@ +A pandas ``DataFrame`` can be constructed in many different ways, +but for a small number of values, it is often convenient to specify it as +a Python dictionary, where the keys are the column names +and the values are the data. + +.. ipython:: python + + df = pd.DataFrame({"x": [1, 3, 5], "y": [2, 4, 6]}) + df diff --git a/doc/source/getting_started/comparison/includes/filtering.rst b/doc/source/getting_started/comparison/includes/filtering.rst new file mode 100644 index 0000000000000..861a93d92c2c2 --- /dev/null +++ b/doc/source/getting_started/comparison/includes/filtering.rst @@ -0,0 +1,16 @@ +DataFrames can be filtered in multiple ways; the most intuitive of which is using +:ref:`boolean indexing <indexing.boolean>` + +.. ipython:: python + + tips[tips["total_bill"] > 10] + +The above statement is simply passing a ``Series`` of ``True``/``False`` objects to the DataFrame, +returning all rows with ``True``. + +.. ipython:: python + + is_dinner = tips["time"] == "Dinner" + is_dinner + is_dinner.value_counts() + tips[is_dinner] diff --git a/doc/source/getting_started/comparison/includes/if_then.rst b/doc/source/getting_started/comparison/includes/if_then.rst new file mode 100644 index 0000000000000..d7977366cfc33 --- /dev/null +++ b/doc/source/getting_started/comparison/includes/if_then.rst @@ -0,0 +1,12 @@ +The same operation in pandas can be accomplished using +the ``where`` method from ``numpy``. + +.. ipython:: python + + tips["bucket"] = np.where(tips["total_bill"] < 10, "low", "high") + tips.head() + +.. ipython:: python + :suppress: + + tips = tips.drop("bucket", axis=1) diff --git a/doc/source/getting_started/comparison/comparison_boilerplate.rst b/doc/source/getting_started/comparison/includes/introduction.rst similarity index 100% rename from doc/source/getting_started/comparison/comparison_boilerplate.rst rename to doc/source/getting_started/comparison/includes/introduction.rst diff --git a/doc/source/getting_started/comparison/includes/length.rst b/doc/source/getting_started/comparison/includes/length.rst new file mode 100644 index 0000000000000..9581c661c0170 --- /dev/null +++ b/doc/source/getting_started/comparison/includes/length.rst @@ -0,0 +1,8 @@ +Python determines the length of a character string with the ``len`` function. +In Python 3, all strings are Unicode strings. ``len`` includes trailing blanks. +Use ``len`` and ``rstrip`` to exclude trailing blanks. + +.. ipython:: python + + tips["time"].str.len().head() + tips["time"].str.rstrip().str.len().head() diff --git a/doc/source/getting_started/comparison/includes/sorting.rst b/doc/source/getting_started/comparison/includes/sorting.rst new file mode 100644 index 0000000000000..23f11ff485474 --- /dev/null +++ b/doc/source/getting_started/comparison/includes/sorting.rst @@ -0,0 +1,7 @@ +pandas objects have a :meth:`DataFrame.sort_values` method, which +takes a list of columns to sort by. + +.. ipython:: python + + tips = tips.sort_values(["sex", "total_bill"]) + tips.head() diff --git a/doc/source/getting_started/comparison/includes/time_date.rst b/doc/source/getting_started/comparison/includes/time_date.rst new file mode 100644 index 0000000000000..12a00b36dc97d --- /dev/null +++ b/doc/source/getting_started/comparison/includes/time_date.rst @@ -0,0 +1,22 @@ +.. ipython:: python + + tips["date1"] = pd.Timestamp("2013-01-15") + tips["date2"] = pd.Timestamp("2015-02-15") + tips["date1_year"] = tips["date1"].dt.year + tips["date2_month"] = tips["date2"].dt.month + tips["date1_next"] = tips["date1"] + pd.offsets.MonthBegin() + tips["months_between"] = tips["date2"].dt.to_period("M") - tips[ + "date1" + ].dt.to_period("M") + + tips[ + ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"] + ].head() + +.. ipython:: python + :suppress: + + tips = tips.drop( + ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"], + axis=1, + ) diff --git a/setup.cfg b/setup.cfg index 56b2fa190ac99..2138e87ae5988 100644 --- a/setup.cfg +++ b/setup.cfg @@ -49,7 +49,10 @@ ignore = E203, # space before : (needed for how black formats slicing) E711, # comparison to none should be 'if cond is none:' exclude = - doc/source/development/contributing_docstring.rst + doc/source/development/contributing_docstring.rst, + # work around issue of undefined variable warnings + # https://github.com/pandas-dev/pandas/pull/38837#issuecomment-752884156 + doc/source/getting_started/comparison/includes/*.rst [tool:pytest] # sync minversion with setup.cfg & install.rst
From original pull request (https://github.com/pandas-dev/pandas/pull/38771): > This will help ensure consistency between the examples. - [ ] ~~closes #xxxx~~ - [x] tests added / passed - [ ] ~~passes `black pandas`~~ - [ ] ~~passes `git diff upstream/master -u -- "*.py" | flake8 --diff`~~ - [ ] ~~whatsnew entry~~
https://api.github.com/repos/pandas-dev/pandas/pulls/38887
2021-01-01T22:35:15Z
2021-01-03T17:26:02Z
2021-01-03T17:26:02Z
2021-01-04T08:43:07Z
CLN: add typing for dtype arg in core/arrays (GH38808)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 3391e2760187c..872f17b7f0770 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -1,7 +1,7 @@ import operator from operator import le, lt import textwrap -from typing import Sequence, Type, TypeVar +from typing import Optional, Sequence, Type, TypeVar, cast import numpy as np @@ -14,7 +14,7 @@ intervals_to_interval_bounds, ) from pandas._libs.missing import NA -from pandas._typing import ArrayLike +from pandas._typing import ArrayLike, Dtype, NpDtype from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender @@ -170,7 +170,7 @@ def __new__( cls, data, closed=None, - dtype=None, + dtype: Optional[Dtype] = None, copy: bool = False, verify_integrity: bool = True, ): @@ -212,7 +212,13 @@ def __new__( @classmethod def _simple_new( - cls, left, right, closed=None, copy=False, dtype=None, verify_integrity=True + cls, + left, + right, + closed=None, + copy=False, + dtype: Optional[Dtype] = None, + verify_integrity=True, ): result = IntervalMixin.__new__(cls) @@ -223,12 +229,14 @@ def _simple_new( if dtype is not None: # GH 19262: dtype must be an IntervalDtype to override inferred dtype = pandas_dtype(dtype) - if not is_interval_dtype(dtype): + if is_interval_dtype(dtype): + dtype = cast(IntervalDtype, dtype) + if dtype.subtype is not None: + left = left.astype(dtype.subtype) + right = right.astype(dtype.subtype) + else: msg = f"dtype must be an IntervalDtype, got {dtype}" raise TypeError(msg) - elif dtype.subtype is not None: - left = left.astype(dtype.subtype) - right = right.astype(dtype.subtype) # coerce dtypes to match if needed if is_float_dtype(left) and is_integer_dtype(right): @@ -279,7 +287,9 @@ def _simple_new( return result @classmethod - def _from_sequence(cls, scalars, *, dtype=None, copy=False): + def _from_sequence( + cls, scalars, *, dtype: Optional[Dtype] = None, copy: bool = False + ): return cls(scalars, dtype=dtype, copy=copy) @classmethod @@ -338,7 +348,9 @@ def _from_factorized(cls, values, original): ), } ) - def from_breaks(cls, breaks, closed="right", copy=False, dtype=None): + def from_breaks( + cls, breaks, closed="right", copy: bool = False, dtype: Optional[Dtype] = None + ): breaks = maybe_convert_platform_interval(breaks) return cls.from_arrays(breaks[:-1], breaks[1:], closed, copy=copy, dtype=dtype) @@ -407,7 +419,9 @@ def from_breaks(cls, breaks, closed="right", copy=False, dtype=None): ), } ) - def from_arrays(cls, left, right, closed="right", copy=False, dtype=None): + def from_arrays( + cls, left, right, closed="right", copy=False, dtype: Optional[Dtype] = None + ): left = maybe_convert_platform_interval(left) right = maybe_convert_platform_interval(right) @@ -464,7 +478,9 @@ def from_arrays(cls, left, right, closed="right", copy=False, dtype=None): ), } ) - def from_tuples(cls, data, closed="right", copy=False, dtype=None): + def from_tuples( + cls, data, closed="right", copy=False, dtype: Optional[Dtype] = None + ): if len(data): left, right = [], [] else: @@ -1277,7 +1293,7 @@ def is_non_overlapping_monotonic(self): # --------------------------------------------------------------------- # Conversion - def __array__(self, dtype=None) -> np.ndarray: + def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray: """ Return the IntervalArray's data as a numpy array of Interval objects (with dtype='object') diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 3cf25847ed3d0..e4a98a54ee94c 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -5,7 +5,7 @@ import numpy as np from pandas._libs import lib, missing as libmissing -from pandas._typing import ArrayLike, Dtype, Scalar +from pandas._typing import ArrayLike, Dtype, NpDtype, Scalar from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly, doc @@ -147,7 +147,10 @@ def __invert__(self: BaseMaskedArrayT) -> BaseMaskedArrayT: return type(self)(~self._data, self._mask) def to_numpy( - self, dtype=None, copy: bool = False, na_value: Scalar = lib.no_default + self, + dtype: Optional[NpDtype] = None, + copy: bool = False, + na_value: Scalar = lib.no_default, ) -> np.ndarray: """ Convert to a NumPy Array. @@ -257,7 +260,7 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: __array_priority__ = 1000 # higher than ndarray so ops dispatch to us - def __array__(self, dtype=None) -> np.ndarray: + def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray: """ the array interface, return my values We return an object array here to preserve our scalar values diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index ae131d8a51ba1..9ed6306e5b9bc 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -1,11 +1,11 @@ import numbers -from typing import Tuple, Type, Union +from typing import Optional, Tuple, Type, Union import numpy as np from numpy.lib.mixins import NDArrayOperatorsMixin from pandas._libs import lib -from pandas._typing import Scalar +from pandas._typing import Dtype, NpDtype, Scalar from pandas.compat.numpy import function as nv from pandas.core.dtypes.dtypes import ExtensionDtype @@ -38,7 +38,7 @@ class PandasDtype(ExtensionDtype): _metadata = ("_dtype",) - def __init__(self, dtype: object): + def __init__(self, dtype: Optional[NpDtype]): self._dtype = np.dtype(dtype) def __repr__(self) -> str: @@ -173,7 +173,7 @@ def __init__(self, values: Union[np.ndarray, "PandasArray"], copy: bool = False) @classmethod def _from_sequence( - cls, scalars, *, dtype=None, copy: bool = False + cls, scalars, *, dtype: Optional[Dtype] = None, copy: bool = False ) -> "PandasArray": if isinstance(dtype, PandasDtype): dtype = dtype._dtype @@ -200,7 +200,7 @@ def dtype(self) -> PandasDtype: # ------------------------------------------------------------------------ # NumPy Array Interface - def __array__(self, dtype=None) -> np.ndarray: + def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray: return np.asarray(self._ndarray, dtype=dtype) _HANDLED_TYPES = (np.ndarray, numbers.Number) @@ -311,7 +311,15 @@ def prod(self, *, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: ) return self._wrap_reduction_result(axis, result) - def mean(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): + def mean( + self, + *, + axis=None, + dtype: Optional[NpDtype] = None, + out=None, + keepdims=False, + skipna=True, + ): nv.validate_mean((), {"dtype": dtype, "out": out, "keepdims": keepdims}) result = nanops.nanmean(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result) @@ -326,7 +334,14 @@ def median( return self._wrap_reduction_result(axis, result) def std( - self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True + self, + *, + axis=None, + dtype: Optional[NpDtype] = None, + out=None, + ddof=1, + keepdims=False, + skipna=True, ): nv.validate_stat_ddof_func( (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="std" @@ -335,7 +350,14 @@ def std( return self._wrap_reduction_result(axis, result) def var( - self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True + self, + *, + axis=None, + dtype: Optional[NpDtype] = None, + out=None, + ddof=1, + keepdims=False, + skipna=True, ): nv.validate_stat_ddof_func( (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="var" @@ -344,7 +366,14 @@ def var( return self._wrap_reduction_result(axis, result) def sem( - self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True + self, + *, + axis=None, + dtype: Optional[NpDtype] = None, + out=None, + ddof=1, + keepdims=False, + skipna=True, ): nv.validate_stat_ddof_func( (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="sem" @@ -352,14 +381,30 @@ def sem( result = nanops.nansem(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) return self._wrap_reduction_result(axis, result) - def kurt(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): + def kurt( + self, + *, + axis=None, + dtype: Optional[NpDtype] = None, + out=None, + keepdims=False, + skipna=True, + ): nv.validate_stat_ddof_func( (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="kurt" ) result = nanops.nankurt(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result) - def skew(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): + def skew( + self, + *, + axis=None, + dtype: Optional[NpDtype] = None, + out=None, + keepdims=False, + skipna=True, + ): nv.validate_stat_ddof_func( (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="skew" ) @@ -370,7 +415,10 @@ def skew(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): # Additional Methods def to_numpy( - self, dtype=None, copy: bool = False, na_value=lib.no_default + self, + dtype: Optional[NpDtype] = None, + copy: bool = False, + na_value=lib.no_default, ) -> np.ndarray: result = np.asarray(self._ndarray, dtype=dtype) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index e0e40a666896d..e06315fbd4f78 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -26,7 +26,7 @@ get_period_field_arr, period_asfreq_arr, ) -from pandas._typing import AnyArrayLike, Dtype +from pandas._typing import AnyArrayLike, Dtype, NpDtype from pandas.util._decorators import cache_readonly, doc from pandas.core.dtypes.common import ( @@ -159,7 +159,7 @@ class PeriodArray(PeriodMixin, dtl.DatelikeOps): # -------------------------------------------------------------------- # Constructors - def __init__(self, values, dtype=None, freq=None, copy=False): + def __init__(self, values, dtype: Optional[Dtype] = None, freq=None, copy=False): freq = validate_dtype_freq(dtype, freq) if freq is not None: @@ -186,7 +186,10 @@ def __init__(self, values, dtype=None, freq=None, copy=False): @classmethod def _simple_new( - cls, values: np.ndarray, freq: Optional[BaseOffset] = None, dtype=None + cls, + values: np.ndarray, + freq: Optional[BaseOffset] = None, + dtype: Optional[Dtype] = None, ) -> "PeriodArray": # alias for PeriodArray.__init__ assertion_msg = "Should be numpy array of type i8" @@ -220,7 +223,7 @@ def _from_sequence( @classmethod def _from_sequence_of_strings( - cls, strings, *, dtype=None, copy=False + cls, strings, *, dtype: Optional[Dtype] = None, copy=False ) -> "PeriodArray": return cls._from_sequence(strings, dtype=dtype, copy=copy) @@ -301,7 +304,7 @@ def freq(self) -> BaseOffset: """ return self.dtype.freq - def __array__(self, dtype=None) -> np.ndarray: + def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray: if dtype == "i8": return self.asi8 elif dtype == bool: diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 26dbe5e0dba44..b4d4fd5cc7106 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -4,7 +4,7 @@ from collections import abc import numbers import operator -from typing import Any, Callable, Sequence, Type, TypeVar, Union +from typing import Any, Callable, Optional, Sequence, Type, TypeVar, Union import warnings import numpy as np @@ -13,7 +13,7 @@ import pandas._libs.sparse as splib from pandas._libs.sparse import BlockIndex, IntIndex, SparseIndex from pandas._libs.tslibs import NaT -from pandas._typing import Scalar +from pandas._typing import Dtype, NpDtype, Scalar from pandas.compat.numpy import function as nv from pandas.errors import PerformanceWarning @@ -174,7 +174,7 @@ def _sparse_array_op( return _wrap_result(name, result, index, fill, dtype=result_dtype) -def _wrap_result(name, data, sparse_index, fill_value, dtype=None): +def _wrap_result(name, data, sparse_index, fill_value, dtype: Optional[Dtype] = None): """ wrap op result to have correct dtype """ @@ -281,7 +281,7 @@ def __init__( index=None, fill_value=None, kind="integer", - dtype=None, + dtype: Optional[Dtype] = None, copy=False, ): @@ -454,7 +454,7 @@ def from_spmatrix(cls, data): return cls._simple_new(arr, index, dtype) - def __array__(self, dtype=None) -> np.ndarray: + def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray: fill_value = self.fill_value if self.sp_index.ngaps == 0: @@ -487,7 +487,7 @@ def __setitem__(self, key, value): raise TypeError(msg) @classmethod - def _from_sequence(cls, scalars, *, dtype=None, copy=False): + def _from_sequence(cls, scalars, *, dtype: Optional[Dtype] = None, copy=False): return cls(scalars, dtype=dtype) @classmethod @@ -998,7 +998,7 @@ def _concat_same_type( return cls(data, sparse_index=sp_index, fill_value=fill_value) - def astype(self, dtype=None, copy=True): + def astype(self, dtype: Optional[Dtype] = None, copy=True): """ Change the dtype of a SparseArray. @@ -1461,7 +1461,9 @@ def _formatter(self, boxed=False): return None -def make_sparse(arr: np.ndarray, kind="block", fill_value=None, dtype=None): +def make_sparse( + arr: np.ndarray, kind="block", fill_value=None, dtype: Optional[NpDtype] = None +): """ Convert ndarray to sparse format diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 74a41a0b64ff8..3d0ac3380ec39 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -1,9 +1,9 @@ -from typing import TYPE_CHECKING, Type, Union +from typing import TYPE_CHECKING, Optional, Type, Union import numpy as np from pandas._libs import lib, missing as libmissing -from pandas._typing import Scalar +from pandas._typing import Dtype, Scalar from pandas.compat.numpy import function as nv from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype @@ -206,7 +206,7 @@ def _validate(self): ) @classmethod - def _from_sequence(cls, scalars, *, dtype=None, copy=False): + def _from_sequence(cls, scalars, *, dtype: Optional[Dtype] = None, copy=False): if dtype: assert dtype == "string" @@ -234,7 +234,9 @@ def _from_sequence(cls, scalars, *, dtype=None, copy=False): return new_string_array @classmethod - def _from_sequence_of_strings(cls, strings, *, dtype=None, copy=False): + def _from_sequence_of_strings( + cls, strings, *, dtype: Optional[Dtype] = None, copy=False + ): return cls._from_sequence(strings, dtype=dtype, copy=copy) def __arrow_array__(self, type=None): @@ -381,7 +383,7 @@ def _cmp_method(self, other, op): # String methods interface _str_na_value = StringDtype.na_value - def _str_map(self, f, na_value=None, dtype=None): + def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None): from pandas.arrays import BooleanArray, IntegerArray, StringArray from pandas.core.arrays.string_ import StringDtype diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 3a351bf497662..d37e91e55a9cf 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -1,11 +1,12 @@ from __future__ import annotations from distutils.version import LooseVersion -from typing import TYPE_CHECKING, Any, Sequence, Type, Union +from typing import TYPE_CHECKING, Any, Optional, Sequence, Type, Union import numpy as np from pandas._libs import lib, missing as libmissing +from pandas._typing import Dtype, NpDtype from pandas.util._validators import validate_fillna_kwargs from pandas.core.dtypes.base import ExtensionDtype @@ -203,14 +204,16 @@ def _chk_pyarrow_available(cls) -> None: raise ImportError(msg) @classmethod - def _from_sequence(cls, scalars, dtype=None, copy=False): + def _from_sequence(cls, scalars, dtype: Optional[Dtype] = None, copy=False): cls._chk_pyarrow_available() # convert non-na-likes to str, and nan-likes to ArrowStringDtype.na_value scalars = lib.ensure_string_array(scalars, copy=False) return cls(pa.array(scalars, type=pa.string(), from_pandas=True)) @classmethod - def _from_sequence_of_strings(cls, strings, dtype=None, copy=False): + def _from_sequence_of_strings( + cls, strings, dtype: Optional[Dtype] = None, copy=False + ): return cls._from_sequence(strings, dtype=dtype, copy=copy) @property @@ -220,7 +223,7 @@ def dtype(self) -> ArrowStringDtype: """ return self._dtype - def __array__(self, dtype=None) -> np.ndarray: + def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray: """Correctly construct numpy arrays when passed to `np.asarray()`.""" return self.to_numpy(dtype=dtype) @@ -229,7 +232,10 @@ def __arrow_array__(self, type=None): return self._data def to_numpy( - self, dtype=None, copy: bool = False, na_value=lib.no_default + self, + dtype: Optional[NpDtype] = None, + copy: bool = False, + na_value=lib.no_default, ) -> np.ndarray: """ Convert to a NumPy ndarray. diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 55136e0dedcf5..62d5a4d30563b 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -22,6 +22,7 @@ ints_to_pytimedelta, parse_timedelta_unit, ) +from pandas._typing import NpDtype from pandas.compat.numpy import function as nv from pandas.core.dtypes.cast import astype_td64_unit_conversion @@ -352,7 +353,7 @@ def sum( self, *, axis=None, - dtype=None, + dtype: Optional[NpDtype] = None, out=None, keepdims: bool = False, initial=None, @@ -372,7 +373,7 @@ def std( self, *, axis=None, - dtype=None, + dtype: Optional[NpDtype] = None, out=None, ddof: int = 1, keepdims: bool = False,
Follow on PR for #38808 - [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38886
2021-01-01T22:25:32Z
2021-01-05T02:02:08Z
2021-01-05T02:02:08Z
2021-01-05T02:02:14Z
CLN: Use signed integers in khash maps for signed integer keys
diff --git a/pandas/_libs/khash.pxd b/pandas/_libs/khash.pxd index 0d0c5ae058b21..e9f5766f78435 100644 --- a/pandas/_libs/khash.pxd +++ b/pandas/_libs/khash.pxd @@ -16,11 +16,11 @@ from numpy cimport ( cdef extern from "khash_python.h": const int KHASH_TRACE_DOMAIN - ctypedef uint32_t khint_t - ctypedef khint_t khiter_t + ctypedef uint32_t khuint_t + ctypedef khuint_t khiter_t ctypedef struct kh_pymap_t: - khint_t n_buckets, size, n_occupied, upper_bound + khuint_t n_buckets, size, n_occupied, upper_bound uint32_t *flags PyObject **keys size_t *vals @@ -28,15 +28,15 @@ cdef extern from "khash_python.h": kh_pymap_t* kh_init_pymap() void kh_destroy_pymap(kh_pymap_t*) void kh_clear_pymap(kh_pymap_t*) - khint_t kh_get_pymap(kh_pymap_t*, PyObject*) - void kh_resize_pymap(kh_pymap_t*, khint_t) - khint_t kh_put_pymap(kh_pymap_t*, PyObject*, int*) - void kh_del_pymap(kh_pymap_t*, khint_t) + khuint_t kh_get_pymap(kh_pymap_t*, PyObject*) + void kh_resize_pymap(kh_pymap_t*, khuint_t) + khuint_t kh_put_pymap(kh_pymap_t*, PyObject*, int*) + void kh_del_pymap(kh_pymap_t*, khuint_t) bint kh_exist_pymap(kh_pymap_t*, khiter_t) ctypedef struct kh_pyset_t: - khint_t n_buckets, size, n_occupied, upper_bound + khuint_t n_buckets, size, n_occupied, upper_bound uint32_t *flags PyObject **keys size_t *vals @@ -44,17 +44,17 @@ cdef extern from "khash_python.h": kh_pyset_t* kh_init_pyset() void kh_destroy_pyset(kh_pyset_t*) void kh_clear_pyset(kh_pyset_t*) - khint_t kh_get_pyset(kh_pyset_t*, PyObject*) - void kh_resize_pyset(kh_pyset_t*, khint_t) - khint_t kh_put_pyset(kh_pyset_t*, PyObject*, int*) - void kh_del_pyset(kh_pyset_t*, khint_t) + khuint_t kh_get_pyset(kh_pyset_t*, PyObject*) + void kh_resize_pyset(kh_pyset_t*, khuint_t) + khuint_t kh_put_pyset(kh_pyset_t*, PyObject*, int*) + void kh_del_pyset(kh_pyset_t*, khuint_t) bint kh_exist_pyset(kh_pyset_t*, khiter_t) ctypedef char* kh_cstr_t ctypedef struct kh_str_t: - khint_t n_buckets, size, n_occupied, upper_bound + khuint_t n_buckets, size, n_occupied, upper_bound uint32_t *flags kh_cstr_t *keys size_t *vals @@ -62,10 +62,10 @@ cdef extern from "khash_python.h": kh_str_t* kh_init_str() nogil void kh_destroy_str(kh_str_t*) nogil void kh_clear_str(kh_str_t*) nogil - khint_t kh_get_str(kh_str_t*, kh_cstr_t) nogil - void kh_resize_str(kh_str_t*, khint_t) nogil - khint_t kh_put_str(kh_str_t*, kh_cstr_t, int*) nogil - void kh_del_str(kh_str_t*, khint_t) nogil + khuint_t kh_get_str(kh_str_t*, kh_cstr_t) nogil + void kh_resize_str(kh_str_t*, khuint_t) nogil + khuint_t kh_put_str(kh_str_t*, kh_cstr_t, int*) nogil + void kh_del_str(kh_str_t*, khuint_t) nogil bint kh_exist_str(kh_str_t*, khiter_t) nogil @@ -74,16 +74,16 @@ cdef extern from "khash_python.h": int starts[256] kh_str_starts_t* kh_init_str_starts() nogil - khint_t kh_put_str_starts_item(kh_str_starts_t* table, char* key, - int* ret) nogil - khint_t kh_get_str_starts_item(kh_str_starts_t* table, char* key) nogil + khuint_t kh_put_str_starts_item(kh_str_starts_t* table, char* key, + int* ret) nogil + khuint_t kh_get_str_starts_item(kh_str_starts_t* table, char* key) nogil void kh_destroy_str_starts(kh_str_starts_t*) nogil - void kh_resize_str_starts(kh_str_starts_t*, khint_t) nogil + void kh_resize_str_starts(kh_str_starts_t*, khuint_t) nogil # sweep factorize ctypedef struct kh_strbox_t: - khint_t n_buckets, size, n_occupied, upper_bound + khuint_t n_buckets, size, n_occupied, upper_bound uint32_t *flags kh_cstr_t *keys PyObject **vals @@ -91,10 +91,10 @@ cdef extern from "khash_python.h": kh_strbox_t* kh_init_strbox() nogil void kh_destroy_strbox(kh_strbox_t*) nogil void kh_clear_strbox(kh_strbox_t*) nogil - khint_t kh_get_strbox(kh_strbox_t*, kh_cstr_t) nogil - void kh_resize_strbox(kh_strbox_t*, khint_t) nogil - khint_t kh_put_strbox(kh_strbox_t*, kh_cstr_t, int*) nogil - void kh_del_strbox(kh_strbox_t*, khint_t) nogil + khuint_t kh_get_strbox(kh_strbox_t*, kh_cstr_t) nogil + void kh_resize_strbox(kh_strbox_t*, khuint_t) nogil + khuint_t kh_put_strbox(kh_strbox_t*, kh_cstr_t, int*) nogil + void kh_del_strbox(kh_strbox_t*, khuint_t) nogil bint kh_exist_strbox(kh_strbox_t*, khiter_t) nogil diff --git a/pandas/_libs/khash_for_primitive_helper.pxi.in b/pandas/_libs/khash_for_primitive_helper.pxi.in index db8d3e0b19417..9073d87aa91cc 100644 --- a/pandas/_libs/khash_for_primitive_helper.pxi.in +++ b/pandas/_libs/khash_for_primitive_helper.pxi.in @@ -24,7 +24,7 @@ primitive_types = [('int64', 'int64_t'), cdef extern from "khash_python.h": ctypedef struct kh_{{name}}_t: - khint_t n_buckets, size, n_occupied, upper_bound + khuint_t n_buckets, size, n_occupied, upper_bound uint32_t *flags {{c_type}} *keys size_t *vals @@ -32,10 +32,10 @@ cdef extern from "khash_python.h": kh_{{name}}_t* kh_init_{{name}}() nogil void kh_destroy_{{name}}(kh_{{name}}_t*) nogil void kh_clear_{{name}}(kh_{{name}}_t*) nogil - khint_t kh_get_{{name}}(kh_{{name}}_t*, {{c_type}}) nogil - void kh_resize_{{name}}(kh_{{name}}_t*, khint_t) nogil - khint_t kh_put_{{name}}(kh_{{name}}_t*, {{c_type}}, int*) nogil - void kh_del_{{name}}(kh_{{name}}_t*, khint_t) nogil + khuint_t kh_get_{{name}}(kh_{{name}}_t*, {{c_type}}) nogil + void kh_resize_{{name}}(kh_{{name}}_t*, khuint_t) nogil + khuint_t kh_put_{{name}}(kh_{{name}}_t*, {{c_type}}, int*) nogil + void kh_del_{{name}}(kh_{{name}}_t*, khuint_t) nogil bint kh_exist_{{name}}(kh_{{name}}_t*, khiter_t) nogil diff --git a/pandas/_libs/src/klib/khash.h b/pandas/_libs/src/klib/khash.h index bb56b2fe2d145..03b11f77580a5 100644 --- a/pandas/_libs/src/klib/khash.h +++ b/pandas/_libs/src/klib/khash.h @@ -134,32 +134,39 @@ int main() { #if UINT_MAX == 0xffffffffu -typedef unsigned int khint32_t; +typedef unsigned int khuint32_t; +typedef signed int khint32_t; #elif ULONG_MAX == 0xffffffffu -typedef unsigned long khint32_t; +typedef unsigned long khuint32_t; +typedef signed long khint32_t; #endif #if ULONG_MAX == ULLONG_MAX -typedef unsigned long khint64_t; +typedef unsigned long khuint64_t; +typedef signed long khint64_t; #else -typedef unsigned long long khint64_t; +typedef unsigned long long khuint64_t; +typedef signed long long khint64_t; #endif #if UINT_MAX == 0xffffu -typedef unsigned int khint16_t; +typedef unsigned int khuint16_t; +typedef signed int khint16_t; #elif USHRT_MAX == 0xffffu -typedef unsigned short khint16_t; +typedef unsigned short khuint16_t; +typedef signed short khint16_t; #endif #if UCHAR_MAX == 0xffu -typedef unsigned char khint8_t; +typedef unsigned char khuint8_t; +typedef signed char khint8_t; #endif typedef double khfloat64_t; typedef float khfloat32_t; -typedef khint32_t khint_t; -typedef khint_t khiter_t; +typedef khuint32_t khuint_t; +typedef khuint_t khiter_t; #define __ac_isempty(flag, i) ((flag[i>>5]>>(i&0x1fU))&1) #define __ac_isdel(flag, i) (0) @@ -172,15 +179,15 @@ typedef khint_t khiter_t; // specializations of https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp -khint32_t PANDAS_INLINE murmur2_32to32(khint32_t k){ - const khint32_t SEED = 0xc70f6907UL; +khuint32_t PANDAS_INLINE murmur2_32to32(khuint32_t k){ + const khuint32_t SEED = 0xc70f6907UL; // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. - const khint32_t M_32 = 0x5bd1e995; + const khuint32_t M_32 = 0x5bd1e995; const int R_32 = 24; // Initialize the hash to a 'random' value - khint32_t h = SEED ^ 4; + khuint32_t h = SEED ^ 4; //handle 4 bytes: k *= M_32; @@ -204,15 +211,15 @@ khint32_t PANDAS_INLINE murmur2_32to32(khint32_t k){ // - the same case for 32bit and 64bit builds // - no performance difference could be measured compared to a possible x64-version -khint32_t PANDAS_INLINE murmur2_32_32to32(khint32_t k1, khint32_t k2){ - const khint32_t SEED = 0xc70f6907UL; +khuint32_t PANDAS_INLINE murmur2_32_32to32(khuint32_t k1, khuint32_t k2){ + const khuint32_t SEED = 0xc70f6907UL; // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. - const khint32_t M_32 = 0x5bd1e995; + const khuint32_t M_32 = 0x5bd1e995; const int R_32 = 24; // Initialize the hash to a 'random' value - khint32_t h = SEED ^ 4; + khuint32_t h = SEED ^ 4; //handle first 4 bytes: k1 *= M_32; @@ -238,9 +245,9 @@ khint32_t PANDAS_INLINE murmur2_32_32to32(khint32_t k1, khint32_t k2){ return h; } -khint32_t PANDAS_INLINE murmur2_64to32(khint64_t k){ - khint32_t k1 = (khint32_t)k; - khint32_t k2 = (khint32_t)(k >> 32); +khuint32_t PANDAS_INLINE murmur2_64to32(khuint64_t k){ + khuint32_t k1 = (khuint32_t)k; + khuint32_t k2 = (khuint32_t)(k >> 32); return murmur2_32_32to32(k1, k2); } @@ -262,23 +269,23 @@ static const double __ac_HASH_UPPER = 0.77; #define KHASH_DECLARE(name, khkey_t, khval_t) \ typedef struct { \ - khint_t n_buckets, size, n_occupied, upper_bound; \ - khint32_t *flags; \ + khuint_t n_buckets, size, n_occupied, upper_bound; \ + khuint32_t *flags; \ khkey_t *keys; \ khval_t *vals; \ } kh_##name##_t; \ extern kh_##name##_t *kh_init_##name(); \ extern void kh_destroy_##name(kh_##name##_t *h); \ extern void kh_clear_##name(kh_##name##_t *h); \ - extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \ - extern void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \ - extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \ - extern void kh_del_##name(kh_##name##_t *h, khint_t x); + extern khuint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \ + extern void kh_resize_##name(kh_##name##_t *h, khuint_t new_n_buckets); \ + extern khuint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \ + extern void kh_del_##name(kh_##name##_t *h, khuint_t x); #define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \ typedef struct { \ - khint_t n_buckets, size, n_occupied, upper_bound; \ - khint32_t *flags; \ + khuint_t n_buckets, size, n_occupied, upper_bound; \ + khuint32_t *flags; \ khkey_t *keys; \ khval_t *vals; \ } kh_##name##_t; \ @@ -296,14 +303,14 @@ static const double __ac_HASH_UPPER = 0.77; SCOPE void kh_clear_##name(kh_##name##_t *h) \ { \ if (h && h->flags) { \ - memset(h->flags, 0xaa, __ac_fsize(h->n_buckets) * sizeof(khint32_t)); \ + memset(h->flags, 0xaa, __ac_fsize(h->n_buckets) * sizeof(khuint32_t)); \ h->size = h->n_occupied = 0; \ } \ } \ - SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ + SCOPE khuint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \ { \ if (h->n_buckets) { \ - khint_t inc, k, i, last, mask; \ + khuint_t inc, k, i, last, mask; \ mask = h->n_buckets - 1; \ k = __hash_func(key); i = k & mask; \ inc = __ac_inc(k, mask); last = i; /* inc==1 for linear probing */ \ @@ -314,17 +321,17 @@ static const double __ac_HASH_UPPER = 0.77; return __ac_iseither(h->flags, i)? h->n_buckets : i; \ } else return 0; \ } \ - SCOPE void kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \ + SCOPE void kh_resize_##name(kh_##name##_t *h, khuint_t new_n_buckets) \ { /* This function uses 0.25*n_bucktes bytes of working space instead of [sizeof(key_t+val_t)+.25]*n_buckets. */ \ - khint32_t *new_flags = 0; \ - khint_t j = 1; \ + khuint32_t *new_flags = 0; \ + khuint_t j = 1; \ { \ kroundup32(new_n_buckets); \ if (new_n_buckets < 4) new_n_buckets = 4; \ - if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) j = 0; /* requested size is too small */ \ + if (h->size >= (khuint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) j = 0; /* requested size is too small */ \ else { /* hash table size to be changed (shrink or expand); rehash */ \ - new_flags = (khint32_t*)KHASH_MALLOC(__ac_fsize(new_n_buckets) * sizeof(khint32_t)); \ - memset(new_flags, 0xff, __ac_fsize(new_n_buckets) * sizeof(khint32_t)); \ + new_flags = (khuint32_t*)KHASH_MALLOC(__ac_fsize(new_n_buckets) * sizeof(khuint32_t)); \ + memset(new_flags, 0xff, __ac_fsize(new_n_buckets) * sizeof(khuint32_t)); \ if (h->n_buckets < new_n_buckets) { /* expand */ \ h->keys = (khkey_t*)KHASH_REALLOC(h->keys, new_n_buckets * sizeof(khkey_t)); \ if (kh_is_map) h->vals = (khval_t*)KHASH_REALLOC(h->vals, new_n_buckets * sizeof(khval_t)); \ @@ -336,12 +343,12 @@ static const double __ac_HASH_UPPER = 0.77; if (__ac_iseither(h->flags, j) == 0) { \ khkey_t key = h->keys[j]; \ khval_t val; \ - khint_t new_mask; \ + khuint_t new_mask; \ new_mask = new_n_buckets - 1; \ if (kh_is_map) val = h->vals[j]; \ __ac_set_isempty_true(h->flags, j); \ while (1) { /* kick-out process; sort of like in Cuckoo hashing */ \ - khint_t inc, k, i; \ + khuint_t inc, k, i; \ k = __hash_func(key); \ i = k & new_mask; \ inc = __ac_inc(k, new_mask); \ @@ -367,18 +374,18 @@ static const double __ac_HASH_UPPER = 0.77; h->flags = new_flags; \ h->n_buckets = new_n_buckets; \ h->n_occupied = h->size; \ - h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \ + h->upper_bound = (khuint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \ } \ } \ - SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ + SCOPE khuint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \ { \ - khint_t x; \ + khuint_t x; \ if (h->n_occupied >= h->upper_bound) { /* update the hash table */ \ if (h->n_buckets > (h->size<<1)) kh_resize_##name(h, h->n_buckets - 1); /* clear "deleted" elements */ \ else kh_resize_##name(h, h->n_buckets + 1); /* expand the hash table */ \ } /* TODO: to implement automatically shrinking; resize() already support shrinking */ \ { \ - khint_t inc, k, i, site, last, mask = h->n_buckets - 1; \ + khuint_t inc, k, i, site, last, mask = h->n_buckets - 1; \ x = site = h->n_buckets; k = __hash_func(key); i = k & mask; \ if (__ac_isempty(h->flags, i)) x = i; /* for speed up */ \ else { \ @@ -407,7 +414,7 @@ static const double __ac_HASH_UPPER = 0.77; } else *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \ return x; \ } \ - SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \ + SCOPE void kh_del_##name(kh_##name##_t *h, khuint_t x) \ { \ if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \ __ac_set_isdel_true(h->flags, x); \ @@ -422,20 +429,23 @@ static const double __ac_HASH_UPPER = 0.77; /*! @function @abstract Integer hash function - @param key The integer [khint32_t] - @return The hash value [khint_t] + @param key The integer [khuint32_t] + @return The hash value [khuint_t] */ -#define kh_int_hash_func(key) (khint32_t)(key) +#define kh_int_hash_func(key) (khuint32_t)(key) /*! @function @abstract Integer comparison function */ #define kh_int_hash_equal(a, b) ((a) == (b)) /*! @function @abstract 64-bit integer hash function - @param key The integer [khint64_t] - @return The hash value [khint_t] + @param key The integer [khuint64_t] + @return The hash value [khuint_t] */ -#define kh_int64_hash_func(key) (khint32_t)((key)>>33^(key)^(key)<<11) +PANDAS_INLINE khuint_t kh_int64_hash_func(khuint64_t key) +{ + return (khuint_t)((key)>>33^(key)^(key)<<11); +} /*! @function @abstract 64-bit integer comparison function */ @@ -446,16 +456,16 @@ static const double __ac_HASH_UPPER = 0.77; @param s Pointer to a null terminated string @return The hash value */ -PANDAS_INLINE khint_t __ac_X31_hash_string(const char *s) +PANDAS_INLINE khuint_t __ac_X31_hash_string(const char *s) { - khint_t h = *s; + khuint_t h = *s; if (h) for (++s ; *s; ++s) h = (h << 5) - h + *s; return h; } /*! @function @abstract Another interface to const char* hash function @param key Pointer to a null terminated string [const char*] - @return The hash value [khint_t] + @return The hash value [khuint_t] */ #define kh_str_hash_func(key) __ac_X31_hash_string(key) /*! @function @@ -463,7 +473,7 @@ PANDAS_INLINE khint_t __ac_X31_hash_string(const char *s) */ #define kh_str_hash_equal(a, b) (strcmp(a, b) == 0) -PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) +PANDAS_INLINE khuint_t __ac_Wang_hash(khuint_t key) { key += ~(key << 15); key ^= (key >> 10); @@ -473,7 +483,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) key ^= (key >> 16); return key; } -#define kh_int_hash_func2(k) __ac_Wang_hash((khint_t)key) +#define kh_int_hash_func2(k) __ac_Wang_hash((khuint_t)key) /* --- END OF HASH FUNCTIONS --- */ @@ -510,7 +520,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) @abstract Resize a hash table. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] - @param s New size [khint_t] + @param s New size [khuint_t] */ #define kh_resize(name, h, s) kh_resize_##name(h, s) @@ -522,7 +532,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) @param r Extra return code: 0 if the key is present in the hash table; 1 if the bucket is empty (never used); 2 if the element in the bucket has been deleted [int*] - @return Iterator to the inserted element [khint_t] + @return Iterator to the inserted element [khuint_t] */ #define kh_put(name, h, k, r) kh_put_##name(h, k, r) @@ -531,7 +541,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] @param k Key [type of keys] - @return Iterator to the found element, or kh_end(h) is the element is absent [khint_t] + @return Iterator to the found element, or kh_end(h) is the element is absent [khuint_t] */ #define kh_get(name, h, k) kh_get_##name(h, k) @@ -539,14 +549,14 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) @abstract Remove a key from the hash table. @param name Name of the hash table [symbol] @param h Pointer to the hash table [khash_t(name)*] - @param k Iterator to the element to be deleted [khint_t] + @param k Iterator to the element to be deleted [khuint_t] */ #define kh_del(name, h, k) kh_del_##name(h, k) /*! @function @abstract Test whether a bucket contains data. @param h Pointer to the hash table [khash_t(name)*] - @param x Iterator to the bucket [khint_t] + @param x Iterator to the bucket [khuint_t] @return 1 if containing data; 0 otherwise [int] */ #define kh_exist(h, x) (!__ac_iseither((h)->flags, (x))) @@ -554,7 +564,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) /*! @function @abstract Get key given an iterator @param h Pointer to the hash table [khash_t(name)*] - @param x Iterator to the bucket [khint_t] + @param x Iterator to the bucket [khuint_t] @return Key [type of keys] */ #define kh_key(h, x) ((h)->keys[x]) @@ -562,7 +572,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) /*! @function @abstract Get value given an iterator @param h Pointer to the hash table [khash_t(name)*] - @param x Iterator to the bucket [khint_t] + @param x Iterator to the bucket [khuint_t] @return Value [type of values] @discussion For hash sets, calling this results in segfault. */ @@ -576,28 +586,28 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) /*! @function @abstract Get the start iterator @param h Pointer to the hash table [khash_t(name)*] - @return The start iterator [khint_t] + @return The start iterator [khuint_t] */ -#define kh_begin(h) (khint_t)(0) +#define kh_begin(h) (khuint_t)(0) /*! @function @abstract Get the end iterator @param h Pointer to the hash table [khash_t(name)*] - @return The end iterator [khint_t] + @return The end iterator [khuint_t] */ #define kh_end(h) ((h)->n_buckets) /*! @function @abstract Get the number of elements in the hash table @param h Pointer to the hash table [khash_t(name)*] - @return Number of elements in the hash table [khint_t] + @return Number of elements in the hash table [khuint_t] */ #define kh_size(h) ((h)->size) /*! @function @abstract Get the number of buckets in the hash table @param h Pointer to the hash table [khash_t(name)*] - @return Number of buckets in the hash table [khint_t] + @return Number of buckets in the hash table [khuint_t] */ #define kh_n_buckets(h) ((h)->n_buckets) @@ -615,25 +625,18 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) @param name Name of the hash table [symbol] @param khval_t Type of values [type] */ - -// we implicitly convert signed int to unsigned int, thus potential overflows -// for operations (<<,*,+) don't trigger undefined behavior, also >>-operator -// is implementation defined for signed ints if sign-bit is set. -// because we never really "get" the keys, there will be no convertion from -// unsigend int to (signed) int (which would be implementation defined behavior) -// this holds also for 64-, 16- and 8-bit integers #define KHASH_MAP_INIT_INT(name, khval_t) \ KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) #define KHASH_MAP_INIT_UINT(name, khval_t) \ - KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) + KHASH_INIT(name, khuint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) /*! @function @abstract Instantiate a hash map containing 64-bit integer keys @param name Name of the hash table [symbol] */ #define KHASH_SET_INIT_UINT64(name) \ - KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) + KHASH_INIT(name, khuint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) #define KHASH_SET_INIT_INT64(name) \ KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal) @@ -644,7 +647,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) @param khval_t Type of values [type] */ #define KHASH_MAP_INIT_UINT64(name, khval_t) \ - KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) + KHASH_INIT(name, khuint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) #define KHASH_MAP_INIT_INT64(name, khval_t) \ KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal) @@ -658,7 +661,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) KHASH_INIT(name, khint16_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) #define KHASH_MAP_INIT_UINT16(name, khval_t) \ - KHASH_INIT(name, khint16_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) + KHASH_INIT(name, khuint16_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) /*! @function @abstract Instantiate a hash map containing 8bit-integer keys @@ -669,7 +672,7 @@ PANDAS_INLINE khint_t __ac_Wang_hash(khint_t key) KHASH_INIT(name, khint8_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) #define KHASH_MAP_INIT_UINT8(name, khval_t) \ - KHASH_INIT(name, khint8_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) + KHASH_INIT(name, khuint8_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal) diff --git a/pandas/_libs/src/klib/khash_python.h b/pandas/_libs/src/klib/khash_python.h index 8e4e61b4f3077..c67eff21a1ab1 100644 --- a/pandas/_libs/src/klib/khash_python.h +++ b/pandas/_libs/src/klib/khash_python.h @@ -75,14 +75,14 @@ void traced_free(void* ptr){ // predisposed to superlinear running times (see GH 36729 for comparison) -khint64_t PANDAS_INLINE asint64(double key) { - khint64_t val; +khuint64_t PANDAS_INLINE asuint64(double key) { + khuint64_t val; memcpy(&val, &key, sizeof(double)); return val; } -khint32_t PANDAS_INLINE asint32(float key) { - khint32_t val; +khuint32_t PANDAS_INLINE asuint32(float key) { + khuint32_t val; memcpy(&val, &key, sizeof(float)); return val; } @@ -90,7 +90,7 @@ khint32_t PANDAS_INLINE asint32(float key) { #define ZERO_HASH 0 #define NAN_HASH 0 -khint32_t PANDAS_INLINE kh_float64_hash_func(double val){ +khuint32_t PANDAS_INLINE kh_float64_hash_func(double val){ // 0.0 and -0.0 should have the same hash: if (val == 0.0){ return ZERO_HASH; @@ -99,11 +99,11 @@ khint32_t PANDAS_INLINE kh_float64_hash_func(double val){ if ( val!=val ){ return NAN_HASH; } - khint64_t as_int = asint64(val); + khuint64_t as_int = asuint64(val); return murmur2_64to32(as_int); } -khint32_t PANDAS_INLINE kh_float32_hash_func(float val){ +khuint32_t PANDAS_INLINE kh_float32_hash_func(float val){ // 0.0 and -0.0 should have the same hash: if (val == 0.0f){ return ZERO_HASH; @@ -112,7 +112,7 @@ khint32_t PANDAS_INLINE kh_float32_hash_func(float val){ if ( val!=val ){ return NAN_HASH; } - khint32_t as_int = asint32(val); + khuint32_t as_int = asuint32(val); return murmur2_32to32(as_int); } @@ -186,15 +186,15 @@ p_kh_str_starts_t PANDAS_INLINE kh_init_str_starts(void) { return result; } -khint_t PANDAS_INLINE kh_put_str_starts_item(kh_str_starts_t* table, char* key, int* ret) { - khint_t result = kh_put_str(table->table, key, ret); +khuint_t PANDAS_INLINE kh_put_str_starts_item(kh_str_starts_t* table, char* key, int* ret) { + khuint_t result = kh_put_str(table->table, key, ret); if (*ret != 0) { table->starts[(unsigned char)key[0]] = 1; } return result; } -khint_t PANDAS_INLINE kh_get_str_starts_item(const kh_str_starts_t* table, const char* key) { +khuint_t PANDAS_INLINE kh_get_str_starts_item(const kh_str_starts_t* table, const char* key) { unsigned char ch = *key; if (table->starts[ch]) { if (ch == '\0' || kh_get_str(table->table, key) != table->table->n_buckets) return 1; @@ -207,6 +207,6 @@ void PANDAS_INLINE kh_destroy_str_starts(kh_str_starts_t* table) { KHASH_FREE(table); } -void PANDAS_INLINE kh_resize_str_starts(kh_str_starts_t* table, khint_t val) { +void PANDAS_INLINE kh_resize_str_starts(kh_str_starts_t* table, khuint_t val) { kh_resize_str(table->table, val); }
- [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` The goal of this PR is to make this comment obsolete: https://github.com/pandas-dev/pandas/blob/1fc5efd76ea1f85979fa2364a292d85482e338aa/pandas/_libs/src/klib/khash.h#L619-L624 see also [this discussion]( https://github.com/pandas-dev/pandas/pull/37920#discussion_r527191378) for even more details. The issue is: - the current way (inherited from khash-original) is too clever (and suprising) - it is wrong as the (unsigned) keys are converted back to signed values (which is implementation defined behavior) for example here: https://github.com/pandas-dev/pandas/blob/1fc5efd76ea1f85979fa2364a292d85482e338aa/pandas/_libs/hashtable_func_helper.pxi.in#L110 Using signed integer, one must take into account that hash-function with signed integers might have undefined/implementation defined behavior, thus we cast signed integers to unsigned counterpart in the (64bit-) hash function now.
https://api.github.com/repos/pandas-dev/pandas/pulls/38882
2021-01-01T20:56:10Z
2021-01-03T16:56:24Z
2021-01-03T16:56:24Z
2021-01-03T16:56:28Z
TST: add missing loc label indexing test
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 89315b16937b1..6c5cd0f335faa 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -56,9 +56,13 @@ def test_loc_getitem_label_out_of_range(self): self.check_result("loc", 20, typs=["floats"], axes=0, fails=KeyError) def test_loc_getitem_label_list(self): - # TODO: test something here? # list of labels - pass + self.check_result( + "loc", [0, 1, 2], typs=["ints", "uints", "floats"], fails=KeyError + ) + self.check_result( + "loc", [1, 3.0, "A"], typs=["ints", "uints", "floats"], fails=KeyError + ) def test_loc_getitem_label_list_with_missing(self): self.check_result("loc", [0, 1, 2], typs=["empty"], fails=KeyError)
- [x] xref #38824 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38880
2021-01-01T19:06:49Z
2021-01-03T17:17:59Z
2021-01-03T17:17:59Z
2023-09-21T16:53:33Z
BUG: silently ignoring dtype kwarg in Index.__new__
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 560f4fccd44fc..2b80fcdcdd0be 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -313,7 +313,7 @@ ExtensionArray Other ^^^^^ - +- Bug in :class:`Index` constructor sometimes silently ignorning a a specified ``dtype`` (:issue:`38879`) - - diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 5869b2cf22516..46aff11835cec 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -1529,6 +1529,19 @@ def is_extension_array_dtype(arr_or_dtype) -> bool: return isinstance(dtype, ExtensionDtype) or registry.find(dtype) is not None +def is_ea_or_datetimelike_dtype(dtype: Optional[DtypeObj]) -> bool: + """ + Check for ExtensionDtype, datetime64 dtype, or timedelta64 dtype. + + Notes + ----- + Checks only for dtype objects, not dtype-castable strings or types. + """ + return isinstance(dtype, ExtensionDtype) or ( + isinstance(dtype, np.dtype) and dtype.kind in ["m", "M"] + ) + + def is_complex_dtype(arr_or_dtype) -> bool: """ Check whether the provided array or dtype is of a complex dtype. diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 17ed42a188b4e..b0c89000a53a9 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -44,8 +44,8 @@ ensure_platform_int, is_bool_dtype, is_categorical_dtype, - is_datetime64_any_dtype, is_dtype_equal, + is_ea_or_datetimelike_dtype, is_extension_array_dtype, is_float, is_float_dtype, @@ -56,10 +56,8 @@ is_iterator, is_list_like, is_object_dtype, - is_period_dtype, is_scalar, is_signed_integer_dtype, - is_timedelta64_dtype, is_unsigned_integer_dtype, needs_i8_conversion, pandas_dtype, @@ -69,6 +67,7 @@ from pandas.core.dtypes.dtypes import ( CategoricalDtype, DatetimeTZDtype, + ExtensionDtype, IntervalDtype, PeriodDtype, ) @@ -87,6 +86,7 @@ import pandas.core.algorithms as algos from pandas.core.arrays import Categorical, ExtensionArray from pandas.core.arrays.datetimes import tz_to_dtype, validate_tz_from_dtype +from pandas.core.arrays.sparse import SparseDtype from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.construction import extract_array @@ -286,44 +286,32 @@ def __new__( # range if isinstance(data, RangeIndex): - return RangeIndex(start=data, copy=copy, dtype=dtype, name=name) + result = RangeIndex(start=data, copy=copy, name=name) + if dtype is not None: + return result.astype(dtype, copy=False) + return result elif isinstance(data, range): - return RangeIndex.from_range(data, dtype=dtype, name=name) - - # categorical - elif is_categorical_dtype(data_dtype) or is_categorical_dtype(dtype): - # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 - from pandas.core.indexes.category import CategoricalIndex - - return _maybe_asobject(dtype, CategoricalIndex, data, copy, name, **kwargs) - - # interval - elif is_interval_dtype(data_dtype) or is_interval_dtype(dtype): - # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 - from pandas.core.indexes.interval import IntervalIndex - - return _maybe_asobject(dtype, IntervalIndex, data, copy, name, **kwargs) - - elif is_datetime64_any_dtype(data_dtype) or is_datetime64_any_dtype(dtype): - # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 - from pandas import DatetimeIndex - - return _maybe_asobject(dtype, DatetimeIndex, data, copy, name, **kwargs) - - elif is_timedelta64_dtype(data_dtype) or is_timedelta64_dtype(dtype): - # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 - from pandas import TimedeltaIndex - - return _maybe_asobject(dtype, TimedeltaIndex, data, copy, name, **kwargs) - - elif is_period_dtype(data_dtype) or is_period_dtype(dtype): - # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 - from pandas import PeriodIndex + result = RangeIndex.from_range(data, name=name) + if dtype is not None: + return result.astype(dtype, copy=False) + return result - return _maybe_asobject(dtype, PeriodIndex, data, copy, name, **kwargs) + if is_ea_or_datetimelike_dtype(dtype): + # non-EA dtype indexes have special casting logic, so we punt here + klass = cls._dtype_to_subclass(dtype) + if klass is not Index: + return klass(data, dtype=dtype, copy=copy, name=name, **kwargs) + + if is_ea_or_datetimelike_dtype(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: + return result.astype(dtype, copy=False) + return result # extension dtype - elif is_extension_array_dtype(data_dtype) or is_extension_array_dtype(dtype): + if is_extension_array_dtype(data_dtype) or is_extension_array_dtype(dtype): if not (dtype is None or is_object_dtype(dtype)): # coerce to the provided dtype ea_cls = dtype.construct_array_type() @@ -407,26 +395,38 @@ def _ensure_array(cls, data, dtype, copy: bool): def _dtype_to_subclass(cls, dtype: DtypeObj): # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 - if isinstance(dtype, DatetimeTZDtype) or dtype == np.dtype("M8[ns]"): + if isinstance(dtype, ExtensionDtype): + if isinstance(dtype, DatetimeTZDtype): + from pandas import DatetimeIndex + + return DatetimeIndex + elif isinstance(dtype, CategoricalDtype): + from pandas import CategoricalIndex + + return CategoricalIndex + elif isinstance(dtype, IntervalDtype): + from pandas import IntervalIndex + + return IntervalIndex + elif isinstance(dtype, PeriodDtype): + from pandas import PeriodIndex + + return PeriodIndex + + elif isinstance(dtype, SparseDtype): + return cls._dtype_to_subclass(dtype.subtype) + + return Index + + if dtype.kind == "M": from pandas import DatetimeIndex return DatetimeIndex - elif dtype == "m8[ns]": + + elif dtype.kind == "m": from pandas import TimedeltaIndex return TimedeltaIndex - elif isinstance(dtype, CategoricalDtype): - from pandas import CategoricalIndex - - return CategoricalIndex - elif isinstance(dtype, IntervalDtype): - from pandas import IntervalIndex - - return IntervalIndex - elif isinstance(dtype, PeriodDtype): - from pandas import PeriodIndex - - return PeriodIndex elif is_float_dtype(dtype): from pandas import Float64Index @@ -445,6 +445,9 @@ def _dtype_to_subclass(cls, dtype: DtypeObj): # NB: assuming away MultiIndex return Index + elif issubclass(dtype.type, (str, bool, np.bool_)): + return Index + raise NotImplementedError(dtype) """ @@ -6253,43 +6256,6 @@ def _try_convert_to_int_array( raise ValueError -def _maybe_asobject(dtype, klass, data, copy: bool, name: Label, **kwargs): - """ - If an object dtype was specified, create the non-object Index - and then convert it to object. - - Parameters - ---------- - dtype : np.dtype, ExtensionDtype, str - klass : Index subclass - data : list-like - copy : bool - name : hashable - **kwargs - - Returns - ------- - Index - - Notes - ----- - We assume that calling .astype(object) on this klass will make a copy. - """ - - # GH#23524 passing `dtype=object` to DatetimeIndex is invalid, - # will raise in the where `data` is already tz-aware. So - # we leave it out of this step and cast to object-dtype after - # the DatetimeIndex construction. - - if is_dtype_equal(_o_dtype, dtype): - # Note we can pass copy=False because the .astype below - # will always make a copy - index = klass(data, copy=False, name=name, **kwargs) - return index.astype(object) - - return klass(data, dtype=dtype, copy=copy, name=name, **kwargs) - - def get_unanimous_names(*indexes: Index) -> Tuple[Label, ...]: """ Return common name if all indices agree, otherwise None (level-by-level). diff --git a/pandas/tests/indexes/ranges/test_constructors.py b/pandas/tests/indexes/ranges/test_constructors.py index 7dd893bd16720..f83c885a7850b 100644 --- a/pandas/tests/indexes/ranges/test_constructors.py +++ b/pandas/tests/indexes/ranges/test_constructors.py @@ -114,11 +114,6 @@ def test_constructor_range(self): expected = RangeIndex(1, 5, 2) tm.assert_index_equal(result, expected, exact=True) - with pytest.raises( - ValueError, - match="Incorrect `dtype` passed: expected signed integer, received float64", - ): - Index(range(1, 5, 2), dtype="float64") msg = r"^from_range\(\) got an unexpected keyword argument" with pytest.raises(TypeError, match=msg): RangeIndex.from_range(range(10), copy=True) diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py index c8f580babc0b2..de0850d37034d 100644 --- a/pandas/tests/indexes/test_index_new.py +++ b/pandas/tests/indexes/test_index_new.py @@ -8,10 +8,12 @@ from pandas import ( NA, + Categorical, CategoricalIndex, DatetimeIndex, Index, Int64Index, + IntervalIndex, MultiIndex, NaT, PeriodIndex, @@ -19,7 +21,9 @@ TimedeltaIndex, Timestamp, UInt64Index, + date_range, period_range, + timedelta_range, ) import pandas._testing as tm @@ -122,6 +126,80 @@ def test_constructor_mixed_nat_objs_infers_object(self, swap_objs): tm.assert_index_equal(Index(np.array(data, dtype=object)), expected) +class TestDtypeEnforced: + # check we don't silently ignore the dtype keyword + + @pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"]) + def test_constructor_range_values_mismatched_dtype(self, dtype): + rng = Index(range(5)) + + result = Index(rng, dtype=dtype) + assert result.dtype == dtype + + result = Index(range(5), dtype=dtype) + assert result.dtype == dtype + + @pytest.mark.parametrize("dtype", [object, "float64", "uint64", "category"]) + def test_constructor_categorical_values_mismatched_non_ea_dtype(self, dtype): + cat = Categorical([1, 2, 3]) + + result = Index(cat, dtype=dtype) + assert result.dtype == dtype + + def test_constructor_categorical_values_mismatched_dtype(self): + dti = date_range("2016-01-01", periods=3) + cat = Categorical(dti) + result = Index(cat, dti.dtype) + tm.assert_index_equal(result, dti) + + dti2 = dti.tz_localize("Asia/Tokyo") + cat2 = Categorical(dti2) + result = Index(cat2, dti2.dtype) + tm.assert_index_equal(result, dti2) + + ii = IntervalIndex.from_breaks(range(5)) + cat3 = Categorical(ii) + result = Index(cat3, dtype=ii.dtype) + tm.assert_index_equal(result, ii) + + def test_constructor_ea_values_mismatched_categorical_dtype(self): + dti = date_range("2016-01-01", periods=3) + result = Index(dti, dtype="category") + expected = CategoricalIndex(dti) + tm.assert_index_equal(result, expected) + + dti2 = date_range("2016-01-01", periods=3, tz="US/Pacific") + result = Index(dti2, dtype="category") + expected = CategoricalIndex(dti2) + tm.assert_index_equal(result, expected) + + def test_constructor_period_values_mismatched_dtype(self): + pi = period_range("2016-01-01", periods=3, freq="D") + result = Index(pi, dtype="category") + expected = CategoricalIndex(pi) + tm.assert_index_equal(result, expected) + + def test_constructor_timedelta64_values_mismatched_dtype(self): + # check we don't silently ignore the dtype keyword + tdi = timedelta_range("4 Days", periods=5) + result = Index(tdi, dtype="category") + expected = CategoricalIndex(tdi) + tm.assert_index_equal(result, expected) + + def test_constructor_interval_values_mismatched_dtype(self): + dti = date_range("2016-01-01", periods=3) + ii = IntervalIndex.from_breaks(dti) + result = Index(ii, dtype="category") + expected = CategoricalIndex(ii) + tm.assert_index_equal(result, expected) + + def test_constructor_datetime64_values_mismatched_period_dtype(self): + dti = date_range("2016-01-01", periods=3) + result = Index(dti, dtype="Period[D]") + expected = dti.to_period("D") + tm.assert_index_equal(result, expected) + + class TestIndexConstructorUnwrapping: # Test passing different arraylike values to pd.Index
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry ATM we handle object but not others, xref #21311
https://api.github.com/repos/pandas-dev/pandas/pulls/38879
2021-01-01T18:37:36Z
2021-01-01T23:02:18Z
2021-01-01T23:02:18Z
2021-01-02T01:37:47Z
TST: Series.update with categorical
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index 8ba8562affb67..410731820dc73 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -218,6 +218,12 @@ def test_repr_range_categories(self): expected = "CategoricalDtype(categories=range(0, 3), ordered=False)" assert result == expected + def test_update_dtype(self): + # GH 27338 + result = CategoricalDtype(["a"]).update_dtype(Categorical(["b"], ordered=True)) + expected = CategoricalDtype(["b"], ordered=True) + assert result == expected + class TestDatetimeTZDtype(Base): @pytest.fixture diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py index d00a4299cb690..51760c451ebca 100644 --- a/pandas/tests/series/methods/test_update.py +++ b/pandas/tests/series/methods/test_update.py @@ -108,3 +108,13 @@ def test_update_from_non_series(self, series, other, expected): def test_update_extension_array_series(self, result, target, expected): result.update(target) tm.assert_series_equal(result, expected) + + def test_update_with_categorical_type(self): + # GH 25744 + dtype = CategoricalDtype(["a", "b", "c", "d"]) + s1 = Series(["a", "b", "c"], index=[1, 2, 3], dtype=dtype) + s2 = Series(["b", "a"], index=[1, 2], dtype=dtype) + s1.update(s2) + result = s1 + expected = Series(["b", "a", "c"], index=[1, 2, 3], dtype=dtype) + tm.assert_series_equal(result, expected)
- [ ] closes #25744, closes #27338 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38873
2021-01-01T08:35:16Z
2021-01-03T17:10:42Z
2021-01-03T17:10:41Z
2021-01-03T17:10:45Z
TST: move generic/methods/ files to frame/methods/
diff --git a/doc/source/development/test_writing.rst b/doc/source/development/test_writing.rst index d9e24bb76eed8..76eae505471b7 100644 --- a/doc/source/development/test_writing.rst +++ b/doc/source/development/test_writing.rst @@ -149,13 +149,6 @@ be located. ``frame_or_series`` fixture, by convention it goes in the ``tests.frame`` file. - - tests.generic.methods.test_mymethod - - .. note:: - - The generic/methods/ directory is only for methods with tests - that are fully parametrized over Series/DataFrame - 7. Is your test for an Index method, not depending on Series/DataFrame? This test likely belongs in one of: diff --git a/pandas/tests/generic/methods/test_dot.py b/pandas/tests/frame/methods/test_dot.py similarity index 100% rename from pandas/tests/generic/methods/test_dot.py rename to pandas/tests/frame/methods/test_dot.py diff --git a/pandas/tests/generic/methods/test_first_valid_index.py b/pandas/tests/frame/methods/test_first_valid_index.py similarity index 100% rename from pandas/tests/generic/methods/test_first_valid_index.py rename to pandas/tests/frame/methods/test_first_valid_index.py diff --git a/pandas/tests/generic/methods/test_pipe.py b/pandas/tests/frame/methods/test_pipe.py similarity index 100% rename from pandas/tests/generic/methods/test_pipe.py rename to pandas/tests/frame/methods/test_pipe.py diff --git a/pandas/tests/generic/methods/test_reorder_levels.py b/pandas/tests/frame/methods/test_reorder_levels.py similarity index 100% rename from pandas/tests/generic/methods/test_reorder_levels.py rename to pandas/tests/frame/methods/test_reorder_levels.py diff --git a/pandas/tests/generic/methods/test_sample.py b/pandas/tests/frame/methods/test_sample.py similarity index 100% rename from pandas/tests/generic/methods/test_sample.py rename to pandas/tests/frame/methods/test_sample.py diff --git a/pandas/tests/generic/methods/test_set_axis.py b/pandas/tests/frame/methods/test_set_axis.py similarity index 100% rename from pandas/tests/generic/methods/test_set_axis.py rename to pandas/tests/frame/methods/test_set_axis.py diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py index e83882be9c680..2c96cf291c154 100644 --- a/pandas/tests/frame/methods/test_to_records.py +++ b/pandas/tests/frame/methods/test_to_records.py @@ -15,6 +15,15 @@ class TestDataFrameToRecords: + def test_to_records_timeseries(self): + index = date_range("1/1/2000", periods=10) + df = DataFrame(np.random.randn(10, 3), index=index, columns=["a", "b", "c"]) + + result = df.to_records() + assert result["index"].dtype == "M8[ns]" + + result = df.to_records(index=False) + def test_to_records_dt64(self): df = DataFrame( [["one", "two", "three"], ["four", "five", "six"]], diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index a16dca256541d..4d57b43df2387 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2221,15 +2221,6 @@ def test_frame_datetime64_mixed_index_ctor_1681(self): d = DataFrame({"A": "foo", "B": ts}, index=dr) assert d["B"].isna().all() - def test_frame_timeseries_to_records(self): - index = date_range("1/1/2000", periods=10) - df = DataFrame(np.random.randn(10, 3), index=index, columns=["a", "b", "c"]) - - result = df.to_records() - result["index"].dtype == "M8[ns]" - - result = df.to_records(index=False) - def test_frame_timeseries_column(self): # GH19157 dr = date_range(start="20130101T10:00:00", periods=3, freq="T", tz="US/Eastern") diff --git a/pandas/tests/generic/methods/__init__.py b/pandas/tests/generic/methods/__init__.py deleted file mode 100644 index 5d18f97b8a55e..0000000000000 --- a/pandas/tests/generic/methods/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -""" -Tests for methods shared by DataFrame and Series. -"""
https://api.github.com/repos/pandas-dev/pandas/pulls/38871
2021-01-01T03:04:28Z
2021-01-01T20:38:59Z
2021-01-01T20:38:59Z
2021-01-01T21:11:38Z
TST/REF: implement tests.frame.constructors
diff --git a/pandas/tests/frame/constructors/__init__.py b/pandas/tests/frame/constructors/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/frame/constructors/test_from_dict.py b/pandas/tests/frame/constructors/test_from_dict.py new file mode 100644 index 0000000000000..6c9e6751fd9a4 --- /dev/null +++ b/pandas/tests/frame/constructors/test_from_dict.py @@ -0,0 +1,186 @@ +from collections import OrderedDict + +import numpy as np +import pytest + +from pandas import DataFrame, Index, MultiIndex, Series +import pandas._testing as tm +from pandas.core.construction import create_series_with_explicit_dtype + + +class TestFromDict: + # Note: these tests are specific to the from_dict method, not for + # passing dictionaries to DataFrame.__init__ + + def test_from_dict_scalars_requires_index(self): + msg = "If using all scalar values, you must pass an index" + with pytest.raises(ValueError, match=msg): + DataFrame.from_dict(OrderedDict([("b", 8), ("a", 5), ("a", 6)])) + + def test_constructor_list_of_odicts(self): + data = [ + OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]), + OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]), + OrderedDict([["a", 1.5], ["d", 6]]), + OrderedDict(), + OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]), + OrderedDict([["b", 3], ["c", 4], ["d", 6]]), + ] + + result = DataFrame(data) + expected = DataFrame.from_dict( + dict(zip(range(len(data)), data)), orient="index" + ) + tm.assert_frame_equal(result, expected.reindex(result.index)) + + def test_constructor_single_row(self): + data = [OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]])] + + result = DataFrame(data) + expected = DataFrame.from_dict(dict(zip([0], data)), orient="index").reindex( + result.index + ) + tm.assert_frame_equal(result, expected) + + def test_constructor_list_of_series(self): + data = [ + OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]), + OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]), + ] + sdict = OrderedDict(zip(["x", "y"], data)) + idx = Index(["a", "b", "c"]) + + # all named + data2 = [ + Series([1.5, 3, 4], idx, dtype="O", name="x"), + Series([1.5, 3, 6], idx, name="y"), + ] + result = DataFrame(data2) + expected = DataFrame.from_dict(sdict, orient="index") + tm.assert_frame_equal(result, expected) + + # some unnamed + data2 = [ + Series([1.5, 3, 4], idx, dtype="O", name="x"), + Series([1.5, 3, 6], idx), + ] + result = DataFrame(data2) + + sdict = OrderedDict(zip(["x", "Unnamed 0"], data)) + expected = DataFrame.from_dict(sdict, orient="index") + tm.assert_frame_equal(result, expected) + + # none named + data = [ + OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]), + OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]), + OrderedDict([["a", 1.5], ["d", 6]]), + OrderedDict(), + OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]), + OrderedDict([["b", 3], ["c", 4], ["d", 6]]), + ] + data = [ + create_series_with_explicit_dtype(d, dtype_if_empty=object) for d in data + ] + + result = DataFrame(data) + sdict = OrderedDict(zip(range(len(data)), data)) + expected = DataFrame.from_dict(sdict, orient="index") + tm.assert_frame_equal(result, expected.reindex(result.index)) + + result2 = DataFrame(data, index=np.arange(6)) + tm.assert_frame_equal(result, result2) + + result = DataFrame([Series(dtype=object)]) + expected = DataFrame(index=[0]) + tm.assert_frame_equal(result, expected) + + data = [ + OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]), + OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]), + ] + sdict = OrderedDict(zip(range(len(data)), data)) + + idx = Index(["a", "b", "c"]) + data2 = [Series([1.5, 3, 4], idx, dtype="O"), Series([1.5, 3, 6], idx)] + result = DataFrame(data2) + expected = DataFrame.from_dict(sdict, orient="index") + tm.assert_frame_equal(result, expected) + + def test_constructor_orient(self, float_string_frame): + data_dict = float_string_frame.T._series + recons = DataFrame.from_dict(data_dict, orient="index") + expected = float_string_frame.reindex(index=recons.index) + tm.assert_frame_equal(recons, expected) + + # dict of sequence + a = {"hi": [32, 3, 3], "there": [3, 5, 3]} + rs = DataFrame.from_dict(a, orient="index") + xp = DataFrame.from_dict(a).T.reindex(list(a.keys())) + tm.assert_frame_equal(rs, xp) + + def test_constructor_from_ordered_dict(self): + # GH#8425 + a = OrderedDict( + [ + ("one", OrderedDict([("col_a", "foo1"), ("col_b", "bar1")])), + ("two", OrderedDict([("col_a", "foo2"), ("col_b", "bar2")])), + ("three", OrderedDict([("col_a", "foo3"), ("col_b", "bar3")])), + ] + ) + expected = DataFrame.from_dict(a, orient="columns").T + result = DataFrame.from_dict(a, orient="index") + tm.assert_frame_equal(result, expected) + + def test_from_dict_columns_parameter(self): + # GH#18529 + # Test new columns parameter for from_dict that was added to make + # from_items(..., orient='index', columns=[...]) easier to replicate + result = DataFrame.from_dict( + OrderedDict([("A", [1, 2]), ("B", [4, 5])]), + orient="index", + columns=["one", "two"], + ) + expected = DataFrame([[1, 2], [4, 5]], index=["A", "B"], columns=["one", "two"]) + tm.assert_frame_equal(result, expected) + + msg = "cannot use columns parameter with orient='columns'" + with pytest.raises(ValueError, match=msg): + DataFrame.from_dict( + {"A": [1, 2], "B": [4, 5]}, + orient="columns", + columns=["one", "two"], + ) + with pytest.raises(ValueError, match=msg): + DataFrame.from_dict({"A": [1, 2], "B": [4, 5]}, columns=["one", "two"]) + + @pytest.mark.parametrize( + "data_dict, keys, orient", + [ + ({}, [], "index"), + ([{("a",): 1}, {("a",): 2}], [("a",)], "columns"), + ([OrderedDict([(("a",), 1), (("b",), 2)])], [("a",), ("b",)], "columns"), + ([{("a", "b"): 1}], [("a", "b")], "columns"), + ], + ) + def test_constructor_from_dict_tuples(self, data_dict, keys, orient): + # GH#16769 + df = DataFrame.from_dict(data_dict, orient) + + result = df.columns + expected = Index(keys, dtype="object", tupleize_cols=False) + + tm.assert_index_equal(result, expected) + + def test_frame_dict_constructor_empty_series(self): + s1 = Series( + [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)]) + ) + s2 = Series( + [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)]) + ) + s3 = Series(dtype=object) + + # it works! + DataFrame({"foo": s1, "bar": s2, "baz": s3}) + DataFrame.from_dict({"foo": s1, "baz": s3, "bar": s2}) diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py new file mode 100644 index 0000000000000..ed6333bac1caa --- /dev/null +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -0,0 +1,440 @@ +from datetime import datetime +from decimal import Decimal + +import numpy as np +import pytest +import pytz + +from pandas.compat import is_platform_little_endian + +from pandas import CategoricalIndex, DataFrame, Index, Interval, RangeIndex, Series +import pandas._testing as tm + + +class TestFromRecords: + def test_from_records_with_datetimes(self): + + # this may fail on certain platforms because of a numpy issue + # related GH#6140 + if not is_platform_little_endian(): + pytest.skip("known failure of test on non-little endian") + + # construction with a null in a recarray + # GH#6140 + expected = DataFrame({"EXPIRY": [datetime(2005, 3, 1, 0, 0), None]}) + + arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] + dtypes = [("EXPIRY", "<M8[ns]")] + + try: + recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + except (ValueError): + pytest.skip("known failure of numpy rec array creation") + + result = DataFrame.from_records(recarray) + tm.assert_frame_equal(result, expected) + + # coercion should work too + arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] + dtypes = [("EXPIRY", "<M8[m]")] + recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) + result = DataFrame.from_records(recarray) + tm.assert_frame_equal(result, expected) + + def test_from_records_sequencelike(self): + df = DataFrame( + { + "A": np.array(np.random.randn(6), dtype=np.float64), + "A1": np.array(np.random.randn(6), dtype=np.float64), + "B": np.array(np.arange(6), dtype=np.int64), + "C": ["foo"] * 6, + "D": np.array([True, False] * 3, dtype=bool), + "E": np.array(np.random.randn(6), dtype=np.float32), + "E1": np.array(np.random.randn(6), dtype=np.float32), + "F": np.array(np.arange(6), dtype=np.int32), + } + ) + + # this is actually tricky to create the recordlike arrays and + # have the dtypes be intact + blocks = df._to_dict_of_blocks() + tuples = [] + columns = [] + dtypes = [] + for dtype, b in blocks.items(): + columns.extend(b.columns) + dtypes.extend([(c, np.dtype(dtype).descr[0][1]) for c in b.columns]) + for i in range(len(df.index)): + tup = [] + for _, b in blocks.items(): + tup.extend(b.iloc[i].values) + tuples.append(tuple(tup)) + + recarray = np.array(tuples, dtype=dtypes).view(np.recarray) + recarray2 = df.to_records() + lists = [list(x) for x in tuples] + + # tuples (lose the dtype info) + result = DataFrame.from_records(tuples, columns=columns).reindex( + columns=df.columns + ) + + # created recarray and with to_records recarray (have dtype info) + result2 = DataFrame.from_records(recarray, columns=columns).reindex( + columns=df.columns + ) + result3 = DataFrame.from_records(recarray2, columns=columns).reindex( + columns=df.columns + ) + + # list of tupels (no dtype info) + result4 = DataFrame.from_records(lists, columns=columns).reindex( + columns=df.columns + ) + + tm.assert_frame_equal(result, df, check_dtype=False) + tm.assert_frame_equal(result2, df) + tm.assert_frame_equal(result3, df) + tm.assert_frame_equal(result4, df, check_dtype=False) + + # tuples is in the order of the columns + result = DataFrame.from_records(tuples) + tm.assert_index_equal(result.columns, RangeIndex(8)) + + # test exclude parameter & we are casting the results here (as we don't + # have dtype info to recover) + columns_to_test = [columns.index("C"), columns.index("E1")] + + exclude = list(set(range(8)) - set(columns_to_test)) + result = DataFrame.from_records(tuples, exclude=exclude) + result.columns = [columns[i] for i in sorted(columns_to_test)] + tm.assert_series_equal(result["C"], df["C"]) + tm.assert_series_equal(result["E1"], df["E1"].astype("float64")) + + # empty case + result = DataFrame.from_records([], columns=["foo", "bar", "baz"]) + assert len(result) == 0 + tm.assert_index_equal(result.columns, Index(["foo", "bar", "baz"])) + + result = DataFrame.from_records([]) + assert len(result) == 0 + assert len(result.columns) == 0 + + def test_from_records_dictlike(self): + + # test the dict methods + df = DataFrame( + { + "A": np.array(np.random.randn(6), dtype=np.float64), + "A1": np.array(np.random.randn(6), dtype=np.float64), + "B": np.array(np.arange(6), dtype=np.int64), + "C": ["foo"] * 6, + "D": np.array([True, False] * 3, dtype=bool), + "E": np.array(np.random.randn(6), dtype=np.float32), + "E1": np.array(np.random.randn(6), dtype=np.float32), + "F": np.array(np.arange(6), dtype=np.int32), + } + ) + + # columns is in a different order here than the actual items iterated + # from the dict + blocks = df._to_dict_of_blocks() + columns = [] + for dtype, b in blocks.items(): + columns.extend(b.columns) + + asdict = {x: y for x, y in df.items()} + asdict2 = {x: y.values for x, y in df.items()} + + # dict of series & dict of ndarrays (have dtype info) + results = [] + results.append(DataFrame.from_records(asdict).reindex(columns=df.columns)) + results.append( + DataFrame.from_records(asdict, columns=columns).reindex(columns=df.columns) + ) + results.append( + DataFrame.from_records(asdict2, columns=columns).reindex(columns=df.columns) + ) + + for r in results: + tm.assert_frame_equal(r, df) + + def test_from_records_with_index_data(self): + df = DataFrame(np.random.randn(10, 3), columns=["A", "B", "C"]) + + data = np.random.randn(10) + df1 = DataFrame.from_records(df, index=data) + tm.assert_index_equal(df1.index, Index(data)) + + def test_from_records_bad_index_column(self): + df = DataFrame(np.random.randn(10, 3), columns=["A", "B", "C"]) + + # should pass + df1 = DataFrame.from_records(df, index=["C"]) + tm.assert_index_equal(df1.index, Index(df.C)) + + df1 = DataFrame.from_records(df, index="C") + tm.assert_index_equal(df1.index, Index(df.C)) + + # should fail + msg = r"Shape of passed values is \(10, 3\), indices imply \(1, 3\)" + with pytest.raises(ValueError, match=msg): + DataFrame.from_records(df, index=[2]) + with pytest.raises(KeyError, match=r"^2$"): + DataFrame.from_records(df, index=2) + + def test_from_records_non_tuple(self): + class Record: + def __init__(self, *args): + self.args = args + + def __getitem__(self, i): + return self.args[i] + + def __iter__(self): + return iter(self.args) + + recs = [Record(1, 2, 3), Record(4, 5, 6), Record(7, 8, 9)] + tups = [tuple(rec) for rec in recs] + + result = DataFrame.from_records(recs) + expected = DataFrame.from_records(tups) + tm.assert_frame_equal(result, expected) + + def test_from_records_len0_with_columns(self): + # GH#2633 + result = DataFrame.from_records([], index="foo", columns=["foo", "bar"]) + expected = Index(["bar"]) + + assert len(result) == 0 + assert result.index.name == "foo" + tm.assert_index_equal(result.columns, expected) + + def test_from_records_series_list_dict(self): + # GH#27358 + expected = DataFrame([[{"a": 1, "b": 2}, {"a": 3, "b": 4}]]).T + data = Series([[{"a": 1, "b": 2}], [{"a": 3, "b": 4}]]) + result = DataFrame.from_records(data) + tm.assert_frame_equal(result, expected) + + def test_from_records_series_categorical_index(self): + # GH#32805 + index = CategoricalIndex( + [Interval(-20, -10), Interval(-10, 0), Interval(0, 10)] + ) + series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index) + frame = DataFrame.from_records(series_of_dicts, index=index) + expected = DataFrame( + {"a": [1, 2, np.NaN], "b": [np.NaN, np.NaN, 3]}, index=index + ) + tm.assert_frame_equal(frame, expected) + + def test_frame_from_records_utc(self): + rec = {"datum": 1.5, "begin_time": datetime(2006, 4, 27, tzinfo=pytz.utc)} + + # it works + DataFrame.from_records([rec], index="begin_time") + + def test_from_records_to_records(self): + # from numpy documentation + arr = np.zeros((2,), dtype=("i4,f4,a10")) + arr[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")] + + # TODO(wesm): unused + frame = DataFrame.from_records(arr) # noqa + + index = Index(np.arange(len(arr))[::-1]) + indexed_frame = DataFrame.from_records(arr, index=index) + tm.assert_index_equal(indexed_frame.index, index) + + # without names, it should go to last ditch + arr2 = np.zeros((2, 3)) + tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2)) + + # wrong length + msg = r"Shape of passed values is \(2, 3\), indices imply \(1, 3\)" + with pytest.raises(ValueError, match=msg): + DataFrame.from_records(arr, index=index[:-1]) + + indexed_frame = DataFrame.from_records(arr, index="f1") + + # what to do? + records = indexed_frame.to_records() + assert len(records.dtype.names) == 3 + + records = indexed_frame.to_records(index=False) + assert len(records.dtype.names) == 2 + assert "index" not in records.dtype.names + + def test_from_records_nones(self): + tuples = [(1, 2, None, 3), (1, 2, None, 3), (None, 2, 5, 3)] + + df = DataFrame.from_records(tuples, columns=["a", "b", "c", "d"]) + assert np.isnan(df["c"][0]) + + def test_from_records_iterator(self): + arr = np.array( + [(1.0, 1.0, 2, 2), (3.0, 3.0, 4, 4), (5.0, 5.0, 6, 6), (7.0, 7.0, 8, 8)], + dtype=[ + ("x", np.float64), + ("u", np.float32), + ("y", np.int64), + ("z", np.int32), + ], + ) + df = DataFrame.from_records(iter(arr), nrows=2) + xp = DataFrame( + { + "x": np.array([1.0, 3.0], dtype=np.float64), + "u": np.array([1.0, 3.0], dtype=np.float32), + "y": np.array([2, 4], dtype=np.int64), + "z": np.array([2, 4], dtype=np.int32), + } + ) + tm.assert_frame_equal(df.reindex_like(xp), xp) + + # no dtypes specified here, so just compare with the default + arr = [(1.0, 2), (3.0, 4), (5.0, 6), (7.0, 8)] + df = DataFrame.from_records(iter(arr), columns=["x", "y"], nrows=2) + tm.assert_frame_equal(df, xp.reindex(columns=["x", "y"]), check_dtype=False) + + def test_from_records_tuples_generator(self): + def tuple_generator(length): + for i in range(length): + letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + yield (i, letters[i % len(letters)], i / length) + + columns_names = ["Integer", "String", "Float"] + columns = [ + [i[j] for i in tuple_generator(10)] for j in range(len(columns_names)) + ] + data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]} + expected = DataFrame(data, columns=columns_names) + + generator = tuple_generator(10) + result = DataFrame.from_records(generator, columns=columns_names) + tm.assert_frame_equal(result, expected) + + def test_from_records_lists_generator(self): + def list_generator(length): + for i in range(length): + letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + yield [i, letters[i % len(letters)], i / length] + + columns_names = ["Integer", "String", "Float"] + columns = [ + [i[j] for i in list_generator(10)] for j in range(len(columns_names)) + ] + data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]} + expected = DataFrame(data, columns=columns_names) + + generator = list_generator(10) + result = DataFrame.from_records(generator, columns=columns_names) + tm.assert_frame_equal(result, expected) + + def test_from_records_columns_not_modified(self): + tuples = [(1, 2, 3), (1, 2, 3), (2, 5, 3)] + + columns = ["a", "b", "c"] + original_columns = list(columns) + + df = DataFrame.from_records(tuples, columns=columns, index="a") # noqa + + assert columns == original_columns + + def test_from_records_decimal(self): + + tuples = [(Decimal("1.5"),), (Decimal("2.5"),), (None,)] + + df = DataFrame.from_records(tuples, columns=["a"]) + assert df["a"].dtype == object + + df = DataFrame.from_records(tuples, columns=["a"], coerce_float=True) + assert df["a"].dtype == np.float64 + assert np.isnan(df["a"].values[-1]) + + def test_from_records_duplicates(self): + result = DataFrame.from_records([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"]) + + expected = DataFrame([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"]) + + tm.assert_frame_equal(result, expected) + + def test_from_records_set_index_name(self): + def create_dict(order_id): + return { + "order_id": order_id, + "quantity": np.random.randint(1, 10), + "price": np.random.randint(1, 10), + } + + documents = [create_dict(i) for i in range(10)] + # demo missing data + documents.append({"order_id": 10, "quantity": 5}) + + result = DataFrame.from_records(documents, index="order_id") + assert result.index.name == "order_id" + + # MultiIndex + result = DataFrame.from_records(documents, index=["order_id", "quantity"]) + assert result.index.names == ("order_id", "quantity") + + def test_from_records_misc_brokenness(self): + # GH#2179 + + data = {1: ["foo"], 2: ["bar"]} + + result = DataFrame.from_records(data, columns=["a", "b"]) + exp = DataFrame(data, columns=["a", "b"]) + tm.assert_frame_equal(result, exp) + + # overlap in index/index_names + + data = {"a": [1, 2, 3], "b": [4, 5, 6]} + + result = DataFrame.from_records(data, index=["a", "b", "c"]) + exp = DataFrame(data, index=["a", "b", "c"]) + tm.assert_frame_equal(result, exp) + + # GH#2623 + rows = [] + rows.append([datetime(2010, 1, 1), 1]) + rows.append([datetime(2010, 1, 2), "hi"]) # test col upconverts to obj + df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) + result = df2_obj.dtypes + expected = Series( + [np.dtype("datetime64[ns]"), np.dtype("object")], index=["date", "test"] + ) + tm.assert_series_equal(result, expected) + + rows = [] + rows.append([datetime(2010, 1, 1), 1]) + rows.append([datetime(2010, 1, 2), 1]) + df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) + result = df2_obj.dtypes + expected = Series( + [np.dtype("datetime64[ns]"), np.dtype("int64")], index=["date", "test"] + ) + tm.assert_series_equal(result, expected) + + def test_from_records_empty(self): + # GH#3562 + result = DataFrame.from_records([], columns=["a", "b", "c"]) + expected = DataFrame(columns=["a", "b", "c"]) + tm.assert_frame_equal(result, expected) + + result = DataFrame.from_records([], columns=["a", "b", "b"]) + expected = DataFrame(columns=["a", "b", "b"]) + tm.assert_frame_equal(result, expected) + + def test_from_records_empty_with_nonempty_fields_gh3682(self): + a = np.array([(1, 2)], dtype=[("id", np.int64), ("value", np.int64)]) + df = DataFrame.from_records(a, index="id") + tm.assert_index_equal(df.index, Index([1], name="id")) + assert df.index.name == "id" + tm.assert_index_equal(df.columns, Index(["value"])) + + b = np.array([], dtype=[("id", np.int64), ("value", np.int64)]) + df = DataFrame.from_records(b, index="id") + tm.assert_index_equal(df.index, Index([], name="id")) + assert df.index.name == "id" diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 94b2431650359..d8308e9988107 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -10,7 +10,6 @@ import pytest import pytz -from pandas.compat import is_platform_little_endian from pandas.compat.numpy import _np_version_under1p19, _np_version_under1p20 from pandas.core.dtypes.common import is_integer_dtype @@ -34,7 +33,6 @@ ) import pandas._testing as tm from pandas.arrays import IntervalArray, PeriodArray, SparseArray -from pandas.core.construction import create_series_with_explicit_dtype MIXED_FLOAT_DTYPES = ["float16", "float32", "float64"] MIXED_INT_DTYPES = [ @@ -1209,35 +1207,12 @@ def test_constructor_generator(self): expected = DataFrame({0: range(10), 1: "a"}) tm.assert_frame_equal(result, expected, check_dtype=False) - def test_constructor_list_of_odicts(self): - data = [ - OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]), - OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]), - OrderedDict([["a", 1.5], ["d", 6]]), - OrderedDict(), - OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]), - OrderedDict([["b", 3], ["c", 4], ["d", 6]]), - ] - - result = DataFrame(data) - expected = DataFrame.from_dict( - dict(zip(range(len(data)), data)), orient="index" - ) - tm.assert_frame_equal(result, expected.reindex(result.index)) + def test_constructor_list_of_dicts(self): result = DataFrame([{}]) expected = DataFrame(index=[0]) tm.assert_frame_equal(result, expected) - def test_constructor_single_row(self): - data = [OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]])] - - result = DataFrame(data) - expected = DataFrame.from_dict(dict(zip([0], data)), orient="index").reindex( - result.index - ) - tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize("dict_type", [dict, OrderedDict]) def test_constructor_ordered_dict_preserve_order(self, dict_type): # see gh-13304 @@ -1279,71 +1254,6 @@ def test_constructor_ordered_dict_conflicting_orders(self, dict_type): result = DataFrame([row_one, row_two, row_three]) tm.assert_frame_equal(result, expected) - def test_constructor_list_of_series(self): - data = [ - OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]), - OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]), - ] - sdict = OrderedDict(zip(["x", "y"], data)) - idx = Index(["a", "b", "c"]) - - # all named - data2 = [ - Series([1.5, 3, 4], idx, dtype="O", name="x"), - Series([1.5, 3, 6], idx, name="y"), - ] - result = DataFrame(data2) - expected = DataFrame.from_dict(sdict, orient="index") - tm.assert_frame_equal(result, expected) - - # some unnamed - data2 = [ - Series([1.5, 3, 4], idx, dtype="O", name="x"), - Series([1.5, 3, 6], idx), - ] - result = DataFrame(data2) - - sdict = OrderedDict(zip(["x", "Unnamed 0"], data)) - expected = DataFrame.from_dict(sdict, orient="index") - tm.assert_frame_equal(result, expected) - - # none named - data = [ - OrderedDict([["a", 1.5], ["b", 3], ["c", 4], ["d", 6]]), - OrderedDict([["a", 1.5], ["b", 3], ["d", 6]]), - OrderedDict([["a", 1.5], ["d", 6]]), - OrderedDict(), - OrderedDict([["a", 1.5], ["b", 3], ["c", 4]]), - OrderedDict([["b", 3], ["c", 4], ["d", 6]]), - ] - data = [ - create_series_with_explicit_dtype(d, dtype_if_empty=object) for d in data - ] - - result = DataFrame(data) - sdict = OrderedDict(zip(range(len(data)), data)) - expected = DataFrame.from_dict(sdict, orient="index") - tm.assert_frame_equal(result, expected.reindex(result.index)) - - result2 = DataFrame(data, index=np.arange(6)) - tm.assert_frame_equal(result, result2) - - result = DataFrame([Series(dtype=object)]) - expected = DataFrame(index=[0]) - tm.assert_frame_equal(result, expected) - - data = [ - OrderedDict([["a", 1.5], ["b", 3.0], ["c", 4.0]]), - OrderedDict([["a", 1.5], ["b", 3.0], ["c", 6.0]]), - ] - sdict = OrderedDict(zip(range(len(data)), data)) - - idx = Index(["a", "b", "c"]) - data2 = [Series([1.5, 3, 4], idx, dtype="O"), Series([1.5, 3, 6], idx)] - result = DataFrame(data2) - expected = DataFrame.from_dict(sdict, orient="index") - tm.assert_frame_equal(result, expected) - def test_constructor_list_of_series_aligned_index(self): series = [Series(i, index=["b", "a", "c"], name=str(i)) for i in range(3)] result = DataFrame(series) @@ -1502,84 +1412,6 @@ def test_constructor_list_of_dict_order(self): result = DataFrame(data) tm.assert_frame_equal(result, expected) - def test_constructor_orient(self, float_string_frame): - data_dict = float_string_frame.T._series - recons = DataFrame.from_dict(data_dict, orient="index") - expected = float_string_frame.reindex(index=recons.index) - tm.assert_frame_equal(recons, expected) - - # dict of sequence - a = {"hi": [32, 3, 3], "there": [3, 5, 3]} - rs = DataFrame.from_dict(a, orient="index") - xp = DataFrame.from_dict(a).T.reindex(list(a.keys())) - tm.assert_frame_equal(rs, xp) - - def test_constructor_from_ordered_dict(self): - # GH8425 - a = OrderedDict( - [ - ("one", OrderedDict([("col_a", "foo1"), ("col_b", "bar1")])), - ("two", OrderedDict([("col_a", "foo2"), ("col_b", "bar2")])), - ("three", OrderedDict([("col_a", "foo3"), ("col_b", "bar3")])), - ] - ) - expected = DataFrame.from_dict(a, orient="columns").T - result = DataFrame.from_dict(a, orient="index") - tm.assert_frame_equal(result, expected) - - def test_from_dict_columns_parameter(self): - # GH 18529 - # Test new columns parameter for from_dict that was added to make - # from_items(..., orient='index', columns=[...]) easier to replicate - result = DataFrame.from_dict( - OrderedDict([("A", [1, 2]), ("B", [4, 5])]), - orient="index", - columns=["one", "two"], - ) - expected = DataFrame([[1, 2], [4, 5]], index=["A", "B"], columns=["one", "two"]) - tm.assert_frame_equal(result, expected) - - msg = "cannot use columns parameter with orient='columns'" - with pytest.raises(ValueError, match=msg): - DataFrame.from_dict( - {"A": [1, 2], "B": [4, 5]}, - orient="columns", - columns=["one", "two"], - ) - with pytest.raises(ValueError, match=msg): - DataFrame.from_dict({"A": [1, 2], "B": [4, 5]}, columns=["one", "two"]) - - @pytest.mark.parametrize( - "data_dict, keys, orient", - [ - ({}, [], "index"), - ([{("a",): 1}, {("a",): 2}], [("a",)], "columns"), - ([OrderedDict([(("a",), 1), (("b",), 2)])], [("a",), ("b",)], "columns"), - ([{("a", "b"): 1}], [("a", "b")], "columns"), - ], - ) - def test_constructor_from_dict_tuples(self, data_dict, keys, orient): - # GH 16769 - df = DataFrame.from_dict(data_dict, orient) - - result = df.columns - expected = Index(keys, dtype="object", tupleize_cols=False) - - tm.assert_index_equal(result, expected) - - def test_frame_dict_constructor_empty_series(self): - s1 = Series( - [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)]) - ) - s2 = Series( - [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)]) - ) - s3 = Series(dtype=object) - - # it works! - DataFrame({"foo": s1, "bar": s2, "baz": s3}) - DataFrame.from_dict({"foo": s1, "baz": s3, "bar": s2}) - def test_constructor_Series_named(self): a = Series([1, 2, 3], index=["a", "b", "c"], name="x") df = DataFrame(a) @@ -1723,10 +1555,6 @@ def test_constructor_column_duplicates(self): tm.assert_frame_equal(idf, edf) - msg = "If using all scalar values, you must pass an index" - with pytest.raises(ValueError, match=msg): - DataFrame.from_dict(OrderedDict([("b", 8), ("a", 5), ("a", 6)])) - def test_constructor_empty_with_string_dtype(self): # GH 9428 expected = DataFrame(index=[0, 1], columns=[0, 1], dtype=object) @@ -1870,8 +1698,6 @@ def test_constructor_with_datetimes(self): # GH 7594 # don't coerce tz-aware - import pytz - tz = pytz.timezone("US/Eastern") dt = tz.localize(datetime(2012, 1, 1)) @@ -2143,211 +1969,6 @@ def test_constructor_categorical_series(self): df = DataFrame({"x": Series(["a", "b", "c"], dtype="category")}, index=index) tm.assert_frame_equal(df, expected) - def test_from_records_to_records(self): - # from numpy documentation - arr = np.zeros((2,), dtype=("i4,f4,a10")) - arr[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")] - - # TODO(wesm): unused - frame = DataFrame.from_records(arr) # noqa - - index = Index(np.arange(len(arr))[::-1]) - indexed_frame = DataFrame.from_records(arr, index=index) - tm.assert_index_equal(indexed_frame.index, index) - - # without names, it should go to last ditch - arr2 = np.zeros((2, 3)) - tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2)) - - # wrong length - msg = r"Shape of passed values is \(2, 3\), indices imply \(1, 3\)" - with pytest.raises(ValueError, match=msg): - DataFrame.from_records(arr, index=index[:-1]) - - indexed_frame = DataFrame.from_records(arr, index="f1") - - # what to do? - records = indexed_frame.to_records() - assert len(records.dtype.names) == 3 - - records = indexed_frame.to_records(index=False) - assert len(records.dtype.names) == 2 - assert "index" not in records.dtype.names - - def test_from_records_nones(self): - tuples = [(1, 2, None, 3), (1, 2, None, 3), (None, 2, 5, 3)] - - df = DataFrame.from_records(tuples, columns=["a", "b", "c", "d"]) - assert np.isnan(df["c"][0]) - - def test_from_records_iterator(self): - arr = np.array( - [(1.0, 1.0, 2, 2), (3.0, 3.0, 4, 4), (5.0, 5.0, 6, 6), (7.0, 7.0, 8, 8)], - dtype=[ - ("x", np.float64), - ("u", np.float32), - ("y", np.int64), - ("z", np.int32), - ], - ) - df = DataFrame.from_records(iter(arr), nrows=2) - xp = DataFrame( - { - "x": np.array([1.0, 3.0], dtype=np.float64), - "u": np.array([1.0, 3.0], dtype=np.float32), - "y": np.array([2, 4], dtype=np.int64), - "z": np.array([2, 4], dtype=np.int32), - } - ) - tm.assert_frame_equal(df.reindex_like(xp), xp) - - # no dtypes specified here, so just compare with the default - arr = [(1.0, 2), (3.0, 4), (5.0, 6), (7.0, 8)] - df = DataFrame.from_records(iter(arr), columns=["x", "y"], nrows=2) - tm.assert_frame_equal(df, xp.reindex(columns=["x", "y"]), check_dtype=False) - - def test_from_records_tuples_generator(self): - def tuple_generator(length): - for i in range(length): - letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - yield (i, letters[i % len(letters)], i / length) - - columns_names = ["Integer", "String", "Float"] - columns = [ - [i[j] for i in tuple_generator(10)] for j in range(len(columns_names)) - ] - data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]} - expected = DataFrame(data, columns=columns_names) - - generator = tuple_generator(10) - result = DataFrame.from_records(generator, columns=columns_names) - tm.assert_frame_equal(result, expected) - - def test_from_records_lists_generator(self): - def list_generator(length): - for i in range(length): - letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - yield [i, letters[i % len(letters)], i / length] - - columns_names = ["Integer", "String", "Float"] - columns = [ - [i[j] for i in list_generator(10)] for j in range(len(columns_names)) - ] - data = {"Integer": columns[0], "String": columns[1], "Float": columns[2]} - expected = DataFrame(data, columns=columns_names) - - generator = list_generator(10) - result = DataFrame.from_records(generator, columns=columns_names) - tm.assert_frame_equal(result, expected) - - def test_from_records_columns_not_modified(self): - tuples = [(1, 2, 3), (1, 2, 3), (2, 5, 3)] - - columns = ["a", "b", "c"] - original_columns = list(columns) - - df = DataFrame.from_records(tuples, columns=columns, index="a") # noqa - - assert columns == original_columns - - def test_from_records_decimal(self): - from decimal import Decimal - - tuples = [(Decimal("1.5"),), (Decimal("2.5"),), (None,)] - - df = DataFrame.from_records(tuples, columns=["a"]) - assert df["a"].dtype == object - - df = DataFrame.from_records(tuples, columns=["a"], coerce_float=True) - assert df["a"].dtype == np.float64 - assert np.isnan(df["a"].values[-1]) - - def test_from_records_duplicates(self): - result = DataFrame.from_records([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"]) - - expected = DataFrame([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "a"]) - - tm.assert_frame_equal(result, expected) - - def test_from_records_set_index_name(self): - def create_dict(order_id): - return { - "order_id": order_id, - "quantity": np.random.randint(1, 10), - "price": np.random.randint(1, 10), - } - - documents = [create_dict(i) for i in range(10)] - # demo missing data - documents.append({"order_id": 10, "quantity": 5}) - - result = DataFrame.from_records(documents, index="order_id") - assert result.index.name == "order_id" - - # MultiIndex - result = DataFrame.from_records(documents, index=["order_id", "quantity"]) - assert result.index.names == ("order_id", "quantity") - - def test_from_records_misc_brokenness(self): - # #2179 - - data = {1: ["foo"], 2: ["bar"]} - - result = DataFrame.from_records(data, columns=["a", "b"]) - exp = DataFrame(data, columns=["a", "b"]) - tm.assert_frame_equal(result, exp) - - # overlap in index/index_names - - data = {"a": [1, 2, 3], "b": [4, 5, 6]} - - result = DataFrame.from_records(data, index=["a", "b", "c"]) - exp = DataFrame(data, index=["a", "b", "c"]) - tm.assert_frame_equal(result, exp) - - # GH 2623 - rows = [] - rows.append([datetime(2010, 1, 1), 1]) - rows.append([datetime(2010, 1, 2), "hi"]) # test col upconverts to obj - df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) - result = df2_obj.dtypes - expected = Series( - [np.dtype("datetime64[ns]"), np.dtype("object")], index=["date", "test"] - ) - tm.assert_series_equal(result, expected) - - rows = [] - rows.append([datetime(2010, 1, 1), 1]) - rows.append([datetime(2010, 1, 2), 1]) - df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) - result = df2_obj.dtypes - expected = Series( - [np.dtype("datetime64[ns]"), np.dtype("int64")], index=["date", "test"] - ) - tm.assert_series_equal(result, expected) - - def test_from_records_empty(self): - # 3562 - result = DataFrame.from_records([], columns=["a", "b", "c"]) - expected = DataFrame(columns=["a", "b", "c"]) - tm.assert_frame_equal(result, expected) - - result = DataFrame.from_records([], columns=["a", "b", "b"]) - expected = DataFrame(columns=["a", "b", "b"]) - tm.assert_frame_equal(result, expected) - - def test_from_records_empty_with_nonempty_fields_gh3682(self): - a = np.array([(1, 2)], dtype=[("id", np.int64), ("value", np.int64)]) - df = DataFrame.from_records(a, index="id") - tm.assert_index_equal(df.index, Index([1], name="id")) - assert df.index.name == "id" - tm.assert_index_equal(df.columns, Index(["value"])) - - b = np.array([], dtype=[("id", np.int64), ("value", np.int64)]) - df = DataFrame.from_records(b, index="id") - tm.assert_index_equal(df.index, Index([], name="id")) - assert df.index.name == "id" - @pytest.mark.parametrize( "dtype", tm.ALL_INT_DTYPES @@ -2375,229 +1996,6 @@ def test_check_dtype_empty_string_column(self, dtype): assert data.b.dtype.name == "object" - def test_from_records_with_datetimes(self): - - # this may fail on certain platforms because of a numpy issue - # related GH6140 - if not is_platform_little_endian(): - pytest.skip("known failure of test on non-little endian") - - # construction with a null in a recarray - # GH 6140 - expected = DataFrame({"EXPIRY": [datetime(2005, 3, 1, 0, 0), None]}) - - arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] - dtypes = [("EXPIRY", "<M8[ns]")] - - try: - recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) - except (ValueError): - pytest.skip("known failure of numpy rec array creation") - - result = DataFrame.from_records(recarray) - tm.assert_frame_equal(result, expected) - - # coercion should work too - arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])] - dtypes = [("EXPIRY", "<M8[m]")] - recarray = np.core.records.fromarrays(arrdata, dtype=dtypes) - result = DataFrame.from_records(recarray) - tm.assert_frame_equal(result, expected) - - def test_from_records_sequencelike(self): - df = DataFrame( - { - "A": np.array(np.random.randn(6), dtype=np.float64), - "A1": np.array(np.random.randn(6), dtype=np.float64), - "B": np.array(np.arange(6), dtype=np.int64), - "C": ["foo"] * 6, - "D": np.array([True, False] * 3, dtype=bool), - "E": np.array(np.random.randn(6), dtype=np.float32), - "E1": np.array(np.random.randn(6), dtype=np.float32), - "F": np.array(np.arange(6), dtype=np.int32), - } - ) - - # this is actually tricky to create the recordlike arrays and - # have the dtypes be intact - blocks = df._to_dict_of_blocks() - tuples = [] - columns = [] - dtypes = [] - for dtype, b in blocks.items(): - columns.extend(b.columns) - dtypes.extend([(c, np.dtype(dtype).descr[0][1]) for c in b.columns]) - for i in range(len(df.index)): - tup = [] - for _, b in blocks.items(): - tup.extend(b.iloc[i].values) - tuples.append(tuple(tup)) - - recarray = np.array(tuples, dtype=dtypes).view(np.recarray) - recarray2 = df.to_records() - lists = [list(x) for x in tuples] - - # tuples (lose the dtype info) - result = DataFrame.from_records(tuples, columns=columns).reindex( - columns=df.columns - ) - - # created recarray and with to_records recarray (have dtype info) - result2 = DataFrame.from_records(recarray, columns=columns).reindex( - columns=df.columns - ) - result3 = DataFrame.from_records(recarray2, columns=columns).reindex( - columns=df.columns - ) - - # list of tupels (no dtype info) - result4 = DataFrame.from_records(lists, columns=columns).reindex( - columns=df.columns - ) - - tm.assert_frame_equal(result, df, check_dtype=False) - tm.assert_frame_equal(result2, df) - tm.assert_frame_equal(result3, df) - tm.assert_frame_equal(result4, df, check_dtype=False) - - # tuples is in the order of the columns - result = DataFrame.from_records(tuples) - tm.assert_index_equal(result.columns, RangeIndex(8)) - - # test exclude parameter & we are casting the results here (as we don't - # have dtype info to recover) - columns_to_test = [columns.index("C"), columns.index("E1")] - - exclude = list(set(range(8)) - set(columns_to_test)) - result = DataFrame.from_records(tuples, exclude=exclude) - result.columns = [columns[i] for i in sorted(columns_to_test)] - tm.assert_series_equal(result["C"], df["C"]) - tm.assert_series_equal(result["E1"], df["E1"].astype("float64")) - - # empty case - result = DataFrame.from_records([], columns=["foo", "bar", "baz"]) - assert len(result) == 0 - tm.assert_index_equal(result.columns, Index(["foo", "bar", "baz"])) - - result = DataFrame.from_records([]) - assert len(result) == 0 - assert len(result.columns) == 0 - - def test_from_records_dictlike(self): - - # test the dict methods - df = DataFrame( - { - "A": np.array(np.random.randn(6), dtype=np.float64), - "A1": np.array(np.random.randn(6), dtype=np.float64), - "B": np.array(np.arange(6), dtype=np.int64), - "C": ["foo"] * 6, - "D": np.array([True, False] * 3, dtype=bool), - "E": np.array(np.random.randn(6), dtype=np.float32), - "E1": np.array(np.random.randn(6), dtype=np.float32), - "F": np.array(np.arange(6), dtype=np.int32), - } - ) - - # columns is in a different order here than the actual items iterated - # from the dict - blocks = df._to_dict_of_blocks() - columns = [] - for dtype, b in blocks.items(): - columns.extend(b.columns) - - asdict = {x: y for x, y in df.items()} - asdict2 = {x: y.values for x, y in df.items()} - - # dict of series & dict of ndarrays (have dtype info) - results = [] - results.append(DataFrame.from_records(asdict).reindex(columns=df.columns)) - results.append( - DataFrame.from_records(asdict, columns=columns).reindex(columns=df.columns) - ) - results.append( - DataFrame.from_records(asdict2, columns=columns).reindex(columns=df.columns) - ) - - for r in results: - tm.assert_frame_equal(r, df) - - def test_from_records_with_index_data(self): - df = DataFrame(np.random.randn(10, 3), columns=["A", "B", "C"]) - - data = np.random.randn(10) - df1 = DataFrame.from_records(df, index=data) - tm.assert_index_equal(df1.index, Index(data)) - - def test_from_records_bad_index_column(self): - df = DataFrame(np.random.randn(10, 3), columns=["A", "B", "C"]) - - # should pass - df1 = DataFrame.from_records(df, index=["C"]) - tm.assert_index_equal(df1.index, Index(df.C)) - - df1 = DataFrame.from_records(df, index="C") - tm.assert_index_equal(df1.index, Index(df.C)) - - # should fail - msg = r"Shape of passed values is \(10, 3\), indices imply \(1, 3\)" - with pytest.raises(ValueError, match=msg): - DataFrame.from_records(df, index=[2]) - with pytest.raises(KeyError, match=r"^2$"): - DataFrame.from_records(df, index=2) - - def test_from_records_non_tuple(self): - class Record: - def __init__(self, *args): - self.args = args - - def __getitem__(self, i): - return self.args[i] - - def __iter__(self): - return iter(self.args) - - recs = [Record(1, 2, 3), Record(4, 5, 6), Record(7, 8, 9)] - tups = [tuple(rec) for rec in recs] - - result = DataFrame.from_records(recs) - expected = DataFrame.from_records(tups) - tm.assert_frame_equal(result, expected) - - def test_from_records_len0_with_columns(self): - # #2633 - result = DataFrame.from_records([], index="foo", columns=["foo", "bar"]) - expected = Index(["bar"]) - - assert len(result) == 0 - assert result.index.name == "foo" - tm.assert_index_equal(result.columns, expected) - - def test_from_records_series_list_dict(self): - # GH27358 - expected = DataFrame([[{"a": 1, "b": 2}, {"a": 3, "b": 4}]]).T - data = Series([[{"a": 1, "b": 2}], [{"a": 3, "b": 4}]]) - result = DataFrame.from_records(data) - tm.assert_frame_equal(result, expected) - - def test_from_records_series_categorical_index(self): - # GH 32805 - index = CategoricalIndex( - [Interval(-20, -10), Interval(-10, 0), Interval(0, 10)] - ) - series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index) - frame = DataFrame.from_records(series_of_dicts, index=index) - expected = DataFrame( - {"a": [1, 2, np.NaN], "b": [np.NaN, np.NaN, 3]}, index=index - ) - tm.assert_frame_equal(frame, expected) - - def test_frame_from_records_utc(self): - rec = {"datum": 1.5, "begin_time": datetime(2006, 4, 27, tzinfo=pytz.utc)} - - # it works - DataFrame.from_records([rec], index="begin_time") - def test_to_frame_with_falsey_names(self): # GH 16114 result = Series(name=0, dtype=object).to_frame().dtypes
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38869
2020-12-31T23:07:40Z
2020-12-31T23:52:13Z
2020-12-31T23:52:13Z
2021-01-01T02:02:11Z
REF: Move aggregation into apply
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index c0c6c9084b560..edb6b97a73e7f 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -1,12 +1,18 @@ import abc import inspect -from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional, Tuple, Type +from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple, Type, cast import numpy as np from pandas._config import option_context -from pandas._typing import AggFuncType, Axis, FrameOrSeriesUnion +from pandas._typing import ( + AggFuncType, + AggFuncTypeBase, + AggFuncTypeDict, + Axis, + FrameOrSeriesUnion, +) from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( @@ -17,6 +23,7 @@ ) from pandas.core.dtypes.generic import ABCSeries +from pandas.core.aggregation import agg_dict_like, agg_list_like from pandas.core.construction import create_series_with_explicit_dtype if TYPE_CHECKING: @@ -27,6 +34,7 @@ def frame_apply( obj: "DataFrame", + how: str, func: AggFuncType, axis: Axis = 0, raw: bool = False, @@ -44,6 +52,7 @@ def frame_apply( return klass( obj, + how, func, raw=raw, result_type=result_type, @@ -84,13 +93,16 @@ def wrap_results_for_axis( def __init__( self, obj: "DataFrame", + how: str, func, raw: bool, result_type: Optional[str], args, kwds, ): + assert how in ("apply", "agg") self.obj = obj + self.how = how self.raw = raw self.args = args or () self.kwds = kwds or {} @@ -104,7 +116,11 @@ def __init__( self.result_type = result_type # curry if needed - if (kwds or args) and not isinstance(func, (np.ufunc, str)): + if ( + (kwds or args) + and not isinstance(func, (np.ufunc, str)) + and not is_list_like(func) + ): def f(x): return func(x, *args, **kwds) @@ -112,7 +128,7 @@ def f(x): else: f = func - self.f = f + self.f: AggFuncType = f @property def res_columns(self) -> "Index": @@ -139,6 +155,54 @@ def agg_axis(self) -> "Index": return self.obj._get_agg_axis(self.axis) def get_result(self): + if self.how == "apply": + return self.apply() + else: + return self.agg() + + def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]: + """ + Provide an implementation for the aggregators. + + Returns + ------- + tuple of result, how. + + Notes + ----- + how can be a string describe the required post-processing, or + None if not required. + """ + obj = self.obj + arg = self.f + args = self.args + kwargs = self.kwds + + _axis = kwargs.pop("_axis", None) + if _axis is None: + _axis = getattr(obj, "axis", 0) + + if isinstance(arg, str): + return obj._try_aggregate_string_function(arg, *args, **kwargs), None + elif is_dict_like(arg): + arg = cast(AggFuncTypeDict, arg) + return agg_dict_like(obj, arg, _axis), True + elif is_list_like(arg): + # we require a list, but not a 'str' + arg = cast(List[AggFuncTypeBase], arg) + return agg_list_like(obj, arg, _axis=_axis), None + else: + result = None + + if callable(arg): + f = obj._get_cython_func(arg) + if f and not args and not kwargs: + return getattr(obj, f)(), None + + # caller can react + return result, True + + def apply(self) -> FrameOrSeriesUnion: """ compute the results """ # dispatch to agg if is_list_like(self.f) or is_dict_like(self.f): @@ -191,6 +255,8 @@ def apply_empty_result(self): we will try to apply the function to an empty series in order to see if this is a reduction function """ + assert callable(self.f) + # we are not asked to reduce or infer reduction # so just return a copy of the existing object if self.result_type not in ["reduce", None]: @@ -246,6 +312,8 @@ def wrapper(*args, **kwargs): return self.obj._constructor_sliced(result, index=self.agg_axis) def apply_broadcast(self, target: "DataFrame") -> "DataFrame": + assert callable(self.f) + result_values = np.empty_like(target.values) # axis which we want to compare compliance @@ -279,6 +347,8 @@ def apply_standard(self): return self.wrap_results(results, res_index) def apply_series_generator(self) -> Tuple[ResType, "Index"]: + assert callable(self.f) + series_gen = self.series_generator res_index = self.result_index diff --git a/pandas/core/frame.py b/pandas/core/frame.py index cc89823cd7817..6e9a8ab972abc 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -121,12 +121,7 @@ from pandas.core import algorithms, common as com, generic, nanops, ops from pandas.core.accessor import CachedAccessor -from pandas.core.aggregation import ( - aggregate, - reconstruct_func, - relabel_result, - transform, -) +from pandas.core.aggregation import reconstruct_func, relabel_result, transform from pandas.core.arraylike import OpsMixin from pandas.core.arrays import ExtensionArray from pandas.core.arrays.sparse import SparseFrameAccessor @@ -7623,13 +7618,24 @@ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): return result def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs): + from pandas.core.apply import frame_apply + + op = frame_apply( + self if axis == 0 else self.T, + how="agg", + func=arg, + axis=0, + args=args, + kwds=kwargs, + ) + result, how = op.get_result() + if axis == 1: # NDFrame.aggregate returns a tuple, and we need to transpose # only result - result, how = aggregate(self.T, arg, *args, **kwargs) result = result.T if result is not None else result - return result, how - return aggregate(self, arg, *args, **kwargs) + + return result, how agg = aggregate @@ -7789,6 +7795,7 @@ def apply( op = frame_apply( self, + how="apply", func=func, axis=axis, raw=raw,
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This is a step toward #35725. We can't simply ban agg from not aggregating because it's used by apply for series, dataframe, groupby, resampler, and rolling. There are two other related issues. First, apply, agg, and transform are all doing similar things but with different implementations leading to unintended inconsistencies. Second, we would also like to ban mutation in apply (and presumably agg and transform for the same reasons). It seems best to me to handle all of these by first combining the implementation into apply, cleaning up and sharing code between the implementations, and then we would be in a good place to ban agg from not aggregating. This starts the process by moving aggregation.aggregate into apply, but it is only utilized for frames. Once this is done for the remaining objects (series, groupby, resampler, rolling), the rest of the functions in aggregation can be moved into apply as well.
https://api.github.com/repos/pandas-dev/pandas/pulls/38867
2020-12-31T21:51:41Z
2021-01-03T16:56:06Z
2021-01-03T16:56:06Z
2021-01-28T23:02:00Z
TST: GH30999 add match=msg to 2 pytest.raises in pandas/tests/io/json/test_normalize.py
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 46f6367a7227f..b232c827f5ece 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -1,4 +1,3 @@ -from contextlib import nullcontext as does_not_raise import json import numpy as np @@ -170,19 +169,21 @@ def test_empty_array(self): tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( - "data, record_path, error", + "data, record_path, exception_type", [ - ([{"a": 0}, {"a": 1}], None, does_not_raise()), - ({"a": [{"a": 0}, {"a": 1}]}, "a", does_not_raise()), - ('{"a": [{"a": 0}, {"a": 1}]}', None, pytest.raises(NotImplementedError)), - (None, None, pytest.raises(NotImplementedError)), + ([{"a": 0}, {"a": 1}], None, None), + ({"a": [{"a": 0}, {"a": 1}]}, "a", None), + ('{"a": [{"a": 0}, {"a": 1}]}', None, NotImplementedError), + (None, None, NotImplementedError), ], ) - def test_accepted_input(self, data, record_path, error): - with error: + def test_accepted_input(self, data, record_path, exception_type): + if exception_type is not None: + with pytest.raises(exception_type, match=tm.EMPTY_STRING_PATTERN): + json_normalize(data, record_path=record_path) + else: result = json_normalize(data, record_path=record_path) expected = DataFrame([0, 1], columns=["a"]) - tm.assert_frame_equal(result, expected) def test_simple_normalize_with_separator(self, deep_nested):
xref #30999 for pandas/tests/io/json/test_normalize.py And with this my work on #30999 is done. Will head over to the issue to explain why I am not fixing the remaining 15 instances of `pytest.raise` - [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38864
2020-12-31T20:06:22Z
2021-01-01T20:43:19Z
2021-01-01T20:43:19Z
2021-01-01T20:43:23Z
BUG: additional keys in groupby indices when NAs are present
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index f66098633b45e..5e6d5c8c7466d 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -285,6 +285,7 @@ Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ - Bug in :meth:`SeriesGroupBy.value_counts` where unobserved categories in a grouped categorical series were not tallied (:issue:`38672`) +- Bug in :meth:`.GroupBy.indices` would contain non-existent indices when null values were present in the groupby keys (:issue:`9304`) - Reshaping diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 4e451fc33b055..0f796b2b65dff 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -888,12 +888,17 @@ def indices_fast(ndarray index, const int64_t[:] labels, list keys, k = len(keys) - if n == 0: + # Start at the first non-null entry + j = 0 + for j in range(0, n): + if labels[j] != -1: + break + else: return result + cur = labels[j] + start = j - start = 0 - cur = labels[0] - for i in range(1, n): + for i in range(j+1, n): lab = labels[i] if lab != cur: diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 90396f1be0755..9417b626386fc 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -542,8 +542,7 @@ def get_indexer_dict( group_index = get_group_index(label_list, shape, sort=True, xnull=True) if np.all(group_index == -1): - # When all keys are nan and dropna=True, indices_fast can't handle this - # and the return is empty anyway + # Short-circuit, lib.indices_fast will return the same return {} ngroups = ( ((group_index.size and group_index.max()) + 1) diff --git a/pandas/tests/groupby/test_missing.py b/pandas/tests/groupby/test_missing.py index 56cf400258f0f..e2ca63d9ab922 100644 --- a/pandas/tests/groupby/test_missing.py +++ b/pandas/tests/groupby/test_missing.py @@ -126,3 +126,12 @@ def test_min_count(func, min_count, value): result = getattr(df.groupby("a"), func)(min_count=min_count) expected = DataFrame({"b": [value], "c": [np.nan]}, index=Index([1], name="a")) tm.assert_frame_equal(result, expected) + + +def test_indicies_with_missing(): + # GH 9304 + df = DataFrame({"a": [1, 1, np.nan], "b": [2, 3, 4], "c": [5, 6, 7]}) + g = df.groupby(["a", "b"]) + result = g.indices + expected = {(1.0, 2): np.array([0]), (1.0, 3): np.array([1])} + assert result == expected
- [x] closes #9304 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry `lib.indices_fast` included logic to skip over null values (-1's), but did not include the case where the first index is null. Currently this function is only used in `sorting.get_indexer_dict` where the case of all null group_index is handled separately.
https://api.github.com/repos/pandas-dev/pandas/pulls/38861
2020-12-31T18:06:26Z
2021-01-01T20:41:44Z
2021-01-01T20:41:44Z
2021-01-02T20:52:46Z
DOC/CI: Fix building docs with --no-api
diff --git a/doc/make.py b/doc/make.py index 40ce9ea3bbcd2..d90cd2428360d 100755 --- a/doc/make.py +++ b/doc/make.py @@ -46,6 +46,7 @@ def __init__( warnings_are_errors=False, ): self.num_jobs = num_jobs + self.include_api = include_api self.verbosity = verbosity self.warnings_are_errors = warnings_are_errors @@ -188,7 +189,14 @@ def _add_redirects(self): if not row or row[0].strip().startswith("#"): continue - path = os.path.join(BUILD_PATH, "html", *row[0].split("/")) + ".html" + html_path = os.path.join(BUILD_PATH, "html") + path = os.path.join(html_path, *row[0].split("/")) + ".html" + + if not self.include_api and ( + os.path.join(html_path, "reference") in path + or os.path.join(html_path, "generated") in path + ): + continue try: title = self._get_page_title(row[1]) @@ -198,11 +206,6 @@ def _add_redirects(self): # sphinx specific stuff title = "this page" - if os.path.exists(path): - raise RuntimeError( - f"Redirection would overwrite an existing file: {path}" - ) - with open(path, "w") as moved_page_fd: html = f"""\ <html> diff --git a/doc/source/conf.py b/doc/source/conf.py index 951a6d4043786..3508dc2edd84c 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -72,13 +72,13 @@ try: import nbconvert except ImportError: - logger.warn("nbconvert not installed. Skipping notebooks.") + logger.warning("nbconvert not installed. Skipping notebooks.") exclude_patterns.append("**/*.ipynb") else: try: nbconvert.utils.pandoc.get_pandoc_version() except nbconvert.utils.pandoc.PandocMissing: - logger.warn("Pandoc not installed. Skipping notebooks.") + logger.warning("Pandoc not installed. Skipping notebooks.") exclude_patterns.append("**/*.ipynb") # sphinx_pattern can be '-api' to exclude the API pages, @@ -86,15 +86,18 @@ # (e.g. '10min.rst' or 'pandas.DataFrame.head') source_path = os.path.dirname(os.path.abspath(__file__)) pattern = os.environ.get("SPHINX_PATTERN") +single_doc = pattern is not None and pattern != "-api" +include_api = pattern != "-api" if pattern: for dirname, dirs, fnames in os.walk(source_path): + reldir = os.path.relpath(dirname, source_path) for fname in fnames: if os.path.splitext(fname)[-1] in (".rst", ".ipynb"): fname = os.path.relpath(os.path.join(dirname, fname), source_path) if fname == "index.rst" and os.path.abspath(dirname) == source_path: continue - elif pattern == "-api" and dirname == "reference": + elif pattern == "-api" and reldir.startswith("reference"): exclude_patterns.append(fname) elif pattern != "-api" and fname != pattern: exclude_patterns.append(fname) @@ -104,11 +107,11 @@ with open(os.path.join(source_path, "index.rst"), "w") as f: f.write( t.render( - include_api=pattern is None, - single_doc=(pattern if pattern is not None and pattern != "-api" else None), + include_api=include_api, + single_doc=(pattern if single_doc else None), ) ) -autosummary_generate = True if pattern is None else ["index"] +autosummary_generate = True if include_api else ["index"] autodoc_typehints = "none" # numpydoc @@ -310,7 +313,7 @@ # ... and each of its public methods moved_api_pages.append((f"{old}.{method}", f"{new}.{method}")) -if pattern is None: +if include_api: html_additional_pages = { "generated/" + page[0]: "api_redirect.html" for page in moved_api_pages } @@ -406,7 +409,7 @@ # latex_use_modindex = True -if pattern is None: +if include_api: intersphinx_mapping = { "dateutil": ("https://dateutil.readthedocs.io/en/latest/", None), "matplotlib": ("https://matplotlib.org/", None),
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Fixes running docs via python make.py --no-api A few notes: - The removed check `if os.path.exists(path):`; will incorrectly raise if docs are being rebuilt. - The value `dirname` returned by `os.walk` is an absolute path, but the check was treating it as relative. - If docs are built with api and then rebuilt with --no-api, we want to exclude everything in the `reference` directory; in particular `reference/api`.
https://api.github.com/repos/pandas-dev/pandas/pulls/38858
2020-12-31T17:28:16Z
2021-01-13T14:30:21Z
2021-01-13T14:30:21Z
2021-01-13T15:03:03Z
BUG: Styler `hide` compatible with `max_columns`
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index a71dd6f33e3c8..ae4e05160e70a 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -316,7 +316,7 @@ def _translate_header(self, sparsify_cols: bool, max_cols: int): self.columns, sparsify_cols, max_cols, self.hidden_columns ) - clabels = self.data.columns.tolist()[:max_cols] # slice to allow trimming + clabels = self.data.columns.tolist() if self.data.columns.nlevels == 1: clabels = [[x] for x in clabels] clabels = list(zip(*clabels)) @@ -339,7 +339,9 @@ def _translate_header(self, sparsify_cols: bool, max_cols: int): and not all(self.hide_index_) and not self.hide_index_names ): - index_names_row = self._generate_index_names_row(clabels, max_cols) + index_names_row = self._generate_index_names_row( + clabels, max_cols, col_lengths + ) head.append(index_names_row) return head @@ -389,9 +391,27 @@ def _generate_col_header_row(self, iter: tuple, max_cols: int, col_lengths: dict ) ] - column_headers = [] + column_headers, visible_col_count = [], 0 for c, value in enumerate(clabels[r]): header_element_visible = _is_visible(c, r, col_lengths) + if header_element_visible: + visible_col_count += col_lengths.get((r, c), 0) + if visible_col_count > max_cols: + # add an extra column with `...` value to indicate trimming + column_headers.append( + _element( + "th", + ( + f"{self.css['col_heading']} {self.css['level']}{r} " + f"{self.css['col_trim']}" + ), + "...", + True, + attributes="", + ) + ) + break + header_element = _element( "th", ( @@ -422,23 +442,9 @@ def _generate_col_header_row(self, iter: tuple, max_cols: int, col_lengths: dict column_headers.append(header_element) - if len(self.data.columns) > max_cols: - # add an extra column with `...` value to indicate trimming - column_headers.append( - _element( - "th", - ( - f"{self.css['col_heading']} {self.css['level']}{r} " - f"{self.css['col_trim']}" - ), - "...", - True, - attributes="", - ) - ) return index_blanks + column_name + column_headers - def _generate_index_names_row(self, iter: tuple, max_cols): + def _generate_index_names_row(self, iter: tuple, max_cols: int, col_lengths: dict): """ Generate the row containing index names @@ -470,22 +476,37 @@ def _generate_index_names_row(self, iter: tuple, max_cols): for c, name in enumerate(self.data.index.names) ] - if not clabels: - blank_len = 0 - elif len(self.data.columns) <= max_cols: - blank_len = len(clabels[0]) - else: - blank_len = len(clabels[0]) + 1 # to allow room for `...` trim col + column_blanks, visible_col_count = [], 0 + if clabels: + last_level = self.columns.nlevels - 1 # use last level since never sparsed + for c, value in enumerate(clabels[last_level]): + header_element_visible = _is_visible(c, last_level, col_lengths) + if header_element_visible: + visible_col_count += 1 + if visible_col_count > max_cols: + column_blanks.append( + _element( + "th", + ( + f"{self.css['blank']} {self.css['col']}{c} " + f"{self.css['col_trim']}" + ), + self.css["blank_value"], + True, + attributes="", + ) + ) + break + + column_blanks.append( + _element( + "th", + f"{self.css['blank']} {self.css['col']}{c}", + self.css["blank_value"], + c not in self.hidden_columns, + ) + ) - column_blanks = [ - _element( - "th", - f"{self.css['blank']} {self.css['col']}{c}", - self.css["blank_value"], - c not in self.hidden_columns, - ) - for c in range(blank_len) - ] return index_names + column_blanks def _translate_body(self, sparsify_index: bool, max_rows: int, max_cols: int): @@ -561,31 +582,36 @@ def _generate_trimmed_row(self, max_cols: int) -> list: for c in range(self.data.index.nlevels) ] - data = [ - _element( - "td", - f"{self.css['data']} {self.css['col']}{c} {self.css['row_trim']}", - "...", - (c not in self.hidden_columns), - attributes="", - ) - for c in range(max_cols) - ] + data, visible_col_count = [], 0 + for c, _ in enumerate(self.columns): + data_element_visible = c not in self.hidden_columns + if data_element_visible: + visible_col_count += 1 + if visible_col_count > max_cols: + data.append( + _element( + "td", + ( + f"{self.css['data']} {self.css['row_trim']} " + f"{self.css['col_trim']}" + ), + "...", + True, + attributes="", + ) + ) + break - if len(self.data.columns) > max_cols: - # columns are also trimmed so we add the final element data.append( _element( "td", - ( - f"{self.css['data']} {self.css['row_trim']} " - f"{self.css['col_trim']}" - ), + f"{self.css['data']} {self.css['col']}{c} {self.css['row_trim']}", "...", - True, + data_element_visible, attributes="", ) ) + return index_headers + data def _generate_body_row( @@ -654,9 +680,14 @@ def _generate_body_row( index_headers.append(header_element) - data = [] + data, visible_col_count = [], 0 for c, value in enumerate(row_tup[1:]): - if c >= max_cols: + data_element_visible = ( + c not in self.hidden_columns and r not in self.hidden_rows + ) + if data_element_visible: + visible_col_count += 1 + if visible_col_count > max_cols: data.append( _element( "td", @@ -676,9 +707,6 @@ def _generate_body_row( if (r, c) in self.cell_context: cls = " " + self.cell_context[r, c] - data_element_visible = ( - c not in self.hidden_columns and r not in self.hidden_rows - ) data_element = _element( "td", ( @@ -1252,15 +1280,15 @@ def _get_level_lengths( elif j not in hidden_elements: # then element must be part of sparsified section and is visible visible_row_count += 1 + if visible_row_count > max_index: + break # do not add a length since the render trim limit reached if lengths[(i, last_label)] == 0: # if previous iteration was first-of-section but hidden then offset last_label = j lengths[(i, last_label)] = 1 else: - # else add to previous iteration but do not extend more than max - lengths[(i, last_label)] = min( - max_index, 1 + lengths[(i, last_label)] - ) + # else add to previous iteration + lengths[(i, last_label)] += 1 non_zero_lengths = { element: length for element, length in lengths.items() if length >= 1 diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py index e15283e558479..b778d18618bf4 100644 --- a/pandas/tests/io/formats/style/test_html.py +++ b/pandas/tests/io/formats/style/test_html.py @@ -668,3 +668,99 @@ def test_hiding_index_columns_multiindex_alignment(): """ ) assert result == expected + + +def test_hiding_index_columns_multiindex_trimming(): + # gh 44272 + df = DataFrame(np.arange(64).reshape(8, 8)) + df.columns = MultiIndex.from_product([[0, 1, 2, 3], [0, 1]]) + df.index = MultiIndex.from_product([[0, 1, 2, 3], [0, 1]]) + df.index.names, df.columns.names = ["a", "b"], ["c", "d"] + styler = Styler(df, cell_ids=False, uuid_len=0) + styler.hide([(0, 0), (0, 1), (1, 0)], axis=1).hide([(0, 0), (0, 1), (1, 0)], axis=0) + with option_context("styler.render.max_rows", 4, "styler.render.max_columns", 4): + result = styler.to_html() + + expected = dedent( + """\ + <style type="text/css"> + </style> + <table id="T_"> + <thead> + <tr> + <th class="blank" >&nbsp;</th> + <th class="index_name level0" >c</th> + <th class="col_heading level0 col3" >1</th> + <th class="col_heading level0 col4" colspan="2">2</th> + <th class="col_heading level0 col6" >3</th> + </tr> + <tr> + <th class="blank" >&nbsp;</th> + <th class="index_name level1" >d</th> + <th class="col_heading level1 col3" >1</th> + <th class="col_heading level1 col4" >0</th> + <th class="col_heading level1 col5" >1</th> + <th class="col_heading level1 col6" >0</th> + <th class="col_heading level1 col_trim" >...</th> + </tr> + <tr> + <th class="index_name level0" >a</th> + <th class="index_name level1" >b</th> + <th class="blank col3" >&nbsp;</th> + <th class="blank col4" >&nbsp;</th> + <th class="blank col5" >&nbsp;</th> + <th class="blank col6" >&nbsp;</th> + <th class="blank col7 col_trim" >&nbsp;</th> + </tr> + </thead> + <tbody> + <tr> + <th class="row_heading level0 row3" >1</th> + <th class="row_heading level1 row3" >1</th> + <td class="data row3 col3" >27</td> + <td class="data row3 col4" >28</td> + <td class="data row3 col5" >29</td> + <td class="data row3 col6" >30</td> + <td class="data row3 col_trim" >...</td> + </tr> + <tr> + <th class="row_heading level0 row4" rowspan="2">2</th> + <th class="row_heading level1 row4" >0</th> + <td class="data row4 col3" >35</td> + <td class="data row4 col4" >36</td> + <td class="data row4 col5" >37</td> + <td class="data row4 col6" >38</td> + <td class="data row4 col_trim" >...</td> + </tr> + <tr> + <th class="row_heading level1 row5" >1</th> + <td class="data row5 col3" >43</td> + <td class="data row5 col4" >44</td> + <td class="data row5 col5" >45</td> + <td class="data row5 col6" >46</td> + <td class="data row5 col_trim" >...</td> + </tr> + <tr> + <th class="row_heading level0 row6" >3</th> + <th class="row_heading level1 row6" >0</th> + <td class="data row6 col3" >51</td> + <td class="data row6 col4" >52</td> + <td class="data row6 col5" >53</td> + <td class="data row6 col6" >54</td> + <td class="data row6 col_trim" >...</td> + </tr> + <tr> + <th class="row_heading level0 row_trim" >...</th> + <th class="row_heading level1 row_trim" >...</th> + <td class="data col3 row_trim" >...</td> + <td class="data col4 row_trim" >...</td> + <td class="data col5 row_trim" >...</td> + <td class="data col6 row_trim" >...</td> + <td class="data row_trim col_trim" >...</td> + </tr> + </tbody> + </table> + """ + ) + + assert result == expected diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 8ac0dd03c9fd6..281ab0d8b8e56 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -216,9 +216,6 @@ def test_render_trimming_mi(): assert {"class": "data row_trim col_trim"}.items() <= ctx["body"][2][4].items() assert len(ctx["body"]) == 3 # 2 data rows + trimming row - assert len(ctx["head"][0]) == 5 # 2 indexes + 2 column headers + trimming col - assert {"attributes": 'colspan="2"'}.items() <= ctx["head"][0][2].items() - def test_render_empty_mi(): # GH 43305 @@ -1600,3 +1597,17 @@ def test_row_trimming_hide_index_mi(): assert ctx["body"][r][1]["display_value"] == val # level 1 index headers for r, val in enumerate(["3", "4", "..."]): assert ctx["body"][r][2]["display_value"] == val # data values + + +def test_col_trimming_hide_columns(): + # gh 44272 + df = DataFrame([[1, 2, 3, 4, 5]]) + with pd.option_context("styler.render.max_columns", 2): + ctx = df.style.hide([0, 1], axis="columns")._translate(True, True) + + assert len(ctx["head"][0]) == 6 # blank, [0, 1 (hidden)], [2 ,3 (visible)], + trim + for c, vals in enumerate([(1, False), (2, True), (3, True), ("...", True)]): + assert ctx["head"][0][c + 2]["value"] == vals[0] + assert ctx["head"][0][c + 2]["is_visible"] == vals[1] + + assert len(ctx["body"][0]) == 6 # index + 2 hidden + 2 visible + trimming col
closes #43704 Description of render trimming and maximums bug: ``` pd.options.styler.render.max_columns = 5 pd.options.styler.render.max_rows = 5 df = DataFrame(np.random.rand(10,10)) df.columns = pd.MultiIndex.from_product([[0,1,2,3,4], [0,1]]) df.index = pd.MultiIndex.from_product([[0,1,2,3,4], [0,1]]) df.index.names, df.columns.names = ["a", "b"], ["c", "d"] df.style.hide([(0,0), (0,1), (1,0)], axis=1).hide([(0,0), (0,1), (1,0)], axis=0) ``` ## Pre #44248 ![Screen Shot 2021-11-01 at 19 02 48](https://user-images.githubusercontent.com/24256554/139718765-88bce097-e5f0-445f-8614-9b351d15e336.png) ## After #44248 (merged) ![Screen Shot 2021-11-01 at 19 03 47](https://user-images.githubusercontent.com/24256554/139718908-c3ce3e29-4360-4f6b-b917-192b516d8ec6.png) ## After this PR ![Screen Shot 2021-11-01 at 19 05 04](https://user-images.githubusercontent.com/24256554/139719076-16d303ed-9688-4305-9f74-04988193f4bb.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/44272
2021-11-01T17:09:57Z
2021-11-05T13:08:39Z
2021-11-05T13:08:39Z
2021-11-05T16:02:46Z
CLN: DataFrame.__repr__
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 565c153603b86..0e74ed0ff1769 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -988,15 +988,13 @@ def __repr__(self) -> str: """ Return a string representation for a particular DataFrame. """ - buf = StringIO("") if self._info_repr(): + buf = StringIO("") self.info(buf=buf) return buf.getvalue() repr_params = fmt.get_dataframe_repr_params() - self.to_string(buf=buf, **repr_params) - - return buf.getvalue() + return self.to_string(**repr_params) def _repr_html_(self) -> str | None: """
Minor clean-up.
https://api.github.com/repos/pandas-dev/pandas/pulls/44271
2021-11-01T16:15:09Z
2021-11-01T17:16:10Z
2021-11-01T17:16:10Z
2021-11-02T10:10:26Z
BUG: Series.replace(method='pad') with EA dtypes
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 1b3be65ee66f2..44250663ede8c 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -653,6 +653,8 @@ 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`) +- .. ***DO NOT USE THIS SECTION*** diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index cbb029f62732a..8deeb44f65188 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -246,6 +246,14 @@ def __getitem__( result = self._from_backing_data(result) return result + def _fill_mask_inplace( + self, method: str, limit, mask: npt.NDArray[np.bool_] + ) -> None: + # (for now) when self.ndim == 2, we assume axis=0 + func = missing.get_fill_func(method, ndim=self.ndim) + func(self._ndarray.T, limit=limit, mask=mask.T) + return + @doc(ExtensionArray.fillna) def fillna( self: NDArrayBackedExtensionArrayT, value=None, method=None, limit=None diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 46b505e7384b4..9ffcad2bd7b84 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -1436,6 +1436,24 @@ def _where( result[~mask] = val return result + def _fill_mask_inplace( + self, method: str, limit, mask: npt.NDArray[np.bool_] + ) -> None: + """ + Replace values in locations specified by 'mask' using pad or backfill. + + See also + -------- + ExtensionArray.fillna + """ + func = missing.get_fill_func(method) + # NB: if we don't copy mask here, it may be altered inplace, which + # would mess up the `self[mask] = ...` below. + new_values, _ = func(self.astype(object), limit=limit, mask=mask.copy()) + new_values = self._from_sequence(new_values, dtype=self.dtype) + self[mask] = new_values[mask] + return + @classmethod def _empty(cls, shape: Shape, dtype: ExtensionDtype): """ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index b53679e2b584a..732508f9b7fb6 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6518,10 +6518,13 @@ def replace( if isinstance(to_replace, (tuple, list)): if isinstance(self, ABCDataFrame): - return self.apply( + result = self.apply( self._constructor_sliced._replace_single, args=(to_replace, method, inplace, limit), ) + if inplace: + return + return result self = cast("Series", self) return self._replace_single(to_replace, method, inplace, limit) diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 68ac7b4968d15..ede0878f15caa 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -97,6 +97,9 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> npt.NDArray[np.bool_]: 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/core/series.py b/pandas/core/series.py index 391169af598c2..0b4e7fe4ee774 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4889,23 +4889,20 @@ def _replace_single(self, to_replace, method: str, inplace: bool, limit): replacement value is given in the replace method """ - orig_dtype = self.dtype result = self if inplace else self.copy() - fill_f = missing.get_fill_func(method) - mask = missing.mask_missing(result.values, to_replace) - values, _ = fill_f(result.values, limit=limit, mask=mask) + values = result._values + mask = missing.mask_missing(values, to_replace) - if values.dtype == orig_dtype and inplace: - return - - result = self._constructor(values, index=self.index, dtype=self.dtype) - result = result.__finalize__(self) + if isinstance(values, ExtensionArray): + # dispatch to the EA's _pad_mask_inplace method + values._fill_mask_inplace(method, limit, mask) + else: + fill_f = missing.get_fill_func(method) + values, _ = fill_f(values, limit=limit, mask=mask) if inplace: - self._update_inplace(result) return - return result # error: Cannot determine type of 'shift' diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index fb9c326bdafd9..3a6cd4eb0face 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -442,6 +442,56 @@ def test_replace_extension_other(self, frame_or_series): # should not have changed dtype tm.assert_equal(obj, result) + def _check_replace_with_method(self, ser: pd.Series): + df = ser.to_frame() + + res = ser.replace(ser[1], method="pad") + expected = pd.Series([ser[0], ser[0]] + list(ser[2:]), dtype=ser.dtype) + tm.assert_series_equal(res, expected) + + res_df = df.replace(ser[1], method="pad") + tm.assert_frame_equal(res_df, expected.to_frame()) + + ser2 = ser.copy() + res2 = ser2.replace(ser[1], method="pad", inplace=True) + assert res2 is None + tm.assert_series_equal(ser2, expected) + + res_df2 = df.replace(ser[1], method="pad", inplace=True) + assert res_df2 is None + tm.assert_frame_equal(df, expected.to_frame()) + + def test_replace_ea_dtype_with_method(self, any_numeric_ea_dtype): + arr = pd.array([1, 2, pd.NA, 4], dtype=any_numeric_ea_dtype) + ser = pd.Series(arr) + + self._check_replace_with_method(ser) + + @pytest.mark.parametrize("as_categorical", [True, False]) + def test_replace_interval_with_method(self, as_categorical): + # in particular interval that can't hold NA + + idx = pd.IntervalIndex.from_breaks(range(4)) + ser = pd.Series(idx) + if as_categorical: + ser = ser.astype("category") + + self._check_replace_with_method(ser) + + @pytest.mark.parametrize("as_period", [True, False]) + @pytest.mark.parametrize("as_categorical", [True, False]) + def test_replace_datetimelike_with_method(self, as_period, as_categorical): + idx = pd.date_range("2016-01-01", periods=5, tz="US/Pacific") + if as_period: + idx = idx.tz_localize(None).to_period("D") + + ser = pd.Series(idx) + ser.iloc[-2] = pd.NaT + if as_categorical: + ser = ser.astype("category") + + self._check_replace_with_method(ser) + def test_replace_with_compiled_regex(self): # https://github.com/pandas-dev/pandas/issues/35680 s = pd.Series(["a", "b", "c"])
- [ ] 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/44270
2021-11-01T16:01:05Z
2021-11-05T18:50:53Z
2021-11-05T18:50:53Z
2021-11-05T18:55:38Z
ENH: Add DataFrameGroupBy.value_counts
diff --git a/doc/source/reference/groupby.rst b/doc/source/reference/groupby.rst index ccf130d03418c..2bb0659264eb0 100644 --- a/doc/source/reference/groupby.rst +++ b/doc/source/reference/groupby.rst @@ -122,6 +122,7 @@ application to columns of a specific data type. DataFrameGroupBy.skew DataFrameGroupBy.take DataFrameGroupBy.tshift + DataFrameGroupBy.value_counts The following methods are available only for ``SeriesGroupBy`` objects. diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 413dbb9cd0850..8b74e485439be 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -217,6 +217,7 @@ Other enhancements - Added :meth:`.ExponentialMovingWindow.sum` (:issue:`13297`) - :meth:`Series.str.split` now supports a ``regex`` argument that explicitly specifies whether the pattern is a regular expression. Default is ``None`` (:issue:`43563`, :issue:`32835`, :issue:`25549`) - :meth:`DataFrame.dropna` now accepts a single label as ``subset`` along with array-like (:issue:`41021`) +- Added :meth:`DataFrameGroupBy.value_counts` (:issue:`43564`) - :class:`ExcelWriter` argument ``if_sheet_exists="overlay"`` option added (:issue:`40231`) - :meth:`read_excel` now accepts a ``decimal`` argument that allow the user to specify the decimal point when parsing string columns to numeric (:issue:`14403`) - :meth:`.GroupBy.mean`, :meth:`.GroupBy.std`, and :meth:`.GroupBy.var` now supports `Numba <http://numba.pydata.org/>`_ execution with the ``engine`` keyword (:issue:`43731`, :issue:`44862`) diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 986aaa07a913c..48faa1fc46759 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -143,6 +143,7 @@ class OutputKey: "take", "transform", "sample", + "value_counts", ] ) # Valid values of `name` for `groupby.transform(name)` diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 4535010b29c3a..9b341845c7170 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -17,6 +17,7 @@ Iterable, Mapping, NamedTuple, + Sequence, TypeVar, Union, cast, @@ -76,6 +77,7 @@ _transform_template, warn_dropping_nuisance_columns_deprecated, ) +from pandas.core.groupby.grouper import get_grouper from pandas.core.indexes.api import ( Index, MultiIndex, @@ -1569,6 +1571,193 @@ def func(df): boxplot = boxplot_frame_groupby + def value_counts( + self, + subset: Sequence[Hashable] | None = None, + normalize: bool = False, + sort: bool = True, + ascending: bool = False, + dropna: bool = True, + ) -> DataFrame | Series: + """ + Return a Series or DataFrame containing counts of unique rows. + + .. versionadded:: 1.4.0 + + Parameters + ---------- + subset : list-like, optional + Columns to use when counting unique combinations. + normalize : bool, default False + Return proportions rather than frequencies. + sort : bool, default True + Sort by frequencies. + ascending : bool, default False + Sort in ascending order. + dropna : bool, default True + Don’t include counts of rows that contain NA values. + + Returns + ------- + Series or DataFrame + Series if the groupby as_index is True, otherwise DataFrame. + + See Also + -------- + Series.value_counts: Equivalent method on Series. + DataFrame.value_counts: Equivalent method on DataFrame. + SeriesGroupBy.value_counts: Equivalent method on SeriesGroupBy. + + Notes + ----- + - If the groupby as_index is True then the returned Series will have a + MultiIndex with one level per input column. + - If the groupby as_index is False then the returned DataFrame will have an + additional column with the value_counts. The column is labelled 'count' or + 'proportion', depending on the ``normalize`` parameter. + + By default, rows that contain any NA values are omitted from + the result. + + By default, the result will be in descending order so that the + first element of each group is the most frequently-occurring row. + + Examples + -------- + >>> df = pd.DataFrame({ + ... 'gender': ['male', 'male', 'female', 'male', 'female', 'male'], + ... 'education': ['low', 'medium', 'high', 'low', 'high', 'low'], + ... 'country': ['US', 'FR', 'US', 'FR', 'FR', 'FR'] + ... }) + + >>> df + gender education country + 0 male low US + 1 male medium FR + 2 female high US + 3 male low FR + 4 female high FR + 5 male low FR + + >>> df.groupby('gender').value_counts() + gender education country + female high FR 1 + US 1 + male low FR 2 + US 1 + medium FR 1 + dtype: int64 + + >>> df.groupby('gender').value_counts(ascending=True) + gender education country + female high FR 1 + US 1 + male low US 1 + medium FR 1 + low FR 2 + dtype: int64 + + >>> df.groupby('gender').value_counts(normalize=True) + gender education country + female high FR 0.50 + US 0.50 + male low FR 0.50 + US 0.25 + medium FR 0.25 + dtype: float64 + + >>> df.groupby('gender', as_index=False).value_counts() + gender education country count + 0 female high FR 1 + 1 female high US 1 + 2 male low FR 2 + 3 male low US 1 + 4 male medium FR 1 + + >>> df.groupby('gender', as_index=False).value_counts(normalize=True) + gender education country proportion + 0 female high FR 0.50 + 1 female high US 0.50 + 2 male low FR 0.50 + 3 male low US 0.25 + 4 male medium FR 0.25 + """ + if self.axis == 1: + raise NotImplementedError( + "DataFrameGroupBy.value_counts only handles axis=0" + ) + + with self._group_selection_context(): + df = self.obj + + in_axis_names = { + grouping.name for grouping in self.grouper.groupings if grouping.in_axis + } + if isinstance(self._selected_obj, Series): + name = self._selected_obj.name + keys = [] if name in in_axis_names else [self._selected_obj] + else: + keys = [ + # Can't use .values because the column label needs to be preserved + self._selected_obj.iloc[:, idx] + for idx, name in enumerate(self._selected_obj.columns) + if name not in in_axis_names + ] + + if subset is not None: + clashing = set(subset) & set(in_axis_names) + if clashing: + raise ValueError( + f"Keys {clashing} in subset cannot be in " + "the groupby column keys" + ) + + groupings = list(self.grouper.groupings) + for key in keys: + grouper, _, _ = get_grouper( + df, + key=key, + axis=self.axis, + sort=self.sort, + dropna=dropna, + ) + groupings += list(grouper.groupings) + + # Take the size of the overall columns + gb = df.groupby( + groupings, + sort=self.sort, + observed=self.observed, + dropna=self.dropna, + ) + result = cast(Series, gb.size()) + + if normalize: + # Normalize the results by dividing by the original group sizes. + # We are guaranteed to have the first N levels be the + # user-requested grouping. + levels = list(range(len(self.grouper.groupings), result.index.nlevels)) + indexed_group_size = result.groupby( + result.index.droplevel(levels), + sort=self.sort, + observed=self.observed, + dropna=self.dropna, + ).transform("sum") + + result /= indexed_group_size + + if sort: + # Sort the values and then resort by the main grouping + index_level = range(len(self.grouper.groupings)) + result = result.sort_values(ascending=ascending).sort_index( + level=index_level, sort_remaining=False + ) + + if not self.as_index: + # Convert to frame + result = result.reset_index(name="proportion" if normalize else "count") + return result.__finalize__(self.obj, method="value_counts") + def _wrap_transform_general_frame( obj: DataFrame, group: DataFrame, res: DataFrame | Series diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index a05f8e581d12f..1e6515084d3b7 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -800,7 +800,7 @@ def get_grouper( # what are we after, exactly? any_callable = any(callable(g) or isinstance(g, dict) for g in keys) - any_groupers = any(isinstance(g, Grouper) for g in keys) + any_groupers = any(isinstance(g, (Grouper, Grouping)) for g in keys) any_arraylike = any( isinstance(g, (list, tuple, Series, Index, np.ndarray)) for g in keys ) diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py index 9d9a2e39e06c7..44778aafdf75f 100644 --- a/pandas/tests/groupby/test_allowlist.py +++ b/pandas/tests/groupby/test_allowlist.py @@ -319,6 +319,7 @@ def test_tab_completion(mframe): "pipe", "sample", "ewm", + "value_counts", } assert results == expected diff --git a/pandas/tests/groupby/test_frame_value_counts.py b/pandas/tests/groupby/test_frame_value_counts.py new file mode 100644 index 0000000000000..79ef46db8e95e --- /dev/null +++ b/pandas/tests/groupby/test_frame_value_counts.py @@ -0,0 +1,444 @@ +import numpy as np +import pytest + +from pandas import ( + CategoricalIndex, + DataFrame, + Index, + MultiIndex, + Series, +) +import pandas._testing as tm + + +@pytest.fixture +def education_df(): + return DataFrame( + { + "gender": ["male", "male", "female", "male", "female", "male"], + "education": ["low", "medium", "high", "low", "high", "low"], + "country": ["US", "FR", "US", "FR", "FR", "FR"], + } + ) + + +def test_axis(education_df): + gp = education_df.groupby("country", axis=1) + with pytest.raises(NotImplementedError, match="axis"): + gp.value_counts() + + +def test_bad_subset(education_df): + gp = education_df.groupby("country") + with pytest.raises(ValueError, match="subset"): + gp.value_counts(subset=["country"]) + + +def test_basic(education_df): + # gh43564 + result = education_df.groupby("country")[["gender", "education"]].value_counts( + normalize=True + ) + expected = Series( + data=[0.5, 0.25, 0.25, 0.5, 0.5], + index=MultiIndex.from_tuples( + [ + ("FR", "male", "low"), + ("FR", "female", "high"), + ("FR", "male", "medium"), + ("US", "female", "high"), + ("US", "male", "low"), + ], + names=["country", "gender", "education"], + ), + ) + tm.assert_series_equal(result, expected) + + +def _frame_value_counts(df, keys, normalize, sort, ascending): + return df[keys].value_counts(normalize=normalize, sort=sort, ascending=ascending) + + +@pytest.mark.parametrize("groupby", ["column", "array", "function"]) +@pytest.mark.parametrize("normalize", [True, False]) +@pytest.mark.parametrize( + "sort, ascending", + [ + (False, None), + (True, True), + (True, False), + ], +) +@pytest.mark.parametrize("as_index", [True, False]) +@pytest.mark.parametrize("frame", [True, False]) +def test_against_frame_and_seriesgroupby( + education_df, groupby, normalize, sort, ascending, as_index, frame +): + # test all parameters: + # - Use column, array or function as by= parameter + # - Whether or not to normalize + # - Whether or not to sort and how + # - Whether or not to use the groupby as an index + # - 3-way compare against: + # - apply with :meth:`~DataFrame.value_counts` + # - `~SeriesGroupBy.value_counts` + by = { + "column": "country", + "array": education_df["country"].values, + "function": lambda x: education_df["country"][x] == "US", + }[groupby] + + gp = education_df.groupby(by=by, as_index=as_index) + result = gp[["gender", "education"]].value_counts( + normalize=normalize, sort=sort, ascending=ascending + ) + if frame: + # compare against apply with DataFrame value_counts + expected = gp.apply( + _frame_value_counts, ["gender", "education"], normalize, sort, ascending + ) + + if as_index: + tm.assert_series_equal(result, expected) + else: + name = "proportion" if normalize else "count" + expected = expected.reset_index().rename({0: name}, axis=1) + if groupby == "column": + expected = expected.rename({"level_0": "country"}, axis=1) + expected["country"] = np.where(expected["country"], "US", "FR") + elif groupby == "function": + expected["level_0"] = expected["level_0"] == 1 + else: + expected["level_0"] = np.where(expected["level_0"], "US", "FR") + tm.assert_frame_equal(result, expected) + else: + # compare against SeriesGroupBy value_counts + education_df["both"] = education_df["gender"] + "-" + education_df["education"] + expected = gp["both"].value_counts( + normalize=normalize, sort=sort, ascending=ascending + ) + expected.name = None + if as_index: + index_frame = expected.index.to_frame(index=False) + index_frame["gender"] = index_frame["both"].str.split("-").str.get(0) + index_frame["education"] = index_frame["both"].str.split("-").str.get(1) + del index_frame["both"] + index_frame = index_frame.rename({0: None}, axis=1) + expected.index = MultiIndex.from_frame(index_frame) + tm.assert_series_equal(result, expected) + else: + expected.insert(1, "gender", expected["both"].str.split("-").str.get(0)) + expected.insert(2, "education", expected["both"].str.split("-").str.get(1)) + del expected["both"] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("normalize", [True, False]) +@pytest.mark.parametrize( + "sort, ascending, expected_rows, expected_count, expected_group_size", + [ + (False, None, [0, 1, 2, 3, 4], [1, 1, 1, 2, 1], [1, 3, 1, 3, 1]), + (True, False, [4, 3, 1, 2, 0], [1, 2, 1, 1, 1], [1, 3, 3, 1, 1]), + (True, True, [4, 1, 3, 2, 0], [1, 1, 2, 1, 1], [1, 3, 3, 1, 1]), + ], +) +def test_compound( + education_df, + normalize, + sort, + ascending, + expected_rows, + expected_count, + expected_group_size, +): + # Multiple groupby keys and as_index=False + gp = education_df.groupby(["country", "gender"], as_index=False, sort=False) + result = gp["education"].value_counts( + normalize=normalize, sort=sort, ascending=ascending + ) + expected = DataFrame() + for column in ["country", "gender", "education"]: + expected[column] = [education_df[column][row] for row in expected_rows] + if normalize: + expected["proportion"] = expected_count + expected["proportion"] /= expected_group_size + else: + expected["count"] = expected_count + tm.assert_frame_equal(result, expected) + + +@pytest.fixture +def animals_df(): + return DataFrame( + {"key": [1, 1, 1, 1], "num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + +@pytest.mark.parametrize( + "sort, ascending, normalize, expected_data, expected_index", + [ + (False, None, False, [1, 2, 1], [(1, 1, 1), (2, 4, 6), (2, 0, 0)]), + (True, True, False, [1, 1, 2], [(1, 1, 1), (2, 6, 4), (2, 0, 0)]), + (True, False, False, [2, 1, 1], [(1, 1, 1), (4, 2, 6), (0, 2, 0)]), + (True, False, True, [0.5, 0.25, 0.25], [(1, 1, 1), (4, 2, 6), (0, 2, 0)]), + ], +) +def test_data_frame_value_counts( + animals_df, sort, ascending, normalize, expected_data, expected_index +): + # 3-way compare with :meth:`~DataFrame.value_counts` + # Tests from frame/methods/test_value_counts.py + result_frame = animals_df.value_counts( + sort=sort, ascending=ascending, normalize=normalize + ) + expected = Series( + data=expected_data, + index=MultiIndex.from_arrays( + expected_index, names=["key", "num_legs", "num_wings"] + ), + ) + tm.assert_series_equal(result_frame, expected) + + result_frame_groupby = animals_df.groupby("key").value_counts( + sort=sort, ascending=ascending, normalize=normalize + ) + + tm.assert_series_equal(result_frame_groupby, expected) + + +@pytest.fixture +def nulls_df(): + n = np.nan + return DataFrame( + { + "A": [1, 1, n, 4, n, 6, 6, 6, 6], + "B": [1, 1, 3, n, n, 6, 6, 6, 6], + "C": [1, 2, 3, 4, 5, 6, n, 8, n], + "D": [1, 2, 3, 4, 5, 6, 7, n, n], + } + ) + + +@pytest.mark.parametrize( + "group_dropna, count_dropna, expected_rows, expected_values", + [ + ( + False, + False, + [0, 1, 3, 5, 7, 6, 8, 2, 4], + [0.5, 0.5, 1.0, 0.25, 0.25, 0.25, 0.25, 1.0, 1.0], + ), + (False, True, [0, 1, 3, 5, 2, 4], [0.5, 0.5, 1.0, 1.0, 1.0, 1.0]), + (True, False, [0, 1, 5, 7, 6, 8], [0.5, 0.5, 0.25, 0.25, 0.25, 0.25]), + (True, True, [0, 1, 5], [0.5, 0.5, 1.0]), + ], +) +def test_dropna_combinations( + nulls_df, group_dropna, count_dropna, expected_rows, expected_values +): + gp = nulls_df.groupby(["A", "B"], dropna=group_dropna) + result = gp.value_counts(normalize=True, sort=True, dropna=count_dropna) + columns = DataFrame() + for column in nulls_df.columns: + columns[column] = [nulls_df[column][row] for row in expected_rows] + index = MultiIndex.from_frame(columns) + expected = Series(data=expected_values, index=index) + tm.assert_series_equal(result, expected) + + +@pytest.fixture +def names_with_nulls_df(nulls_fixture): + return DataFrame( + { + "key": [1, 1, 1, 1], + "first_name": ["John", "Anne", "John", "Beth"], + "middle_name": ["Smith", nulls_fixture, nulls_fixture, "Louise"], + }, + ) + + +@pytest.mark.parametrize( + "dropna, expected_data, expected_index", + [ + ( + True, + [1, 1], + MultiIndex.from_arrays( + [(1, 1), ("Beth", "John"), ("Louise", "Smith")], + names=["key", "first_name", "middle_name"], + ), + ), + ( + False, + [1, 1, 1, 1], + MultiIndex( + levels=[ + Index([1]), + Index(["Anne", "Beth", "John"]), + Index(["Louise", "Smith", np.nan]), + ], + codes=[[0, 0, 0, 0], [0, 1, 2, 2], [2, 0, 1, 2]], + names=["key", "first_name", "middle_name"], + ), + ), + ], +) +@pytest.mark.parametrize("normalize", [False, True]) +def test_data_frame_value_counts_dropna( + names_with_nulls_df, dropna, normalize, expected_data, expected_index +): + # GH 41334 + # 3-way compare with :meth:`~DataFrame.value_counts` + # Tests with nulls from frame/methods/test_value_counts.py + result_frame = names_with_nulls_df.value_counts(dropna=dropna, normalize=normalize) + expected = Series( + data=expected_data, + index=expected_index, + ) + if normalize: + expected /= float(len(expected_data)) + + tm.assert_series_equal(result_frame, expected) + + result_frame_groupby = names_with_nulls_df.groupby("key").value_counts( + dropna=dropna, normalize=normalize + ) + + tm.assert_series_equal(result_frame_groupby, expected) + + +@pytest.mark.parametrize("as_index", [False, True]) +@pytest.mark.parametrize( + "observed, expected_index", + [ + ( + False, + [ + ("FR", "male", "low"), + ("FR", "female", "high"), + ("FR", "male", "medium"), + ("FR", "female", "low"), + ("FR", "female", "medium"), + ("FR", "male", "high"), + ("US", "female", "high"), + ("US", "male", "low"), + ("US", "female", "low"), + ("US", "female", "medium"), + ("US", "male", "high"), + ("US", "male", "medium"), + ], + ), + ( + True, + [ + ("FR", "male", "low"), + ("FR", "female", "high"), + ("FR", "male", "medium"), + ("US", "female", "high"), + ("US", "male", "low"), + ], + ), + ], +) +@pytest.mark.parametrize( + "normalize, expected_data", + [ + (False, np.array([2, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], dtype=np.int64)), + ( + True, + np.array([0.5, 0.25, 0.25, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]), + ), + ], +) +def test_categorical( + education_df, as_index, observed, expected_index, normalize, expected_data +): + # Test categorical data whether or not observed + gp = education_df.astype("category").groupby( + "country", as_index=as_index, observed=observed + ) + result = gp.value_counts(normalize=normalize) + + expected_series = Series( + data=expected_data[expected_data > 0.0] if observed else expected_data, + index=MultiIndex.from_tuples( + expected_index, + names=["country", "gender", "education"], + ), + ) + for i in range(3): + expected_series.index = expected_series.index.set_levels( + CategoricalIndex(expected_series.index.levels[i]), level=i + ) + + if as_index: + tm.assert_series_equal(result, expected_series) + else: + expected = expected_series.reset_index( + name="proportion" if normalize else "count" + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "normalize, expected_label, expected_values", + [ + (False, "count", [1, 1, 1]), + (True, "proportion", [0.5, 0.5, 1.0]), + ], +) +def test_mixed_groupings(normalize, expected_label, expected_values): + # Test multiple groupings + df = DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]}) + gp = df.groupby([[4, 5, 4], "A", lambda i: 7 if i == 1 else 8], as_index=False) + result = gp.value_counts(sort=True, normalize=normalize) + expected = DataFrame( + { + "level_0": [4, 4, 5], + "A": [1, 1, 2], + "level_2": [8, 8, 7], + "B": [1, 3, 2], + expected_label: expected_values, + } + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "test, expected_names", + [ + ("repeat", ["a", None, "d", "b", "b", "e"]), + ("level", ["a", None, "d", "b", "c", "level_1"]), + ], +) +@pytest.mark.parametrize("as_index", [False, True]) +def test_column_name_clashes(test, expected_names, as_index): + df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6], "d": [7, 8], "e": [9, 10]}) + if test == "repeat": + df.columns = list("abbde") + else: + df.columns = list("abcd") + ["level_1"] + + if as_index: + result = df.groupby(["a", [0, 1], "d"], as_index=as_index).value_counts() + expected = Series( + data=(1, 1), + index=MultiIndex.from_tuples( + [(1, 0, 7, 3, 5, 9), (2, 1, 8, 4, 6, 10)], + names=expected_names, + ), + ) + tm.assert_series_equal(result, expected) + else: + with pytest.raises(ValueError, match="cannot insert"): + df.groupby(["a", [0, 1], "d"], as_index=as_index).value_counts() + + +def test_ambiguous_grouping(): + # Test that groupby is not confused by groupings length equal to row count + df = DataFrame({"a": [1, 1]}) + gb = df.groupby([1, 1]) + result = gb.value_counts() + expected = Series([2], index=MultiIndex.from_tuples([[1, 1]], names=[None, "a"])) + tm.assert_series_equal(result, expected)
- [x] closes #43564 - [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/44267
2021-11-01T07:34:22Z
2021-12-19T23:25:42Z
2021-12-19T23:25:42Z
2021-12-20T08:05:12Z
⬆️ UPGRADE: Autoupdate pre-commit config
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 469c4066e2387..21f325dd01913 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,7 +9,7 @@ repos: - id: absolufy-imports files: ^pandas/ - repo: https://github.com/python/black - rev: 21.9b0 + rev: 21.10b0 hooks: - id: black - repo: https://github.com/codespell-project/codespell @@ -74,7 +74,7 @@ repos: types: [text] # overwrite types: [rst] types_or: [python, rst] - repo: https://github.com/asottile/yesqa - rev: v1.2.3 + rev: v1.3.0 hooks: - id: yesqa additional_dependencies: *flake8_dependencies
<!-- START pr-commits --> <!-- END pr-commits --> ## Base PullRequest default branch (https://github.com/pandas-dev/pandas/tree/master) ## Command results <details> <summary>Details: </summary> <details> <summary><em>add path</em></summary> ```Shell /home/runner/work/_actions/technote-space/create-pr-action/v2/node_modules/npm-check-updates/bin ``` </details> <details> <summary><em>pip install pre-commit</em></summary> ```Shell Collecting pre-commit Downloading pre_commit-2.15.0-py2.py3-none-any.whl (191 kB) Collecting toml Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB) Collecting nodeenv>=0.11.1 Downloading nodeenv-1.6.0-py2.py3-none-any.whl (21 kB) Collecting virtualenv>=20.0.8 Downloading virtualenv-20.9.0-py2.py3-none-any.whl (5.6 MB) Collecting pyyaml>=5.1 Downloading PyYAML-6.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (682 kB) Collecting cfgv>=2.0.0 Downloading cfgv-3.3.1-py2.py3-none-any.whl (7.3 kB) Collecting identify>=1.0.0 Downloading identify-2.3.3-py2.py3-none-any.whl (98 kB) Collecting platformdirs<3,>=2 Downloading platformdirs-2.4.0-py3-none-any.whl (14 kB) Collecting filelock<4,>=3.2 Downloading filelock-3.3.2-py3-none-any.whl (9.7 kB) Collecting six<2,>=1.9.0 Downloading six-1.16.0-py2.py3-none-any.whl (11 kB) Collecting distlib<1,>=0.3.1 Downloading distlib-0.3.3-py2.py3-none-any.whl (496 kB) Collecting backports.entry-points-selectable>=1.0.4 Downloading backports.entry_points_selectable-1.1.0-py2.py3-none-any.whl (6.2 kB) Installing collected packages: six, platformdirs, filelock, distlib, backports.entry-points-selectable, virtualenv, toml, pyyaml, nodeenv, identify, cfgv, pre-commit Successfully installed backports.entry-points-selectable-1.1.0 cfgv-3.3.1 distlib-0.3.3 filelock-3.3.2 identify-2.3.3 nodeenv-1.6.0 platformdirs-2.4.0 pre-commit-2.15.0 pyyaml-6.0 six-1.16.0 toml-0.10.2 virtualenv-20.9.0 ``` ### stderr: ```Shell WARNING: You are using pip version 21.3; however, version 21.3.1 is available. You should consider upgrading via the '/opt/hostedtoolcache/Python/3.10.0/x64/bin/python -m pip install --upgrade pip' command. ``` </details> <details> <summary><em>pre-commit autoupdate || (exit 0);</em></summary> ```Shell Updating https://github.com/MarcoGorelli/absolufy-imports ... [INFO] Initializing environment for https://github.com/MarcoGorelli/absolufy-imports. already up to date. Updating https://github.com/python/black ... [INFO] Initializing environment for https://github.com/python/black. updating 21.9b0 -> 21.10b0. Updating https://github.com/codespell-project/codespell ... [INFO] Initializing environment for https://github.com/codespell-project/codespell. already up to date. Updating https://github.com/pre-commit/pre-commit-hooks ... [INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks. already up to date. Updating https://github.com/cpplint/cpplint ... [INFO] Initializing environment for https://github.com/cpplint/cpplint. already up to date. Updating https://gitlab.com/pycqa/flake8 ... [INFO] Initializing environment for https://gitlab.com/pycqa/flake8. already up to date. Updating https://github.com/PyCQA/isort ... [INFO] Initializing environment for https://github.com/PyCQA/isort. already up to date. Updating https://github.com/asottile/pyupgrade ... [INFO] Initializing environment for https://github.com/asottile/pyupgrade. already up to date. Updating https://github.com/pre-commit/pygrep-hooks ... [INFO] Initializing environment for https://github.com/pre-commit/pygrep-hooks. already up to date. Updating https://github.com/asottile/yesqa ... [INFO] Initializing environment for https://github.com/asottile/yesqa. updating v1.2.3 -> v1.3.0. ``` </details> <details> <summary><em>pre-commit run -a || (exit 0);</em></summary> ```Shell [INFO] Initializing environment for https://gitlab.com/pycqa/flake8:flake8-bugbear==21.3.2,flake8-comprehensions==3.1.0,flake8==3.9.2,pandas-dev-flaker==0.2.0. [INFO] Initializing environment for https://github.com/asottile/yesqa:flake8-bugbear==21.3.2,flake8-comprehensions==3.1.0,flake8==3.9.2,pandas-dev-flaker==0.2.0. [INFO] Initializing environment for local:pyright@1.1.171. [INFO] Initializing environment for local:flake8-rst==0.7.0,flake8==3.7.9. [INFO] Initializing environment for local:pyyaml,toml. [INFO] Initializing environment for local:pyyaml. [INFO] Initializing environment for local. [INFO] Installing environment for https://github.com/MarcoGorelli/absolufy-imports. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/python/black. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/codespell-project/codespell. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/cpplint/cpplint. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://gitlab.com/pycqa/flake8. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://gitlab.com/pycqa/flake8. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/PyCQA/isort. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/asottile/pyupgrade. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/asottile/yesqa. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for local. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for local. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for local. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for local. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... absolufy-imports................................................................................................Passed black...........................................................................................................Passed codespell.......................................................................................................Passed Debug Statements (Python).......................................................................................Passed Fix End of Files................................................................................................Passed Trim Trailing Whitespace........................................................................................Passed cpplint.........................................................................................................Passed flake8..........................................................................................................Passed flake8 (cython).................................................................................................Failed - hook id: flake8 - exit code: 1 multiprocessing.pool.RemoteTraceback: """ Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 478, in run_ast_checks ast = self.processor.build_ast() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/processor.py", line 225, in build_ast return ast.parse("".join(self.lines)) File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/ast.py", line 50, in parse return compile(source, filename, mode, flags, File "<unknown>", line 9 cimport numpy as cnp ^^^^^^^^^^^^^ SyntaxError: invalid syntax. Perhaps you forgot a comma? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 125, in worker result = (True, func(*args, **kwds)) File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 48, in mapstar return list(map(*args)) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 676, in _run_checks return checker.run_checks() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 589, in run_checks self.run_ast_checks() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 480, in run_ast_checks row, column = self._extract_syntax_information(e) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 465, in _extract_syntax_information lines = physical_line.rstrip("\n").split("\n") AttributeError: 'int' object has no attribute 'rstrip' """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/bin/flake8", line 8, in <module> sys.exit(main()) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/cli.py", line 22, in main app.run(argv) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 363, in run self._run(argv) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 351, in _run self.run_checks() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 264, in run_checks self.file_checker_manager.run() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 321, in run self.run_parallel() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 287, in run_parallel for ret in pool_map: File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 448, in <genexpr> return (item for chunk in result for item in chunk) File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 870, in next raise value AttributeError: 'int' object has no attribute 'rstrip' flake8 (cython template)........................................................................................Failed - hook id: flake8 - exit code: 1 multiprocessing.pool.RemoteTraceback: """ Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 478, in run_ast_checks ast = self.processor.build_ast() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/processor.py", line 225, in build_ast return ast.parse("".join(self.lines)) File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/ast.py", line 50, in parse return compile(source, filename, mode, flags, File "<unknown>", line 12 def ensure_platform_int(object arr): ^^^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 125, in worker result = (True, func(*args, **kwds)) File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 48, in mapstar return list(map(*args)) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 676, in _run_checks return checker.run_checks() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 589, in run_checks self.run_ast_checks() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 480, in run_ast_checks row, column = self._extract_syntax_information(e) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 465, in _extract_syntax_information lines = physical_line.rstrip("\n").split("\n") AttributeError: 'int' object has no attribute 'rstrip' """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/bin/flake8", line 8, in <module> sys.exit(main()) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/cli.py", line 22, in main app.run(argv) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 363, in run self._run(argv) File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 351, in _run self.run_checks() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 264, in run_checks self.file_checker_manager.run() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 321, in run self.run_parallel() File "/home/runner/.cache/pre-commit/repovgz80w1u/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 287, in run_parallel for ret in pool_map: File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 448, in <genexpr> return (item for chunk in result for item in chunk) File "/opt/hostedtoolcache/Python/3.10.0/x64/lib/python3.10/multiprocessing/pool.py", line 870, in next raise value AttributeError: 'int' object has no attribute 'rstrip' isort...........................................................................................................Passed pyupgrade.......................................................................................................Passed rst ``code`` is two backticks...................................................................................Passed rst directives end with two colons..............................................................................Passed rst ``inline code`` next to normal text.........................................................................Passed Strip unnecessary `# noqa`s.....................................................................................Passed flake8-rst......................................................................................................Failed - hook id: flake8-rst - exit code: 1 Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 486, in run_ast_checks ast = self.processor.build_ast() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/processor.py", line 212, in build_ast return compile("".join(self.lines), "", "exec", PyCF_ONLY_AST) File "", line 86 gb.<TAB> # noqa: E225, E999 ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/bin/flake8-rst", line 8, in <module> sys.exit(main()) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8_rst/cli.py", line 16, in main app.run(argv) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 393, in run self._run(argv) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 381, in _run self.run_checks() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 300, in run_checks self.file_checker_manager.run() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 331, in run self.run_serial() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 315, in run_serial checker.run_checks() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 598, in run_checks self.run_ast_checks() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 488, in run_ast_checks row, column = self._extract_syntax_information(e) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 473, in _extract_syntax_information lines = physical_line.rstrip("\n").split("\n") AttributeError: 'int' object has no attribute 'rstrip' Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 486, in run_ast_checks ast = self.processor.build_ast() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/processor.py", line 212, in build_ast return compile("".join(self.lines), "", "exec", PyCF_ONLY_AST) File "", line 35 df.plot.<TAB> # noqa: E225, E999 ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/bin/flake8-rst", line 8, in <module> sys.exit(main()) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8_rst/cli.py", line 16, in main app.run(argv) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 393, in run self._run(argv) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 381, in _run self.run_checks() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/main/application.py", line 300, in run_checks self.file_checker_manager.run() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 331, in run self.run_serial() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 315, in run_serial checker.run_checks() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 598, in run_checks self.run_ast_checks() File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 488, in run_ast_checks row, column = self._extract_syntax_information(e) File "/home/runner/.cache/pre-commit/repomx8iiwnk/py_env-python3.10/lib/python3.10/site-packages/flake8/checker.py", line 473, in _extract_syntax_information lines = physical_line.rstrip("\n").split("\n") AttributeError: 'int' object has no attribute 'rstrip' Unwanted patterns...............................................................................................Passed Check Cython casting is `<type>obj`, not `<type> obj`...........................................................Passed Check for backticks incorrectly rendering because of missing spaces.............................................Passed Check for unnecessary random seeds in asv benchmarks............................................................Passed Check for usage of numpy testing or array_equal.................................................................Passed Check for invalid EA testing....................................................................................Passed Generate pip dependency from conda..............................................................................Passed Check flake8 version is synced across flake8, yesqa, and environment.yml........................................Passed Validate correct capitalization among titles in documentation...................................................Passed Import pandas.array as pd_array in core.........................................................................Passed Use bool_t instead of bool in pandas/core/generic.py............................................................Passed Ensure pandas errors are documented in doc/source/reference/general_utility_functions.rst.......................Passed ``` </details> </details> ## Changed files <details> <summary>Changed file: </summary> - .pre-commit-config.yaml </details> <hr> [:octocat: Repo](https://github.com/technote-space/create-pr-action) | [:memo: Issues](https://github.com/technote-space/create-pr-action/issues) | [:department_store: Marketplace](https://github.com/marketplace/actions/create-pr-action)
https://api.github.com/repos/pandas-dev/pandas/pulls/44266
2021-11-01T07:07:30Z
2021-11-01T08:56:55Z
2021-11-01T08:56:54Z
2021-11-01T08:56:58Z
Fix formatting typo in user_guide/style.ipynb
diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb index 5fe619c749d42..3a991b5338c38 100644 --- a/doc/source/user_guide/style.ipynb +++ b/doc/source/user_guide/style.ipynb @@ -1412,7 +1412,7 @@ "source": [ "## Limitations\n", "\n", - "- DataFrame only `(use Series.to_frame().style)`\n", + "- DataFrame only (use `Series.to_frame().style`)\n", "- The index and columns must be unique\n", "- No large repr, and construction performance isn't great; although we have some [HTML optimizations](#Optimization)\n", "- You can only style the *values*, not the index or columns (except with `table_styles` above)\n",
Seems to be incorrect: > - DataFrame only `(use Series.to_frame().style)` Fixed: > - DataFrame only (use `Series.to_frame().style`)
https://api.github.com/repos/pandas-dev/pandas/pulls/44264
2021-11-01T04:24:52Z
2021-11-01T13:48:52Z
2021-11-01T13:48:52Z
2021-11-01T13:48:56Z
ENH/PERF: RangeIndex.argsort accept kind; pd.isna(rangeindex) fastpath
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 38553bc1be8d6..c457b52cf4b0e 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -169,13 +169,17 @@ def _isna(obj, inf_as_na: bool = False): return False elif isinstance(obj, (np.ndarray, ABCExtensionArray)): return _isna_array(obj, inf_as_na=inf_as_na) - elif isinstance(obj, (ABCSeries, ABCIndex)): + elif isinstance(obj, ABCIndex): + # Try to use cached isna, which also short-circuits for integer dtypes + # and avoids materializing RangeIndex._values + if not obj._can_hold_na: + return obj.isna() + return _isna_array(obj._values, inf_as_na=inf_as_na) + + elif isinstance(obj, ABCSeries): result = _isna_array(obj._values, inf_as_na=inf_as_na) # box - if isinstance(obj, ABCSeries): - result = obj._constructor( - result, index=obj.index, name=obj.name, copy=False - ) + result = obj._constructor(result, index=obj.index, name=obj.name, copy=False) return result elif isinstance(obj, ABCDataFrame): return obj.isna() diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 8aedc56d8e1cd..aed7a7a467db3 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -496,6 +496,7 @@ def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]: numpy.ndarray.argsort """ ascending = kwargs.pop("ascending", True) # EA compat + kwargs.pop("kind", None) # e.g. "mergesort" is irrelevant nv.validate_argsort(args, kwargs) if self._range.step > 0: diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 8f37413dd53c8..e34620d4caf17 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -333,11 +333,9 @@ def test_numpy_argsort(self, index): expected = index.argsort() tm.assert_numpy_array_equal(result, expected) - if not isinstance(index, RangeIndex): - # TODO: add compatibility to RangeIndex? - result = np.argsort(index, kind="mergesort") - expected = index.argsort(kind="mergesort") - tm.assert_numpy_array_equal(result, expected) + result = np.argsort(index, kind="mergesort") + expected = index.argsort(kind="mergesort") + tm.assert_numpy_array_equal(result, expected) # these are the only two types that perform # pandas compatibility input validation - the
- [ ] 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 - [ ] whatsnew entry We could use the cached index.isna more if #44262 is addressed.
https://api.github.com/repos/pandas-dev/pandas/pulls/44263
2021-11-01T02:22:03Z
2021-11-01T23:33:42Z
2021-11-01T23:33:41Z
2021-11-02T01:43:20Z
BUG: Series[int8][:3] = range(3) unnecessary upcasting to int64
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2a718fdcf16e7..0430db0c9dda7 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -537,7 +537,8 @@ Indexing - Bug in :meth:`Index.get_indexer_non_unique` when index contains multiple ``np.datetime64("NaT")`` and ``np.timedelta64("NaT")`` (:issue:`43869`) - Bug in setting a scalar :class:`Interval` value into a :class:`Series` with ``IntervalDtype`` when the scalar's sides are floats and the values' sides are integers (:issue:`44201`) - Bug when setting string-backed :class:`Categorical` values that can be parsed to datetimes into a :class:`DatetimeArray` or :class:`Series` or :class:`DataFrame` column backed by :class:`DatetimeArray` failing to parse these strings (:issue:`44236`) - +- Bug in :meth:`Series.__setitem__` with an integer dtype other than ``int64`` setting with a ``range`` object unnecessarily upcasting to ``int64`` (:issue:`44261`) +- Missing ^^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index c0ac9098ec7fc..8be4fc13ed991 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -2197,6 +2197,9 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if dtype.kind in ["i", "u"]: + if isinstance(element, range): + return _dtype_can_hold_range(element, dtype) + if tipo is not None: if tipo.kind not in ["i", "u"]: if is_float(element) and element.is_integer(): @@ -2209,6 +2212,7 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool: # i.e. nullable IntegerDtype; we can put this into an ndarray # losslessly iff it has no NAs return not element._mask.any() + return True # We have not inferred an integer from the dtype @@ -2249,3 +2253,14 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool: return isinstance(element, bytes) and len(element) <= dtype.itemsize raise NotImplementedError(dtype) + + +def _dtype_can_hold_range(rng: range, dtype: np.dtype) -> bool: + """ + maybe_infer_dtype_type infers to int64 (and float64 for very large endpoints), + but in many cases a range can be held by a smaller integer dtype. + Check if this is one of those cases. + """ + if not len(rng): + return True + return np.can_cast(rng[0], dtype) and np.can_cast(rng[-1], dtype) diff --git a/pandas/tests/dtypes/cast/test_can_hold_element.py b/pandas/tests/dtypes/cast/test_can_hold_element.py new file mode 100644 index 0000000000000..c4776f2a1e143 --- /dev/null +++ b/pandas/tests/dtypes/cast/test_can_hold_element.py @@ -0,0 +1,42 @@ +import numpy as np + +from pandas.core.dtypes.cast import can_hold_element + + +def test_can_hold_element_range(any_int_numpy_dtype): + # GH#44261 + dtype = np.dtype(any_int_numpy_dtype) + arr = np.array([], dtype=dtype) + + rng = range(2, 127) + assert can_hold_element(arr, rng) + + # negatives -> can't be held by uint dtypes + rng = range(-2, 127) + if dtype.kind == "i": + assert can_hold_element(arr, rng) + else: + assert not can_hold_element(arr, rng) + + rng = range(2, 255) + if dtype == "int8": + assert not can_hold_element(arr, rng) + else: + assert can_hold_element(arr, rng) + + rng = range(-255, 65537) + if dtype.kind == "u": + assert not can_hold_element(arr, rng) + elif dtype.itemsize < 4: + assert not can_hold_element(arr, rng) + else: + assert can_hold_element(arr, rng) + + # empty + rng = range(-(10 ** 10), -(10 ** 10)) + assert len(rng) == 0 + # assert can_hold_element(arr, rng) + + rng = range(10 ** 10, 10 ** 10) + assert len(rng) == 0 + assert can_hold_element(arr, rng) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 5521bee09b19b..5f0710dfbb85a 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -6,6 +6,8 @@ import numpy as np import pytest +from pandas.core.dtypes.common import is_list_like + from pandas import ( Categorical, DataFrame, @@ -622,6 +624,16 @@ def test_mask_key(self, obj, key, expected, val, indexer_sli): tm.assert_series_equal(obj, expected) def test_series_where(self, obj, key, expected, val, is_inplace): + if is_list_like(val) and len(val) < len(obj): + # Series.where is not valid here + if isinstance(val, range): + return + + # FIXME: The remaining TestSetitemDT64IntoInt that go through here + # are relying on technically-incorrect behavior because Block.where + # uses np.putmask instead of expressions.where in those cases, + # which has different length-checking semantics. + mask = np.zeros(obj.shape, dtype=bool) mask[key] = True @@ -973,6 +985,35 @@ def expected(self, obj, val): return Series(idx) +class TestSetitemRangeIntoIntegerSeries(SetitemCastingEquivalents): + # GH#44261 Setting a range with sufficiently-small integers into + # small-itemsize integer dtypes should not need to upcast + + @pytest.fixture + def obj(self, any_int_numpy_dtype): + dtype = np.dtype(any_int_numpy_dtype) + ser = Series(range(5), dtype=dtype) + return ser + + @pytest.fixture + def val(self): + return range(2, 4) + + @pytest.fixture + def key(self): + return slice(0, 2) + + @pytest.fixture + def expected(self, any_int_numpy_dtype): + dtype = np.dtype(any_int_numpy_dtype) + exp = Series([2, 3, 2, 3, 4], dtype=dtype) + return exp + + @pytest.fixture + def inplace(self): + return True + + def test_setitem_int_as_positional_fallback_deprecation(): # GH#42215 deprecated falling back to positional on __setitem__ with an # int not contained in the index
- [ ] 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/44261
2021-11-01T01:59:06Z
2021-11-04T00:37:12Z
2021-11-04T00:37:12Z
2021-11-04T01:12:03Z
CLN: tighten flake8/cython.cfg
diff --git a/flake8/cython.cfg b/flake8/cython.cfg index a9584ad2e0994..bf1f41647b34e 100644 --- a/flake8/cython.cfg +++ b/flake8/cython.cfg @@ -9,9 +9,5 @@ extend_ignore= E226, # missing whitespace around bitwise or shift operator E227, - # ambiguous variable name (# FIXME maybe this one can be fixed) - E741, # invalid syntax E999, - # invalid escape sequence (# FIXME maybe this one can be fixed) - W605, diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 68c09f83e1cdf..3d099a53163bc 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -259,15 +259,15 @@ cdef inline numeric_t kth_smallest_c(numeric_t* arr, Py_ssize_t k, Py_ssize_t n) in groupby.pyx """ cdef: - Py_ssize_t i, j, l, m + Py_ssize_t i, j, left, m numeric_t x - l = 0 + left = 0 m = n - 1 - while l < m: + while left < m: x = arr[k] - i = l + i = left j = m while 1: @@ -284,7 +284,7 @@ cdef inline numeric_t kth_smallest_c(numeric_t* arr, Py_ssize_t k, Py_ssize_t n) break if j < k: - l = i + left = i if k < i: m = j return arr[k] diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx index 75eee4d432637..39caf04ddf2f8 100644 --- a/pandas/_libs/hashing.pyx +++ b/pandas/_libs/hashing.pyx @@ -52,7 +52,7 @@ def hash_object_array( mixed array types will raise TypeError. """ cdef: - Py_ssize_t i, l, n + Py_ssize_t i, n uint64_t[:] result bytes data, k uint8_t *kb @@ -97,8 +97,7 @@ def hash_object_array( "must be string or null" ) - l = len(data) - lens[i] = l + lens[i] = len(data) cdata = data # keep the references alive through the end of the diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index 957432df20395..ac423ef6c0ca2 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -179,7 +179,7 @@ cdef class BlockPlacement: cdef BlockPlacement iadd(self, other): cdef: slice s = self._ensure_has_slice() - Py_ssize_t other_int, start, stop, step, l + Py_ssize_t other_int, start, stop, step if is_integer_object(other) and s is not None: other_int = <Py_ssize_t>other @@ -188,7 +188,7 @@ cdef class BlockPlacement: # BlockPlacement is treated as immutable return self - start, stop, step, l = slice_get_indices_ex(s) + start, stop, step, _ = slice_get_indices_ex(s) start += other_int stop += other_int @@ -226,14 +226,14 @@ cdef class BlockPlacement: """ cdef: slice nv, s = self._ensure_has_slice() - Py_ssize_t other_int, start, stop, step, l + Py_ssize_t other_int, start, stop, step ndarray[intp_t, ndim=1] newarr if s is not None: # see if we are either all-above or all-below, each of which # have fastpaths available. - start, stop, step, l = slice_get_indices_ex(s) + start, stop, step, _ = slice_get_indices_ex(s) if start < loc and stop <= loc: # We are entirely below, nothing to increment diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index b8f957a4c2ea8..f2b480642e083 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -808,12 +808,12 @@ class _timelex: # TODO: Change \s --> \s+ (this doesn't match existing behavior) # TODO: change the punctuation block to punc+ (does not match existing) # TODO: can we merge the two digit patterns? - tokens = re.findall('\s|' - '(?<![\.\d])\d+\.\d+(?![\.\d])' - '|\d+' - '|[a-zA-Z]+' - '|[\./:]+' - '|[^\da-zA-Z\./:\s]+', stream) + tokens = re.findall(r"\s|" + r"(?<![\.\d])\d+\.\d+(?![\.\d])" + r"|\d+" + r"|[a-zA-Z]+" + r"|[\./:]+" + r"|[^\da-zA-Z\./:\s]+", stream) # Re-combine token tuples of the form ["59", ",", "456"] because # in this context the "," is treated as a decimal diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index dcf4323bc8755..337876d610c5e 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -983,14 +983,14 @@ def periodarr_to_dt64arr(const int64_t[:] periodarr, int freq): """ cdef: int64_t[:] out - Py_ssize_t i, l + Py_ssize_t i, N if freq < 6000: # i.e. FR_DAY, hard-code to avoid need to cast - l = len(periodarr) - out = np.empty(l, dtype="i8") + N = len(periodarr) + out = np.empty(N, dtype="i8") # We get here with freqs that do not correspond to a datetime64 unit - for i in range(l): + for i in range(N): out[i] = period_ordinal_to_dt64(periodarr[i], freq) return out.base # .base to access underlying np.ndarray @@ -2248,7 +2248,7 @@ cdef class _Period(PeriodMixin): return (Period, object_state) def strftime(self, fmt: str) -> str: - """ + r""" Returns the string representation of the :class:`Period`, depending on the selected ``fmt``. ``fmt`` must be a string containing one or several directives. The method recognizes the same diff --git a/pandas/_libs/writers.pyx b/pandas/_libs/writers.pyx index 79f551c9ebf6f..46f04cf8e15b3 100644 --- a/pandas/_libs/writers.pyx +++ b/pandas/_libs/writers.pyx @@ -125,15 +125,15 @@ def max_len_string_array(pandas_string[:] arr) -> Py_ssize_t: Return the maximum size of elements in a 1-dim string array. """ cdef: - Py_ssize_t i, m = 0, l = 0, length = arr.shape[0] + Py_ssize_t i, m = 0, wlen = 0, length = arr.shape[0] pandas_string val for i in range(length): val = arr[i] - l = word_len(val) + wlen = word_len(val) - if l > m: - m = l + if wlen > m: + m = wlen return m @@ -143,14 +143,14 @@ cpdef inline Py_ssize_t word_len(object val): Return the maximum length of a string or bytes value. """ cdef: - Py_ssize_t l = 0 + Py_ssize_t wlen = 0 if isinstance(val, str): - l = PyUnicode_GET_LENGTH(val) + wlen = PyUnicode_GET_LENGTH(val) elif isinstance(val, bytes): - l = PyBytes_GET_SIZE(val) + wlen = PyBytes_GET_SIZE(val) - return l + return wlen # ------------------------------------------------------------------ # PyTables Helpers
- [ ] 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/44260
2021-10-31T23:50:27Z
2021-11-01T12:50:38Z
2021-11-01T12:50:38Z
2021-11-01T15:43:53Z
CLN: address TODOs, FIXMEs
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx index dc3bb09c1b462..b908fa2c65e4d 100644 --- a/pandas/_libs/join.pyx +++ b/pandas/_libs/join.pyx @@ -264,6 +264,9 @@ def left_join_indexer_unique( ndarray[numeric_object_t] left, ndarray[numeric_object_t] right ): + """ + Both left and right are strictly monotonic increasing. + """ cdef: Py_ssize_t i, j, nleft, nright ndarray[intp_t] indexer @@ -311,6 +314,9 @@ def left_join_indexer_unique( def left_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] right): """ Two-pass algorithm for monotonic indexes. Handles many-to-one merges. + + Both left and right are monotonic increasing, but at least one of them + is non-unique (if both were unique we'd use left_join_indexer_unique). """ cdef: Py_ssize_t i, j, k, nright, nleft, count @@ -321,6 +327,7 @@ def left_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] nleft = len(left) nright = len(right) + # First pass is to find the size 'count' of our output indexers. i = 0 j = 0 count = 0 @@ -334,6 +341,8 @@ def left_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] rval = right[j] if lval == rval: + # This block is identical across + # left_join_indexer, inner_join_indexer, outer_join_indexer count += 1 if i < nleft - 1: if j < nright - 1 and right[j + 1] == rval: @@ -398,12 +407,14 @@ def left_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] # end of the road break elif lval < rval: + # i.e. lval not in right; we keep for left_join_indexer lindexer[count] = i rindexer[count] = -1 - result[count] = left[i] + result[count] = lval count += 1 i += 1 else: + # i.e. rval not in left; we discard for left_join_indexer j += 1 return result, lindexer, rindexer @@ -414,6 +425,8 @@ def left_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] def inner_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] right): """ Two-pass algorithm for monotonic indexes. Handles many-to-one merges. + + Both left and right are monotonic increasing but not necessarily unique. """ cdef: Py_ssize_t i, j, k, nright, nleft, count @@ -424,6 +437,7 @@ def inner_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] nleft = len(left) nright = len(right) + # First pass is to find the size 'count' of our output indexers. i = 0 j = 0 count = 0 @@ -453,8 +467,10 @@ def inner_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] # end of the road break elif lval < rval: + # i.e. lval not in right; we discard for inner_indexer i += 1 else: + # i.e. rval not in left; we discard for inner_indexer j += 1 # do it again now that result size is known @@ -478,7 +494,7 @@ def inner_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] if lval == rval: lindexer[count] = i rindexer[count] = j - result[count] = rval + result[count] = lval count += 1 if i < nleft - 1: if j < nright - 1 and right[j + 1] == rval: @@ -495,8 +511,10 @@ def inner_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] # end of the road break elif lval < rval: + # i.e. lval not in right; we discard for inner_indexer i += 1 else: + # i.e. rval not in left; we discard for inner_indexer j += 1 return result, lindexer, rindexer @@ -505,6 +523,9 @@ def inner_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] @cython.wraparound(False) @cython.boundscheck(False) def outer_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] right): + """ + Both left and right are monotonic increasing but not necessarily unique. + """ cdef: Py_ssize_t i, j, nright, nleft, count numeric_object_t lval, rval @@ -514,6 +535,9 @@ def outer_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] nleft = len(left) nright = len(right) + # First pass is to find the size 'count' of our output indexers. + # count will be length of left plus the number of elements of right not in + # left (counting duplicates) i = 0 j = 0 count = 0 @@ -616,12 +640,14 @@ def outer_join_indexer(ndarray[numeric_object_t] left, ndarray[numeric_object_t] # end of the road break elif lval < rval: + # i.e. lval not in right; we keep for outer_join_indexer lindexer[count] = i rindexer[count] = -1 result[count] = lval count += 1 i += 1 else: + # i.e. rval not in left; we keep for outer_join_indexer lindexer[count] = -1 rindexer[count] = j result[count] = rval diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 2c4b420656259..c1915e719f515 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -198,7 +198,7 @@ cdef inline bint _is_on_month(int month, int compare_month, int modby) nogil: @cython.wraparound(False) @cython.boundscheck(False) def get_start_end_field(const int64_t[:] dtindex, str field, - object freqstr=None, int month_kw=12): + str freqstr=None, int month_kw=12): """ Given an int64-based datetime index return array of indicators of whether timestamps are at the start/end of the month/quarter/year diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index a8f69497d4019..ac27aaa42d151 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -9,7 +9,10 @@ import numpy as np from pandas._libs import lib -from pandas._typing import ArrayLike +from pandas._typing import ( + ArrayLike, + npt, +) from pandas.core.dtypes.cast import ( convert_scalar_for_putitemlike, @@ -26,13 +29,14 @@ from pandas.core.arrays import ExtensionArray -def putmask_inplace(values: ArrayLike, mask: np.ndarray, value: Any) -> None: +def putmask_inplace(values: ArrayLike, mask: npt.NDArray[np.bool_], value: Any) -> None: """ ExtensionArray-compatible implementation of np.putmask. The main difference is we do not handle repeating or truncating like numpy. Parameters ---------- + values: np.ndarray or ExtensionArray mask : np.ndarray[bool] We assume extract_bool_array has already been called. value : Any @@ -51,6 +55,7 @@ def putmask_inplace(values: ArrayLike, mask: np.ndarray, value: Any) -> None: ) ): # GH#19266 using np.putmask gives unexpected results with listlike value + # along with object dtype if is_list_like(value) and len(value) == len(values): values[mask] = value[mask] else: diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 6be2e803b5910..21675ca0cdc7c 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -1259,7 +1259,6 @@ def __from_arrow__( return IntervalArray._concat_same_type(results) def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: - # NB: this doesn't handle checking for closed match if not all(isinstance(x, IntervalDtype) for x in dtypes): return None diff --git a/pandas/core/indexers/utils.py b/pandas/core/indexers/utils.py index bf901683de602..b1824413512c5 100644 --- a/pandas/core/indexers/utils.py +++ b/pandas/core/indexers/utils.py @@ -104,14 +104,14 @@ def is_scalar_indexer(indexer, ndim: int) -> bool: return False -def is_empty_indexer(indexer, arr_value: np.ndarray) -> bool: +def is_empty_indexer(indexer, arr_value: ArrayLike) -> bool: """ Check if we have an empty indexer. Parameters ---------- indexer : object - arr_value : np.ndarray + arr_value : np.ndarray or ExtensionArray Returns ------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 926ab0b544abd..0cbe16c9aaf13 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3123,7 +3123,9 @@ def _union(self, other: Index, sort): and not (self.has_duplicates and other.has_duplicates) and self._can_use_libjoin ): - # Both are unique and monotonic, so can use outer join + # Both are monotonic and at least one is unique, so can use outer join + # (actually don't need either unique, but without this restriction + # test_union_same_value_duplicated_in_both fails) try: return self._outer_indexer(other)[0] except (TypeError, IncompatibleFrequency): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8327e5f1bb532..751cf41a09f14 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -918,7 +918,7 @@ def setitem(self, indexer, value): check_setitem_lengths(indexer, value, values) if is_empty_indexer(indexer, arr_value): - # GH#8669 empty indexers + # GH#8669 empty indexers, test_loc_setitem_boolean_mask_allfalse pass elif is_scalar_indexer(indexer, self.ndim): @@ -1698,7 +1698,7 @@ def putmask(self, mask, new) -> list[Block]: mask = extract_bool_array(mask) if not self._can_hold_element(new): - return self.astype(_dtype_obj).putmask(mask, new) + return self.coerce_to_target_dtype(new).putmask(mask, new) arr = self.values arr.T.putmask(mask, new) @@ -1755,7 +1755,9 @@ def fillna( # We support filling a DatetimeTZ with a `value` whose timezone # is different by coercing to object. # TODO: don't special-case td64 - return self.astype(_dtype_obj).fillna(value, limit, inplace, downcast) + return self.coerce_to_target_dtype(value).fillna( + value, limit, inplace, downcast + ) values = self.values values = values if inplace else values.copy() diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 7765c29ee59c8..f0d01f8727d5a 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -2075,7 +2075,7 @@ def test_td64arr_div_numeric_array( with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser - def test_td64arr_mul_int_series(self, box_with_array, names, request): + def test_td64arr_mul_int_series(self, box_with_array, names): # GH#19042 test for correct name attachment box = box_with_array exname = get_expected_name(box, names)
Will have to see what the CI says about the cython flake8 config change. <b>update</b> cython flake8 config moved to #44260
https://api.github.com/repos/pandas-dev/pandas/pulls/44258
2021-10-31T20:45:21Z
2021-11-01T17:08:28Z
2021-11-01T17:08:28Z
2021-11-01T17:35:16Z
TST: Add test for where inplace
diff --git a/pandas/_testing/_hypothesis.py b/pandas/_testing/_hypothesis.py new file mode 100644 index 0000000000000..0e506f5e878b4 --- /dev/null +++ b/pandas/_testing/_hypothesis.py @@ -0,0 +1,85 @@ +""" +Hypothesis data generator helpers. +""" +from datetime import datetime + +from hypothesis import strategies as st +from hypothesis.extra.dateutil import timezones as dateutil_timezones +from hypothesis.extra.pytz import timezones as pytz_timezones + +from pandas.compat import is_platform_windows + +import pandas as pd + +from pandas.tseries.offsets import ( + BMonthBegin, + BMonthEnd, + BQuarterBegin, + BQuarterEnd, + BYearBegin, + BYearEnd, + MonthBegin, + MonthEnd, + QuarterBegin, + QuarterEnd, + YearBegin, + YearEnd, +) + +OPTIONAL_INTS = st.lists(st.one_of(st.integers(), st.none()), max_size=10, min_size=3) + +OPTIONAL_FLOATS = st.lists(st.one_of(st.floats(), st.none()), max_size=10, min_size=3) + +OPTIONAL_TEXT = st.lists(st.one_of(st.none(), st.text()), max_size=10, min_size=3) + +OPTIONAL_DICTS = st.lists( + st.one_of(st.none(), st.dictionaries(st.text(), st.integers())), + max_size=10, + min_size=3, +) + +OPTIONAL_LISTS = st.lists( + st.one_of(st.none(), st.lists(st.text(), max_size=10, min_size=3)), + max_size=10, + min_size=3, +) + +if is_platform_windows(): + DATETIME_NO_TZ = st.datetimes(min_value=datetime(1900, 1, 1)) +else: + DATETIME_NO_TZ = st.datetimes() + +DATETIME_JAN_1_1900_OPTIONAL_TZ = st.datetimes( + min_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), + max_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), + timezones=st.one_of(st.none(), dateutil_timezones(), pytz_timezones()), +) + +DATETIME_IN_PD_TIMESTAMP_RANGE_NO_TZ = st.datetimes( + min_value=pd.Timestamp.min.to_pydatetime(warn=False), + max_value=pd.Timestamp.max.to_pydatetime(warn=False), +) + +INT_NEG_999_TO_POS_999 = st.integers(-999, 999) + +# The strategy for each type is registered in conftest.py, as they don't carry +# enough runtime information (e.g. type hints) to infer how to build them. +YQM_OFFSET = st.one_of( + *map( + st.from_type, + [ + MonthBegin, + MonthEnd, + BMonthBegin, + BMonthEnd, + QuarterBegin, + QuarterEnd, + BQuarterBegin, + BQuarterEnd, + YearBegin, + YearEnd, + BYearBegin, + BYearEnd, + ], + ) +) diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 0906186418c0a..525bf75476fc7 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -1,5 +1,9 @@ from datetime import datetime +from hypothesis import ( + given, + strategies as st, +) import numpy as np import pytest @@ -16,6 +20,13 @@ isna, ) import pandas._testing as tm +from pandas._testing._hypothesis import ( + OPTIONAL_DICTS, + OPTIONAL_FLOATS, + OPTIONAL_INTS, + OPTIONAL_LISTS, + OPTIONAL_TEXT, +) @pytest.fixture(params=["default", "float_string", "mixed_float", "mixed_int"]) @@ -797,3 +808,16 @@ def test_where_columns_casting(): result = df.where(pd.notnull(df), None) # make sure dtypes don't change tm.assert_frame_equal(expected, result) + + +@given( + data=st.one_of( + OPTIONAL_DICTS, OPTIONAL_FLOATS, OPTIONAL_INTS, OPTIONAL_LISTS, OPTIONAL_TEXT + ) +) +def test_where_inplace_casting(data): + # GH 22051 + df = DataFrame({"a": data}) + df_copy = df.where(pd.notnull(df), None).copy() + df.where(pd.notnull(df), None, inplace=True) + tm.assert_equal(df, df_copy) diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 1cfc86899f1e7..13a457500d6fb 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -14,7 +14,6 @@ from hypothesis import ( given, settings, - strategies as st, ) import numpy as np import pytest @@ -22,10 +21,7 @@ from pandas._libs.tslibs import parsing from pandas._libs.tslibs.parsing import parse_datetime_string -from pandas.compat import ( - is_platform_windows, - np_array_datetime64_compat, -) +from pandas.compat import np_array_datetime64_compat from pandas.compat.pyarrow import pa_version_under6p0 import pandas as pd @@ -38,6 +34,7 @@ Timestamp, ) import pandas._testing as tm +from pandas._testing._hypothesis import DATETIME_NO_TZ from pandas.core.indexes.datetimes import date_range import pandas.io.date_converters as conv @@ -52,12 +49,6 @@ # constant _DEFAULT_DATETIME = datetime(1, 1, 1) -# Strategy for hypothesis -if is_platform_windows(): - date_strategy = st.datetimes(min_value=datetime(1900, 1, 1)) -else: - date_strategy = st.datetimes() - @xfail_pyarrow def test_read_csv_with_custom_date_parser(all_parsers): @@ -1683,7 +1674,7 @@ def _helper_hypothesis_delimited_date(call, date_string, **kwargs): @skip_pyarrow -@given(date_strategy) +@given(DATETIME_NO_TZ) @settings(deadline=None) @pytest.mark.parametrize("delimiter", list(" -./")) @pytest.mark.parametrize("dayfirst", [True, False]) diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py index 2d88f6690a794..ef9f2390922ff 100644 --- a/pandas/tests/tseries/offsets/test_offsets_properties.py +++ b/pandas/tests/tseries/offsets/test_offsets_properties.py @@ -7,92 +7,26 @@ You may wish to consult the previous version for inspiration on further tests, or when trying to pin down the bugs exposed by the tests below. """ -import warnings - from hypothesis import ( assume, given, - strategies as st, ) from hypothesis.errors import Flaky -from hypothesis.extra.dateutil import timezones as dateutil_timezones -from hypothesis.extra.pytz import timezones as pytz_timezones import pytest import pytz import pandas as pd -from pandas import Timestamp - -from pandas.tseries.offsets import ( - BMonthBegin, - BMonthEnd, - BQuarterBegin, - BQuarterEnd, - BYearBegin, - BYearEnd, - MonthBegin, - MonthEnd, - QuarterBegin, - QuarterEnd, - YearBegin, - YearEnd, -) - -# ---------------------------------------------------------------- -# Helpers for generating random data - -with warnings.catch_warnings(): - warnings.simplefilter("ignore") - min_dt = Timestamp(1900, 1, 1).to_pydatetime() - max_dt = Timestamp(1900, 1, 1).to_pydatetime() - -gen_date_range = st.builds( - pd.date_range, - start=st.datetimes( - # TODO: Choose the min/max values more systematically - min_value=Timestamp(1900, 1, 1).to_pydatetime(), - max_value=Timestamp(2100, 1, 1).to_pydatetime(), - ), - periods=st.integers(min_value=2, max_value=100), - freq=st.sampled_from("Y Q M D H T s ms us ns".split()), - tz=st.one_of(st.none(), dateutil_timezones(), pytz_timezones()), +from pandas._testing._hypothesis import ( + DATETIME_JAN_1_1900_OPTIONAL_TZ, + YQM_OFFSET, ) -gen_random_datetime = st.datetimes( - min_value=min_dt, - max_value=max_dt, - timezones=st.one_of(st.none(), dateutil_timezones(), pytz_timezones()), -) - -# The strategy for each type is registered in conftest.py, as they don't carry -# enough runtime information (e.g. type hints) to infer how to build them. -gen_yqm_offset = st.one_of( - *map( - st.from_type, - [ - MonthBegin, - MonthEnd, - BMonthBegin, - BMonthEnd, - QuarterBegin, - QuarterEnd, - BQuarterBegin, - BQuarterEnd, - YearBegin, - YearEnd, - BYearBegin, - BYearEnd, - ], - ) -) - - # ---------------------------------------------------------------- # Offset-specific behaviour tests @pytest.mark.arm_slow -@given(gen_random_datetime, gen_yqm_offset) +@given(DATETIME_JAN_1_1900_OPTIONAL_TZ, YQM_OFFSET) def test_on_offset_implementations(dt, offset): assume(not offset.normalize) # check that the class-specific implementations of is_on_offset match @@ -112,7 +46,7 @@ def test_on_offset_implementations(dt, offset): @pytest.mark.xfail(strict=False, raises=Flaky, reason="unreliable test timings") -@given(gen_yqm_offset) +@given(YQM_OFFSET) 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 diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py index 464eeaed1e725..47e7b2aa4d401 100644 --- a/pandas/tests/tseries/offsets/test_ticks.py +++ b/pandas/tests/tseries/offsets/test_ticks.py @@ -11,7 +11,6 @@ example, given, settings, - strategies as st, ) import numpy as np import pytest @@ -23,6 +22,7 @@ Timestamp, ) import pandas._testing as tm +from pandas._testing._hypothesis import INT_NEG_999_TO_POS_999 from pandas.tests.tseries.offsets.common import assert_offset_equal from pandas.tseries import offsets @@ -66,7 +66,7 @@ def test_delta_to_tick(): @example(n=2, m=3) @example(n=800, m=300) @example(n=1000, m=5) -@given(n=st.integers(-999, 999), m=st.integers(-999, 999)) +@given(n=INT_NEG_999_TO_POS_999, m=INT_NEG_999_TO_POS_999) def test_tick_add_sub(cls, n, m): # For all Tick subclasses and all integers n, m, we should have # tick(n) + tick(m) == tick(n+m) @@ -86,7 +86,7 @@ def test_tick_add_sub(cls, n, m): @pytest.mark.parametrize("cls", tick_classes) @settings(deadline=None) @example(n=2, m=3) -@given(n=st.integers(-999, 999), m=st.integers(-999, 999)) +@given(n=INT_NEG_999_TO_POS_999, m=INT_NEG_999_TO_POS_999) def test_tick_equality(cls, n, m): assume(m != n) # tick == tock iff tick.n == tock.n diff --git a/pandas/tests/tslibs/test_ccalendar.py b/pandas/tests/tslibs/test_ccalendar.py index bba833abd3ad0..6a0d0a8d92955 100644 --- a/pandas/tests/tslibs/test_ccalendar.py +++ b/pandas/tests/tslibs/test_ccalendar.py @@ -3,16 +3,13 @@ datetime, ) -from hypothesis import ( - given, - strategies as st, -) +from hypothesis import given import numpy as np import pytest from pandas._libs.tslibs import ccalendar -import pandas as pd +from pandas._testing._hypothesis import DATETIME_IN_PD_TIMESTAMP_RANGE_NO_TZ @pytest.mark.parametrize( @@ -59,12 +56,7 @@ def test_dt_correct_iso_8601_year_week_and_day(input_date_tuple, expected_iso_tu assert result == expected_iso_tuple -@given( - st.datetimes( - min_value=pd.Timestamp.min.to_pydatetime(warn=False), - max_value=pd.Timestamp.max.to_pydatetime(warn=False), - ) -) +@given(DATETIME_IN_PD_TIMESTAMP_RANGE_NO_TZ) def test_isocalendar(dt): expected = dt.isocalendar() result = ccalendar.get_iso_calendar(dt.year, dt.month, dt.day)
This adds a test for ensuring that None-to-NaN type-casting is consistent with `where` when `inplace=True` and otherwise. - [x] closes #22051 - [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/44255
2021-10-31T17:49:05Z
2021-12-02T02:02:05Z
2021-12-02T02:02:05Z
2021-12-02T02:02:09Z
TYP: check typings with pyright
diff --git a/pyproject.toml b/pyproject.toml index d84024eb09de2..98ab112ab459a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -150,7 +150,7 @@ skip = "pandas/__init__.py" [tool.pyright] pythonVersion = "3.8" typeCheckingMode = "strict" -include = ["pandas"] +include = ["pandas", "typings"] exclude = ["pandas/tests", "pandas/io/clipboard", "pandas/util/version"] reportGeneralTypeIssues = false reportConstantRedefinition = false diff --git a/typings/numba.pyi b/typings/numba.pyi index d6a2729d36db3..526119951a000 100644 --- a/typings/numba.pyi +++ b/typings/numba.pyi @@ -1,3 +1,4 @@ +# pyright: reportIncompleteStub = false from typing import ( Any, Callable,
small followup to #44233
https://api.github.com/repos/pandas-dev/pandas/pulls/44254
2021-10-31T16:35:33Z
2021-11-02T08:56:44Z
2021-11-02T08:56:44Z
2021-11-02T08:56:53Z
TYP: Subset of "Improved the type stubs in the _libs directory to help with type checking"
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 9d5922f8a50bd..aba635e19995a 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -516,9 +516,9 @@ def intervals_to_interval_bounds(ndarray intervals, bint validate_closed=True): Returns ------- - tuple of tuples - left : (ndarray, object, array) - right : (ndarray, object, array) + tuple of + left : ndarray + right : ndarray closed: str """ cdef: diff --git a/pandas/_libs/missing.pyi b/pandas/_libs/missing.pyi new file mode 100644 index 0000000000000..1177e82906190 --- /dev/null +++ b/pandas/_libs/missing.pyi @@ -0,0 +1,15 @@ +import numpy as np +from numpy import typing as npt + +class NAType: ... + +NA: NAType + +def is_matching_na( + left: object, right: object, nan_matches_none: bool = ... +) -> bool: ... +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 is_numeric_na(values: np.ndarray) -> npt.NDArray[np.bool_]: ... diff --git a/pandas/_libs/tslibs/dtypes.pyi b/pandas/_libs/tslibs/dtypes.pyi index 8c510b05de4ce..8e47993e9d85f 100644 --- a/pandas/_libs/tslibs/dtypes.pyi +++ b/pandas/_libs/tslibs/dtypes.pyi @@ -18,33 +18,33 @@ class PeriodDtypeBase: def resolution(self) -> Resolution: ... class FreqGroup(Enum): - FR_ANN: int = ... - FR_QTR: int = ... - FR_MTH: int = ... - FR_WK: int = ... - FR_BUS: int = ... - FR_DAY: int = ... - FR_HR: int = ... - FR_MIN: int = ... - FR_SEC: int = ... - FR_MS: int = ... - FR_US: int = ... - FR_NS: int = ... - FR_UND: int = ... + FR_ANN: int + FR_QTR: int + FR_MTH: int + FR_WK: int + FR_BUS: int + FR_DAY: int + FR_HR: int + FR_MIN: int + FR_SEC: int + FR_MS: int + FR_US: int + FR_NS: int + FR_UND: int @staticmethod def get_freq_group(code: int) -> FreqGroup: ... class Resolution(Enum): - RESO_NS: int = ... - RESO_US: int = ... - RESO_MS: int = ... - RESO_SEC: int = ... - RESO_MIN: int = ... - RESO_HR: int = ... - RESO_DAY: int = ... - RESO_MTH: int = ... - RESO_QTR: int = ... - RESO_YR: int = ... + RESO_NS: int + RESO_US: int + RESO_MS: int + RESO_SEC: int + RESO_MIN: int + RESO_HR: int + RESO_DAY: int + RESO_MTH: int + RESO_QTR: int + RESO_YR: int def __lt__(self, other: Resolution) -> bool: ... def __ge__(self, other: Resolution) -> bool: ... @property diff --git a/pandas/_libs/tslibs/nattype.pyi b/pandas/_libs/tslibs/nattype.pyi index 6a5555cfff030..a7ee9a70342d4 100644 --- a/pandas/_libs/tslibs/nattype.pyi +++ b/pandas/_libs/tslibs/nattype.pyi @@ -12,6 +12,8 @@ NaT: NaTType iNaT: int nat_strings: set[str] +def is_null_datetimelike(val: object, inat_is_null: bool = ...) -> bool: ... + class NaTType(datetime): value: np.int64 def asm8(self) -> np.datetime64: ... diff --git a/pandas/_libs/tslibs/np_datetime.pyi b/pandas/_libs/tslibs/np_datetime.pyi new file mode 100644 index 0000000000000..db0c277b73bd5 --- /dev/null +++ b/pandas/_libs/tslibs/np_datetime.pyi @@ -0,0 +1 @@ +class OutOfBoundsDatetime(ValueError): ... diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index f293557a51ac2..7e6d8fa38aa45 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -3573,7 +3573,7 @@ cpdef to_offset(freq): Parameters ---------- - freq : str, tuple, datetime.timedelta, DateOffset or None + freq : str, datetime.timedelta, BaseOffset or None Returns ------- @@ -3586,7 +3586,7 @@ cpdef to_offset(freq): See Also -------- - DateOffset : Standard kind of date increment used for a date range. + BaseOffset : Standard kind of date increment used for a date range. Examples -------- diff --git a/pandas/_libs/tslibs/timestamps.pyi b/pandas/_libs/tslibs/timestamps.pyi index a89d0aecfc26c..17df594a39c44 100644 --- a/pandas/_libs/tslibs/timestamps.pyi +++ b/pandas/_libs/tslibs/timestamps.pyi @@ -17,7 +17,6 @@ import numpy as np from pandas._libs.tslibs import ( BaseOffset, - NaT, NaTType, Period, Timedelta, @@ -25,7 +24,7 @@ from pandas._libs.tslibs import ( _S = TypeVar("_S") -def integer_op_not_supported(obj) -> None: ... +def integer_op_not_supported(obj) -> TypeError: ... class Timestamp(datetime): min: ClassVar[Timestamp] diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index df71501d55b20..c6987d9a11e4c 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -512,7 +512,9 @@ def _cmp_method(self, other, op): # ------------------------------------------------------------------------ # String methods interface - _str_na_value = StringDtype.na_value + # error: Incompatible types in assignment (expression has type "NAType", + # base class "PandasArray" defined the type as "float") + _str_na_value = StringDtype.na_value # type: ignore[assignment] def _str_map( self, f, na_value=None, dtype: Dtype | None = None, convert: bool = True diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 79ea7731466d4..3b04490ae098c 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -912,6 +912,10 @@ def maybe_upcast( # We get a copy in all cases _except_ (values.dtype == new_dtype and not copy) upcast_values = values.astype(new_dtype, copy=copy) + # error: Incompatible return value type (got "Tuple[ndarray[Any, dtype[Any]], + # Union[Union[str, int, float, bool] Union[Period, Timestamp, Timedelta, Any]]]", + # expected "Tuple[NumpyArrayT, Union[Union[str, int, float, bool], Union[Period, + # Timestamp, Timedelta, Any]]]") return upcast_values, fill_value # type: ignore[return-value] diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 71da0a4b20b41..e74d73b84e94b 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -876,15 +876,15 @@ def freq(self): @classmethod def _parse_dtype_strict(cls, freq: str_type) -> BaseOffset: - if isinstance(freq, str): + if isinstance(freq, str): # note: freq is already of type str! if freq.startswith("period[") or freq.startswith("Period["): m = cls._match.search(freq) if m is not None: freq = m.group("freq") - freq = to_offset(freq) - if freq is not None: - return freq + freq_offset = to_offset(freq) + if freq_offset is not None: + return freq_offset raise ValueError("could not construct PeriodDtype") diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 47949334df021..4e3306e84c1a1 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -241,7 +241,10 @@ def _isna_array(values: ArrayLike, inf_as_na: bool = False): if inf_as_na and is_categorical_dtype(dtype): result = libmissing.isnaobj(values.to_numpy(), inf_as_na=inf_as_na) else: - result = values.isna() + # error: Incompatible types in assignment (expression has type + # "Union[ndarray[Any, Any], ExtensionArraySupportsAnyAll]", variable has + # type "ndarray[Any, dtype[bool_]]") + result = values.isna() # type: ignore[assignment] elif is_string_or_object_np_dtype(values.dtype): result = _isna_string_dtype(values, inf_as_na=inf_as_na) elif needs_i8_conversion(dtype): diff --git a/pandas/core/ops/mask_ops.py b/pandas/core/ops/mask_ops.py index d21c80b81b582..57bacba0d4bee 100644 --- a/pandas/core/ops/mask_ops.py +++ b/pandas/core/ops/mask_ops.py @@ -12,8 +12,8 @@ def kleene_or( - left: bool | np.ndarray, - right: bool | np.ndarray, + left: bool | np.ndarray | libmissing.NAType, + right: bool | np.ndarray | libmissing.NAType, left_mask: np.ndarray | None, right_mask: np.ndarray | None, ): @@ -37,12 +37,13 @@ def kleene_or( The result of the logical or, and the new mask. """ # To reduce the number of cases, we ensure that `left` & `left_mask` - # always come from an array, not a scalar. This is safe, since because + # always come from an array, not a scalar. This is safe, since # A | B == B | A if left_mask is None: return kleene_or(right, left, right_mask, left_mask) - assert isinstance(left, np.ndarray) + if not isinstance(left, np.ndarray): + raise TypeError("Either `left` or `right` need to be a np.ndarray.") raise_for_nan(right, method="or") @@ -73,8 +74,8 @@ def kleene_or( def kleene_xor( - left: bool | np.ndarray, - right: bool | np.ndarray, + left: bool | np.ndarray | libmissing.NAType, + right: bool | np.ndarray | libmissing.NAType, left_mask: np.ndarray | None, right_mask: np.ndarray | None, ): @@ -99,16 +100,20 @@ def kleene_xor( result, mask: ndarray[bool] The result of the logical xor, and the new mask. """ + # To reduce the number of cases, we ensure that `left` & `left_mask` + # always come from an array, not a scalar. This is safe, since + # A ^ B == B ^ A if left_mask is None: return kleene_xor(right, left, right_mask, left_mask) + if not isinstance(left, np.ndarray): + raise TypeError("Either `left` or `right` need to be a np.ndarray.") + raise_for_nan(right, method="xor") if right is libmissing.NA: result = np.zeros_like(left) else: - # error: Incompatible types in assignment (expression has type - # "Union[bool, Any]", variable has type "ndarray") - result = left ^ right # type: ignore[assignment] + result = left ^ right if right_mask is None: if right is libmissing.NA: @@ -146,12 +151,13 @@ def kleene_and( The result of the logical xor, and the new mask. """ # To reduce the number of cases, we ensure that `left` & `left_mask` - # always come from an array, not a scalar. This is safe, since because - # A | B == B | A + # always come from an array, not a scalar. This is safe, since + # A & B == B & A if left_mask is None: return kleene_and(right, left, right_mask, left_mask) - assert isinstance(left, np.ndarray) + if not isinstance(left, np.ndarray): + raise TypeError("Either `left` or `right` need to be a np.ndarray.") raise_for_nan(right, method="and") if right is libmissing.NA: diff --git a/pandas/core/resample.py b/pandas/core/resample.py index f132dd88d5147..e00defcfcffd1 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -2012,30 +2012,30 @@ def _adjust_dates_anchored( if closed == "right": if foffset > 0: # roll back - fresult = first.value - foffset + fresult_int = first.value - foffset else: - fresult = first.value - freq.nanos + fresult_int = first.value - freq.nanos if loffset > 0: # roll forward - lresult = last.value + (freq.nanos - loffset) + lresult_int = last.value + (freq.nanos - loffset) else: # already the end of the road - lresult = last.value + lresult_int = last.value else: # closed == 'left' if foffset > 0: - fresult = first.value - foffset + fresult_int = first.value - foffset else: # start of the road - fresult = first.value + fresult_int = first.value if loffset > 0: # roll forward - lresult = last.value + (freq.nanos - loffset) + lresult_int = last.value + (freq.nanos - loffset) else: - lresult = last.value + freq.nanos - fresult = Timestamp(fresult) - lresult = Timestamp(lresult) + lresult_int = last.value + freq.nanos + fresult = Timestamp(fresult_int) + lresult = Timestamp(lresult_int) if first_tzinfo is not None: fresult = fresult.tz_localize("UTC").tz_convert(first_tzinfo) if last_tzinfo is not None: diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 2ce5c0cbea272..6b0380a292f07 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -193,7 +193,7 @@ def rep(x, r): return result def _str_match( - self, pat: str, case: bool = True, flags: int = 0, na: Scalar = None + self, pat: str, case: bool = True, flags: int = 0, na: Scalar | None = None ): if not case: flags |= re.IGNORECASE @@ -208,7 +208,7 @@ def _str_fullmatch( pat: str | re.Pattern, case: bool = True, flags: int = 0, - na: Scalar = None, + na: Scalar | None = None, ): if not case: flags |= re.IGNORECASE diff --git a/pandas/tests/arrays/boolean/test_logical.py b/pandas/tests/arrays/boolean/test_logical.py index 938fa8f1a5d6a..b4cca635fa238 100644 --- a/pandas/tests/arrays/boolean/test_logical.py +++ b/pandas/tests/arrays/boolean/test_logical.py @@ -6,6 +6,11 @@ import pandas as pd import pandas._testing as tm from pandas.arrays import BooleanArray +from pandas.core.ops.mask_ops import ( + kleene_and, + kleene_or, + kleene_xor, +) from pandas.tests.extension.base import BaseOpsUtil @@ -239,3 +244,11 @@ def test_no_masked_assumptions(self, other, all_logical_operators): result = getattr(a, all_logical_operators)(other) expected = getattr(b, all_logical_operators)(other) tm.assert_extension_array_equal(result, expected) + + +@pytest.mark.parametrize("operation", [kleene_or, kleene_xor, kleene_and]) +def test_error_both_scalar(operation): + msg = r"Either `left` or `right` need to be a np\.ndarray." + with pytest.raises(TypeError, match=msg): + # masks need to be non-None, otherwise it ends up in an infinite recursion + operation(True, True, np.zeros(1), np.zeros(1))
The two big parts missing from #43744 are interval.pyi and offsets.pyi as they result in many mypy errors. I had already made changes to somewhat accommodate for interval.pyi and offsets.pyi (if these files are included, we have now "only" ~100 mypy errors). I kept these changes in this PR.
https://api.github.com/repos/pandas-dev/pandas/pulls/44251
2021-10-31T13:33:16Z
2021-12-14T01:38:43Z
2021-12-14T01:38:43Z
2022-03-09T02:56:32Z
DataFrame.convert_dtypes doesn't preserve subclasses
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index ee1dd58149451..560c3fad59e5e 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -538,6 +538,7 @@ Conversion - Bug in :class:`Series` constructor returning 0 for missing values with dtype ``int64`` and ``False`` for dtype ``bool`` (:issue:`43017`, :issue:`43018`) - 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`) - Strings diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 23608cf0192df..6b51456006021 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -18,6 +18,7 @@ Literal, Mapping, Sequence, + Type, cast, final, overload, @@ -6219,8 +6220,12 @@ def convert_dtypes( for col_name, col in self.items() ] if len(results) > 0: + result = concat(results, axis=1, copy=False) + cons = cast(Type["DataFrame"], self._constructor) + result = cons(result) + result = result.__finalize__(self, method="convert_dtypes") # https://github.com/python/mypy/issues/8354 - return cast(NDFrameT, concat(results, axis=1, copy=False)) + return cast(NDFrameT, result) else: return self.copy() diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index 42474ff00ad6d..8d9957b24300f 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -13,6 +13,16 @@ import pandas._testing as tm +@pytest.fixture() +def gpd_style_subclass_df(): + class SubclassedDataFrame(DataFrame): + @property + def _constructor(self): + return SubclassedDataFrame + + return SubclassedDataFrame({"a": [1, 2, 3]}) + + class TestDataFrameSubclassing: def test_frame_subclassing_and_slicing(self): # Subclass frame and ensure it returns the right class on slicing it @@ -704,6 +714,15 @@ def test_idxmax_preserves_subclass(self): result = df.idxmax() assert isinstance(result, tm.SubclassedSeries) + def test_convert_dtypes_preserves_subclass(self, gpd_style_subclass_df): + # GH 43668 + df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) + result = df.convert_dtypes() + assert isinstance(result, tm.SubclassedDataFrame) + + result = gpd_style_subclass_df.convert_dtypes() + assert isinstance(result, type(gpd_style_subclass_df)) + def test_equals_subclass(self): # https://github.com/pandas-dev/pandas/pull/34402 # allow subclass in both directions diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index c1f8b5dd7cf41..135e8cc7b7aba 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -347,10 +347,7 @@ operator.methodcaller("infer_objects"), ), (pd.Series, ([1, 2],), operator.methodcaller("convert_dtypes")), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("convert_dtypes")), - marks=not_implemented_mark, - ), + (pd.DataFrame, frame_data, operator.methodcaller("convert_dtypes")), (pd.Series, ([1, None, 3],), operator.methodcaller("interpolate")), (pd.DataFrame, ({"A": [1, None, 3]},), operator.methodcaller("interpolate")), (pd.Series, ([1, 2],), operator.methodcaller("clip", lower=1)),
- [x] closes #43668 - [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 I've added a fixture for the specific construction of a subclassed dataframe from the issue - which mirrors the setup in geopandas, I expect this probably needs to be relocated (I could have constructed this inline with the test and maybe that's the right solution, but I can see analogous changes for `astype` perhaps being useful in the geopandas context as well). I've also added the call to `__finalize__` although it's not strictly needed, since that's also needed by #28283 (Note that the 1 dimensional case already has `__finalize__` called indirectly via `astype`.
https://api.github.com/repos/pandas-dev/pandas/pulls/44249
2021-10-31T07:57:37Z
2021-11-13T17:03:31Z
2021-11-13T17:03:31Z
2023-09-16T01:22:47Z
BUG: styler render when using `hide`, `MultiIndex` and `max_rows` in combination
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 5601048c409e1..210dfc0050bf4 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -81,7 +81,7 @@ Styler - Naive sparsification is now possible for LaTeX without the multirow package (:issue:`43369`) - :meth:`.Styler.to_html` omits CSSStyle rules for hidden table elements (:issue:`43619`) - Custom CSS classes can now be directly specified without string replacement (:issue:`43686`) - - Bug where row trimming failed to reflect hidden rows (:issue:`43703`) + - Bug where row trimming failed to reflect hidden rows (:issue:`43703`, :issue:`44247`) - Update and expand the export and use mechanics (:issue:`40675`) - New method :meth:`.Styler.hide` added and deprecates :meth:`.Styler.hide_index` and :meth:`.Styler.hide_columns` (:issue:`43758`) diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 27a5170e48949..a71dd6f33e3c8 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -1230,29 +1230,37 @@ def _get_level_lengths( return lengths for i, lvl in enumerate(levels): + visible_row_count = 0 # used to break loop due to display trimming for j, row in enumerate(lvl): - if j >= max_index: - # stop the loop due to display trimming + if visible_row_count > max_index: break if not sparsify: + # then lengths will always equal 1 since no aggregation. if j not in hidden_elements: lengths[(i, j)] = 1 + visible_row_count += 1 elif (row is not lib.no_default) and (j not in hidden_elements): + # this element has not been sparsified so must be the start of section last_label = j lengths[(i, last_label)] = 1 + visible_row_count += 1 elif row is not lib.no_default: - # even if its hidden, keep track of it in case - # length >1 and later elements are visible + # even if the above is hidden, keep track of it in case length > 1 and + # later elements are visible last_label = j lengths[(i, last_label)] = 0 elif j not in hidden_elements: + # then element must be part of sparsified section and is visible + visible_row_count += 1 if lengths[(i, last_label)] == 0: - # if the previous iteration was first-of-kind but hidden then offset + # if previous iteration was first-of-section but hidden then offset last_label = j lengths[(i, last_label)] = 1 else: - # else add to previous iteration - lengths[(i, last_label)] += 1 + # else add to previous iteration but do not extend more than max + lengths[(i, last_label)] = min( + max_index, 1 + lengths[(i, last_label)] + ) non_zero_lengths = { element: length for element, length in lengths.items() if length >= 1 diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index cf2ec347015d1..8ac0dd03c9fd6 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -1577,3 +1577,26 @@ def test_row_trimming_hide_index(): assert len(ctx["body"]) == 3 for r, val in enumerate(["3", "4", "..."]): assert ctx["body"][r][1]["display_value"] == val + + +def test_row_trimming_hide_index_mi(): + # gh 44247 + df = DataFrame([[1], [2], [3], [4], [5]]) + df.index = MultiIndex.from_product([[0], [0, 1, 2, 3, 4]]) + with pd.option_context("styler.render.max_rows", 2): + ctx = df.style.hide([(0, 0), (0, 1)], axis="index")._translate(True, True) + assert len(ctx["body"]) == 3 + + # level 0 index headers (sparsified) + assert {"value": 0, "attributes": 'rowspan="2"', "is_visible": True}.items() <= ctx[ + "body" + ][0][0].items() + assert {"value": 0, "attributes": "", "is_visible": False}.items() <= ctx["body"][ + 1 + ][0].items() + assert {"value": "...", "is_visible": True}.items() <= ctx["body"][2][0].items() + + for r, val in enumerate(["2", "3", "..."]): + assert ctx["body"][r][1]["display_value"] == val # level 1 index headers + for r, val in enumerate(["3", "4", "..."]): + assert ctx["body"][r][2]["display_value"] == val # data values
There was a previous fix for #43703 but that dealt only with the SingleIndex case - [x] closes #44247 - [x] tests added / passed - [x] whatsnew entry Visuals of the fix compared to the issue: ![Screen Shot 2021-10-31 at 08 51 43](https://user-images.githubusercontent.com/24256554/139573572-1663d3fa-ceac-4e9a-b677-2108b6f2cef7.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/44248
2021-10-31T07:54:14Z
2021-11-01T13:50:40Z
2021-11-01T13:50:39Z
2022-03-06T07:43:41Z
TST: Old issues
diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py index 48f984c21623b..1d0b64c1835df 100644 --- a/pandas/tests/apply/test_series_apply.py +++ b/pandas/tests/apply/test_series_apply.py @@ -878,3 +878,15 @@ def test_apply_dictlike_transformer(string_series, ops): expected.name = string_series.name result = string_series.apply(ops) tm.assert_series_equal(result, expected) + + +def test_apply_retains_column_name(): + # GH 16380 + df = DataFrame({"x": range(3)}, Index(range(3), name="x")) + result = df.x.apply(lambda x: Series(range(x + 1), Index(range(x + 1), name="y"))) + expected = DataFrame( + [[0.0, np.nan, np.nan], [0.0, 1.0, np.nan], [0.0, 1.0, 2.0]], + columns=Index(range(3), name="y"), + index=Index(range(3), name="x"), + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/arithmetic/test_categorical.py b/pandas/tests/arithmetic/test_categorical.py index 924f32b5ac9ac..d6f3a13ce6705 100644 --- a/pandas/tests/arithmetic/test_categorical.py +++ b/pandas/tests/arithmetic/test_categorical.py @@ -13,3 +13,13 @@ def test_categorical_nan_equality(self): expected = Series([True, True, True, False]) result = cat == cat tm.assert_series_equal(result, expected) + + def test_categorical_tuple_equality(self): + # GH 18050 + ser = Series([(0, 0), (0, 1), (0, 0), (1, 0), (1, 1)]) + expected = Series([True, False, True, False, False]) + result = ser == (0, 0) + tm.assert_series_equal(result, expected) + + result = ser.astype("category") == (0, 0) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index 905b33b285625..404baecdfecac 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -2081,3 +2081,21 @@ def test_unstack_categorical_columns(self): ) expected.columns = MultiIndex.from_tuples([("cat", 0), ("cat", 1)]) tm.assert_frame_equal(result, expected) + + def test_stack_unsorted(self): + # GH 16925 + PAE = ["ITA", "FRA"] + VAR = ["A1", "A2"] + TYP = ["CRT", "DBT", "NET"] + MI = MultiIndex.from_product([PAE, VAR, TYP], names=["PAE", "VAR", "TYP"]) + + V = list(range(len(MI))) + DF = DataFrame(data=V, index=MI, columns=["VALUE"]) + + DF = DF.unstack(["VAR", "TYP"]) + DF.columns = DF.columns.droplevel(0) + DF.loc[:, ("A0", "NET")] = 9999 + + result = DF.stack(["VAR", "TYP"]).sort_index() + expected = DF.sort_index(axis=1).stack(["VAR", "TYP"]).sort_index() + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 3ae11847cc06b..3c402480ea2ec 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1155,3 +1155,13 @@ def test_groupby_sum_below_mincount_nullable_integer(): result = grouped.sum(min_count=2) expected = DataFrame({"b": [pd.NA] * 3, "c": [pd.NA] * 3}, dtype="Int64", index=idx) tm.assert_frame_equal(result, expected) + + +def test_mean_on_timedelta(): + # GH 17382 + df = DataFrame({"time": pd.to_timedelta(range(10)), "cat": ["A", "B"] * 5}) + result = df.groupby("cat")["time"].mean() + expected = Series( + pd.to_timedelta([4, 5]), name="time", index=Index(["A", "B"], name="cat") + ) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py index c006d5a287bcd..83b8d5c29bbf0 100644 --- a/pandas/tests/groupby/test_rank.py +++ b/pandas/tests/groupby/test_rank.py @@ -648,3 +648,16 @@ def test_groupby_axis0_cummax_axis1(): expected = df[[0, 1]].astype(np.float64) expected[2] = expected[1] tm.assert_frame_equal(cmax, expected) + + +def test_non_unique_index(): + # GH 16577 + df = DataFrame( + {"A": [1.0, 2.0, 3.0, np.nan], "value": 1.0}, + index=[pd.Timestamp("20170101", tz="US/Eastern")] * 4, + ) + result = df.groupby([df.index, "A"]).value.rank(ascending=True, pct=True) + expected = Series( + [1.0] * 4, index=[pd.Timestamp("20170101", tz="US/Eastern")] * 4, name="value" + ) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 441cbfe66f1d8..1e78bb1e58583 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -1289,3 +1289,11 @@ def test_transform_cumcount(): result = grp.transform("cumcount") tm.assert_series_equal(result, expected) + + +def test_null_group_lambda_self(): + # GH 17093 + df = DataFrame({"A": [1, np.nan], "B": [1, 1]}) + result = df.groupby("A").transform(lambda x: x) + expected = DataFrame([1], columns=["B"]) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index 6b136618de721..8d1fa97f9f8bb 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -853,3 +853,12 @@ def test_len_colspecs_len_names_with_index_col( index_col=index_col, ) tm.assert_frame_equal(result, expected) + + +def test_colspecs_with_comment(): + # GH 14135 + result = read_fwf( + StringIO("#\nA1K\n"), colspecs=[(1, 2), (2, 3)], comment="#", header=None + ) + expected = DataFrame([[1, "K"]], columns=[0, 1]) + tm.assert_frame_equal(result, expected)
- [x] closes #16380 - [x] closes #14135 - [x] closes #16577 - [x] closes #16925 - [x] closes #17093 - [x] closes #17382 - [x] closes #18050 - [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/44245
2021-10-31T03:29:23Z
2021-11-01T13:14:52Z
2021-11-01T13:14:50Z
2021-11-01T21:45:20Z
Revert "Backport PR #44204 on branch 1.3.x (CI: Python Dev build)"
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index 96d5542451f06..4fe58ad4d60e9 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -17,6 +17,7 @@ env: PANDAS_CI: 1 PATTERN: "not slow and not network and not clipboard" COVERAGE: true + PYTEST_TARGET: pandas jobs: build: @@ -25,13 +26,12 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macOS-latest, windows-latest] - pytest_target: ["pandas/tests/[a-h]*", "pandas/tests/[i-z]*"] name: actions-310-dev - timeout-minutes: 80 + timeout-minutes: 60 concurrency: - group: ${{ github.ref }}-${{ matrix.os }}-${{ matrix.pytest_target }}-dev + group: ${{ github.ref }}-${{ matrix.os }}-dev cancel-in-progress: ${{github.event_name == 'pull_request'}} steps: @@ -63,8 +63,6 @@ jobs: python -c "import pandas; pandas.show_versions();" - name: Test with pytest - env: - PYTEST_TARGET: ${{ matrix.pytest_target }} shell: bash run: | ci/run_tests.sh
Reverts pandas-dev/pandas#44208 THIS IS ONLY ON 1.3.x. Let's try reverting this. In theory, the test changes that caused the timeouts shouldn't be backported, so this shouldn't be needed.
https://api.github.com/repos/pandas-dev/pandas/pulls/44244
2021-10-30T23:58:48Z
2021-10-31T11:48:27Z
2021-10-31T11:48:27Z
2021-10-31T13:17:53Z
DEPR: datetime64tz cast mismatched timezones on setitemlike
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 699d8a81243db..d2433402662f7 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -394,6 +394,9 @@ Other Deprecations - Deprecated :meth:`.Rolling.validate`, :meth:`.Expanding.validate`, and :meth:`.ExponentialMovingWindow.validate` (:issue:`43665`) - Deprecated silent dropping of columns that raised a ``TypeError`` in :class:`Series.transform` and :class:`DataFrame.transform` when used with a dictionary (:issue:`43740`) - 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`) +- .. --------------------------------------------------------------------------- diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 71d38d3b3f73b..4fecbe4be9681 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -39,6 +39,7 @@ ) from pandas._typing import npt from pandas.errors import PerformanceWarning +from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_inclusive from pandas.core.dtypes.cast import astype_dt64_to_dt64tz @@ -509,6 +510,19 @@ def _check_compatible_with(self, other, setitem: bool = False): if setitem: # Stricter check for setitem vs comparison methods if not timezones.tz_compare(self.tz, other.tz): + # TODO(2.0): remove this check. GH#37605 + warnings.warn( + "Setitem-like behavior with mismatched timezones is deprecated " + "and will change in a future version. Instead of raising " + "(or for Index, Series, and DataFrame methods, coercing to " + "object dtype), the value being set (or passed as a " + "fill_value, or inserted) will be cast to the existing " + "DatetimeArray/DatetimeIndex/Series/DataFrame column's " + "timezone. To retain the old behavior, explicitly cast to " + "object dtype before the operation.", + FutureWarning, + stacklevel=find_stack_level(), + ) raise ValueError(f"Timezones don't match. '{self.tz}' != '{other.tz}'") # ----------------------------------------------------------------- diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 1e150f1b431c7..c7c1ce6c04692 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -883,7 +883,15 @@ def test_take_fill_valid(self, arr1d): msg = "Timezones don't match. .* != 'Australia/Melbourne'" with pytest.raises(ValueError, match=msg): # require tz match, not just tzawareness match - arr.take([-1, 1], allow_fill=True, fill_value=value) + with tm.assert_produces_warning( + FutureWarning, match="mismatched timezone" + ): + result = arr.take([-1, 1], allow_fill=True, fill_value=value) + + # once deprecation is enforced + # expected = arr.take([-1, 1], allow_fill=True, + # fill_value=value.tz_convert(arr.dtype.tz)) + # tm.assert_equal(result, expected) def test_concat_same_type_invalid(self, arr1d): # different timezones diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index b9c1113e7f441..180fb9d29224e 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -128,8 +128,14 @@ def test_setitem_different_tz_raises(self): with pytest.raises(TypeError, match="Cannot compare tz-naive and tz-aware"): arr[0] = pd.Timestamp("2000") + ts = pd.Timestamp("2000", tz="US/Eastern") with pytest.raises(ValueError, match="US/Central"): - arr[0] = pd.Timestamp("2000", tz="US/Eastern") + with tm.assert_produces_warning( + FutureWarning, match="mismatched timezones" + ): + arr[0] = ts + # once deprecation is enforced + # assert arr[0] == ts.tz_convert("US/Central") def test_setitem_clears_freq(self): a = DatetimeArray(pd.date_range("2000", periods=2, freq="D", tz="US/Central")) @@ -385,7 +391,14 @@ def test_shift_requires_tzmatch(self): msg = "Timezones don't match. 'UTC' != 'US/Pacific'" with pytest.raises(ValueError, match=msg): - dta.shift(1, fill_value=fill_value) + with tm.assert_produces_warning( + FutureWarning, match="mismatched timezones" + ): + dta.shift(1, fill_value=fill_value) + + # once deprecation is enforced + # expected = dta.shift(1, fill_value=fill_value.tz_convert("UTC")) + # tm.assert_equal(result, expected) def test_tz_localize_t2d(self): dti = pd.date_range("1994-05-12", periods=12, tz="US/Pacific") diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index a89e089f3d8a2..5e321ad33a2bb 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1109,12 +1109,17 @@ def test_replace_datetimetz(self): # coerce to object result = df.copy() result.iloc[1, 0] = np.nan - result = result.replace({"A": pd.NaT}, Timestamp("20130104", tz="US/Pacific")) + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + result = result.replace( + {"A": pd.NaT}, Timestamp("20130104", tz="US/Pacific") + ) expected = DataFrame( { "A": [ Timestamp("20130101", tz="US/Eastern"), Timestamp("20130104", tz="US/Pacific"), + # once deprecation is enforced + # Timestamp("20130104", tz="US/Pacific").tz_convert("US/Eastern"), Timestamp("20130103", tz="US/Eastern"), ], "B": [0, np.nan, 2], diff --git a/pandas/tests/indexes/datetimes/methods/test_insert.py b/pandas/tests/indexes/datetimes/methods/test_insert.py index aa9b2c5291585..016a29e4cc266 100644 --- a/pandas/tests/indexes/datetimes/methods/test_insert.py +++ b/pandas/tests/indexes/datetimes/methods/test_insert.py @@ -197,18 +197,32 @@ def test_insert_mismatched_tz(self): # mismatched tz -> cast to object (could reasonably cast to same tz or UTC) item = Timestamp("2000-01-04", tz="US/Eastern") - result = idx.insert(3, item) + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + result = idx.insert(3, item) expected = Index( - list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx" + list(idx[:3]) + [item] + list(idx[3:]), + dtype=object, + # once deprecation is enforced + # list(idx[:3]) + [item.tz_convert(idx.tz)] + list(idx[3:]), + name="idx", ) + # once deprecation is enforced + # assert expected.dtype == idx.dtype tm.assert_index_equal(result, expected) # mismatched tz -> cast to object (could reasonably cast to same tz) item = datetime(2000, 1, 4, tzinfo=pytz.timezone("US/Eastern")) - result = idx.insert(3, item) + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + result = idx.insert(3, item) expected = Index( - list(idx[:3]) + [item] + list(idx[3:]), dtype=object, name="idx" + list(idx[:3]) + [item] + list(idx[3:]), + dtype=object, + # once deprecation is enforced + # list(idx[:3]) + [item.astimezone(idx.tzinfo)] + list(idx[3:]), + name="idx", ) + # once deprecation is enforced + # assert expected.dtype == idx.dtype tm.assert_index_equal(result, expected) @pytest.mark.parametrize( diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 9a22a16106469..27aeb411e36f0 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -237,11 +237,17 @@ def test_setitem_series_datetime64tz(self, val, exp_dtype): [ pd.Timestamp("2011-01-01", tz=tz), val, + # once deprecation is enforced + # val if getattr(val, "tz", None) is None else val.tz_convert(tz), pd.Timestamp("2011-01-03", tz=tz), pd.Timestamp("2011-01-04", tz=tz), ] ) - self._assert_setitem_series_conversion(obj, val, exp, exp_dtype) + warn = None + if getattr(val, "tz", None) is not None and val.tz != obj[0].tz: + warn = FutureWarning + with tm.assert_produces_warning(warn, match="mismatched timezones"): + self._assert_setitem_series_conversion(obj, val, exp, exp_dtype) @pytest.mark.parametrize( "val,exp_dtype", @@ -467,9 +473,12 @@ def test_insert_index_datetimes(self, request, fill_val, exp_dtype, insert_value # mismatched tz --> cast to object (could reasonably cast to common tz) ts = pd.Timestamp("2012-01-01", tz="Asia/Tokyo") - result = obj.insert(1, ts) + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + result = obj.insert(1, ts) + # once deprecation is enforced: + # expected = obj.insert(1, ts.tz_convert(obj.dtype.tz)) + # assert expected.dtype == obj.dtype expected = obj.astype(object).insert(1, ts) - assert expected.dtype == object tm.assert_index_equal(result, expected) else: @@ -990,11 +999,18 @@ def test_fillna_datetime64tz(self, index_or_series, fill_val, fill_dtype): [ pd.Timestamp("2011-01-01", tz=tz), fill_val, + # Once deprecation is enforced, this becomes: + # fill_val.tz_convert(tz) if getattr(fill_val, "tz", None) + # is not None else fill_val, pd.Timestamp("2011-01-03", tz=tz), pd.Timestamp("2011-01-04", tz=tz), ] ) - self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype) + warn = None + if getattr(fill_val, "tz", None) is not None and fill_val.tz != obj[0].tz: + warn = FutureWarning + with tm.assert_produces_warning(warn, match="mismatched timezone"): + self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype) @pytest.mark.xfail(reason="Test not implemented") def test_fillna_series_int64(self): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index b82ecac37634e..cf2a4a75f95b5 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1890,7 +1890,8 @@ def test_setitem_with_expansion(self): # trying to set a single element on a part of a different timezone # this converts to object df2 = df.copy() - df2.loc[df2.new_col == "new", "time"] = v + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + df2.loc[df2.new_col == "new", "time"] = v expected = Series([v[0], df.loc[1, "time"]], name="time") tm.assert_series_equal(df2.time, expected) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index a922a937ce9d3..5521bee09b19b 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -898,6 +898,18 @@ def expected(self): ) return expected + @pytest.fixture(autouse=True) + def assert_warns(self, request): + # check that we issue a FutureWarning about timezone-matching + if request.function.__name__ == "test_slice_key": + key = request.getfixturevalue("key") + if not isinstance(key, slice): + # The test is a no-op, so no warning will be issued + yield + return + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + yield + @pytest.mark.parametrize( "obj,expected", diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index a28da1d856cf9..2feaf4e951ab8 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -523,7 +523,8 @@ def test_datetime64_tz_fillna(self, tz): tm.assert_series_equal(expected, result) tm.assert_series_equal(isna(ser), null_loc) - result = ser.fillna(Timestamp("20130101", tz="US/Pacific")) + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + result = ser.fillna(Timestamp("20130101", tz="US/Pacific")) expected = Series( [ Timestamp("2011-01-01 10:00", tz=tz), @@ -766,8 +767,15 @@ def test_fillna_datetime64_with_timezone_tzinfo(self): # but we dont (yet) consider distinct tzinfos for non-UTC tz equivalent ts = Timestamp("2000-01-01", tz="US/Pacific") ser2 = Series(ser._values.tz_convert("dateutil/US/Pacific")) - result = ser2.fillna(ts) + assert ser2.dtype.kind == "M" + with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): + result = ser2.fillna(ts) expected = Series([ser[0], ts, ser[2]], dtype=object) + # once deprecation is enforced + # expected = Series( + # [ser2[0], ts.tz_convert(ser2.dtype.tz), ser2[2]], + # dtype=ser2.dtype, + # ) tm.assert_series_equal(result, expected) def test_fillna_pos_args_deprecation(self):
- [x] closes #37605 - [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/44243
2021-10-30T23:46:55Z
2021-10-31T14:53:56Z
2021-10-31T14:53:56Z
2021-10-31T15:32:01Z
TST: fixturize, collect
diff --git a/pandas/conftest.py b/pandas/conftest.py index 1e1d14f46cc6e..65d4b936efe44 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -995,17 +995,19 @@ def all_reductions(request): return request.param -@pytest.fixture(params=["__eq__", "__ne__", "__le__", "__lt__", "__ge__", "__gt__"]) -def all_compare_operators(request): +@pytest.fixture( + params=[ + operator.eq, + operator.ne, + operator.gt, + operator.ge, + operator.lt, + operator.le, + ] +) +def comparison_op(request): """ - Fixture for dunder names for common compare operations - - * >= - * > - * == - * != - * < - * <= + Fixture for operator module comparison functions. """ return request.param diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index e511c1bdaca9c..82f1e60f0aea5 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -365,18 +365,14 @@ def test_dt64arr_timestamp_equality(self, box_with_array): class TestDatetimeIndexComparisons: # TODO: moved from tests.indexes.test_base; parametrize and de-duplicate - @pytest.mark.parametrize( - "op", - [operator.eq, operator.ne, operator.gt, operator.lt, operator.ge, operator.le], - ) - def test_comparators(self, op): + def test_comparators(self, comparison_op): index = tm.makeDateIndex(100) element = index[len(index) // 2] element = Timestamp(element).to_datetime64() arr = np.array(index) - arr_result = op(arr, element) - index_result = op(index, element) + arr_result = comparison_op(arr, element) + index_result = comparison_op(index, element) assert isinstance(index_result, np.ndarray) tm.assert_numpy_array_equal(arr_result, index_result) @@ -554,12 +550,9 @@ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self): expected = np.array([True, True, False, True, True, True]) tm.assert_numpy_array_equal(result, expected) - @pytest.mark.parametrize( - "op", - [operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le], - ) - def test_comparison_tzawareness_compat(self, op, box_with_array): + def test_comparison_tzawareness_compat(self, comparison_op, box_with_array): # GH#18162 + op = comparison_op box = box_with_array dr = date_range("2016-01-01", periods=6) @@ -606,12 +599,10 @@ def test_comparison_tzawareness_compat(self, op, box_with_array): assert np.all(np.array(tolist(dz), dtype=object) == dz) assert np.all(dz == np.array(tolist(dz), dtype=object)) - @pytest.mark.parametrize( - "op", - [operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le], - ) - def test_comparison_tzawareness_compat_scalars(self, op, box_with_array): + def test_comparison_tzawareness_compat_scalars(self, comparison_op, box_with_array): # GH#18162 + op = comparison_op + dr = date_range("2016-01-01", periods=6) dz = dr.tz_localize("US/Pacific") @@ -638,10 +629,6 @@ def test_comparison_tzawareness_compat_scalars(self, op, box_with_array): with pytest.raises(TypeError, match=msg): op(ts, dz) - @pytest.mark.parametrize( - "op", - [operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le], - ) @pytest.mark.parametrize( "other", [datetime(2016, 1, 1), Timestamp("2016-01-01"), np.datetime64("2016-01-01")], @@ -652,8 +639,9 @@ def test_comparison_tzawareness_compat_scalars(self, op, box_with_array): @pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning") @pytest.mark.filterwarnings("ignore:Converting timezone-aware:FutureWarning") def test_scalar_comparison_tzawareness( - self, op, other, tz_aware_fixture, box_with_array + self, comparison_op, other, tz_aware_fixture, box_with_array ): + op = comparison_op box = box_with_array tz = tz_aware_fixture dti = date_range("2016-01-01", periods=2, tz=tz) @@ -680,13 +668,11 @@ def test_scalar_comparison_tzawareness( with pytest.raises(TypeError, match=msg): op(other, dtarr) - @pytest.mark.parametrize( - "op", - [operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le], - ) - def test_nat_comparison_tzawareness(self, op): + def test_nat_comparison_tzawareness(self, comparison_op): # GH#19276 # tzaware DatetimeIndex should not raise when compared to NaT + op = comparison_op + dti = DatetimeIndex( ["2014-01-01", NaT, "2014-03-01", NaT, "2014-05-01", "2014-07-01"] ) diff --git a/pandas/tests/arrays/boolean/test_comparison.py b/pandas/tests/arrays/boolean/test_comparison.py index 8730837b518e5..2741d13ee599b 100644 --- a/pandas/tests/arrays/boolean/test_comparison.py +++ b/pandas/tests/arrays/boolean/test_comparison.py @@ -21,25 +21,23 @@ def dtype(): class TestComparisonOps(ComparisonOps): - def test_compare_scalar(self, data, all_compare_operators): - op_name = all_compare_operators - self._compare_other(data, op_name, True) + def test_compare_scalar(self, data, comparison_op): + self._compare_other(data, comparison_op, True) - def test_compare_array(self, data, all_compare_operators): - op_name = all_compare_operators + def test_compare_array(self, data, comparison_op): other = pd.array([True] * len(data), dtype="boolean") - self._compare_other(data, op_name, other) + self._compare_other(data, comparison_op, other) other = np.array([True] * len(data)) - self._compare_other(data, op_name, other) + self._compare_other(data, comparison_op, other) other = pd.Series([True] * len(data)) - self._compare_other(data, op_name, other) + self._compare_other(data, comparison_op, other) @pytest.mark.parametrize("other", [True, False, pd.NA]) - def test_scalar(self, other, all_compare_operators, dtype): - ComparisonOps.test_scalar(self, other, all_compare_operators, dtype) + def test_scalar(self, other, comparison_op, dtype): + ComparisonOps.test_scalar(self, other, comparison_op, dtype) - def test_array(self, all_compare_operators): - op = self.get_op_from_name(all_compare_operators) + def test_array(self, comparison_op): + op = comparison_op a = pd.array([True] * 3 + [False] * 3 + [None] * 3, dtype="boolean") b = pd.array([True, False, None] * 3, dtype="boolean") diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index 4a00df2d783cf..06296a954c059 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -1,4 +1,3 @@ -import operator import warnings import numpy as np @@ -145,9 +144,9 @@ def test_compare_frame(self): expected = DataFrame([[False, True, True, False]]) tm.assert_frame_equal(result, expected) - def test_compare_frame_raises(self, all_compare_operators): + def test_compare_frame_raises(self, comparison_op): # alignment raises unless we transpose - op = getattr(operator, all_compare_operators) + op = comparison_op cat = Categorical(["a", "b", 2, "a"]) df = DataFrame(cat) msg = "Unable to coerce to Series, length must be 1: given 4" diff --git a/pandas/tests/arrays/floating/test_comparison.py b/pandas/tests/arrays/floating/test_comparison.py index bfd54e125159c..c4163c25ae74d 100644 --- a/pandas/tests/arrays/floating/test_comparison.py +++ b/pandas/tests/arrays/floating/test_comparison.py @@ -10,11 +10,11 @@ class TestComparisonOps(NumericOps, ComparisonOps): @pytest.mark.parametrize("other", [True, False, pd.NA, -1.0, 0.0, 1]) - def test_scalar(self, other, all_compare_operators, dtype): - ComparisonOps.test_scalar(self, other, all_compare_operators, dtype) + def test_scalar(self, other, comparison_op, dtype): + ComparisonOps.test_scalar(self, other, comparison_op, dtype) - def test_compare_with_integerarray(self, all_compare_operators): - op = self.get_op_from_name(all_compare_operators) + def test_compare_with_integerarray(self, comparison_op): + op = comparison_op a = pd.array([0, 1, None] * 3, dtype="Int64") b = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype="Float64") other = b.astype("Int64") diff --git a/pandas/tests/arrays/integer/test_comparison.py b/pandas/tests/arrays/integer/test_comparison.py index 043f5d64d159b..3bbf6866076e8 100644 --- a/pandas/tests/arrays/integer/test_comparison.py +++ b/pandas/tests/arrays/integer/test_comparison.py @@ -9,18 +9,19 @@ class TestComparisonOps(NumericOps, ComparisonOps): @pytest.mark.parametrize("other", [True, False, pd.NA, -1, 0, 1]) - def test_scalar(self, other, all_compare_operators, dtype): - ComparisonOps.test_scalar(self, other, all_compare_operators, dtype) + def test_scalar(self, other, comparison_op, dtype): + ComparisonOps.test_scalar(self, other, comparison_op, dtype) - def test_compare_to_int(self, dtype, all_compare_operators): + def test_compare_to_int(self, dtype, comparison_op): # GH 28930 + op_name = f"__{comparison_op.__name__}__" s1 = pd.Series([1, None, 3], dtype=dtype) s2 = pd.Series([1, None, 3], dtype="float") - method = getattr(s1, all_compare_operators) + method = getattr(s1, op_name) result = method(2) - method = getattr(s2, all_compare_operators) + method = getattr(s2, op_name) expected = method(2).astype("boolean") expected[s2.isna()] = pd.NA diff --git a/pandas/tests/arrays/masked_shared.py b/pandas/tests/arrays/masked_shared.py index 1a461777e08e3..06c05e458958b 100644 --- a/pandas/tests/arrays/masked_shared.py +++ b/pandas/tests/arrays/masked_shared.py @@ -9,8 +9,7 @@ class ComparisonOps(BaseOpsUtil): - def _compare_other(self, data, op_name, other): - op = self.get_op_from_name(op_name) + def _compare_other(self, data, op, other): # array result = pd.Series(op(data, other)) @@ -34,8 +33,8 @@ def _compare_other(self, data, op_name, other): tm.assert_series_equal(result, expected) # subclass will override to parametrize 'other' - def test_scalar(self, other, all_compare_operators, dtype): - op = self.get_op_from_name(all_compare_operators) + def test_scalar(self, other, comparison_op, dtype): + op = comparison_op left = pd.array([1, 0, None], dtype=dtype) result = op(left, other) @@ -59,8 +58,8 @@ def test_no_shared_mask(self, data): result = data + 1 assert np.shares_memory(result._mask, data._mask) is False - def test_array(self, all_compare_operators, dtype): - op = self.get_op_from_name(all_compare_operators) + def test_array(self, comparison_op, dtype): + op = comparison_op left = pd.array([0, 1, 2, None, None, None], dtype=dtype) right = pd.array([0, 1, None, 0, 1, None], dtype=dtype) @@ -81,8 +80,8 @@ def test_array(self, all_compare_operators, dtype): right, pd.array([0, 1, None, 0, 1, None], dtype=dtype) ) - def test_compare_with_booleanarray(self, all_compare_operators, dtype): - op = self.get_op_from_name(all_compare_operators) + def test_compare_with_booleanarray(self, comparison_op, dtype): + op = comparison_op left = pd.array([True, False, None] * 3, dtype="boolean") right = pd.array([0] * 3 + [1] * 3 + [None] * 3, dtype=dtype) diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index fa564ac76f8bb..501a79a8bc5ed 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -199,8 +199,8 @@ def test_add_frame(dtype): tm.assert_frame_equal(result, expected) -def test_comparison_methods_scalar(all_compare_operators, dtype): - op_name = all_compare_operators +def test_comparison_methods_scalar(comparison_op, dtype): + op_name = f"__{comparison_op.__name__}__" a = pd.array(["a", None, "c"], dtype=dtype) other = "a" result = getattr(a, op_name)(other) @@ -209,21 +209,21 @@ def test_comparison_methods_scalar(all_compare_operators, dtype): tm.assert_extension_array_equal(result, expected) -def test_comparison_methods_scalar_pd_na(all_compare_operators, dtype): - op_name = all_compare_operators +def test_comparison_methods_scalar_pd_na(comparison_op, dtype): + op_name = f"__{comparison_op.__name__}__" a = pd.array(["a", None, "c"], dtype=dtype) result = getattr(a, op_name)(pd.NA) expected = pd.array([None, None, None], dtype="boolean") tm.assert_extension_array_equal(result, expected) -def test_comparison_methods_scalar_not_string(all_compare_operators, dtype, request): - if all_compare_operators not in ["__eq__", "__ne__"]: +def test_comparison_methods_scalar_not_string(comparison_op, dtype, request): + op_name = f"__{comparison_op.__name__}__" + if op_name not in ["__eq__", "__ne__"]: reason = "comparison op not supported between instances of 'str' and 'int'" mark = pytest.mark.xfail(raises=TypeError, reason=reason) request.node.add_marker(mark) - op_name = all_compare_operators a = pd.array(["a", None, "c"], dtype=dtype) other = 42 result = getattr(a, op_name)(other) @@ -234,14 +234,14 @@ def test_comparison_methods_scalar_not_string(all_compare_operators, dtype, requ tm.assert_extension_array_equal(result, expected) -def test_comparison_methods_array(all_compare_operators, dtype, request): +def test_comparison_methods_array(comparison_op, dtype, request): if dtype.storage == "pyarrow": mark = pytest.mark.xfail( raises=AssertionError, reason="left is not an ExtensionArray" ) request.node.add_marker(mark) - op_name = all_compare_operators + op_name = f"__{comparison_op.__name__}__" a = pd.array(["a", None, "c"], dtype=dtype) other = [None, None, "c"] diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 180fb9d29224e..5b9df44f5b565 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -1,8 +1,6 @@ """ Tests for DatetimeArray """ -import operator - import numpy as np import pytest @@ -17,10 +15,9 @@ class TestDatetimeArrayComparisons: # TODO: merge this into tests/arithmetic/test_datetime64 once it is # sufficiently robust - def test_cmp_dt64_arraylike_tznaive(self, all_compare_operators): + def test_cmp_dt64_arraylike_tznaive(self, comparison_op): # arbitrary tz-naive DatetimeIndex - opname = all_compare_operators.strip("_") - op = getattr(operator, opname) + op = comparison_op dti = pd.date_range("2016-01-1", freq="MS", periods=9, tz=None) arr = DatetimeArray(dti) @@ -30,7 +27,7 @@ def test_cmp_dt64_arraylike_tznaive(self, all_compare_operators): right = dti expected = np.ones(len(arr), dtype=bool) - if opname in ["ne", "gt", "lt"]: + if comparison_op.__name__ in ["ne", "gt", "lt"]: # for these the comparisons should be all-False expected = ~expected diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 73bff29305f20..bf3985ad198dd 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -138,6 +138,7 @@ def test_getitem_invalid(self, data): "list index out of range", # json "index out of bounds", # pyarrow "Out of bounds access", # Sparse + f"loc must be an integer between -{ub} and {ub}", # Sparse f"index {ub+1} is out of bounds for axis 0 with size {ub}", f"index -{ub+1} is out of bounds for axis 0 with size {ub}", ] diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index 88437321b1028..c52f20255eb81 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -130,10 +130,9 @@ def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): class BaseComparisonOpsTests(BaseOpsUtil): """Various Series and DataFrame comparison ops methods.""" - def _compare_other(self, ser: pd.Series, data, op_name: str, other): + def _compare_other(self, ser: pd.Series, data, op, other): - op = self.get_op_from_name(op_name) - if op_name in ["__eq__", "__ne__"]: + if op.__name__ in ["eq", "ne"]: # comparison should match point-wise comparisons result = op(ser, other) expected = ser.combine(other, op) @@ -154,23 +153,22 @@ def _compare_other(self, ser: pd.Series, data, op_name: str, other): with pytest.raises(type(exc)): ser.combine(other, op) - def test_compare_scalar(self, data, all_compare_operators): - op_name = all_compare_operators + def test_compare_scalar(self, data, comparison_op): ser = pd.Series(data) - self._compare_other(ser, data, op_name, 0) + self._compare_other(ser, data, comparison_op, 0) - def test_compare_array(self, data, all_compare_operators): - op_name = all_compare_operators + def test_compare_array(self, data, comparison_op): ser = pd.Series(data) other = pd.Series([data[0]] * len(data)) - self._compare_other(ser, data, op_name, other) + self._compare_other(ser, data, comparison_op, other) - @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) - def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): + def test_direct_arith_with_ndframe_returns_not_implemented( + self, data, frame_or_series + ): # EAs should return NotImplemented for ops with Series/DataFrame # Pandas takes care of unboxing the series and calling the EA's op. other = pd.Series(data) - if box is pd.DataFrame: + if frame_or_series is pd.DataFrame: other = other.to_frame() if hasattr(data, "__eq__"): diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 461dbe5575022..bca87bb8ec2aa 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -266,19 +266,17 @@ def _check_divmod_op(self, s, op, other, exc=NotImplementedError): class TestComparisonOps(base.BaseComparisonOpsTests): - def test_compare_scalar(self, data, all_compare_operators): - op_name = all_compare_operators + def test_compare_scalar(self, data, comparison_op): s = pd.Series(data) - self._compare_other(s, data, op_name, 0.5) + self._compare_other(s, data, comparison_op, 0.5) - def test_compare_array(self, data, all_compare_operators): - op_name = all_compare_operators + def test_compare_array(self, data, comparison_op): s = pd.Series(data) alter = np.random.choice([-1, 0, 1], len(data)) # Randomly double, halve or keep same value other = pd.Series(data) * [decimal.Decimal(pow(2.0, i)) for i in alter] - self._compare_other(s, data, op_name, other) + self._compare_other(s, data, comparison_op, other) class DecimalArrayWithoutFromSequence(DecimalArray): diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py index 9c4bf76b27c14..05455905860d2 100644 --- a/pandas/tests/extension/test_boolean.py +++ b/pandas/tests/extension/test_boolean.py @@ -151,11 +151,11 @@ def check_opname(self, s, op_name, other, exc=None): super().check_opname(s, op_name, other, exc=None) @pytest.mark.skip(reason="Tested in tests/arrays/test_boolean.py") - def test_compare_scalar(self, data, all_compare_operators): + def test_compare_scalar(self, data, comparison_op): pass @pytest.mark.skip(reason="Tested in tests/arrays/test_boolean.py") - def test_compare_array(self, data, all_compare_operators): + def test_compare_array(self, data, comparison_op): pass diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index ea8b1cfb738f5..e9dc63e9bd903 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -270,8 +270,8 @@ def _check_divmod_op(self, s, op, other, exc=NotImplementedError): class TestComparisonOps(base.BaseComparisonOpsTests): - def _compare_other(self, s, data, op_name, other): - op = self.get_op_from_name(op_name) + def _compare_other(self, s, data, op, other): + op_name = f"__{op.__name__}__" if op_name == "__eq__": result = op(s, other) expected = s.combine(other, lambda x, y: x == y) diff --git a/pandas/tests/extension/test_floating.py b/pandas/tests/extension/test_floating.py index 500c2fbb74d17..2b08c5b7be450 100644 --- a/pandas/tests/extension/test_floating.py +++ b/pandas/tests/extension/test_floating.py @@ -142,7 +142,8 @@ def _check_op(self, s, op, other, op_name, exc=NotImplementedError): def check_opname(self, s, op_name, other, exc=None): super().check_opname(s, op_name, other, exc=None) - def _compare_other(self, s, data, op_name, other): + def _compare_other(self, s, data, op, other): + op_name = f"__{op.__name__}__" self.check_opname(s, op_name, other) diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index c9c0a4de60a46..7d343aab3c7a0 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -161,7 +161,8 @@ def _check_op(self, s, op, other, op_name, exc=NotImplementedError): def check_opname(self, s, op_name, other, exc=None): super().check_opname(s, op_name, other, exc=None) - def _compare_other(self, s, data, op_name, other): + def _compare_other(self, s, data, op, other): + op_name = f"__{op.__name__}__" self.check_opname(s, op_name, other) diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 6358b2fe27ef3..012a3fbb12cac 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -432,8 +432,8 @@ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request): class TestComparisonOps(BaseSparseTests, base.BaseComparisonOpsTests): - def _compare_other(self, s, data, op_name, other): - op = self.get_op_from_name(op_name) + def _compare_other(self, s, data, comparison_op, other): + op = comparison_op # array result = pd.Series(op(data, other)) diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index af86c359c4c00..5049116a9320e 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -166,15 +166,15 @@ class TestCasting(base.BaseCastingTests): class TestComparisonOps(base.BaseComparisonOpsTests): - def _compare_other(self, s, data, op_name, other): + def _compare_other(self, s, data, op, other): + op_name = f"__{op.__name__}__" result = getattr(s, op_name)(other) expected = getattr(s.astype(object), op_name)(other).astype("boolean") self.assert_series_equal(result, expected) - def test_compare_scalar(self, data, all_compare_operators): - op_name = all_compare_operators + def test_compare_scalar(self, data, comparison_op): s = pd.Series(data) - self._compare_other(s, data, op_name, "abc") + self._compare_other(s, data, comparison_op, "abc") class TestParsing(base.BaseParsingTests): diff --git a/pandas/tests/indexes/base_class/test_reshape.py b/pandas/tests/indexes/base_class/test_reshape.py index 5ebab965e6f04..acb6936f70d0f 100644 --- a/pandas/tests/indexes/base_class/test_reshape.py +++ b/pandas/tests/indexes/base_class/test_reshape.py @@ -35,6 +35,13 @@ def test_insert(self): null_index = Index([]) tm.assert_index_equal(Index(["a"]), null_index.insert(0, "a")) + def test_insert_missing(self, nulls_fixture): + # GH#22295 + # test there is no mangling of NA values + expected = Index(["a", nulls_fixture, "b", "c"]) + result = Index(list("abc")).insert(1, nulls_fixture) + tm.assert_index_equal(result, expected) + @pytest.mark.parametrize( "pos,expected", [ @@ -48,6 +55,12 @@ def test_delete(self, pos, expected): tm.assert_index_equal(result, expected) assert result.name == expected.name + def test_delete_raises(self): + index = Index(["a", "b", "c", "d"], name="index") + msg = "index 5 is out of bounds for axis 0 with size 4" + with pytest.raises(IndexError, match=msg): + index.delete(5) + def test_append_multiple(self): index = Index(["a", "b", "c", "d", "e", "f"]) diff --git a/pandas/tests/indexes/categorical/test_reindex.py b/pandas/tests/indexes/categorical/test_reindex.py index 72130ef9e4627..5a0b2672e397c 100644 --- a/pandas/tests/indexes/categorical/test_reindex.py +++ b/pandas/tests/indexes/categorical/test_reindex.py @@ -10,7 +10,7 @@ class TestReindex: - def test_reindex_dtype(self): + def test_reindex_list_non_unique(self): # GH#11586 ci = CategoricalIndex(["a", "b", "c", "a"]) with tm.assert_produces_warning(FutureWarning, match="non-unique"): @@ -19,6 +19,7 @@ def test_reindex_dtype(self): tm.assert_index_equal(res, Index(["a", "a", "c"]), exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 3, 2], dtype=np.intp)) + def test_reindex_categorcal_non_unique(self): ci = CategoricalIndex(["a", "b", "c", "a"]) with tm.assert_produces_warning(FutureWarning, match="non-unique"): res, indexer = ci.reindex(Categorical(["a", "c"])) @@ -27,6 +28,7 @@ def test_reindex_dtype(self): tm.assert_index_equal(res, exp, exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 3, 2], dtype=np.intp)) + def test_reindex_list_non_unique_unused_category(self): ci = CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"]) with tm.assert_produces_warning(FutureWarning, match="non-unique"): res, indexer = ci.reindex(["a", "c"]) @@ -34,6 +36,7 @@ def test_reindex_dtype(self): tm.assert_index_equal(res, exp, exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 3, 2], dtype=np.intp)) + def test_reindex_categorical_non_unique_unused_category(self): ci = CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"]) with tm.assert_produces_warning(FutureWarning, match="non-unique"): res, indexer = ci.reindex(Categorical(["a", "c"])) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index ea76a4b4b1cfc..8f37413dd53c8 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -333,6 +333,12 @@ def test_numpy_argsort(self, index): expected = index.argsort() tm.assert_numpy_array_equal(result, expected) + if not isinstance(index, RangeIndex): + # TODO: add compatibility to RangeIndex? + result = np.argsort(index, kind="mergesort") + expected = index.argsort(kind="mergesort") + tm.assert_numpy_array_equal(result, expected) + # these are the only two types that perform # pandas compatibility input validation - the # rest already perform separate (or no) such @@ -340,16 +346,11 @@ def test_numpy_argsort(self, index): # defined in pandas.core.indexes/base.py - they # cannot be changed at the moment due to # backwards compatibility concerns - if isinstance(type(index), (CategoricalIndex, RangeIndex)): - # TODO: why type(index)? + if isinstance(index, (CategoricalIndex, RangeIndex)): msg = "the 'axis' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, axis=1) - msg = "the 'kind' parameter is not supported" - with pytest.raises(ValueError, match=msg): - np.argsort(index, kind="mergesort") - msg = "the 'order' parameter is not supported" with pytest.raises(ValueError, match=msg): np.argsort(index, order=("a", "b")) diff --git a/pandas/tests/indexes/datetimes/test_pickle.py b/pandas/tests/indexes/datetimes/test_pickle.py index 3905daa9688ac..922b4a18119f4 100644 --- a/pandas/tests/indexes/datetimes/test_pickle.py +++ b/pandas/tests/indexes/datetimes/test_pickle.py @@ -18,7 +18,7 @@ def test_pickle(self): assert idx_p[2] == idx[2] def test_pickle_dont_infer_freq(self): - # GH##11002 + # GH#11002 # don't infer freq idx = date_range("1750-1-1", "2050-1-1", freq="7D") idx_p = tm.round_trip_pickle(idx) diff --git a/pandas/tests/indexes/datetimes/test_unique.py b/pandas/tests/indexes/datetimes/test_unique.py index a6df9cb748294..68ac770f612e6 100644 --- a/pandas/tests/indexes/datetimes/test_unique.py +++ b/pandas/tests/indexes/datetimes/test_unique.py @@ -3,8 +3,6 @@ timedelta, ) -import pytest - from pandas import ( DatetimeIndex, NaT, @@ -13,18 +11,12 @@ import pandas._testing as tm -@pytest.mark.parametrize( - "arr, expected", - [ - (DatetimeIndex(["2017", "2017"]), DatetimeIndex(["2017"])), - ( - DatetimeIndex(["2017", "2017"], tz="US/Eastern"), - DatetimeIndex(["2017"], tz="US/Eastern"), - ), - ], -) -def test_unique(arr, expected): - result = arr.unique() +def test_unique(tz_naive_fixture): + + idx = DatetimeIndex(["2017"] * 2, tz=tz_naive_fixture) + expected = idx[:1] + + result = idx.unique() tm.assert_index_equal(result, expected) # GH#21737 # Ensure the underlying data is consistent @@ -60,6 +52,8 @@ def test_index_unique(rand_series_with_duplicate_datetimeindex): assert result.name == "foo" tm.assert_index_equal(result, expected) + +def test_index_unique2(): # NaT, note this is excluded arr = [1370745748 + t for t in range(20)] + [NaT.value] idx = DatetimeIndex(arr * 3) @@ -67,6 +61,8 @@ def test_index_unique(rand_series_with_duplicate_datetimeindex): assert idx.nunique() == 20 assert idx.nunique(dropna=False) == 21 + +def test_index_unique3(): arr = [ Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20) ] + [NaT] diff --git a/pandas/tests/indexes/period/test_join.py b/pandas/tests/indexes/period/test_join.py index b8b15708466cb..27cba8676d22b 100644 --- a/pandas/tests/indexes/period/test_join.py +++ b/pandas/tests/indexes/period/test_join.py @@ -42,10 +42,12 @@ def test_join_does_not_recur(self): c_idx_type="p", r_idx_type="dt", ) - s = df.iloc[:2, 0] + ser = df.iloc[:2, 0] - res = s.index.join(df.columns, how="outer") - expected = Index([s.index[0], s.index[1], df.columns[0], df.columns[1]], object) + res = ser.index.join(df.columns, how="outer") + expected = Index( + [ser.index[0], ser.index[1], df.columns[0], df.columns[1]], object + ) tm.assert_index_equal(res, expected) def test_join_mismatched_freq_raises(self): diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index 2313afcae607a..39a1ddcbc8a6a 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -117,7 +117,7 @@ def test_tolist_matches_list(self, index): class TestRoundTrips: def test_pickle_roundtrip(self, index): result = tm.round_trip_pickle(index) - tm.assert_index_equal(result, index) + tm.assert_index_equal(result, index, exact=True) if result.nlevels > 1: # GH#8367 round-trip with timezone assert index.equal_levels(result) @@ -133,7 +133,7 @@ class TestIndexing: def test_slice_keeps_name(self, index): assert index.name == index[1:].name - @pytest.mark.parametrize("item", [101, "no_int"]) + @pytest.mark.parametrize("item", [101, "no_int", 2.5]) # FutureWarning from non-tuple sequence of nd indexing @pytest.mark.filterwarnings("ignore::FutureWarning") def test_getitem_error(self, index, item): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index cbcb00a4230cc..f1ece3e363bb6 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -181,29 +181,6 @@ def test_constructor_from_frame_series_freq(self): freq = pd.infer_freq(df["date"]) assert freq == "MS" - @pytest.mark.parametrize( - "array", - [ - np.arange(5), - np.array(["a", "b", "c"]), - date_range("2000-01-01", periods=3).values, - ], - ) - def test_constructor_ndarray_like(self, array): - # GH 5460#issuecomment-44474502 - # it should be possible to convert any object that satisfies the numpy - # ndarray interface directly into an Index - class ArrayLike: - def __init__(self, array): - self.array = array - - def __array__(self, dtype=None) -> np.ndarray: - return self.array - - expected = Index(array) - result = Index(ArrayLike(array)) - tm.assert_index_equal(result, expected) - def test_constructor_int_dtype_nan(self): # see gh-15187 data = [np.nan] @@ -211,20 +188,6 @@ def test_constructor_int_dtype_nan(self): result = Index(data, dtype="float") tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("dtype", ["int64", "uint64"]) - def test_constructor_int_dtype_nan_raises(self, dtype): - # see gh-15187 - data = [np.nan] - msg = "cannot convert" - with pytest.raises(ValueError, match=msg): - Index(data, dtype=dtype) - - def test_constructor_no_pandas_array(self): - ser = Series([1, 2, 3]) - result = Index(ser.array) - expected = Index([1, 2, 3]) - tm.assert_index_equal(result, expected) - @pytest.mark.parametrize( "klass,dtype,na_val", [ @@ -497,19 +460,6 @@ def test_equals_object(self): def test_not_equals_object(self, comp): assert not Index(["a", "b", "c"]).equals(comp) - def test_insert_missing(self, nulls_fixture): - # GH 22295 - # test there is no mangling of NA values - expected = Index(["a", nulls_fixture, "b", "c"]) - result = Index(list("abc")).insert(1, nulls_fixture) - tm.assert_index_equal(result, expected) - - def test_delete_raises(self): - index = Index(["a", "b", "c", "d"], name="index") - msg = "index 5 is out of bounds for axis 0 with size 4" - with pytest.raises(IndexError, match=msg): - index.delete(5) - def test_identical(self): # index @@ -1574,10 +1524,9 @@ def test_is_monotonic_na(self, index): assert index._is_strictly_monotonic_increasing is False assert index._is_strictly_monotonic_decreasing is False - @pytest.mark.parametrize("klass", [Series, DataFrame]) - def test_int_name_format(self, klass): + def test_int_name_format(self, frame_or_series): index = Index(["a", "b", "c"], name=0) - result = klass(list(range(3)), index=index) + result = frame_or_series(list(range(3)), index=index) assert "0" in repr(result) def test_str_to_bytes_raises(self): diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py index e9bbe60f2d5ea..293aa6dd57124 100644 --- a/pandas/tests/indexes/test_index_new.py +++ b/pandas/tests/indexes/test_index_new.py @@ -224,6 +224,14 @@ def test_constructor_datetime64_values_mismatched_period_dtype(self): expected = dti.to_period("D") tm.assert_index_equal(result, expected) + @pytest.mark.parametrize("dtype", ["int64", "uint64"]) + def test_constructor_int_dtype_nan_raises(self, dtype): + # see GH#15187 + data = [np.nan] + msg = "cannot convert" + with pytest.raises(ValueError, match=msg): + Index(data, dtype=dtype) + class TestIndexConstructorUnwrapping: # Test passing different arraylike values to pd.Index @@ -235,3 +243,32 @@ def test_constructor_from_series_dt64(self, klass): ser = Series(stamps) result = klass(ser) tm.assert_index_equal(result, expected) + + def test_constructor_no_pandas_array(self): + ser = Series([1, 2, 3]) + result = Index(ser.array) + expected = Index([1, 2, 3]) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "array", + [ + np.arange(5), + np.array(["a", "b", "c"]), + date_range("2000-01-01", periods=3).values, + ], + ) + def test_constructor_ndarray_like(self, array): + # GH#5460#issuecomment-44474502 + # it should be possible to convert any object that satisfies the numpy + # ndarray interface directly into an Index + class ArrayLike: + def __init__(self, array): + self.array = array + + def __array__(self, dtype=None) -> np.ndarray: + return self.array + + expected = Index(array) + result = Index(ArrayLike(array)) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py index ee36223eb2496..b7cb7ca8d7069 100644 --- a/pandas/tests/scalar/timestamp/test_comparisons.py +++ b/pandas/tests/scalar/timestamp/test_comparisons.py @@ -49,8 +49,7 @@ def test_comparison_dt64_ndarray(self): tm.assert_numpy_array_equal(result, np.array([[True, False]], dtype=bool)) @pytest.mark.parametrize("reverse", [True, False]) - def test_comparison_dt64_ndarray_tzaware(self, reverse, all_compare_operators): - op = getattr(operator, all_compare_operators.strip("__")) + def test_comparison_dt64_ndarray_tzaware(self, reverse, comparison_op): ts = Timestamp.now("UTC") arr = np.array([ts.asm8, ts.asm8], dtype="M8[ns]") @@ -59,18 +58,18 @@ def test_comparison_dt64_ndarray_tzaware(self, reverse, all_compare_operators): if reverse: left, right = arr, ts - if op is operator.eq: + if comparison_op is operator.eq: expected = np.array([False, False], dtype=bool) - result = op(left, right) + result = comparison_op(left, right) tm.assert_numpy_array_equal(result, expected) - elif op is operator.ne: + elif comparison_op is operator.ne: expected = np.array([True, True], dtype=bool) - result = op(left, right) + result = comparison_op(left, right) tm.assert_numpy_array_equal(result, expected) else: msg = "Cannot compare tz-naive and tz-aware timestamps" with pytest.raises(TypeError, match=msg): - op(left, right) + comparison_op(left, right) def test_comparison_object_array(self): # GH#15183 diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index e4f9366be8dd7..ed83377f31317 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -322,22 +322,20 @@ def test_arithmetic_with_duplicate_index(self): class TestSeriesFlexComparison: @pytest.mark.parametrize("axis", [0, None, "index"]) - def test_comparison_flex_basic(self, axis, all_compare_operators): - op = all_compare_operators.strip("__") + def test_comparison_flex_basic(self, axis, comparison_op): left = Series(np.random.randn(10)) right = Series(np.random.randn(10)) - result = getattr(left, op)(right, axis=axis) - expected = getattr(operator, op)(left, right) + result = getattr(left, comparison_op.__name__)(right, axis=axis) + expected = comparison_op(left, right) tm.assert_series_equal(result, expected) - def test_comparison_bad_axis(self, all_compare_operators): - op = all_compare_operators.strip("__") + def test_comparison_bad_axis(self, comparison_op): left = Series(np.random.randn(10)) right = Series(np.random.randn(10)) msg = "No axis named 1 for object type" with pytest.raises(ValueError, match=msg): - getattr(left, op)(right, axis=1) + getattr(left, comparison_op.__name__)(right, axis=1) @pytest.mark.parametrize( "values, op", @@ -598,20 +596,17 @@ def test_comparison_tuples(self): expected = Series([True, False]) tm.assert_series_equal(result, expected) - def test_comparison_operators_with_nas(self, all_compare_operators): - op = all_compare_operators + def test_comparison_operators_with_nas(self, comparison_op): ser = Series(bdate_range("1/1/2000", periods=10), dtype=object) ser[::2] = np.nan - f = getattr(operator, op) - # test that comparisons work val = ser[5] - result = f(ser, val) - expected = f(ser.dropna(), val).reindex(ser.index) + result = comparison_op(ser, val) + expected = comparison_op(ser.dropna(), val).reindex(ser.index) - if op == "__ne__": + if comparison_op is operator.ne: expected = expected.fillna(True).astype(bool) else: expected = expected.fillna(False).astype(bool) @@ -619,8 +614,8 @@ def test_comparison_operators_with_nas(self, all_compare_operators): tm.assert_series_equal(result, expected) # FIXME: dont leave commented-out - # result = f(val, ser) - # expected = f(val, ser.dropna()).reindex(ser.index) + # result = comparison_op(val, ser) + # expected = comparison_op(val, ser.dropna()).reindex(ser.index) # tm.assert_series_equal(result, expected) def test_ne(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/44242
2021-10-30T23:41:44Z
2021-10-31T17:26:12Z
2021-10-31T17:26:12Z
2021-11-06T10:22:50Z
CLN/TST: Remove redundant/unnecessary windows/moments tests
diff --git a/ci/run_tests.sh b/ci/run_tests.sh index 53a2bf151d3bf..9fea696b6ea81 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -22,9 +22,7 @@ fi PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET" if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then - # GH#37455 windows py38 build appears to be running out of memory - # skip collection of window tests - PYTEST_CMD="$PYTEST_CMD --ignore=pandas/tests/window/moments --ignore=pandas/tests/plotting/" + PYTEST_CMD="$PYTEST_CMD --ignore=pandas/tests/plotting/" fi echo $PYTEST_CMD diff --git a/pandas/tests/window/moments/conftest.py b/pandas/tests/window/moments/conftest.py index e843caa48f6d7..b192f72c8f08b 100644 --- a/pandas/tests/window/moments/conftest.py +++ b/pandas/tests/window/moments/conftest.py @@ -1,3 +1,5 @@ +import itertools + import numpy as np import pytest @@ -12,133 +14,20 @@ def _create_consistency_data(): def create_series(): return [ - Series(dtype=object), - Series([np.nan]), - Series([np.nan, np.nan]), - Series([3.0]), - Series([np.nan, 3.0]), - Series([3.0, np.nan]), - Series([1.0, 3.0]), - Series([2.0, 2.0]), - Series([3.0, 1.0]), - Series( - [5.0, 5.0, 5.0, 5.0, np.nan, np.nan, np.nan, 5.0, 5.0, np.nan, np.nan] - ), - Series( - [ - np.nan, - 5.0, - 5.0, - 5.0, - np.nan, - np.nan, - np.nan, - 5.0, - 5.0, - np.nan, - np.nan, - ] - ), - Series( - [ - np.nan, - np.nan, - 5.0, - 5.0, - np.nan, - np.nan, - np.nan, - 5.0, - 5.0, - np.nan, - np.nan, - ] - ), - Series( - [ - np.nan, - 3.0, - np.nan, - 3.0, - 4.0, - 5.0, - 6.0, - np.nan, - np.nan, - 7.0, - 12.0, - 13.0, - 14.0, - 15.0, - ] - ), - Series( - [ - np.nan, - 5.0, - np.nan, - 2.0, - 4.0, - 0.0, - 9.0, - np.nan, - np.nan, - 3.0, - 12.0, - 13.0, - 14.0, - 15.0, - ] - ), - Series( - [ - 2.0, - 3.0, - np.nan, - 3.0, - 4.0, - 5.0, - 6.0, - np.nan, - np.nan, - 7.0, - 12.0, - 13.0, - 14.0, - 15.0, - ] - ), - Series( - [ - 2.0, - 5.0, - np.nan, - 2.0, - 4.0, - 0.0, - 9.0, - np.nan, - np.nan, - 3.0, - 12.0, - 13.0, - 14.0, - 15.0, - ] - ), - Series(range(10)), - Series(range(20, 0, -2)), + Series(dtype=np.float64, name="a"), + Series([np.nan] * 5), + Series([1.0] * 5), + Series(range(5, 0, -1)), + Series(range(5)), + Series([np.nan, 1.0, np.nan, 1.0, 1.0]), + Series([np.nan, 1.0, np.nan, 2.0, 3.0]), + Series([np.nan, 1.0, np.nan, 3.0, 2.0]), ] def create_dataframes(): return [ - DataFrame(), - DataFrame(columns=["a"]), DataFrame(columns=["a", "a"]), - DataFrame(columns=["a", "b"]), - DataFrame(np.arange(10).reshape((5, 2))), - DataFrame(np.arange(25).reshape((5, 5))), - DataFrame(np.arange(25).reshape((5, 5)), columns=["a", "b", 99, "d", "d"]), + DataFrame(np.arange(15).reshape((5, 3)), columns=["a", "a", 99]), ] + [DataFrame(s) for s in create_series()] def is_constant(x): @@ -148,13 +37,34 @@ def is_constant(x): def no_nans(x): return x.notna().all().all() - # data is a tuple(object, is_constant, no_nans) - data = create_series() + create_dataframes() - - return [(x, is_constant(x), no_nans(x)) for x in data] + return [ + (x, is_constant(x), no_nans(x)) + for x in itertools.chain(create_dataframes(), create_dataframes()) + ] @pytest.fixture(params=_create_consistency_data()) def consistency_data(request): - """Create consistency data""" + """ + Test: + - Empty Series / DataFrame + - All NaN + - All consistent value + - Monotonically decreasing + - Monotonically increasing + - Monotonically consistent with NaNs + - Monotonically increasing with NaNs + - Monotonically decreasing with NaNs + """ + return request.param + + +@pytest.fixture(params=[(1, 0), (5, 1)]) +def rolling_consistency_cases(request): + """window, min_periods""" + return request.param + + +@pytest.fixture(params=[0, 2]) +def min_periods(request): return request.param diff --git a/pandas/tests/window/moments/test_moments_consistency_ewm.py b/pandas/tests/window/moments/test_moments_consistency_ewm.py index 800ee2164693b..8feec32ba99c5 100644 --- a/pandas/tests/window/moments/test_moments_consistency_ewm.py +++ b/pandas/tests/window/moments/test_moments_consistency_ewm.py @@ -18,7 +18,7 @@ def create_mock_weights(obj, com, adjust, ignore_na): create_mock_series_weights( obj.iloc[:, i], com=com, adjust=adjust, ignore_na=ignore_na ) - for i, _ in enumerate(obj.columns) + for i in range(len(obj.columns)) ], axis=1, ) @@ -58,7 +58,6 @@ def create_mock_series_weights(s, com, adjust, ignore_na): return w -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) def test_ewm_consistency_mean(consistency_data, adjust, ignore_na, min_periods): x, is_constant, no_nans = consistency_data com = 3.0 @@ -76,7 +75,6 @@ def test_ewm_consistency_mean(consistency_data, adjust, ignore_na, min_periods): tm.assert_equal(result, expected.astype("float64")) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) def test_ewm_consistency_consistent(consistency_data, adjust, ignore_na, min_periods): x, is_constant, no_nans = consistency_data com = 3.0 @@ -102,7 +100,6 @@ def test_ewm_consistency_consistent(consistency_data, adjust, ignore_na, min_per tm.assert_equal(corr_x_x, expected) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) def test_ewm_consistency_var_debiasing_factors( consistency_data, adjust, ignore_na, min_periods ): @@ -128,7 +125,6 @@ def test_ewm_consistency_var_debiasing_factors( tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("bias", [True, False]) def test_moments_consistency_var( consistency_data, adjust, ignore_na, min_periods, bias @@ -154,7 +150,6 @@ def test_moments_consistency_var( tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x)) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("bias", [True, False]) def test_moments_consistency_var_constant( consistency_data, adjust, ignore_na, min_periods, bias @@ -176,7 +171,6 @@ def test_moments_consistency_var_constant( tm.assert_equal(var_x, expected) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("bias", [True, False]) def test_ewm_consistency_std(consistency_data, adjust, ignore_na, min_periods, bias): x, is_constant, no_nans = consistency_data @@ -184,26 +178,16 @@ def test_ewm_consistency_std(consistency_data, adjust, ignore_na, min_periods, b var_x = x.ewm( com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na ).var(bias=bias) + assert not (var_x < 0).any().any() + std_x = x.ewm( com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na ).std(bias=bias) - assert not (var_x < 0).any().any() assert not (std_x < 0).any().any() # check that var(x) == std(x)^2 tm.assert_equal(var_x, std_x * std_x) - -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) -@pytest.mark.parametrize("bias", [True, False]) -def test_ewm_consistency_cov(consistency_data, adjust, ignore_na, min_periods, bias): - x, is_constant, no_nans = consistency_data - com = 3.0 - var_x = x.ewm( - com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na - ).var(bias=bias) - assert not (var_x < 0).any().any() - cov_x_x = x.ewm( com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na ).cov(x, bias=bias) @@ -213,7 +197,6 @@ def test_ewm_consistency_cov(consistency_data, adjust, ignore_na, min_periods, b tm.assert_equal(var_x, cov_x_x) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("bias", [True, False]) def test_ewm_consistency_series_cov_corr( consistency_data, adjust, ignore_na, min_periods, bias diff --git a/pandas/tests/window/moments/test_moments_consistency_expanding.py b/pandas/tests/window/moments/test_moments_consistency_expanding.py index d0fe7bf9fc2d2..14314f80f152c 100644 --- a/pandas/tests/window/moments/test_moments_consistency_expanding.py +++ b/pandas/tests/window/moments/test_moments_consistency_expanding.py @@ -5,13 +5,14 @@ import pandas._testing as tm -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) -@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum]) +@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum]) def test_expanding_apply_consistency_sum_nans(consistency_data, min_periods, f): x, is_constant, no_nans = consistency_data if f is np.nansum and min_periods == 0: pass + elif f is np.sum and not no_nans: + pass else: expanding_f_result = x.expanding(min_periods=min_periods).sum() expanding_apply_f_result = x.expanding(min_periods=min_periods).apply( @@ -20,39 +21,20 @@ def test_expanding_apply_consistency_sum_nans(consistency_data, min_periods, f): tm.assert_equal(expanding_f_result, expanding_apply_f_result) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) -@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum]) -def test_expanding_apply_consistency_sum_no_nans(consistency_data, min_periods, f): - - x, is_constant, no_nans = consistency_data - - if no_nans: - if f is np.nansum and min_periods == 0: - pass - else: - expanding_f_result = x.expanding(min_periods=min_periods).sum() - expanding_apply_f_result = x.expanding(min_periods=min_periods).apply( - func=f, raw=True - ) - tm.assert_equal(expanding_f_result, expanding_apply_f_result) - - -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("ddof", [0, 1]) def test_moments_consistency_var(consistency_data, min_periods, ddof): x, is_constant, no_nans = consistency_data - mean_x = x.expanding(min_periods=min_periods).mean() var_x = x.expanding(min_periods=min_periods).var(ddof=ddof) assert not (var_x < 0).any().any() if ddof == 0: # check that biased var(x) == mean(x^2) - mean(x)^2 mean_x2 = (x * x).expanding(min_periods=min_periods).mean() + mean_x = x.expanding(min_periods=min_periods).mean() tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x)) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("ddof", [0, 1]) def test_moments_consistency_var_constant(consistency_data, min_periods, ddof): x, is_constant, no_nans = consistency_data @@ -70,27 +52,19 @@ def test_moments_consistency_var_constant(consistency_data, min_periods, ddof): tm.assert_equal(var_x, expected) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("ddof", [0, 1]) -def test_expanding_consistency_std(consistency_data, min_periods, ddof): +def test_expanding_consistency_var_std_cov(consistency_data, min_periods, ddof): x, is_constant, no_nans = consistency_data var_x = x.expanding(min_periods=min_periods).var(ddof=ddof) - std_x = x.expanding(min_periods=min_periods).std(ddof=ddof) assert not (var_x < 0).any().any() + + std_x = x.expanding(min_periods=min_periods).std(ddof=ddof) assert not (std_x < 0).any().any() # check that var(x) == std(x)^2 tm.assert_equal(var_x, std_x * std_x) - -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) -@pytest.mark.parametrize("ddof", [0, 1]) -def test_expanding_consistency_cov(consistency_data, min_periods, ddof): - x, is_constant, no_nans = consistency_data - var_x = x.expanding(min_periods=min_periods).var(ddof=ddof) - assert not (var_x < 0).any().any() - cov_x_x = x.expanding(min_periods=min_periods).cov(x, ddof=ddof) assert not (cov_x_x < 0).any().any() @@ -98,7 +72,6 @@ def test_expanding_consistency_cov(consistency_data, min_periods, ddof): tm.assert_equal(var_x, cov_x_x) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("ddof", [0, 1]) def test_expanding_consistency_series_cov_corr(consistency_data, min_periods, ddof): x, is_constant, no_nans = consistency_data @@ -128,7 +101,6 @@ def test_expanding_consistency_series_cov_corr(consistency_data, min_periods, dd tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y)) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) def test_expanding_consistency_mean(consistency_data, min_periods): x, is_constant, no_nans = consistency_data @@ -140,7 +112,6 @@ def test_expanding_consistency_mean(consistency_data, min_periods): tm.assert_equal(result, expected.astype("float64")) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) def test_expanding_consistency_constant(consistency_data, min_periods): x, is_constant, no_nans = consistency_data @@ -162,7 +133,6 @@ def test_expanding_consistency_constant(consistency_data, min_periods): tm.assert_equal(corr_x_x, expected) -@pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) def test_expanding_consistency_var_debiasing_factors(consistency_data, min_periods): x, is_constant, no_nans = consistency_data diff --git a/pandas/tests/window/moments/test_moments_consistency_rolling.py b/pandas/tests/window/moments/test_moments_consistency_rolling.py index bda8ba05d4024..49bc5af4e9d69 100644 --- a/pandas/tests/window/moments/test_moments_consistency_rolling.py +++ b/pandas/tests/window/moments/test_moments_consistency_rolling.py @@ -5,26 +5,17 @@ import pandas._testing as tm -def _rolling_consistency_cases(): - for window in [1, 2, 3, 10, 20]: - for min_periods in {0, 1, 2, 3, 4, window}: - if min_periods and (min_periods > window): - continue - for center in [False, True]: - yield window, min_periods, center - - -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) -@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum]) -def test_rolling_apply_consistency_sum_nans( - consistency_data, window, min_periods, center, f +@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum]) +def test_rolling_apply_consistency_sum( + consistency_data, rolling_consistency_cases, center, f ): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases if f is np.nansum and min_periods == 0: pass + elif f is np.sum and not no_nans: + pass else: rolling_f_result = x.rolling( window=window, min_periods=min_periods, center=center @@ -35,36 +26,13 @@ def test_rolling_apply_consistency_sum_nans( tm.assert_equal(rolling_f_result, rolling_apply_f_result) -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) -@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum]) -def test_rolling_apply_consistency_sum_no_nans( - consistency_data, window, min_periods, center, f -): - x, is_constant, no_nans = consistency_data - - if no_nans: - if f is np.nansum and min_periods == 0: - pass - else: - rolling_f_result = x.rolling( - window=window, min_periods=min_periods, center=center - ).sum() - rolling_apply_f_result = x.rolling( - window=window, min_periods=min_periods, center=center - ).apply(func=f, raw=True) - tm.assert_equal(rolling_f_result, rolling_apply_f_result) - - -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) @pytest.mark.parametrize("ddof", [0, 1]) -def test_moments_consistency_var(consistency_data, window, min_periods, center, ddof): +def test_moments_consistency_var( + consistency_data, rolling_consistency_cases, center, ddof +): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases - mean_x = x.rolling(window=window, min_periods=min_periods, center=center).mean() var_x = x.rolling(window=window, min_periods=min_periods, center=center).var( ddof=ddof ) @@ -72,6 +40,7 @@ def test_moments_consistency_var(consistency_data, window, min_periods, center, if ddof == 0: # check that biased var(x) == mean(x^2) - mean(x)^2 + mean_x = x.rolling(window=window, min_periods=min_periods, center=center).mean() mean_x2 = ( (x * x) .rolling(window=window, min_periods=min_periods, center=center) @@ -80,14 +49,12 @@ def test_moments_consistency_var(consistency_data, window, min_periods, center, tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x)) -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) @pytest.mark.parametrize("ddof", [0, 1]) def test_moments_consistency_var_constant( - consistency_data, window, min_periods, center, ddof + consistency_data, rolling_consistency_cases, center, ddof ): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases if is_constant: count_x = x.rolling( @@ -106,37 +73,26 @@ def test_moments_consistency_var_constant( tm.assert_equal(var_x, expected) -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) @pytest.mark.parametrize("ddof", [0, 1]) -def test_rolling_consistency_std(consistency_data, window, min_periods, center, ddof): +def test_rolling_consistency_var_std_cov( + consistency_data, rolling_consistency_cases, center, ddof +): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases var_x = x.rolling(window=window, min_periods=min_periods, center=center).var( ddof=ddof ) + assert not (var_x < 0).any().any() + std_x = x.rolling(window=window, min_periods=min_periods, center=center).std( ddof=ddof ) - assert not (var_x < 0).any().any() assert not (std_x < 0).any().any() # check that var(x) == std(x)^2 tm.assert_equal(var_x, std_x * std_x) - -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) -@pytest.mark.parametrize("ddof", [0, 1]) -def test_rolling_consistency_cov(consistency_data, window, min_periods, center, ddof): - x, is_constant, no_nans = consistency_data - var_x = x.rolling(window=window, min_periods=min_periods, center=center).var( - ddof=ddof - ) - assert not (var_x < 0).any().any() - cov_x_x = x.rolling(window=window, min_periods=min_periods, center=center).cov( x, ddof=ddof ) @@ -146,14 +102,12 @@ def test_rolling_consistency_cov(consistency_data, window, min_periods, center, tm.assert_equal(var_x, cov_x_x) -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) @pytest.mark.parametrize("ddof", [0, 1]) def test_rolling_consistency_series_cov_corr( - consistency_data, window, min_periods, center, ddof + consistency_data, rolling_consistency_cases, center, ddof ): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases if isinstance(x, Series): var_x_plus_y = ( @@ -204,11 +158,9 @@ def test_rolling_consistency_series_cov_corr( tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y)) -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) -def test_rolling_consistency_mean(consistency_data, window, min_periods, center): +def test_rolling_consistency_mean(consistency_data, rolling_consistency_cases, center): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases result = x.rolling(window=window, min_periods=min_periods, center=center).mean() expected = ( @@ -221,11 +173,11 @@ def test_rolling_consistency_mean(consistency_data, window, min_periods, center) tm.assert_equal(result, expected.astype("float64")) -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) -def test_rolling_consistency_constant(consistency_data, window, min_periods, center): +def test_rolling_consistency_constant( + consistency_data, rolling_consistency_cases, center +): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases if is_constant: count_x = x.rolling( @@ -249,13 +201,11 @@ def test_rolling_consistency_constant(consistency_data, window, min_periods, cen tm.assert_equal(corr_x_x, expected) -@pytest.mark.parametrize( - "window,min_periods,center", list(_rolling_consistency_cases()) -) def test_rolling_consistency_var_debiasing_factors( - consistency_data, window, min_periods, center + consistency_data, rolling_consistency_cases, center ): x, is_constant, no_nans = consistency_data + window, min_periods = rolling_consistency_cases # check variance debiasing factors var_unbiased_x = x.rolling(
- [x] closes #37535 - [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 * Avoids running similar `def test_*` checks more than once * Thins out the `consistency_data` pytest fixture to test data with certain properties only once (constant values, all nans, monotonically increasing, etc)
https://api.github.com/repos/pandas-dev/pandas/pulls/44239
2021-10-30T06:42:28Z
2021-10-30T14:10:07Z
2021-10-30T14:10:06Z
2021-10-30T17:07:20Z
CLN: de-duplicate Ellipsis-handling
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index bed64efc690ec..69d89e2f32203 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -42,6 +42,7 @@ from pandas.compat.numpy import function as nv from pandas.errors import PerformanceWarning from pandas.util._exceptions import find_stack_level +from pandas.util._validators import validate_insert_loc from pandas.core.dtypes.cast import ( astype_nansafe, @@ -81,7 +82,10 @@ extract_array, sanitize_array, ) -from pandas.core.indexers import check_array_indexer +from pandas.core.indexers import ( + check_array_indexer, + unpack_tuple_and_ellipses, +) from pandas.core.missing import interpolate_2d from pandas.core.nanops import check_below_min_count import pandas.core.ops as ops @@ -878,16 +882,13 @@ def __getitem__( ) -> SparseArrayT | Any: if isinstance(key, tuple): - if len(key) > 1: - if key[0] is Ellipsis: - key = key[1:] - elif key[-1] is Ellipsis: - key = key[:-1] - if len(key) > 1: - raise IndexError("too many indices for array.") - if key[0] is Ellipsis: + key = unpack_tuple_and_ellipses(key) + # Non-overlapping identity check (left operand type: + # "Union[Union[Union[int, integer[Any]], Union[slice, List[int], + # ndarray[Any, Any]]], Tuple[Union[int, ellipsis], ...]]", + # right operand type: "ellipsis") + if key is Ellipsis: # type: ignore[comparison-overlap] raise ValueError("Cannot slice with Ellipsis") - key = key[0] if is_integer(key): return self._get_val_at(key) @@ -952,12 +953,7 @@ def __getitem__( return type(self)(data_slice, kind=self.kind) def _get_val_at(self, loc): - n = len(self) - if loc < 0: - loc += n - - if loc >= n or loc < 0: - raise IndexError("Out of bounds access") + loc = validate_insert_loc(loc, len(self)) sp_loc = self.sp_index.lookup(loc) if sp_loc == -1: diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 4e3bd05d2cc8d..e6058ad9dbaf2 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -58,6 +58,7 @@ ) from pandas.core.indexers import ( check_array_indexer, + unpack_tuple_and_ellipses, validate_indices, ) from pandas.core.strings.object_array import ObjectStringArrayMixin @@ -313,14 +314,7 @@ def __getitem__( "boolean arrays are valid indices." ) elif isinstance(item, tuple): - # possibly unpack arr[..., n] to arr[n] - if len(item) == 1: - item = item[0] - elif len(item) == 2: - if item[0] is Ellipsis: - item = item[1] - elif item[1] is Ellipsis: - item = item[0] + item = unpack_tuple_and_ellipses(item) # We are not an array indexer, so maybe e.g. a slice or integer # indexer. We dispatch to pyarrow. diff --git a/pandas/core/indexers/__init__.py b/pandas/core/indexers/__init__.py index 1558b03162d22..86ec36144b134 100644 --- a/pandas/core/indexers/__init__.py +++ b/pandas/core/indexers/__init__.py @@ -11,6 +11,7 @@ length_of_indexer, maybe_convert_indices, unpack_1tuple, + unpack_tuple_and_ellipses, validate_indices, ) @@ -28,4 +29,5 @@ "unpack_1tuple", "check_key_length", "check_array_indexer", + "unpack_tuple_and_ellipses", ] diff --git a/pandas/core/indexers/utils.py b/pandas/core/indexers/utils.py index cf9be5eb95eb4..bc51dbd54d010 100644 --- a/pandas/core/indexers/utils.py +++ b/pandas/core/indexers/utils.py @@ -435,6 +435,24 @@ def check_key_length(columns: Index, key, value: DataFrame) -> None: raise ValueError("Columns must be same length as key") +def unpack_tuple_and_ellipses(item: tuple): + """ + Possibly unpack arr[..., n] to arr[n] + """ + if len(item) > 1: + # Note: we are assuming this indexing is being done on a 1D arraylike + if item[0] is Ellipsis: + item = item[1:] + elif item[-1] is Ellipsis: + item = item[:-1] + + if len(item) > 1: + raise IndexError("too many indices for array.") + + item = item[0] + return item + + # ----------------------------------------------------------- # Public indexer validation diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 07ae7511bb333..96021bfa18fb7 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -258,7 +258,7 @@ def test_get_item(self): assert self.zarr[2] == 1 assert self.zarr[7] == 5 - errmsg = re.compile("bounds") + errmsg = "must be an integer between -10 and 10" with pytest.raises(IndexError, match=errmsg): self.arr[11] diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 2eef828288e59..e3e5e092f143b 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -40,6 +40,7 @@ ExtensionDtype, ) from pandas.api.types import is_bool_dtype +from pandas.core.indexers import unpack_tuple_and_ellipses class JSONDtype(ExtensionDtype): @@ -86,14 +87,7 @@ def _from_factorized(cls, values, original): def __getitem__(self, item): if isinstance(item, tuple): - if len(item) > 1: - if item[0] is Ellipsis: - item = item[1:] - elif item[-1] is Ellipsis: - item = item[:-1] - if len(item) > 1: - raise IndexError("too many indices for array.") - item = item[0] + item = unpack_tuple_and_ellipses(item) if isinstance(item, numbers.Integral): return self.data[item]
- [ ] 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/44238
2021-10-30T04:40:19Z
2021-10-30T18:40:12Z
2021-10-30T18:40:12Z
2021-10-30T18:40:12Z
BUG: all-NaT TDI division with object dtype preserve td64
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 5601048c409e1..ae3154f651384 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -479,7 +479,7 @@ Datetimelike 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`) - Timezones diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 040c7e6804f64..3d8f9f7edcc74 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -573,12 +573,17 @@ def __truediv__(self, other): # We need to do dtype inference in order to keep DataFrame ops # behavior consistent with Series behavior - inferred = lib.infer_dtype(result) + inferred = lib.infer_dtype(result, skipna=False) if inferred == "timedelta": flat = result.ravel() result = type(self)._from_sequence(flat).reshape(result.shape) elif inferred == "floating": result = result.astype(float) + elif inferred == "datetime": + # GH#39750 this occurs when result is all-NaT, in which case + # we want to interpret these NaTs as td64. + # We construct an all-td64NaT result. + result = self * np.nan return result @@ -679,13 +684,22 @@ def __floordiv__(self, other): elif is_object_dtype(other.dtype): # error: Incompatible types in assignment (expression has type # "List[Any]", variable has type "ndarray") - result = [ # type: ignore[assignment] - self[n] // other[n] for n in range(len(self)) - ] - result = np.array(result) - if lib.infer_dtype(result, skipna=False) == "timedelta": + srav = self.ravel() + orav = other.ravel() + res_list = [srav[n] // orav[n] for n in range(len(srav))] + result_flat = np.asarray(res_list) + inferred = lib.infer_dtype(result_flat, skipna=False) + + result = result_flat.reshape(self.shape) + + if inferred == "timedelta": result, _ = sequence_to_td64ns(result) return type(self)(result) + if inferred == "datetime": + # GH#39750 occurs when result is all-NaT, which in this + # case should be interpreted as td64nat. This can only + # occur when self is all-td64nat + return self * np.nan return result elif is_integer_dtype(other.dtype) or is_float_dtype(other.dtype): diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 7765c29ee59c8..0b43cb4f3d78c 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -2022,7 +2022,7 @@ def test_td64arr_rmul_numeric_array( ids=lambda x: type(x).__name__, ) def test_td64arr_div_numeric_array( - self, box_with_array, vector, any_real_numpy_dtype, using_array_manager + self, box_with_array, vector, any_real_numpy_dtype ): # GH#4521 # divide/multiply by integers @@ -2062,14 +2062,6 @@ def test_td64arr_div_numeric_array( expected = tm.box_expected(expected, xbox) assert tm.get_dtype(expected) == "m8[ns]" - if using_array_manager and box_with_array is DataFrame: - # TODO the behaviour is buggy here (third column with all-NaT - # as result doesn't get preserved as timedelta64 dtype). - # Reported at https://github.com/pandas-dev/pandas/issues/39750 - # Changing the expected instead of xfailing to continue to test - # the correct behaviour for the other columns - expected[2] = Series([NaT, NaT], dtype=object) - tm.assert_equal(result, expected) with pytest.raises(TypeError, match=pattern): @@ -2137,6 +2129,19 @@ def test_float_series_rdiv_td64arr(self, box_with_array, names): else: tm.assert_equal(result, expected) + def test_td64arr_all_nat_div_object_dtype_numeric(self, box_with_array): + # GH#39750 make sure we infer the result as td64 + tdi = TimedeltaIndex([NaT, NaT]) + + left = tm.box_expected(tdi, box_with_array) + right = np.array([2, 2.0], dtype=object) + + result = left / right + tm.assert_equal(result, left) + + result = left // right + tm.assert_equal(result, left) + class TestTimedelta64ArrayLikeArithmetic: # Arithmetic tests for timedelta64[ns] vectors fully parametrized over
- [x] closes #39750 - [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/44237
2021-10-30T02:44:17Z
2021-11-06T22:58:58Z
2021-11-06T22:58:58Z
2021-11-06T23:37:19Z
BUG: setitem into td64/dt64 series/frame with Categorical[strings]
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 5601048c409e1..492df4f1e3612 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -535,7 +535,7 @@ Indexing - Bug in :meth:`DataFrame.sort_index` where ``ignore_index=True`` was not being respected when the index was already sorted (:issue:`43591`) - Bug in :meth:`Index.get_indexer_non_unique` when index contains multiple ``np.datetime64("NaT")`` and ``np.timedelta64("NaT")`` (:issue:`43869`) - Bug in setting a scalar :class:`Interval` value into a :class:`Series` with ``IntervalDtype`` when the scalar's sides are floats and the values' sides are integers (:issue:`44201`) -- +- Bug when setting string-backed :class:`Categorical` values that can be parsed to datetimes into a :class:`DatetimeArray` or :class:`Series` or :class:`DataFrame` column backed by :class:`DatetimeArray` failing to parse these strings (:issue:`44236`) Missing diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 72c00dfe7c65a..f8aa1656c8c30 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -68,6 +68,7 @@ from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( + is_all_strings, is_categorical_dtype, is_datetime64_any_dtype, is_datetime64_dtype, @@ -720,7 +721,7 @@ def _validate_listlike(self, value, allow_object: bool = False): value = pd_array(value) value = extract_array(value, extract_numpy=True) - if is_dtype_equal(value.dtype, "string"): + if is_all_strings(value): # We got a StringArray try: # TODO: Could use from_sequence_of_strings if implemented diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 0788ecdd8b4b5..815a0a2040ddb 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -15,6 +15,7 @@ Interval, Period, algos, + lib, ) from pandas._libs.tslibs import conversion from pandas._typing import ( @@ -1788,3 +1789,23 @@ def pandas_dtype(dtype) -> DtypeObj: raise TypeError(f"dtype '{dtype}' not understood") return npdtype + + +def is_all_strings(value: ArrayLike) -> bool: + """ + Check if this is an array of strings that we should try parsing. + + Includes object-dtype ndarray containing all-strings, StringArray, + and Categorical with all-string categories. + Does not include numpy string dtypes. + """ + dtype = value.dtype + + if isinstance(dtype, np.dtype): + return ( + dtype == np.dtype("object") + and lib.infer_dtype(value, skipna=False) == "string" + ) + elif isinstance(dtype, CategoricalDtype): + return dtype.categories.inferred_type == "string" + return dtype == "string" diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 4604fad019eca..d6402e027be98 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -871,7 +871,7 @@ def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer_sli): else: assert ser._values is values - @pytest.mark.parametrize("box", [list, np.array, pd.array]) + @pytest.mark.parametrize("box", [list, np.array, pd.array, pd.Categorical, Index]) @pytest.mark.parametrize( "key", [[0, 1], slice(0, 2), np.array([True, True, False])] ) @@ -911,7 +911,7 @@ def test_setitem_td64_scalar(self, indexer_sli, scalar): indexer_sli(ser)[0] = scalar assert ser._values._data is values._data - @pytest.mark.parametrize("box", [list, np.array, pd.array]) + @pytest.mark.parametrize("box", [list, np.array, pd.array, pd.Categorical, Index]) @pytest.mark.parametrize( "key", [[0, 1], slice(0, 2), np.array([True, True, False])] )
- [ ] 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/44236
2021-10-30T02:05:44Z
2021-11-01T13:55:56Z
2021-11-01T13:55:56Z
2021-11-01T15:42:32Z
CI: Don't split tests on Windows Python 3.10
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index 96d5542451f06..d6647e8059306 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -24,8 +24,12 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macOS-latest, windows-latest] + os: [ubuntu-latest, macOS-latest] pytest_target: ["pandas/tests/[a-h]*", "pandas/tests/[i-z]*"] + include: + # No need to split tests on windows + - os: windows-latest + pytest_target: pandas name: actions-310-dev timeout-minutes: 80
Ref: https://github.com/pandas-dev/pandas/issues/44173
https://api.github.com/repos/pandas-dev/pandas/pulls/44235
2021-10-29T23:03:02Z
2021-10-30T11:18:39Z
2021-10-30T11:18:39Z
2021-11-11T01:37:42Z
REF: simplify is_scalar_indexer
diff --git a/pandas/core/indexers/utils.py b/pandas/core/indexers/utils.py index cf9be5eb95eb4..fe003281fb82e 100644 --- a/pandas/core/indexers/utils.py +++ b/pandas/core/indexers/utils.py @@ -100,10 +100,7 @@ def is_scalar_indexer(indexer, ndim: int) -> bool: # GH37748: allow indexer to be an integer for Series return True if isinstance(indexer, tuple) and len(indexer) == ndim: - return all( - is_integer(x) or (isinstance(x, np.ndarray) and x.ndim == len(x) == 1) - for x in indexer - ) + return all(is_integer(x) for x in indexer) return False diff --git a/pandas/tests/indexing/test_indexers.py b/pandas/tests/indexing/test_indexers.py index 45dcaf95ffdd0..ddc5c039160d5 100644 --- a/pandas/tests/indexing/test_indexers.py +++ b/pandas/tests/indexing/test_indexers.py @@ -22,10 +22,10 @@ def test_is_scalar_indexer(): assert not is_scalar_indexer(indexer[0], 2) indexer = (np.array([2]), 1) - assert is_scalar_indexer(indexer, 2) + assert not is_scalar_indexer(indexer, 2) indexer = (np.array([2]), np.array([3])) - assert is_scalar_indexer(indexer, 2) + assert not is_scalar_indexer(indexer, 2) indexer = (np.array([2]), np.array([3, 4])) assert not is_scalar_indexer(indexer, 2)
- [ ] 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/44234
2021-10-29T20:52:41Z
2021-10-30T20:29:58Z
2021-10-30T20:29:58Z
2021-10-30T21:38:33Z
TYP: numba stub
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 21250789fde9f..ea9595fd88630 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -106,7 +106,7 @@ if [[ -z "$CHECK" || "$CHECK" == "typing" ]]; then mypy --version MSG='Performing static analysis using mypy' ; echo $MSG - mypy pandas + mypy RET=$(($RET + $?)) ; echo $MSG "DONE" # run pyright, if it is installed diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 936db7d1bee88..4cea030546635 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -399,7 +399,7 @@ pandas uses `mypy <http://mypy-lang.org>`_ and `pyright <https://github.com/micr .. code-block:: shell - mypy pandas + mypy # let pre-commit setup and run pyright pre-commit run --hook-stage manual --all-files pyright diff --git a/pandas/core/_numba/kernels/mean_.py b/pandas/core/_numba/kernels/mean_.py index f3a2c7c2170a8..8f67dd9b51c06 100644 --- a/pandas/core/_numba/kernels/mean_.py +++ b/pandas/core/_numba/kernels/mean_.py @@ -14,8 +14,7 @@ from pandas.core._numba.kernels.shared import is_monotonic_increasing -# error: Untyped decorator makes function "add_mean" untyped -@numba.jit(nopython=True, nogil=True, parallel=False) # type: ignore[misc] +@numba.jit(nopython=True, nogil=True, parallel=False) def add_mean( val: float, nobs: int, sum_x: float, neg_ct: int, compensation: float ) -> tuple[int, float, int, float]: @@ -30,8 +29,7 @@ def add_mean( return nobs, sum_x, neg_ct, compensation -# error: Untyped decorator makes function "remove_mean" untyped -@numba.jit(nopython=True, nogil=True, parallel=False) # type: ignore[misc] +@numba.jit(nopython=True, nogil=True, parallel=False) def remove_mean( val: float, nobs: int, sum_x: float, neg_ct: int, compensation: float ) -> tuple[int, float, int, float]: @@ -46,8 +44,7 @@ def remove_mean( return nobs, sum_x, neg_ct, compensation -# error: Untyped decorator makes function "sliding_mean" untyped -@numba.jit(nopython=True, nogil=True, parallel=False) # type: ignore[misc] +@numba.jit(nopython=True, nogil=True, parallel=False) def sliding_mean( values: np.ndarray, start: np.ndarray, diff --git a/pandas/core/_numba/kernels/shared.py b/pandas/core/_numba/kernels/shared.py index 7c2e7636c7d81..ec25e78a8d897 100644 --- a/pandas/core/_numba/kernels/shared.py +++ b/pandas/core/_numba/kernels/shared.py @@ -2,9 +2,12 @@ import numpy as np -# error: Untyped decorator makes function "is_monotonic_increasing" untyped -@numba.jit( # type: ignore[misc] - numba.boolean(numba.int64[:]), nopython=True, nogil=True, parallel=False +@numba.jit( + # error: Any? not callable + numba.boolean(numba.int64[:]), # type: ignore[misc] + nopython=True, + nogil=True, + parallel=False, ) def is_monotonic_increasing(bounds: np.ndarray) -> bool: """Check if int64 values are monotonically increasing.""" diff --git a/pandas/core/_numba/kernels/sum_.py b/pandas/core/_numba/kernels/sum_.py index 66a1587c49f3f..c2e81b4990ba9 100644 --- a/pandas/core/_numba/kernels/sum_.py +++ b/pandas/core/_numba/kernels/sum_.py @@ -14,8 +14,7 @@ from pandas.core._numba.kernels.shared import is_monotonic_increasing -# error: Untyped decorator makes function "add_sum" untyped -@numba.jit(nopython=True, nogil=True, parallel=False) # type: ignore[misc] +@numba.jit(nopython=True, nogil=True, parallel=False) def add_sum( val: float, nobs: int, sum_x: float, compensation: float ) -> tuple[int, float, float]: @@ -28,8 +27,7 @@ def add_sum( return nobs, sum_x, compensation -# error: Untyped decorator makes function "remove_sum" untyped -@numba.jit(nopython=True, nogil=True, parallel=False) # type: ignore[misc] +@numba.jit(nopython=True, nogil=True, parallel=False) def remove_sum( val: float, nobs: int, sum_x: float, compensation: float ) -> tuple[int, float, float]: @@ -42,8 +40,7 @@ def remove_sum( return nobs, sum_x, compensation -# error: Untyped decorator makes function "sliding_sum" untyped -@numba.jit(nopython=True, nogil=True, parallel=False) # type: ignore[misc] +@numba.jit(nopython=True, nogil=True, parallel=False) def sliding_sum( values: np.ndarray, start: np.ndarray, diff --git a/pyproject.toml b/pyproject.toml index 7966e94cff2f3..d84024eb09de2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,6 +60,8 @@ markers = [ [tool.mypy] # Import discovery +mypy_path = "typings" +files = ["pandas", "typings"] namespace_packages = false explicit_package_bases = false ignore_missing_imports = true diff --git a/typings/numba.pyi b/typings/numba.pyi new file mode 100644 index 0000000000000..d6a2729d36db3 --- /dev/null +++ b/typings/numba.pyi @@ -0,0 +1,41 @@ +from typing import ( + Any, + Callable, + Literal, + overload, +) + +import numba + +from pandas._typing import F + +def __getattr__(name: str) -> Any: ... # incomplete +@overload +def jit( + signature_or_function: F = ..., +) -> F: ... +@overload +def jit( + signature_or_function: str + | list[str] + | numba.core.types.abstract.Type + | list[numba.core.types.abstract.Type] = ..., + locals: dict = ..., # TODO: Mapping of local variable names to Numba types + cache: bool = ..., + pipeline_class: numba.compiler.CompilerBase = ..., + boundscheck: bool | None = ..., + *, + nopython: bool = ..., + forceobj: bool = ..., + looplift: bool = ..., + error_model: Literal["python", "numpy"] = ..., + inline: Literal["never", "always"] | Callable = ..., + # TODO: If a callable is provided it will be called with the call expression + # node that is requesting inlining, the caller's IR and callee's IR as + # arguments, it is expected to return Truthy as to whether to inline. + target: Literal["cpu", "gpu", "npyufunc", "cuda"] = ..., # deprecated + nogil: bool = ..., + parallel: bool = ..., +) -> Callable[[F], F]: ... + +njit = jit
partial stub to preserve type signatures for decorated functions. draft since will rebase once #43828 is merged. cc @twoertwein @mroeschke
https://api.github.com/repos/pandas-dev/pandas/pulls/44233
2021-10-29T20:45:56Z
2021-10-31T14:54:12Z
2021-10-31T14:54:11Z
2021-11-01T18:35:24Z
REF: RangeIndex.delete defer to .difference
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 41ef824afc2a7..3fae0fbe7d2a0 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -807,24 +807,17 @@ def delete(self, loc) -> Index: # type: ignore[override] return self[1:] if loc == -1 or loc == len(self) - 1: return self[:-1] + if len(self) == 3 and (loc == 1 or loc == -2): + return self[::2] elif lib.is_list_like(loc): slc = lib.maybe_indices_to_slice(np.asarray(loc, dtype=np.intp), len(self)) - if isinstance(slc, slice) and slc.step is not None and slc.step < 0: - rng = range(len(self))[slc][::-1] - slc = slice(rng.start, rng.stop, rng.step) - - if isinstance(slc, slice) and slc.step in [1, None]: - # Note: maybe_indices_to_slice will never return a slice - # with 'slc.start is None'; may have slc.stop None in cases - # with negative step - if slc.start == 0: - return self[slc.stop :] - elif slc.stop in [len(self), None]: - return self[: slc.start] - - # TODO: more generally, self.difference(self[slc]), - # once _difference is better about retaining RangeIndex + + if isinstance(slc, slice): + # defer to RangeIndex._difference, which is optimized to return + # a RangeIndex whenever possible + other = self[slc] + return self.difference(other, sort=False) return super().delete(loc) diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index d58dff191cc73..277f686a8487a 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -178,6 +178,15 @@ def test_delete_preserves_rangeindex(self): result = idx.delete(1) tm.assert_index_equal(result, expected, exact=True) + def test_delete_preserves_rangeindex_middle(self): + idx = Index(range(3), name="foo") + result = idx.delete(1) + expected = idx[::2] + tm.assert_index_equal(result, expected, exact=True) + + result = idx.delete(-2) + tm.assert_index_equal(result, expected, exact=True) + def test_delete_preserves_rangeindex_list_at_end(self): idx = RangeIndex(0, 6, 1)
- [ ] 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/44232
2021-10-29T17:38:24Z
2021-10-29T21:50:03Z
2021-10-29T21:50:03Z
2021-10-29T22:49:09Z
Backport PR #44195 on branch 1.3.x (Fix series with none equals float series)
diff --git a/doc/source/whatsnew/v1.3.5.rst b/doc/source/whatsnew/v1.3.5.rst index ba9fcb5c1bfeb..589092c0dd7e3 100644 --- a/doc/source/whatsnew/v1.3.5.rst +++ b/doc/source/whatsnew/v1.3.5.rst @@ -14,6 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ +- Fixed regression in :meth:`Series.equals` when comparing floats with dtype object to None (:issue:`44190`) - Fixed performance regression in :func:`read_csv` (:issue:`44106`) - diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index cbe79d11fbfc9..835b288778473 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -64,7 +64,7 @@ cpdef bint is_matching_na(object left, object right, bint nan_matches_none=False elif left is NaT: return right is NaT elif util.is_float_object(left): - if nan_matches_none and right is None: + if nan_matches_none and right is None and util.is_nan(left): return True return ( util.is_nan(left) diff --git a/pandas/tests/series/methods/test_equals.py b/pandas/tests/series/methods/test_equals.py index 0b3689afac764..a3faf783fd3fb 100644 --- a/pandas/tests/series/methods/test_equals.py +++ b/pandas/tests/series/methods/test_equals.py @@ -125,3 +125,18 @@ def test_equals_none_vs_nan(): assert ser.equals(ser2) assert Index(ser).equals(Index(ser2)) assert ser.array.equals(ser2.array) + + +def test_equals_None_vs_float(): + # GH#44190 + left = Series([-np.inf, np.nan, -1.0, 0.0, 1.0, 10 / 3, np.inf], dtype=object) + right = Series([None] * len(left)) + + # these series were found to be equal due to a bug, check that they are correctly + # found to not equal + assert not left.equals(right) + assert not right.equals(left) + assert not left.to_frame().equals(right.to_frame()) + assert not right.to_frame().equals(left.to_frame()) + assert not Index(left, dtype="object").equals(Index(right, dtype="object")) + assert not Index(right, dtype="object").equals(Index(left, dtype="object"))
Backport PR #44195: Fix series with none equals float series
https://api.github.com/repos/pandas-dev/pandas/pulls/44229
2021-10-29T13:17:50Z
2021-10-29T15:42:52Z
2021-10-29T15:42:52Z
2021-10-29T15:42:52Z
DOC: local py.typed for users
diff --git a/.gitignore b/.gitignore index 2c337be60e94e..87224f1d6060f 100644 --- a/.gitignore +++ b/.gitignore @@ -50,6 +50,8 @@ dist *.egg-info .eggs .pypirc +# type checkers +pandas/py.typed # tox testing tool .tox diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 4cea030546635..8baf103369a13 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -410,6 +410,26 @@ A recent version of ``numpy`` (>=1.21.0) is required for type validation. .. _contributing.ci: +Testing type hints in code using pandas +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. warning:: + + * Pandas is not yet a py.typed library (:pep:`561`)! + The primary purpose of locally declaring pandas as a py.typed library is to test and + improve the pandas-builtin type annotations. + +Until pandas becomes a py.typed library, it is possible to easily experiment with the type +annotations shipped with pandas by creating an empty file named "py.typed" in the pandas +installation folder: + +.. code-block:: none + + python -c "import pandas; import pathlib; (pathlib.Path(pandas.__path__[0]) / 'py.typed').touch()" + +The existence of the py.typed file signals to type checkers that pandas is already a py.typed +library. This makes type checkers aware of the type annotations shipped with pandas. + Testing with continuous integration -----------------------------------
xref https://github.com/pandas-dev/pandas/pull/44223#issuecomment-954672983
https://api.github.com/repos/pandas-dev/pandas/pulls/44228
2021-10-29T12:55:21Z
2021-12-17T22:01:59Z
2021-12-17T22:01:58Z
2022-03-09T02:56:36Z
TYP: type annotations for nancorr
diff --git a/pandas/_libs/algos.pyi b/pandas/_libs/algos.pyi index 6dd1c7c9fb209..df8ac3f3b0696 100644 --- a/pandas/_libs/algos.pyi +++ b/pandas/_libs/algos.pyi @@ -50,18 +50,14 @@ def kth_smallest( # Pairwise correlation/covariance def nancorr( - mat: np.ndarray, # const float64_t[:, :] + mat: npt.NDArray[np.float64], # const float64_t[:, :] cov: bool = ..., - minp=..., -) -> np.ndarray: ... # ndarray[float64_t, ndim=2] + minp: int | None = ..., +) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2] def nancorr_spearman( - mat: np.ndarray, # ndarray[float64_t, ndim=2] + mat: npt.NDArray[np.float64], # ndarray[float64_t, ndim=2] minp: int = ..., -) -> np.ndarray: ... # ndarray[float64_t, ndim=2] -def nancorr_kendall( - mat: np.ndarray, # ndarray[float64_t, ndim=2] - minp: int = ..., -) -> np.ndarray: ... # ndarray[float64_t, ndim=2] +) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2] # ----------------------------------------------------------------------
null
https://api.github.com/repos/pandas-dev/pandas/pulls/44227
2021-10-29T12:22:40Z
2021-10-29T21:56:23Z
2021-10-29T21:56:23Z
2021-10-29T21:56:23Z
DOC: added examples to DataFrame.std
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7ff48a262c4d6..c2fa345f7639d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10639,6 +10639,7 @@ def mad(self, axis=None, skipna=None, level=None): name2=name2, axis_descr=axis_descr, notes="", + examples="", ) def sem( self, @@ -10661,6 +10662,7 @@ def sem( name2=name2, axis_descr=axis_descr, notes="", + examples="", ) def var( self, @@ -10679,11 +10681,12 @@ def var( _num_ddof_doc, desc="Return sample standard deviation over requested axis." "\n\nNormalized by N-1 by default. This can be changed using the " - "ddof argument", + "ddof argument.", name1=name1, name2=name2, axis_descr=axis_descr, notes=_std_notes, + examples=_std_examples, ) def std( self, @@ -11175,7 +11178,8 @@ def _doc_params(cls): Returns ------- {name1} or {name2} (if level specified) \ -{notes} +{notes}\ +{examples} """ _std_notes = """ @@ -11185,6 +11189,34 @@ def _doc_params(cls): To have the same behaviour as `numpy.std`, use `ddof=0` (instead of the default `ddof=1`)""" +_std_examples = """ + +Examples +-------- +>>> df = pd.DataFrame({'person_id': [0, 1, 2, 3], +... 'age': [21, 25, 62, 43], +... 'height': [1.61, 1.87, 1.49, 2.01]} +... ).set_index('person_id') +>>> df + age height +person_id +0 21 1.61 +1 25 1.87 +2 62 1.49 +3 43 2.01 + +The standard deviation of the columns can be found as follows: + +>>> df.std() +age 18.786076 +height 0.237417 + +Alternatively, `ddof=0` can be set to normalize by N instead of N-1: + +>>> df.std(ddof=0) +age 16.269219 +height 0.205609""" + _bool_doc = """ {desc}
xref https://github.com/pandas-dev/pandas/issues/44162 - [x] Added two examples to the documentation of DataFrame.std function so that users can understand how to use it with different delta degrees of freedom. - [ ] Add examples to the documentation of DataFrame.var function --- - [x] tests added / passed - [x] All pre-commit linting tests pass
https://api.github.com/repos/pandas-dev/pandas/pulls/44226
2021-10-29T11:03:40Z
2021-11-01T17:09:11Z
2021-11-01T17:09:11Z
2021-11-01T17:09:24Z
Update is_platform_arm() to detect 32-bit arm and other variants
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 3233de8e3b6d1..fd5c46f7a6d5a 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -99,7 +99,9 @@ def is_platform_arm() -> bool: bool True if the running platform uses ARM architecture. """ - return platform.machine() in ("arm64", "aarch64") + return platform.machine() in ("arm64", "aarch64") or platform.machine().startswith( + "armv" + ) def import_lzma():
- When running an arm32 ("linux32'd") chroot on an arm64 machine, Python's platform.machine() will return "armv8l". - In other cases, on "real" arm32, it'll return whatever uname says (just like in the first case) which might be e.g. armv7a. Keeping the other options ("aarch64", "arm64") given that Windows or other kernels might choose to return different values and these were added for a reason, but at least this fixes detection on Linux. This allows tests like test_subtype_integer_errors to be skipped as intended on arm. Bug: https://bugs.gentoo.org/818964 Signed-off-by: Sam James <sam@gentoo.org> - [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/44225
2021-10-29T11:01:32Z
2021-10-29T16:24:01Z
2021-10-29T16:24:01Z
2021-11-01T00:28:35Z
CLN: remove last getattr(arg, '_values', arg) usages
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 3116f2b40900a..005c5f75e6cfa 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -53,7 +53,6 @@ @inherit_names( [ "argsort", - "_internal_get_values", "tolist", "codes", "categories", diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 2838c33a42716..aca751362c915 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -69,6 +69,7 @@ objects_to_datetime64ns, tz_to_dtype, ) +from pandas.core.construction import extract_array from pandas.core.indexes.base import Index from pandas.core.indexes.datetimes import DatetimeIndex @@ -516,7 +517,7 @@ def _to_datetime_with_unit(arg, unit, name, tz, errors: str) -> Index: """ to_datetime specalized to the case where a 'unit' is passed. """ - arg = getattr(arg, "_values", arg) # TODO: extract_array + arg = extract_array(arg, extract_numpy=True) # GH#30050 pass an ndarray to tslib.array_with_unit_to_datetime # because it expects an ndarray argument
- [x] closes #27167 - [ ] 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/44224
2021-10-29T02:21:02Z
2021-10-29T16:05:30Z
2021-10-29T16:05:29Z
2021-10-29T17:04:33Z
CLN: remove checks for python < 3.8
diff --git a/pandas/_libs/tslibs/timestamps.pyi b/pandas/_libs/tslibs/timestamps.pyi index ff6b18835322e..a89d0aecfc26c 100644 --- a/pandas/_libs/tslibs/timestamps.pyi +++ b/pandas/_libs/tslibs/timestamps.pyi @@ -5,7 +5,6 @@ from datetime import ( timedelta, tzinfo as _tzinfo, ) -import sys from time import struct_time from typing import ( ClassVar, @@ -89,16 +88,8 @@ class Timestamp(datetime): def today(cls: Type[_S]) -> _S: ... @classmethod def fromordinal(cls: Type[_S], n: int) -> _S: ... - if sys.version_info >= (3, 8): - @classmethod - def now(cls: Type[_S], tz: _tzinfo | str | None = ...) -> _S: ... - else: - @overload - @classmethod - def now(cls: Type[_S], tz: None = ...) -> _S: ... - @overload - @classmethod - def now(cls, tz: _tzinfo) -> datetime: ... + @classmethod + def now(cls: Type[_S], tz: _tzinfo | str | None = ...) -> _S: ... @classmethod def utcnow(cls: Type[_S]) -> _S: ... @classmethod @@ -129,10 +120,7 @@ class Timestamp(datetime): *, fold: int = ..., ) -> datetime: ... - if sys.version_info >= (3, 8): - def astimezone(self: _S, tz: _tzinfo | None = ...) -> _S: ... - else: - def astimezone(self, tz: _tzinfo | None = ...) -> datetime: ... + def astimezone(self: _S, tz: _tzinfo | None = ...) -> _S: ... def ctime(self) -> str: ... def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... @classmethod @@ -144,12 +132,8 @@ class Timestamp(datetime): def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore - if sys.version_info >= (3, 8): - def __add__(self: _S, other: timedelta) -> _S: ... - def __radd__(self: _S, other: timedelta) -> _S: ... - else: - def __add__(self, other: timedelta) -> datetime: ... - def __radd__(self, other: timedelta) -> datetime: ... + def __add__(self: _S, other: timedelta) -> _S: ... + def __radd__(self: _S, other: timedelta) -> _S: ... @overload # type: ignore def __sub__(self, other: datetime) -> timedelta: ... @overload diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 71f1d03ea6d1f..89b8783462f7e 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -1,7 +1,6 @@ """Tests for Table Schema integration.""" from collections import OrderedDict import json -import sys import numpy as np import pytest @@ -691,7 +690,6 @@ class TestTableOrientReader: }, ], ) - @pytest.mark.skipif(sys.version_info[:3] == (3, 7, 0), reason="GH-35309") def test_read_json_table_orient(self, index_nm, vals, recwarn): df = DataFrame(vals, index=pd.Index(range(4), name=index_nm)) out = df.to_json(orient="table") @@ -741,7 +739,6 @@ def test_read_json_table_orient_raises(self, index_nm, vals, recwarn): }, ], ) - @pytest.mark.skipif(sys.version_info[:3] == (3, 7, 0), reason="GH-35309") def test_read_json_table_timezones_orient(self, idx, vals, recwarn): # GH 35973 df = DataFrame(vals, index=idx)
null
https://api.github.com/repos/pandas-dev/pandas/pulls/44223
2021-10-28T21:49:08Z
2021-10-29T13:10:29Z
2021-10-29T13:10:29Z
2022-04-01T01:36:46Z
CLN: simplify io.formats.format.get_series_repr_params
diff --git a/pandas/core/series.py b/pandas/core/series.py index 13bedac664ea3..15715af05f904 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1458,7 +1458,7 @@ def __repr__(self) -> str: """ Return a string representation for a particular Series. """ - repr_params = fmt.get_series_repr_params(self) + repr_params = fmt.get_series_repr_params() return self.to_string(**repr_params) def to_string( diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 4bab85a3c6739..ba85a1b340d05 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -516,7 +516,7 @@ def get_dataframe_repr_params() -> dict[str, Any]: } -def get_series_repr_params(series: Series) -> dict[str, Any]: +def get_series_repr_params() -> dict[str, Any]: """Get the parameters used to repr(Series) calls using Series.to_string. Supplying these parameters to Series.to_string is equivalent to calling @@ -529,7 +529,7 @@ def get_series_repr_params(series: Series) -> dict[str, Any]: >>> import pandas as pd >>> >>> ser = pd.Series([1, 2, 3, 4]) - >>> repr_params = pd.io.formats.format.get_series_repr_params(ser) + >>> repr_params = pd.io.formats.format.get_series_repr_params() >>> repr(ser) == ser.to_string(**repr_params) True """ @@ -546,8 +546,8 @@ def get_series_repr_params(series: Series) -> dict[str, Any]: ) return { - "name": series.name, - "dtype": series.dtype, + "name": True, + "dtype": True, "min_rows": min_rows, "max_rows": max_rows, "length": get_option("display.show_dimensions"),
Some of the returned values should be booleans. Follow-up to #44218.
https://api.github.com/repos/pandas-dev/pandas/pulls/44221
2021-10-28T19:34:21Z
2021-10-29T14:29:42Z
2021-10-29T14:29:42Z
2021-10-29T16:59:15Z
TST/REF: share tz_localize tests, move misplaced arith
diff --git a/pandas/tests/series/methods/test_tz_convert.py b/pandas/tests/series/methods/test_tz_convert.py deleted file mode 100644 index d826dde646cfb..0000000000000 --- a/pandas/tests/series/methods/test_tz_convert.py +++ /dev/null @@ -1,17 +0,0 @@ -import numpy as np - -from pandas import ( - DatetimeIndex, - Series, -) -import pandas._testing as tm - - -class TestTZConvert: - def test_series_tz_convert_to_utc(self): - base = DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], tz="UTC") - idx1 = base.tz_convert("Asia/Tokyo")[:2] - idx2 = base.tz_convert("US/Eastern")[1:] - - res = Series([1, 2], index=idx1) + Series([1, 1], index=idx2) - tm.assert_series_equal(res, Series([np.nan, 3, np.nan], index=base)) diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py index a32c1fb8df502..b8a1ea55db4fe 100644 --- a/pandas/tests/series/methods/test_tz_localize.py +++ b/pandas/tests/series/methods/test_tz_localize.py @@ -68,22 +68,39 @@ def test_series_tz_localize_matching_index(self): ["foo", "invalid"], ], ) - def test_series_tz_localize_nonexistent(self, tz, method, exp): + def test_tz_localize_nonexistent(self, tz, method, exp): # GH 8917 n = 60 dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min") - s = Series(1, dti) + ser = Series(1, index=dti) + df = ser.to_frame() + if method == "raise": + + with tm.external_error_raised(pytz.NonExistentTimeError): + dti.tz_localize(tz, nonexistent=method) + with tm.external_error_raised(pytz.NonExistentTimeError): + ser.tz_localize(tz, nonexistent=method) with tm.external_error_raised(pytz.NonExistentTimeError): - s.tz_localize(tz, nonexistent=method) + df.tz_localize(tz, nonexistent=method) + elif exp == "invalid": with pytest.raises(ValueError, match="argument must be one of"): dti.tz_localize(tz, nonexistent=method) + with pytest.raises(ValueError, match="argument must be one of"): + ser.tz_localize(tz, nonexistent=method) + with pytest.raises(ValueError, match="argument must be one of"): + df.tz_localize(tz, nonexistent=method) + else: - result = s.tz_localize(tz, nonexistent=method) + result = ser.tz_localize(tz, nonexistent=method) expected = Series(1, index=DatetimeIndex([exp] * n, tz=tz)) tm.assert_series_equal(result, expected) + result = df.tz_localize(tz, nonexistent=method) + expected = expected.to_frame() + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_series_tz_localize_empty(self, tzstr): # GH#2248 diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 103130484f0e1..e4f9366be8dd7 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -714,6 +714,16 @@ def test_series_add_tz_mismatch_converts_to_utc(self): assert result.index.tz == pytz.UTC tm.assert_series_equal(result, expected) + # TODO: redundant with test_series_add_tz_mismatch_converts_to_utc? + def test_series_arithmetic_mismatched_tzs_convert_to_utc(self): + base = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], tz="UTC") + idx1 = base.tz_convert("Asia/Tokyo")[:2] + idx2 = base.tz_convert("US/Eastern")[1:] + + res = Series([1, 2], index=idx1) + Series([1, 1], index=idx2) + expected = Series([np.nan, 3, np.nan], index=base) + tm.assert_series_equal(res, expected) + def test_series_add_aware_naive_raises(self): rng = date_range("1/1/2011", periods=10, freq="H") ser = Series(np.random.randn(len(rng)), index=rng)
- [ ] 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/44220
2021-10-28T18:00:31Z
2021-10-29T13:15:06Z
2021-10-29T13:15:06Z
2021-10-29T15:20:29Z
REF/TST: share asfreq tests
diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py index 0d28af5ed7be9..0a8d7c43adffe 100644 --- a/pandas/tests/frame/methods/test_asfreq.py +++ b/pandas/tests/frame/methods/test_asfreq.py @@ -1,12 +1,14 @@ from datetime import datetime import numpy as np +import pytest from pandas import ( DataFrame, DatetimeIndex, Series, date_range, + period_range, to_datetime, ) import pandas._testing as tm @@ -15,29 +17,128 @@ class TestAsFreq: - def test_asfreq_resample_set_correct_freq(self): + def test_asfreq2(self, frame_or_series): + ts = frame_or_series( + [0.0, 1.0, 2.0], + index=DatetimeIndex( + [ + datetime(2009, 10, 30), + datetime(2009, 11, 30), + datetime(2009, 12, 31), + ], + freq="BM", + ), + ) + + daily_ts = ts.asfreq("B") + monthly_ts = daily_ts.asfreq("BM") + tm.assert_equal(monthly_ts, ts) + + daily_ts = ts.asfreq("B", method="pad") + monthly_ts = daily_ts.asfreq("BM") + tm.assert_equal(monthly_ts, ts) + + daily_ts = ts.asfreq(offsets.BDay()) + monthly_ts = daily_ts.asfreq(offsets.BMonthEnd()) + tm.assert_equal(monthly_ts, ts) + + result = ts[:0].asfreq("M") + assert len(result) == 0 + assert result is not ts + + if frame_or_series is Series: + daily_ts = ts.asfreq("D", fill_value=-1) + result = daily_ts.value_counts().sort_index() + expected = Series([60, 1, 1, 1], index=[-1.0, 2.0, 1.0, 0.0]).sort_index() + tm.assert_series_equal(result, expected) + + def test_asfreq_datetimeindex_empty(self, frame_or_series): + # GH#14320 + index = DatetimeIndex(["2016-09-29 11:00"]) + expected = frame_or_series(index=index, dtype=object).asfreq("H") + result = frame_or_series([3], index=index.copy()).asfreq("H") + tm.assert_index_equal(expected.index, result.index) + + @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) + def test_tz_aware_asfreq_smoke(self, tz, frame_or_series): + dr = date_range("2011-12-01", "2012-07-20", freq="D", tz=tz) + + obj = frame_or_series(np.random.randn(len(dr)), index=dr) + + # it works! + obj.asfreq("T") + + def test_asfreq_normalize(self, frame_or_series): + rng = date_range("1/1/2000 09:30", periods=20) + norm = date_range("1/1/2000", periods=20) + + vals = np.random.randn(20, 3) + + obj = DataFrame(vals, index=rng) + expected = DataFrame(vals, index=norm) + if frame_or_series is Series: + obj = obj[0] + expected = expected[0] + + result = obj.asfreq("D", normalize=True) + tm.assert_equal(result, expected) + + def test_asfreq_keep_index_name(self, frame_or_series): + # GH#9854 + 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"] + + assert index_name == obj.index.name + assert index_name == obj.asfreq("10D").index.name + + 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] + + result = obj.asfreq("D", how="end") + exp_index = index.asfreq("D", how="end") + assert len(result) == len(obj) + tm.assert_index_equal(result.index, exp_index) + + result = obj.asfreq("D", how="start") + exp_index = index.asfreq("D", how="start") + assert len(result) == len(obj) + tm.assert_index_equal(result.index, exp_index) + + def test_asfreq_resample_set_correct_freq(self, frame_or_series): # GH#5613 # we test if .asfreq() and .resample() set the correct value for .freq - df = DataFrame( - {"date": ["2012-01-01", "2012-01-02", "2012-01-03"], "col": [1, 2, 3]} - ) - df = df.set_index(to_datetime(df.date)) + 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"] # testing the settings before calling .asfreq() and .resample() - assert df.index.freq is None - assert df.index.inferred_freq == "D" + assert obj.index.freq is None + assert obj.index.inferred_freq == "D" # does .asfreq() set .freq correctly? - assert df.asfreq("D").index.freq == "D" + assert obj.asfreq("D").index.freq == "D" # does .resample() set .freq correctly? - assert df.resample("D").asfreq().index.freq == "D" + assert obj.resample("D").asfreq().index.freq == "D" + + def test_asfreq_empty(self, datetime_frame): + # test does not blow up on length-0 DataFrame + zero_length = datetime_frame.reindex([]) + result = zero_length.asfreq("BM") + assert result is not zero_length def test_asfreq(self, datetime_frame): offset_monthly = datetime_frame.asfreq(offsets.BMonthEnd()) rule_monthly = datetime_frame.asfreq("BM") - tm.assert_almost_equal(offset_monthly["A"], rule_monthly["A"]) + tm.assert_frame_equal(offset_monthly, rule_monthly) filled = rule_monthly.asfreq("B", method="pad") # noqa # TODO: actually check that this worked. @@ -45,11 +146,6 @@ def test_asfreq(self, datetime_frame): # don't forget! filled_dep = rule_monthly.asfreq("B", method="pad") # noqa - # test does not blow up on length-0 DataFrame - zero_length = datetime_frame.reindex([]) - result = zero_length.asfreq("BM") - assert result is not zero_length - def test_asfreq_datetimeindex(self): df = DataFrame( {"A": [1, 2, 3]}, diff --git a/pandas/tests/series/methods/test_asfreq.py b/pandas/tests/series/methods/test_asfreq.py deleted file mode 100644 index 9a7f2343984d6..0000000000000 --- a/pandas/tests/series/methods/test_asfreq.py +++ /dev/null @@ -1,116 +0,0 @@ -from datetime import datetime - -import numpy as np -import pytest - -from pandas import ( - DataFrame, - DatetimeIndex, - Series, - date_range, - period_range, -) -import pandas._testing as tm - -from pandas.tseries.offsets import ( - BDay, - BMonthEnd, -) - - -class TestAsFreq: - # TODO: de-duplicate/parametrize or move DataFrame test - def test_asfreq_ts(self): - index = period_range(freq="A", start="1/1/2001", end="12/31/2010") - ts = Series(np.random.randn(len(index)), index=index) - df = DataFrame(np.random.randn(len(index), 3), index=index) - - result = ts.asfreq("D", how="end") - df_result = df.asfreq("D", how="end") - exp_index = index.asfreq("D", how="end") - assert len(result) == len(ts) - tm.assert_index_equal(result.index, exp_index) - tm.assert_index_equal(df_result.index, exp_index) - - result = ts.asfreq("D", how="start") - assert len(result) == len(ts) - tm.assert_index_equal(result.index, index.asfreq("D", how="start")) - - @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) - def test_tz_aware_asfreq(self, tz): - dr = date_range("2011-12-01", "2012-07-20", freq="D", tz=tz) - - ser = Series(np.random.randn(len(dr)), index=dr) - - # it works! - ser.asfreq("T") - - def test_asfreq(self): - ts = Series( - [0.0, 1.0, 2.0], - index=DatetimeIndex( - [ - datetime(2009, 10, 30), - datetime(2009, 11, 30), - datetime(2009, 12, 31), - ], - freq="BM", - ), - ) - - daily_ts = ts.asfreq("B") - monthly_ts = daily_ts.asfreq("BM") - tm.assert_series_equal(monthly_ts, ts) - - daily_ts = ts.asfreq("B", method="pad") - monthly_ts = daily_ts.asfreq("BM") - tm.assert_series_equal(monthly_ts, ts) - - daily_ts = ts.asfreq(BDay()) - monthly_ts = daily_ts.asfreq(BMonthEnd()) - tm.assert_series_equal(monthly_ts, ts) - - result = ts[:0].asfreq("M") - assert len(result) == 0 - assert result is not ts - - daily_ts = ts.asfreq("D", fill_value=-1) - result = daily_ts.value_counts().sort_index() - expected = Series([60, 1, 1, 1], index=[-1.0, 2.0, 1.0, 0.0]).sort_index() - tm.assert_series_equal(result, expected) - - def test_asfreq_datetimeindex_empty_series(self): - # GH#14320 - index = DatetimeIndex(["2016-09-29 11:00"]) - expected = Series(index=index, dtype=object).asfreq("H") - result = Series([3], index=index.copy()).asfreq("H") - tm.assert_index_equal(expected.index, result.index) - - def test_asfreq_keep_index_name(self): - # GH#9854 - index_name = "bar" - index = date_range("20130101", periods=20, name=index_name) - df = DataFrame(list(range(20)), columns=["foo"], index=index) - - assert index_name == df.index.name - assert index_name == df.asfreq("10D").index.name - - def test_asfreq_normalize(self): - rng = date_range("1/1/2000 09:30", periods=20) - norm = date_range("1/1/2000", periods=20) - vals = np.random.randn(20) - ts = Series(vals, index=rng) - - result = ts.asfreq("D", normalize=True) - norm = date_range("1/1/2000", periods=20) - expected = Series(vals, index=norm) - - tm.assert_series_equal(result, expected) - - vals = np.random.randn(20, 3) - ts = DataFrame(vals, index=rng) - - result = ts.asfreq("D", normalize=True) - expected = DataFrame(vals, index=norm) - - tm.assert_frame_equal(result, expected)
- [ ] 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/44219
2021-10-28T17:38:05Z
2021-10-29T17:20:49Z
2021-10-29T17:20:49Z
2021-10-29T17:20:49Z
REF: extract params used in Series.__repr__
diff --git a/pandas/core/series.py b/pandas/core/series.py index 65592be32b5ef..13bedac664ea3 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3,8 +3,6 @@ """ from __future__ import annotations -from io import StringIO -from shutil import get_terminal_size from textwrap import dedent from typing import ( IO, @@ -1460,29 +1458,8 @@ def __repr__(self) -> str: """ Return a string representation for a particular Series. """ - buf = StringIO("") - width, height = get_terminal_size() - max_rows = ( - height - if get_option("display.max_rows") == 0 - else get_option("display.max_rows") - ) - min_rows = ( - height - if get_option("display.max_rows") == 0 - else get_option("display.min_rows") - ) - show_dimensions = get_option("display.show_dimensions") - - self.to_string( - buf=buf, - name=self.name, - dtype=self.dtype, - min_rows=min_rows, - max_rows=max_rows, - length=show_dimensions, - ) - return buf.getvalue() + repr_params = fmt.get_series_repr_params(self) + return self.to_string(**repr_params) def to_string( self, diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 07811be909330..4bab85a3c6739 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -489,6 +489,8 @@ def get_dataframe_repr_params() -> dict[str, Any]: Supplying these parameters to DataFrame.to_string is equivalent to calling ``repr(DataFrame)``. This is useful if you want to adjust the repr output. + .. versionadded:: 1.4.0 + Example ------- >>> import pandas as pd @@ -514,6 +516,44 @@ def get_dataframe_repr_params() -> dict[str, Any]: } +def get_series_repr_params(series: Series) -> dict[str, Any]: + """Get the parameters used to repr(Series) calls using Series.to_string. + + Supplying these parameters to Series.to_string is equivalent to calling + ``repr(series)``. This is useful if you want to adjust the series repr output. + + .. versionadded:: 1.4.0 + + Example + ------- + >>> import pandas as pd + >>> + >>> ser = pd.Series([1, 2, 3, 4]) + >>> repr_params = pd.io.formats.format.get_series_repr_params(ser) + >>> repr(ser) == ser.to_string(**repr_params) + True + """ + width, height = get_terminal_size() + max_rows = ( + height + if get_option("display.max_rows") == 0 + else get_option("display.max_rows") + ) + min_rows = ( + height + if get_option("display.max_rows") == 0 + else get_option("display.min_rows") + ) + + return { + "name": series.name, + "dtype": series.dtype, + "min_rows": min_rows, + "max_rows": max_rows, + "length": get_option("display.show_dimensions"), + } + + class DataFrameFormatter: """Class for processing dataframe formatting options and data."""
This PR gives flexibility if we want the series string output to be like the Series repr, but with some adjustments. So with this PR we we can now do: ```python >>> params = pd.io.formats.format.get_series_repr_params(ser) >>> params[my_param] = new_value >>> ser.to_string(**params) ``` Followup to #43987.
https://api.github.com/repos/pandas-dev/pandas/pulls/44218
2021-10-28T10:46:53Z
2021-10-28T13:17:57Z
2021-10-28T13:17:57Z
2021-10-28T16:32:58Z
TST: parametrize/share indexing tests
diff --git a/pandas/tests/frame/indexing/test_mask.py b/pandas/tests/frame/indexing/test_mask.py index 70ec02a2334af..dd75e232051fa 100644 --- a/pandas/tests/frame/indexing/test_mask.py +++ b/pandas/tests/frame/indexing/test_mask.py @@ -29,6 +29,7 @@ def test_mask(self): tm.assert_frame_equal(rs, df.mask(df <= 0, other)) tm.assert_frame_equal(rs, df.mask(~cond, other)) + def test_mask2(self): # see GH#21891 df = DataFrame([1, 2]) res = df.mask([[True], [False]]) @@ -91,18 +92,23 @@ def test_mask_dtype_bool_conversion(self): result = bools.mask(mask) tm.assert_frame_equal(result, expected) - def test_mask_pos_args_deprecation(self): + def test_mask_pos_args_deprecation(self, frame_or_series): # https://github.com/pandas-dev/pandas/issues/41485 - df = DataFrame({"a": range(5)}) + obj = DataFrame({"a": range(5)}) expected = DataFrame({"a": [-1, 1, -1, 3, -1]}) - cond = df % 2 == 0 + if frame_or_series is Series: + obj = obj["a"] + expected = expected["a"] + + cond = obj % 2 == 0 msg = ( - r"In a future version of pandas all arguments of DataFrame.mask except for " + r"In a future version of pandas all arguments of " + f"{frame_or_series.__name__}.mask except for " r"the arguments 'cond' and 'other' will be keyword-only" ) with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.mask(cond, -1, False) - tm.assert_frame_equal(result, expected) + result = obj.mask(cond, -1, False) + tm.assert_equal(result, expected) def test_mask_try_cast_deprecated(frame_or_series): @@ -118,25 +124,30 @@ def test_mask_try_cast_deprecated(frame_or_series): obj.mask(mask, -1, try_cast=True) -def test_mask_stringdtype(): +def test_mask_stringdtype(frame_or_series): # GH 40824 - df = DataFrame( + obj = DataFrame( {"A": ["foo", "bar", "baz", NA]}, index=["id1", "id2", "id3", "id4"], dtype=StringDtype(), ) - filtered_df = DataFrame( + filtered_obj = DataFrame( {"A": ["this", "that"]}, index=["id2", "id3"], dtype=StringDtype() ) - filter_ser = Series([False, True, True, False]) - result = df.mask(filter_ser, filtered_df) - expected = DataFrame( {"A": [NA, "this", "that", NA]}, index=["id1", "id2", "id3", "id4"], dtype=StringDtype(), ) - tm.assert_frame_equal(result, expected) + if frame_or_series is Series: + obj = obj["A"] + filtered_obj = filtered_obj["A"] + expected = expected["A"] + + filter_ser = Series([False, True, True, False]) + result = obj.mask(filter_ser, filtered_obj) + + tm.assert_equal(result, expected) def test_mask_where_dtype_timedelta(): diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index eaafd2f017e79..b675e9d703f44 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -598,12 +598,12 @@ def test_where_callable(self): tm.assert_frame_equal(result, exp) tm.assert_frame_equal(result, (df + 2).where((df + 2) > 8, (df + 2) + 10)) - def test_where_tz_values(self, tz_naive_fixture): - df1 = DataFrame( + def test_where_tz_values(self, tz_naive_fixture, frame_or_series): + obj1 = DataFrame( DatetimeIndex(["20150101", "20150102", "20150103"], tz=tz_naive_fixture), columns=["date"], ) - df2 = DataFrame( + obj2 = DataFrame( DatetimeIndex(["20150103", "20150104", "20150105"], tz=tz_naive_fixture), columns=["date"], ) @@ -612,8 +612,14 @@ def test_where_tz_values(self, tz_naive_fixture): DatetimeIndex(["20150101", "20150102", "20150105"], tz=tz_naive_fixture), columns=["date"], ) - result = df1.where(mask, df2) - tm.assert_frame_equal(exp, result) + if frame_or_series is Series: + obj1 = obj1["date"] + obj2 = obj2["date"] + mask = mask["date"] + exp = exp["date"] + + result = obj1.where(mask, obj2) + tm.assert_equal(exp, result) def test_df_where_change_dtype(self): # GH#16979 @@ -759,18 +765,18 @@ def test_where_none_nan_coerce(): tm.assert_frame_equal(result, expected) -def test_where_non_keyword_deprecation(): +def test_where_non_keyword_deprecation(frame_or_series): # GH 41485 - s = DataFrame(range(5)) + obj = frame_or_series(range(5)) msg = ( "In a future version of pandas all arguments of " - "DataFrame.where except for the arguments 'cond' " + f"{frame_or_series.__name__}.where except for the arguments 'cond' " "and 'other' will be keyword-only" ) with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.where(s > 1, 10, False) - expected = DataFrame([10, 10, 2, 3, 4]) - tm.assert_frame_equal(expected, result) + result = obj.where(obj > 1, 10, False) + expected = frame_or_series([10, 10, 2, 3, 4]) + tm.assert_equal(expected, result) def test_where_columns_casting(): diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index 62537d37a8c11..59de1ab0c1ce9 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -5,12 +5,25 @@ from pandas import ( DataFrame, + DatetimeIndex, date_range, ) import pandas._testing as tm class TestTranspose: + def test_transpose_empty_preserves_datetimeindex(self): + # GH#41382 + df = DataFrame(index=DatetimeIndex([])) + + expected = DatetimeIndex([], dtype="datetime64[ns]", freq=None) + + result1 = df.T.sum().index + result2 = df.sum(axis=1).index + + tm.assert_index_equal(result1, expected) + tm.assert_index_equal(result2, expected) + def test_transpose_tzaware_1col_single_tz(self): # GH#26825 dti = date_range("2016-04-05 04:30", periods=3, tz="UTC") diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index 2aea2cc9b37cd..e46eed05caa86 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -10,21 +10,6 @@ class TestDatetimeIndex: - def test_datetimeindex_transpose_empty_df(self): - """ - Regression test for: - https://github.com/pandas-dev/pandas/issues/41382 - """ - df = DataFrame(index=pd.DatetimeIndex([])) - - expected = pd.DatetimeIndex([], dtype="datetime64[ns]", freq=None) - - result1 = df.T.sum().index - result2 = df.sum(axis=1).index - - tm.assert_index_equal(result1, expected) - tm.assert_index_equal(result2, expected) - def test_indexing_with_datetime_tz(self): # GH#8260 diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 53ed840f9cc72..77c04ae34ea5f 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -480,7 +480,6 @@ def test_floating_index_doc_example(self): s = Series(range(5), index=index) assert s[3] == 2 assert s.loc[3] == 2 - assert s.loc[3] == 2 assert s.iloc[3] == 3 def test_floating_misc(self, indexer_sl): diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index b8c53c7b59239..6484ac1f8a8e2 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -270,17 +270,15 @@ def test_iloc_non_integer_raises(self, index, columns, index_vals, column_vals): with pytest.raises(IndexError, match=msg): df.iloc[index_vals, column_vals] - @pytest.mark.parametrize("dims", [1, 2]) - def test_iloc_getitem_invalid_scalar(self, dims): + def test_iloc_getitem_invalid_scalar(self, frame_or_series): # GH 21982 - if dims == 1: - s = Series(np.arange(10)) - else: - s = DataFrame(np.arange(100).reshape(10, 10)) + obj = DataFrame(np.arange(100).reshape(10, 10)) + if frame_or_series is Series: + obj = obj[0] with pytest.raises(TypeError, match="Cannot index by location index"): - s.iloc["a"] + obj.iloc["a"] def test_iloc_array_not_mutating_negative_indices(self): diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 01407f1f9bae7..4604fad019eca 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -710,10 +710,10 @@ def assert_slices_equivalent(l_slc, i_slc): assert_slices_equivalent(SLC[idx[13] : idx[9] : -1], SLC[13:8:-1]) assert_slices_equivalent(SLC[idx[9] : idx[13] : -1], SLC[:0]) - def test_slice_with_zero_step_raises(self, indexer_sl): - ser = Series(np.arange(20), index=_mklbl("A", 20)) + def test_slice_with_zero_step_raises(self, indexer_sl, frame_or_series): + obj = frame_or_series(np.arange(20), index=_mklbl("A", 20)) with pytest.raises(ValueError, match="slice step cannot be zero"): - indexer_sl(ser)[::0] + indexer_sl(obj)[::0] def test_loc_setitem_indexing_assignment_dict_already_exists(self): index = Index([-5, 0, 5], name="z") diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index c7c575b479988..b82ecac37634e 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -368,6 +368,7 @@ def test_loc_to_fail(self): with pytest.raises(KeyError, match=msg): df.loc[[1, 2], [1, 2]] + def test_loc_to_fail2(self): # GH 7496 # loc should not fallback @@ -406,6 +407,7 @@ def test_loc_to_fail(self): with pytest.raises(KeyError, match=msg): s.loc[[-2]] = 0 + def test_loc_to_fail3(self): # inconsistency between .loc[values] and .loc[values,:] # GH 7999 df = DataFrame([["a"], ["b"]], index=[1, 2], columns=["value"]) diff --git a/pandas/tests/series/indexing/test_mask.py b/pandas/tests/series/indexing/test_mask.py index 30a9d925ed7e5..dc4fb530dbb52 100644 --- a/pandas/tests/series/indexing/test_mask.py +++ b/pandas/tests/series/indexing/test_mask.py @@ -1,11 +1,7 @@ import numpy as np import pytest -from pandas import ( - NA, - Series, - StringDtype, -) +from pandas import Series import pandas._testing as tm @@ -67,36 +63,3 @@ def test_mask_inplace(): rs = s.copy() rs.mask(cond, -s, inplace=True) tm.assert_series_equal(rs, s.mask(cond, -s)) - - -def test_mask_stringdtype(): - # GH 40824 - ser = Series( - ["foo", "bar", "baz", NA], - index=["id1", "id2", "id3", "id4"], - dtype=StringDtype(), - ) - filtered_ser = Series(["this", "that"], index=["id2", "id3"], dtype=StringDtype()) - filter_ser = Series([False, True, True, False]) - result = ser.mask(filter_ser, filtered_ser) - - expected = Series( - [NA, "this", "that", NA], - index=["id1", "id2", "id3", "id4"], - dtype=StringDtype(), - ) - tm.assert_series_equal(result, expected) - - -def test_mask_pos_args_deprecation(): - # https://github.com/pandas-dev/pandas/issues/41485 - s = Series(range(5)) - expected = Series([-1, 1, -1, 3, -1]) - cond = s % 2 == 0 - msg = ( - r"In a future version of pandas all arguments of Series.mask except for " - r"the arguments 'cond' and 'other' will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.mask(cond, -1, False) - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index ed1ba11c5fd55..178928b91b621 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -144,20 +144,6 @@ def test_where(): tm.assert_series_equal(rs, expected) -def test_where_non_keyword_deprecation(): - # GH 41485 - s = Series(range(5)) - msg = ( - "In a future version of pandas all arguments of " - "Series.where except for the arguments 'cond' " - "and 'other' will be keyword-only" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.where(s > 1, 10, False) - expected = Series([10, 10, 2, 3, 4]) - tm.assert_series_equal(expected, result) - - def test_where_error(): s = Series(np.random.randn(5)) cond = s > 0 @@ -397,72 +383,38 @@ def test_where_numeric_with_string(): assert w.dtype == "object" -def test_where_timedelta_coerce(): - s = Series([1, 2], dtype="timedelta64[ns]") +@pytest.mark.parametrize("dtype", ["timedelta64[ns]", "datetime64[ns]"]) +def test_where_datetimelike_coerce(dtype): + ser = Series([1, 2], dtype=dtype) expected = Series([10, 10]) mask = np.array([False, False]) - rs = s.where(mask, [10, 10]) + rs = ser.where(mask, [10, 10]) tm.assert_series_equal(rs, expected) - rs = s.where(mask, 10) + rs = ser.where(mask, 10) tm.assert_series_equal(rs, expected) - rs = s.where(mask, 10.0) + rs = ser.where(mask, 10.0) tm.assert_series_equal(rs, expected) - rs = s.where(mask, [10.0, 10.0]) + rs = ser.where(mask, [10.0, 10.0]) tm.assert_series_equal(rs, expected) - rs = s.where(mask, [10.0, np.nan]) + rs = ser.where(mask, [10.0, np.nan]) expected = Series([10, None], dtype="object") tm.assert_series_equal(rs, expected) -def test_where_datetime_conversion(): - s = Series(date_range("20130102", periods=2)) - expected = Series([10, 10]) - mask = np.array([False, False]) - - rs = s.where(mask, [10, 10]) - tm.assert_series_equal(rs, expected) - - rs = s.where(mask, 10) - tm.assert_series_equal(rs, expected) - - rs = s.where(mask, 10.0) - tm.assert_series_equal(rs, expected) - - rs = s.where(mask, [10.0, 10.0]) - tm.assert_series_equal(rs, expected) - - rs = s.where(mask, [10.0, np.nan]) - expected = Series([10, None], dtype="object") - tm.assert_series_equal(rs, expected) - +def test_where_datetimetz(): # GH 15701 timestamps = ["2016-12-31 12:00:04+00:00", "2016-12-31 12:00:04.010000+00:00"] - s = Series([Timestamp(t) for t in timestamps]) - rs = s.where(Series([False, True])) - expected = Series([pd.NaT, s[1]]) + ser = Series([Timestamp(t) for t in timestamps], dtype="datetime64[ns, UTC]") + rs = ser.where(Series([False, True])) + expected = Series([pd.NaT, ser[1]], dtype="datetime64[ns, UTC]") tm.assert_series_equal(rs, expected) -def test_where_dt_tz_values(tz_naive_fixture): - ser1 = Series( - pd.DatetimeIndex(["20150101", "20150102", "20150103"], tz=tz_naive_fixture) - ) - ser2 = Series( - pd.DatetimeIndex(["20160514", "20160515", "20160516"], tz=tz_naive_fixture) - ) - mask = Series([True, True, False]) - result = ser1.where(mask, ser2) - exp = Series( - pd.DatetimeIndex(["20150101", "20150102", "20160516"], tz=tz_naive_fixture) - ) - tm.assert_series_equal(exp, result) - - def test_where_sparse(): # GH#17198 make sure we dont get an AttributeError for sp_index ser = Series(pd.arrays.SparseArray([1, 2])) @@ -478,14 +430,13 @@ def test_where_empty_series_and_empty_cond_having_non_bool_dtypes(): tm.assert_series_equal(result, ser) -@pytest.mark.parametrize("klass", [Series, pd.DataFrame]) -def test_where_categorical(klass): +def test_where_categorical(frame_or_series): # https://github.com/pandas-dev/pandas/issues/18888 - exp = klass( + exp = frame_or_series( pd.Categorical(["A", "A", "B", "B", np.nan], categories=["A", "B", "C"]), dtype="category", ) - df = klass(["A", "A", "B", "B", "C"], dtype="category") + df = frame_or_series(["A", "A", "B", "B", "C"], dtype="category") res = df.where(df != "C") tm.assert_equal(exp, res)
- [ ] 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/44215
2021-10-28T04:54:14Z
2021-10-28T12:32:18Z
2021-10-28T12:32:18Z
2021-10-28T15:13:23Z
TST: parametrize cumulative tests
diff --git a/pandas/tests/frame/test_cumulative.py b/pandas/tests/frame/test_cumulative.py index 39714a4566494..5bd9c42612315 100644 --- a/pandas/tests/frame/test_cumulative.py +++ b/pandas/tests/frame/test_cumulative.py @@ -7,6 +7,7 @@ """ import numpy as np +import pytest from pandas import ( DataFrame, @@ -19,53 +20,22 @@ class TestDataFrameCumulativeOps: # --------------------------------------------------------------------- # Cumulative Operations - cumsum, cummax, ... - def test_cumsum_corner(self): - dm = DataFrame(np.arange(20).reshape(4, 5), index=range(4), columns=range(5)) - # TODO(wesm): do something with this? - result = dm.cumsum() # noqa - - def test_cumsum(self, datetime_frame): - datetime_frame.iloc[5:10, 0] = np.nan - datetime_frame.iloc[10:15, 1] = np.nan - datetime_frame.iloc[15:, 2] = np.nan - - # axis = 0 - cumsum = datetime_frame.cumsum() - expected = datetime_frame.apply(Series.cumsum) - tm.assert_frame_equal(cumsum, expected) - - # axis = 1 - cumsum = datetime_frame.cumsum(axis=1) - expected = datetime_frame.apply(Series.cumsum, axis=1) - tm.assert_frame_equal(cumsum, expected) - - # works + def test_cumulative_ops_smoke(self): + # it works df = DataFrame({"A": np.arange(20)}, index=np.arange(20)) + df.cummax() + df.cummin() df.cumsum() - # fix issue - cumsum_xs = datetime_frame.cumsum(axis=1) - assert np.shape(cumsum_xs) == np.shape(datetime_frame) + dm = DataFrame(np.arange(20).reshape(4, 5), index=range(4), columns=range(5)) + # TODO(wesm): do something with this? + dm.cumsum() - def test_cumprod(self, datetime_frame): + def test_cumprod_smoke(self, datetime_frame): datetime_frame.iloc[5:10, 0] = np.nan datetime_frame.iloc[10:15, 1] = np.nan datetime_frame.iloc[15:, 2] = np.nan - # axis = 0 - cumprod = datetime_frame.cumprod() - expected = datetime_frame.apply(Series.cumprod) - tm.assert_frame_equal(cumprod, expected) - - # axis = 1 - cumprod = datetime_frame.cumprod(axis=1) - expected = datetime_frame.apply(Series.cumprod, axis=1) - tm.assert_frame_equal(cumprod, expected) - - # fix issue - cumprod_xs = datetime_frame.cumprod(axis=1) - assert np.shape(cumprod_xs) == np.shape(datetime_frame) - # ints df = datetime_frame.fillna(0).astype(int) df.cumprod(0) @@ -76,53 +46,26 @@ def test_cumprod(self, datetime_frame): df.cumprod(0) df.cumprod(1) - def test_cummin(self, datetime_frame): - datetime_frame.iloc[5:10, 0] = np.nan - datetime_frame.iloc[10:15, 1] = np.nan - datetime_frame.iloc[15:, 2] = np.nan - - # axis = 0 - cummin = datetime_frame.cummin() - expected = datetime_frame.apply(Series.cummin) - tm.assert_frame_equal(cummin, expected) - - # axis = 1 - cummin = datetime_frame.cummin(axis=1) - expected = datetime_frame.apply(Series.cummin, axis=1) - tm.assert_frame_equal(cummin, expected) - - # it works - df = DataFrame({"A": np.arange(20)}, index=np.arange(20)) - df.cummin() - - # fix issue - cummin_xs = datetime_frame.cummin(axis=1) - assert np.shape(cummin_xs) == np.shape(datetime_frame) - - def test_cummax(self, datetime_frame): + @pytest.mark.parametrize("method", ["cumsum", "cumprod", "cummin", "cummax"]) + def test_cumulative_ops_match_series_apply(self, datetime_frame, method): datetime_frame.iloc[5:10, 0] = np.nan datetime_frame.iloc[10:15, 1] = np.nan datetime_frame.iloc[15:, 2] = np.nan # axis = 0 - cummax = datetime_frame.cummax() - expected = datetime_frame.apply(Series.cummax) - tm.assert_frame_equal(cummax, expected) + result = getattr(datetime_frame, method)() + expected = datetime_frame.apply(getattr(Series, method)) + tm.assert_frame_equal(result, expected) # axis = 1 - cummax = datetime_frame.cummax(axis=1) - expected = datetime_frame.apply(Series.cummax, axis=1) - tm.assert_frame_equal(cummax, expected) - - # it works - df = DataFrame({"A": np.arange(20)}, index=np.arange(20)) - df.cummax() + result = getattr(datetime_frame, method)(axis=1) + expected = datetime_frame.apply(getattr(Series, method), axis=1) + tm.assert_frame_equal(result, expected) - # fix issue - cummax_xs = datetime_frame.cummax(axis=1) - assert np.shape(cummax_xs) == np.shape(datetime_frame) + # fix issue TODO: GH ref? + assert np.shape(result) == np.shape(datetime_frame) - def test_cumulative_ops_preserve_dtypes(self): + def test_cumsum_preserve_dtypes(self): # GH#19296 dont incorrectly upcast to object df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3.0], "C": [True, False, False]}) diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py index e070b86717503..74ab9376ed00f 100644 --- a/pandas/tests/series/test_cumulative.py +++ b/pandas/tests/series/test_cumulative.py @@ -5,7 +5,6 @@ -------- tests.frame.test_cumulative """ -from itertools import product import numpy as np import pytest @@ -13,6 +12,13 @@ import pandas as pd import pandas._testing as tm +methods = { + "cumsum": np.cumsum, + "cumprod": np.cumprod, + "cummin": np.minimum.accumulate, + "cummax": np.maximum.accumulate, +} + def _check_accum_op(name, series, check_dtype=True): func = getattr(np, name) @@ -37,130 +43,82 @@ def test_cumsum(self, datetime_series): def test_cumprod(self, datetime_series): _check_accum_op("cumprod", datetime_series) - def test_cummin(self, datetime_series): - tm.assert_numpy_array_equal( - datetime_series.cummin().values, - np.minimum.accumulate(np.array(datetime_series)), - ) - ts = datetime_series.copy() - ts[::2] = np.NaN - result = ts.cummin()[1::2] - expected = np.minimum.accumulate(ts.dropna()) + @pytest.mark.parametrize("method", ["cummin", "cummax"]) + def test_cummin_cummax(self, datetime_series, method): + ufunc = methods[method] - result.index = result.index._with_freq(None) - tm.assert_series_equal(result, expected) + result = getattr(datetime_series, method)().values + expected = ufunc(np.array(datetime_series)) - def test_cummax(self, datetime_series): - tm.assert_numpy_array_equal( - datetime_series.cummax().values, - np.maximum.accumulate(np.array(datetime_series)), - ) + tm.assert_numpy_array_equal(result, expected) ts = datetime_series.copy() ts[::2] = np.NaN - result = ts.cummax()[1::2] - expected = np.maximum.accumulate(ts.dropna()) + result = getattr(ts, method)()[1::2] + expected = ufunc(ts.dropna()) result.index = result.index._with_freq(None) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("tz", [None, "US/Pacific"]) - def test_cummin_datetime64(self, tz): - s = pd.Series( - pd.to_datetime( - ["NaT", "2000-1-2", "NaT", "2000-1-1", "NaT", "2000-1-3"] - ).tz_localize(tz) - ) - - expected = pd.Series( - pd.to_datetime( - ["NaT", "2000-1-2", "NaT", "2000-1-1", "NaT", "2000-1-1"] - ).tz_localize(tz) - ) - result = s.cummin(skipna=True) + @pytest.mark.parametrize( + "ts", + [ + pd.Timedelta(0), + pd.Timestamp("1999-12-31"), + pd.Timestamp("1999-12-31").tz_localize("US/Pacific"), + ], + ) + def test_cummin_cummax_datetimelike(self, ts): + # 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) - expected = pd.Series( - pd.to_datetime( - ["NaT", "2000-1-2", "2000-1-2", "2000-1-1", "2000-1-1", "2000-1-1"] - ).tz_localize(tz) - ) - result = s.cummin(skipna=False) + 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) - @pytest.mark.parametrize("tz", [None, "US/Pacific"]) - def test_cummax_datetime64(self, tz): - s = pd.Series( - pd.to_datetime( - ["NaT", "2000-1-2", "NaT", "2000-1-1", "NaT", "2000-1-3"] - ).tz_localize(tz) + exp_tdi = pd.to_timedelta( + ["NaT", "2 days", "2 days", "2 days", "2 days", "3 days"] ) - - expected = pd.Series( - pd.to_datetime( - ["NaT", "2000-1-2", "NaT", "2000-1-2", "NaT", "2000-1-3"] - ).tz_localize(tz) - ) - result = s.cummax(skipna=True) + expected = pd.Series(exp_tdi + ts) + result = ser.cummax(skipna=False) tm.assert_series_equal(expected, result) - expected = pd.Series( - pd.to_datetime( - ["NaT", "2000-1-2", "2000-1-2", "2000-1-2", "2000-1-2", "2000-1-3"] - ).tz_localize(tz) + exp_tdi = pd.to_timedelta( + ["NaT", "2 days", "2 days", "1 days", "1 days", "1 days"] ) - result = s.cummax(skipna=False) + expected = pd.Series(exp_tdi + ts) + result = ser.cummin(skipna=False) tm.assert_series_equal(expected, result) - def test_cummin_timedelta64(self): - s = pd.Series(pd.to_timedelta(["NaT", "2 min", "NaT", "1 min", "NaT", "3 min"])) + def test_cummethods_bool(self): + # GH#6270 + # checking Series method vs the ufunc applied to the values - expected = pd.Series( - pd.to_timedelta(["NaT", "2 min", "NaT", "1 min", "NaT", "1 min"]) - ) - result = s.cummin(skipna=True) - tm.assert_series_equal(expected, result) + a = pd.Series([False, False, False, True, True, False, False]) + c = pd.Series([False] * len(a)) - expected = pd.Series( - pd.to_timedelta(["NaT", "2 min", "2 min", "1 min", "1 min", "1 min"]) - ) - result = s.cummin(skipna=False) - tm.assert_series_equal(expected, result) + for method in methods: + for ser in [a, ~a, c, ~c]: + ufunc = methods[method] - def test_cummax_timedelta64(self): - s = pd.Series(pd.to_timedelta(["NaT", "2 min", "NaT", "1 min", "NaT", "3 min"])) + exp_vals = ufunc(ser.values) + expected = pd.Series(exp_vals) - expected = pd.Series( - pd.to_timedelta(["NaT", "2 min", "NaT", "2 min", "NaT", "3 min"]) - ) - result = s.cummax(skipna=True) - tm.assert_series_equal(expected, result) + result = getattr(ser, method)() - expected = pd.Series( - pd.to_timedelta(["NaT", "2 min", "2 min", "2 min", "2 min", "3 min"]) - ) - result = s.cummax(skipna=False) - tm.assert_series_equal(expected, result) + tm.assert_series_equal(result, expected) - def test_cummethods_bool(self): - # GH#6270 + def test_cummethods_bool_in_object_dtype(self): - a = pd.Series([False, False, False, True, True, False, False]) - b = ~a - c = pd.Series([False] * len(b)) - d = ~c - methods = { - "cumsum": np.cumsum, - "cumprod": np.cumprod, - "cummin": np.minimum.accumulate, - "cummax": np.maximum.accumulate, - } - args = product((a, b, c, d), methods) - for s, method in args: - expected = pd.Series(methods[method](s.values)) - result = getattr(s, method)() - tm.assert_series_equal(result, expected) - - e = pd.Series([False, True, np.nan, False]) + 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]) @@ -168,5 +126,5 @@ def test_cummethods_bool(self): expecteds = {"cumsum": cse, "cumprod": cpe, "cummin": cmin, "cummax": cmax} for method in methods: - res = getattr(e, method)() + res = getattr(ser, method)() tm.assert_series_equal(res, expecteds[method])
- [ ] 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/44214
2021-10-28T03:46:48Z
2021-10-29T13:13:48Z
2021-10-29T13:13:47Z
2021-10-29T15:18:39Z
BUG: Index/Series.to_frame not respecting explicit name=None
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 495669d316e95..24ba8a1272eec 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -642,6 +642,7 @@ Other - Bug in :meth:`CustomBusinessMonthBegin.__add__` (:meth:`CustomBusinessMonthEnd.__add__`) not applying the extra ``offset`` parameter when beginning (end) of the target month is already a business day (:issue:`41356`) - 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`) .. ***DO NOT USE THIS SECTION*** diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e82bd61938f15..d44a25c2677d1 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1510,7 +1510,9 @@ def to_series(self, index=None, name: Hashable = None) -> Series: return Series(self._values.copy(), index=index, name=name) - def to_frame(self, index: bool = True, name: Hashable = None) -> DataFrame: + def to_frame( + self, index: bool = True, name: Hashable = lib.no_default + ) -> DataFrame: """ Create a DataFrame with a column containing the Index. @@ -1561,7 +1563,7 @@ def to_frame(self, index: bool = True, name: Hashable = None) -> DataFrame: """ from pandas import DataFrame - if name is None: + if name is lib.no_default: name = self.name or 0 result = DataFrame({name: self._values.copy()}) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index e2f1a2d6a1e23..156488ca08102 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1684,7 +1684,7 @@ def unique(self, level=None): level = self._get_level_number(level) return self._get_level_values(level=level, unique=True) - def to_frame(self, index: bool = True, name=None) -> DataFrame: + def to_frame(self, index: bool = True, name=lib.no_default) -> DataFrame: """ Create a DataFrame with the levels of the MultiIndex as columns. @@ -1736,7 +1736,7 @@ def to_frame(self, index: bool = True, name=None) -> DataFrame: """ from pandas import DataFrame - if name is not None: + if name is not lib.no_default: if not is_list_like(name): raise TypeError("'name' must be a list / sequence of column names.") diff --git a/pandas/core/series.py b/pandas/core/series.py index 15715af05f904..2c6d4ed445394 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1317,7 +1317,7 @@ def repeat(self, repeats, axis=None) -> Series: ) @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "level"]) - def reset_index(self, level=None, drop=False, name=None, inplace=False): + def reset_index(self, level=None, drop=False, name=lib.no_default, inplace=False): """ Generate a new DataFrame or Series with the index reset. @@ -1427,6 +1427,9 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False): """ inplace = validate_bool_kwarg(inplace, "inplace") if drop: + if name is lib.no_default: + name = self.name + new_index = default_index(len(self)) if level is not None: if not isinstance(level, (tuple, list)): @@ -1448,6 +1451,14 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False): "Cannot reset_index inplace on a Series to create a DataFrame" ) else: + if name is lib.no_default: + # For backwards compatibility, keep columns as [0] instead of + # [None] when self.name is None + if self.name is None: + name = 0 + else: + name = self.name + df = self.to_frame(name) return df.reset_index(level=level, drop=drop) @@ -1697,7 +1708,7 @@ def to_dict(self, into=dict): into_c = com.standardize_mapping(into) return into_c((k, maybe_box_native(v)) for k, v in self.items()) - def to_frame(self, name=None) -> DataFrame: + def to_frame(self, name: Hashable = lib.no_default) -> DataFrame: """ Convert Series to DataFrame. @@ -1723,7 +1734,7 @@ def to_frame(self, name=None) -> DataFrame: 2 c """ columns: Index - if name is None: + if name is lib.no_default: name = self.name if name is None: # default to [0], same as we would get with DataFrame(self) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 061e36e457443..ba47391513ed2 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -460,7 +460,11 @@ def _compute_plot_data(self): label = self.label if label is None and data.name is None: label = "None" - data = data.to_frame(name=label) + if label is None: + # We'll end up with columns of [0] instead of [None] + data = data.to_frame() + else: + data = data.to_frame(name=label) elif self._kind in ("hist", "box"): cols = self.columns if self.by is None else self.columns + self.by data = data.loc[:, cols] diff --git a/pandas/tests/indexes/datetimes/methods/test_to_frame.py b/pandas/tests/indexes/datetimes/methods/test_to_frame.py index ec6254f52f4d5..80e8284abe031 100644 --- a/pandas/tests/indexes/datetimes/methods/test_to_frame.py +++ b/pandas/tests/indexes/datetimes/methods/test_to_frame.py @@ -1,5 +1,6 @@ from pandas import ( DataFrame, + Index, date_range, ) import pandas._testing as tm @@ -12,3 +13,14 @@ def test_to_frame_datetime_tz(self): result = idx.to_frame() expected = DataFrame(idx, index=idx) tm.assert_frame_equal(result, expected) + + def test_to_frame_respects_none_name(self): + # GH#44212 if we explicitly pass name=None, then that should be respected, + # not changed to 0 + idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC") + result = idx.to_frame(name=None) + exp_idx = Index([None], dtype=object) + tm.assert_index_equal(exp_idx, result.columns) + + result = idx.rename("foo").to_frame(name=None) + tm.assert_index_equal(exp_idx, result.columns) diff --git a/pandas/tests/series/methods/test_to_frame.py b/pandas/tests/series/methods/test_to_frame.py index 66e44f1a0caf0..55d49b8fbee70 100644 --- a/pandas/tests/series/methods/test_to_frame.py +++ b/pandas/tests/series/methods/test_to_frame.py @@ -1,11 +1,24 @@ from pandas import ( DataFrame, + Index, Series, ) import pandas._testing as tm class TestToFrame: + def test_to_frame_respects_name_none(self): + # GH#44212 if we explicitly pass name=None, then that should be respected, + # not changed to 0 + ser = Series(range(3)) + result = ser.to_frame(None) + + exp_index = Index([None], dtype=object) + tm.assert_index_equal(result.columns, exp_index) + + result = ser.rename("foo").to_frame(None) + tm.assert_index_equal(result.columns, exp_index) + def test_to_frame(self, datetime_series): datetime_series.name = None rs = datetime_series.to_frame()
- [ ] 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/44212
2021-10-27T23:23:00Z
2021-10-30T15:02:18Z
2021-10-30T15:02:18Z
2021-10-30T15:09:53Z
CLN/TST: address TODOs
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index cf9820c3aa8f8..848e724949bc5 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -197,8 +197,8 @@ def shift(self, periods=1, fill_value=None, axis=0): return self._from_backing_data(new_values) def _validate_shift_value(self, fill_value): - # TODO: after deprecation in datetimelikearraymixin is enforced, - # we can remove this and ust validate_fill_value directly + # TODO(2.0): after deprecation in datetimelikearraymixin is enforced, + # we can remove this and use validate_fill_value directly return self._validate_scalar(fill_value) def __setitem__(self, key, value): diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 35e2dd25678e5..107cefdf31188 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -524,7 +524,6 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike: self = self.copy() if copy else self result = self._set_dtype(dtype) - # TODO: consolidate with ndarray case? elif isinstance(dtype, ExtensionDtype): return super().astype(dtype, copy=copy) diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 6684e559b6f88..915e13bc3bbb2 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -371,7 +371,7 @@ def _subtype_with_str(self): def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: # TODO for now only handle SparseDtypes and numpy dtypes => extend - # with other compatibtle extension dtypes + # with other compatible extension dtypes if any( isinstance(x, ExtensionDtype) and not isinstance(x, SparseDtype) for x in dtypes diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 51af2cd732d09..f8716ca1bafe0 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -253,7 +253,6 @@ def _filter_nodes(superclass, all_nodes=_all_nodes): assert not intersection, _msg -# TODO: Python 3.6.2: replace Callable[..., None] with Callable[..., NoReturn] def _node_not_implemented(node_name: str) -> Callable[..., None]: """ Return a function that raises a NotImplementedError with a passed node name. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5afb19f1d91fe..2488048e30ccb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5356,7 +5356,6 @@ def _replace_columnwise( """ Dispatch to Series.replace column-wise. - Parameters ---------- mapping : dict diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6895455a43160..8b2774fd0f1b3 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4974,7 +4974,7 @@ def _reindex_with_indexers( if indexer is not None: indexer = ensure_platform_int(indexer) - # TODO: speed up on homogeneous DataFrame objects + # TODO: speed up on homogeneous DataFrame objects (see _reindex_multi) new_data = new_data.reindex_indexer( index, indexer, @@ -6420,7 +6420,7 @@ def fillna( ) elif isinstance(value, ABCDataFrame) and self.ndim == 2: - new_data = self.where(self.notna(), value)._data + new_data = self.where(self.notna(), value)._mgr else: raise ValueError(f"invalid fill value with a {type(value)}") diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 8a2ba69a61ed9..77281441c2ed2 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1797,7 +1797,7 @@ def count(self) -> Series | DataFrame: is_series = data.ndim == 1 def hfunc(bvalues: ArrayLike) -> ArrayLike: - # TODO(2DEA): reshape would not be necessary with 2D EAs + # TODO(EA2D): reshape would not be necessary with 2D EAs if bvalues.ndim == 1: # EA masked = mask & ~isna(bvalues).reshape(1, -1) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 7e533233d5ecf..bc9f5c3243705 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -917,7 +917,7 @@ def setitem(self, indexer, value): value = np.nan # coerce if block dtype can store value - values = self.values + values = cast(np.ndarray, self.values) if not self._can_hold_element(value): # current dtype cannot store value, coerce to common dtype return self.coerce_to_target_dtype(value).setitem(indexer, value) @@ -946,11 +946,7 @@ def setitem(self, indexer, value): values[indexer] = value else: - # error: Argument 1 to "setitem_datetimelike_compat" has incompatible type - # "Union[ndarray, ExtensionArray]"; expected "ndarray" - value = setitem_datetimelike_compat( - values, len(values[indexer]), value # type: ignore[arg-type] - ) + value = setitem_datetimelike_compat(values, len(values[indexer]), value) values[indexer] = value if transpose: @@ -1729,8 +1725,7 @@ def is_view(self) -> bool: def setitem(self, indexer, value): if not self._can_hold_element(value): - # TODO: general case needs casting logic. - return self.astype(_dtype_obj).setitem(indexer, value) + return self.coerce_to_target_dtype(value).setitem(indexer, value) values = self.values if self.ndim > 1: @@ -1751,7 +1746,6 @@ def putmask(self, mask, new) -> list[Block]: return [self] def where(self, other, cond, errors="raise") -> list[Block]: - # TODO(EA2D): reshape unnecessary with 2D EAs arr = self.values cond = extract_bool_array(cond) diff --git a/pandas/core/series.py b/pandas/core/series.py index 9795e1f7141ee..65592be32b5ef 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4528,6 +4528,9 @@ def rename( 5 3 dtype: int64 """ + if axis is not None: + axis = self._get_axis_number(axis) + if callable(index) or is_dict_like(index): return super().rename( index, copy=copy, inplace=inplace, level=level, errors=errors diff --git a/pandas/tests/arithmetic/common.py b/pandas/tests/arithmetic/common.py index 649ad562307c0..6f4e35ad4dfb2 100644 --- a/pandas/tests/arithmetic/common.py +++ b/pandas/tests/arithmetic/common.py @@ -34,9 +34,18 @@ def assert_invalid_addsub_type(left, right, msg=None): right - left +def get_expected_box(box): + """ + Get the box to use for 'expected' in a comparison operation. + """ + if box in [Index, array]: + return np.ndarray + return box + + def get_upcast_box(box, vector): """ - Given two box-types, find the one that takes priority + Given two box-types, find the one that takes priority. """ if box is DataFrame or isinstance(vector, DataFrame): return DataFrame diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 0d3f7dcaaf65b..e511c1bdaca9c 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -43,6 +43,7 @@ from pandas.tests.arithmetic.common import ( assert_invalid_addsub_type, assert_invalid_comparison, + get_expected_box, get_upcast_box, ) @@ -59,9 +60,7 @@ def test_compare_zerodim(self, tz_naive_fixture, box_with_array): # Test comparison with zero-dimensional array is unboxed tz = tz_naive_fixture box = box_with_array - xbox = ( - box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray - ) + xbox = get_expected_box(box) dti = date_range("20130101", periods=3, tz=tz) other = np.array(dti.to_numpy()[0]) @@ -148,7 +147,7 @@ def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array): # GH#22242, GH#22163 DataFrame considered NaT == ts incorrectly tz = tz_naive_fixture box = box_with_array - xbox = box if box not in [pd.Index, pd.array] else np.ndarray + xbox = get_expected_box(box) ts = Timestamp.now(tz) ser = Series([ts, NaT]) @@ -245,7 +244,7 @@ def test_nat_comparisons_scalar(self, dtype, data, box_with_array): # on older numpys (since they check object identity) return - xbox = box if box not in [pd.Index, pd.array] else np.ndarray + xbox = get_expected_box(box) left = Series(data, dtype=dtype) left = tm.box_expected(left, box) @@ -324,9 +323,7 @@ def test_timestamp_compare_series(self, left, right): def test_dt64arr_timestamp_equality(self, box_with_array): # GH#11034 - xbox = ( - box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray - ) + xbox = get_expected_box(box_with_array) ser = Series([Timestamp("2000-01-29 01:59:00"), Timestamp("2000-01-30"), NaT]) ser = tm.box_expected(ser, box_with_array) @@ -424,9 +421,7 @@ def test_dti_cmp_nat(self, dtype, box_with_array): # on older numpys (since they check object identity) return - xbox = ( - box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray - ) + xbox = get_expected_box(box_with_array) left = DatetimeIndex([Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")]) right = DatetimeIndex([NaT, NaT, Timestamp("2011-01-03")]) @@ -662,7 +657,7 @@ def test_scalar_comparison_tzawareness( box = box_with_array tz = tz_aware_fixture dti = date_range("2016-01-01", periods=2, tz=tz) - xbox = box if box not in [pd.Index, pd.array] else np.ndarray + xbox = get_expected_box(box) dtarr = tm.box_expected(dti, box_with_array) if op in [operator.eq, operator.ne]: @@ -2283,7 +2278,7 @@ def test_sub_dti_dti(self): # cleanup, box-parametrization, and de-duplication @pytest.mark.parametrize("op", [operator.add, operator.sub]) - def test_timedelta64_equal_timedelta_supported_ops(self, op): + def test_timedelta64_equal_timedelta_supported_ops(self, op, box_with_array): ser = Series( [ Timestamp("20130301"), @@ -2292,6 +2287,7 @@ def test_timedelta64_equal_timedelta_supported_ops(self, op): Timestamp("20130228 21:00:00"), ] ) + obj = box_with_array(ser) intervals = ["D", "h", "m", "s", "us"] @@ -2302,10 +2298,10 @@ def timedelta64(*args): for d, h, m, s, us in product(*([range(2)] * 5)): nptd = timedelta64(d, h, m, s, us) pytd = timedelta(days=d, hours=h, minutes=m, seconds=s, microseconds=us) - lhs = op(ser, nptd) - rhs = op(ser, pytd) + lhs = op(obj, nptd) + rhs = op(obj, pytd) - tm.assert_series_equal(lhs, rhs) + tm.assert_equal(lhs, rhs) def test_ops_nat_mixed_datetime64_timedelta64(self): # GH#11349 diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 7d215c940c031..0c42be517b798 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -25,7 +25,10 @@ import pandas._testing as tm from pandas.core import ops from pandas.core.arrays import TimedeltaArray -from pandas.tests.arithmetic.common import assert_invalid_comparison +from pandas.tests.arithmetic.common import ( + assert_invalid_comparison, + get_expected_box, +) # ------------------------------------------------------------------ # Comparisons @@ -38,9 +41,7 @@ class TestPeriodArrayLikeComparisons: def test_compare_zerodim(self, box_with_array): # GH#26689 make sure we unbox zero-dimensional arrays - xbox = ( - box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray - ) + xbox = get_expected_box(box_with_array) pi = period_range("2000", periods=4) other = np.array(pi.to_numpy()[0]) @@ -77,11 +78,10 @@ def test_compare_invalid_listlike(self, box_with_array, other): @pytest.mark.parametrize("other_box", [list, np.array, lambda x: x.astype(object)]) def test_compare_object_dtype(self, box_with_array, other_box): + xbox = get_expected_box(box_with_array) pi = period_range("2000", periods=5) parr = tm.box_expected(pi, box_with_array) - xbox = np.ndarray if box_with_array in [pd.Index, pd.array] else box_with_array - other = other_box(pi) expected = np.array([True, True, True, True, True]) @@ -187,9 +187,7 @@ def test_pi_cmp_period(self): # TODO: moved from test_datetime64; de-duplicate with version below def test_parr_cmp_period_scalar2(self, box_with_array): - xbox = ( - box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray - ) + xbox = get_expected_box(box_with_array) pi = period_range("2000-01-01", periods=10, freq="D") @@ -210,7 +208,7 @@ def test_parr_cmp_period_scalar2(self, box_with_array): @pytest.mark.parametrize("freq", ["M", "2M", "3M"]) def test_parr_cmp_period_scalar(self, freq, box_with_array): # GH#13200 - xbox = np.ndarray if box_with_array in [pd.Index, pd.array] else box_with_array + xbox = get_expected_box(box_with_array) base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq) base = tm.box_expected(base, box_with_array) @@ -249,7 +247,7 @@ def test_parr_cmp_period_scalar(self, freq, box_with_array): @pytest.mark.parametrize("freq", ["M", "2M", "3M"]) def test_parr_cmp_pi(self, freq, box_with_array): # GH#13200 - xbox = np.ndarray if box_with_array in [pd.Index, pd.array] else box_with_array + xbox = get_expected_box(box_with_array) base = PeriodIndex(["2011-01", "2011-02", "2011-03", "2011-04"], freq=freq) base = tm.box_expected(base, box_with_array) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index a2b7d93884a4e..7765c29ee59c8 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -1198,7 +1198,7 @@ def test_td64arr_addsub_integer_array_no_freq(self, box_with_array): # ------------------------------------------------------------------ # Operations with timedelta-like others - def test_td64arr_add_td64_array(self, box_with_array): + def test_td64arr_add_sub_td64_array(self, box_with_array): box = box_with_array dti = pd.date_range("2016-01-01", periods=3) tdi = dti - dti.shift(1) @@ -1213,20 +1213,11 @@ def test_td64arr_add_td64_array(self, box_with_array): result = tdarr + tdi tm.assert_equal(result, expected) - def test_td64arr_sub_td64_array(self, box_with_array): - box = box_with_array - dti = pd.date_range("2016-01-01", periods=3) - tdi = dti - dti.shift(1) - tdarr = tdi.values - - expected = 0 * tdi - tdi = tm.box_expected(tdi, box) - expected = tm.box_expected(expected, box) - + expected_sub = 0 * tdi result = tdi - tdarr - tm.assert_equal(result, expected) + tm.assert_equal(result, expected_sub) result = tdarr - tdi - tm.assert_equal(result, expected) + tm.assert_equal(result, expected_sub) def test_td64arr_add_sub_tdi(self, box_with_array, names): # GH#17250 make sure result dtype is correct @@ -1263,37 +1254,25 @@ def test_td64arr_add_sub_tdi(self, box_with_array, names): tm.assert_equal(result, -expected) assert_dtype(result, "timedelta64[ns]") - def test_td64arr_add_sub_td64_nat(self, box_with_array): - # GH#23320 special handling for timedelta64("NaT") + @pytest.mark.parametrize("tdnat", [np.timedelta64("NaT"), NaT]) + def test_td64arr_add_sub_td64_nat(self, box_with_array, tdnat): + # GH#18808, GH#23320 special handling for timedelta64("NaT") box = box_with_array tdi = TimedeltaIndex([NaT, Timedelta("1s")]) - other = np.timedelta64("NaT") expected = TimedeltaIndex(["NaT"] * 2) obj = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box) - result = obj + other + result = obj + tdnat tm.assert_equal(result, expected) - result = other + obj + result = tdnat + obj tm.assert_equal(result, expected) - result = obj - other + result = obj - tdnat tm.assert_equal(result, expected) - result = other - obj + result = tdnat - obj tm.assert_equal(result, expected) - def test_td64arr_sub_NaT(self, box_with_array): - # GH#18808 - box = box_with_array - ser = Series([NaT, Timedelta("1s")]) - expected = Series([NaT, NaT], dtype="timedelta64[ns]") - - ser = tm.box_expected(ser, box) - expected = tm.box_expected(expected, box) - - res = ser - NaT - tm.assert_equal(res, expected) - def test_td64arr_add_timedeltalike(self, two_hours, box_with_array): # only test adding/sub offsets as + is now numeric # GH#10699 for Tick cases @@ -1328,7 +1307,7 @@ def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array): # ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets - def test_td64arr_add_offset_index(self, names, box_with_array): + def test_td64arr_add_sub_offset_index(self, names, box_with_array): # GH#18849, GH#19744 box = box_with_array exname = get_expected_name(box, names) @@ -1340,8 +1319,13 @@ def test_td64arr_add_offset_index(self, names, box_with_array): expected = TimedeltaIndex( [tdi[n] + other[n] for n in range(len(tdi))], freq="infer", name=exname ) + expected_sub = TimedeltaIndex( + [tdi[n] - other[n] for n in range(len(tdi))], freq="infer", name=exname + ) + tdi = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box) + expected_sub = tm.box_expected(expected_sub, box) with tm.assert_produces_warning(PerformanceWarning): res = tdi + other @@ -1351,10 +1335,12 @@ def test_td64arr_add_offset_index(self, names, box_with_array): res2 = other + tdi tm.assert_equal(res2, expected) - # TODO: combine with test_td64arr_add_offset_index by parametrizing - # over second box? - def test_td64arr_add_offset_array(self, box_with_array): - # GH#18849 + with tm.assert_produces_warning(PerformanceWarning): + res_sub = tdi - other + tm.assert_equal(res_sub, expected_sub) + + def test_td64arr_add_sub_offset_array(self, box_with_array): + # GH#18849, GH#18824 box = box_with_array tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"]) other = np.array([offsets.Hour(n=1), offsets.Minute(n=-2)]) @@ -1362,6 +1348,9 @@ def test_td64arr_add_offset_array(self, box_with_array): expected = TimedeltaIndex( [tdi[n] + other[n] for n in range(len(tdi))], freq="infer" ) + expected_sub = TimedeltaIndex( + [tdi[n] - other[n] for n in range(len(tdi))], freq="infer" + ) tdi = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box) @@ -1374,41 +1363,10 @@ def test_td64arr_add_offset_array(self, box_with_array): res2 = other + tdi tm.assert_equal(res2, expected) - def test_td64arr_sub_offset_index(self, names, box_with_array): - # GH#18824, GH#19744 - box = box_with_array - xbox = box if box not in [tm.to_array, pd.array] else pd.Index - exname = get_expected_name(box, names) - - tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0]) - other = pd.Index([offsets.Hour(n=1), offsets.Minute(n=-2)], name=names[1]) - - expected = TimedeltaIndex( - [tdi[n] - other[n] for n in range(len(tdi))], freq="infer", name=exname - ) - - tdi = tm.box_expected(tdi, box) - expected = tm.box_expected(expected, xbox) - + expected_sub = tm.box_expected(expected_sub, box_with_array) with tm.assert_produces_warning(PerformanceWarning): - res = tdi - other - tm.assert_equal(res, expected) - - def test_td64arr_sub_offset_array(self, box_with_array): - # GH#18824 - tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"]) - other = np.array([offsets.Hour(n=1), offsets.Minute(n=-2)]) - - expected = TimedeltaIndex( - [tdi[n] - other[n] for n in range(len(tdi))], freq="infer" - ) - - tdi = tm.box_expected(tdi, box_with_array) - expected = tm.box_expected(expected, box_with_array) - - with tm.assert_produces_warning(PerformanceWarning): - res = tdi - other - tm.assert_equal(res, expected) + res_sub = tdi - other + tm.assert_equal(res_sub, expected_sub) def test_td64arr_with_offset_series(self, names, box_with_array): # GH#18849 @@ -1968,10 +1926,12 @@ def test_td64arr_mul_tdscalar_invalid(self, box_with_array, scalar_td): def test_td64arr_mul_too_short_raises(self, box_with_array): idx = TimedeltaIndex(np.arange(5, dtype="int64")) idx = tm.box_expected(idx, box_with_array) - msg = ( - "cannot use operands with types dtype|" - "Cannot multiply with unequal lengths|" - "Unable to coerce to Series" + msg = "|".join( + [ + "cannot use operands with types dtype", + "Cannot multiply with unequal lengths", + "Unable to coerce to Series", + ] ) with pytest.raises(TypeError, match=msg): # length check before dtype check @@ -2079,12 +2039,14 @@ def test_td64arr_div_numeric_array( result = tdser / vector tm.assert_equal(result, expected) - pattern = ( - "true_divide'? cannot use operands|" - "cannot perform __div__|" - "cannot perform __truediv__|" - "unsupported operand|" - "Cannot divide" + pattern = "|".join( + [ + "true_divide'? cannot use operands", + "cannot perform __div__", + "cannot perform __truediv__", + "unsupported operand", + "Cannot divide", + ] ) with pytest.raises(TypeError, match=pattern): vector / tdser diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index ac181af7875b5..7efd3bdb6920a 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -233,9 +233,9 @@ def test_getitem_integer_with_missing_raises(self, data, idx): # FIXME: dont leave commented-out # TODO: this raises KeyError about labels not found (it tries label-based) # import pandas._testing as tm - # s = pd.Series(data, index=[tm.rands(4) for _ in range(len(data))]) + # ser = pd.Series(data, index=[tm.rands(4) for _ in range(len(data))]) # with pytest.raises(ValueError, match=msg): - # s[idx] + # ser[idx] def test_getitem_slice(self, data): # getitem[slice] should return an array diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index 344b0be20fc7b..c9c0a4de60a46 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -115,15 +115,16 @@ def check_opname(self, s, op_name, other, exc=None): def _check_op(self, s, op, other, op_name, exc=NotImplementedError): if exc is None: sdtype = tm.get_dtype(s) - if sdtype.is_unsigned_integer and (op_name == "__rsub__"): - # TODO see https://github.com/pandas-dev/pandas/issues/22023 - pytest.skip("unsigned subtraction gives negative values") if ( hasattr(other, "dtype") and not is_extension_array_dtype(other.dtype) and is_integer_dtype(other.dtype) + and sdtype.is_unsigned_integer ): + # TODO: comment below is inaccurate; other can be int8, int16, ... + # and the trouble is that e.g. if s is UInt8 and other is int8, + # then result is UInt16 # other is np.int64 and would therefore always result in # upcasting, so keeping other as same numpy_dtype other = other.astype(sdtype.numpy_dtype) @@ -133,20 +134,9 @@ def _check_op(self, s, op, other, op_name, exc=NotImplementedError): if op_name in ("__rtruediv__", "__truediv__", "__div__"): expected = expected.fillna(np.nan).astype("Float64") - elif op_name.startswith("__r"): - # TODO reverse operators result in object dtype - # see https://github.com/pandas-dev/pandas/issues/22024 - expected = expected.astype(sdtype) - result = result.astype(sdtype) else: # combine method result in 'biggest' (int64) dtype expected = expected.astype(sdtype) - pass - - if (op_name == "__rpow__") and isinstance(other, pd.Series): - # TODO pow on Int arrays gives different result with NA - # see https://github.com/pandas-dev/pandas/issues/22022 - result = result.fillna(1) self.assert_equal(result, expected) else: diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 1ea436520bf20..74460a75d7b63 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1165,12 +1165,10 @@ def test_getitem_boolean_indexing_mixed(self): def test_type_error_multiindex(self): # See gh-12218 - df = DataFrame( - columns=["i", "c", "x", "y"], - data=[[0, 0, 1, 2], [1, 0, 3, 4], [0, 1, 1, 2], [1, 1, 3, 4]], + mi = MultiIndex.from_product([["x", "y"], [0, 1]], names=[None, "c"]) + dg = DataFrame( + [[1, 1, 2, 2], [3, 3, 4, 4]], columns=mi, index=Index([0, 1], name="i") ) - dg = df.pivot_table(index="i", columns="c", values=["x", "y"]) - # TODO: Is this test for pivot_table? with pytest.raises(TypeError, match="unhashable type"): dg[:, 0] diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index f68bde2188e67..2313afcae607a 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -1,7 +1,5 @@ """ Tests that can be parametrized over _any_ Index object. - -TODO: consider using hypothesis for these. """ import re diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index 669bbe23af559..fc8abb83ed302 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -248,8 +248,7 @@ def test_take_invalid_kwargs(self): with pytest.raises(ValueError, match=msg): idx.take(indices, mode="clip") - # TODO: This method came from test_timedelta; de-dup with version above - def test_take2(self): + def test_take_equiv_getitem(self): tds = ["1day 02:00:00", "1 day 04:00:00", "1 day 10:00:00"] idx = timedelta_range(start="1d", end="2d", freq="H", name="idx") expected = TimedeltaIndex(tds, freq=None, name="idx") diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 95da68510be6b..d9bd8f6809c73 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -239,7 +239,7 @@ def test_repr_truncation(self): assert "..." not in repr(df) def test_repr_deprecation_negative_int(self): - # FIXME: remove in future version after deprecation cycle + # TODO(2.0): remove in future version after deprecation cycle # Non-regression test for: # https://github.com/pandas-dev/pandas/issues/31532 width = get_option("display.max_colwidth") diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 6d269a27e2656..f74cab9ed04da 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -6,7 +6,6 @@ timedelta, ) import pickle -import sys import numpy as np import pytest @@ -1526,14 +1525,8 @@ def _check_plot_works(f, freq=None, series=None, *args, **kwargs): with tm.ensure_clean(return_filelike=True) as path: plt.savefig(path) - # GH18439 - # this is supported only in Python 3 pickle since - # pickle in Python2 doesn't support instancemethod pickling - # TODO(statsmodels 0.10.0): Remove the statsmodels check - # https://github.com/pandas-dev/pandas/issues/24088 - # https://github.com/statsmodels/statsmodels/issues/4772 - if "statsmodels" not in sys.modules: - with tm.ensure_clean(return_filelike=True) as path: - pickle.dump(fig, path) + # GH18439, GH#24088, statsmodels#4772 + with tm.ensure_clean(return_filelike=True) as path: + pickle.dump(fig, path) finally: plt.close(fig) diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index 2c5c977624470..b8291471225d7 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -137,14 +137,14 @@ def test_getitem_setitem_datetimeindex(): tm.assert_series_equal(result, expected) # But we do not give datetimes a pass on tzawareness compat - # TODO: do the same with Timestamps and dt64 msg = "Cannot compare tz-naive and tz-aware datetime-like objects" naive = datetime(1990, 1, 1, 4) - with tm.assert_produces_warning(FutureWarning): - # GH#36148 will require tzawareness compat - result = ts[naive] - expected = ts[4] - assert result == expected + for key in [naive, Timestamp(naive), np.datetime64(naive, "ns")]: + with tm.assert_produces_warning(FutureWarning): + # GH#36148 will require tzawareness compat + result = ts[key] + expected = ts[4] + assert result == expected result = ts.copy() with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/series/methods/test_between.py b/pandas/tests/series/methods/test_between.py index 9c11b71e4bee6..d81017633ff76 100644 --- a/pandas/tests/series/methods/test_between.py +++ b/pandas/tests/series/methods/test_between.py @@ -11,8 +11,6 @@ class TestBetween: - - # TODO: redundant with test_between_datetime_values? def test_between(self): series = Series(date_range("1/1/2000", periods=10)) left, right = series[[2, 7]] @@ -21,7 +19,7 @@ def test_between(self): expected = (series >= left) & (series <= right) tm.assert_series_equal(result, expected) - def test_between_datetime_values(self): + def test_between_datetime_object_dtype(self): ser = Series(bdate_range("1/1/2000", periods=20).astype(object)) ser[::2] = np.nan diff --git a/pandas/tests/series/methods/test_rename.py b/pandas/tests/series/methods/test_rename.py index 2930c657eb3b2..a78abfa63cff4 100644 --- a/pandas/tests/series/methods/test_rename.py +++ b/pandas/tests/series/methods/test_rename.py @@ -1,6 +1,7 @@ from datetime import datetime import numpy as np +import pytest from pandas import ( Index, @@ -65,10 +66,9 @@ def test_rename_axis_supported(self): ser = Series(range(5)) ser.rename({}, axis=0) ser.rename({}, axis="index") - # FIXME: dont leave commented-out - # TODO: clean up shared index validation - # with pytest.raises(ValueError, match="No axis named 5"): - # ser.rename({}, axis=5) + + with pytest.raises(ValueError, match="No axis named 5"): + ser.rename({}, axis=5) def test_rename_inplace(self, datetime_series): renamer = lambda x: x.strftime("%Y%m%d") diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 4d1c75da72399..103130484f0e1 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -251,6 +251,7 @@ def test_add_corner_cases(self, datetime_series): # deltas5 = deltas * 5 # deltas = deltas + sub_deltas + def test_add_float_plus_int(self, datetime_series): # float + int int_ts = datetime_series.astype(int)[:-5] added = datetime_series + int_ts
- [ ] 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/44211
2021-10-27T22:26:58Z
2021-10-28T00:39:02Z
2021-10-28T00:39:02Z
2021-11-07T18:05:10Z
REF: clarify missing.interpolate_2d is inplace
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 87fcf54ed684b..45c55fc6bd3f2 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -743,8 +743,10 @@ def fillna( elif method is not None: msg = "fillna with 'method' requires high memory usage." warnings.warn(msg, PerformanceWarning) - filled = interpolate_2d(np.asarray(self), method=method, limit=limit) - return type(self)(filled, fill_value=self.fill_value) + new_values = np.asarray(self) + # interpolate_2d modifies new_values inplace + interpolate_2d(new_values, method=method, limit=limit) + return type(self)(new_values, fill_value=self.fill_value) else: new_values = np.where(isna(self.sp_values), value, self.sp_values) diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 9e85cbec0f299..68ac7b4968d15 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -214,9 +214,11 @@ def interpolate_array_2d( coerce: bool = False, downcast: str | None = None, **kwargs, -): +) -> np.ndarray: """ Wrapper to dispatch to either interpolate_2d or _interpolate_2d_with_fill. + + Returned ndarray has same dtype as 'data'. """ try: m = clean_fill_method(method) @@ -228,13 +230,14 @@ def interpolate_array_2d( # similar to validate_fillna_kwargs raise ValueError("Cannot pass both fill_value and method") - interp_values = interpolate_2d( + interpolate_2d( data, method=m, axis=axis, limit=limit, limit_area=limit_area, ) + interp_values = data else: assert index is not None # for mypy @@ -687,14 +690,14 @@ def _cubicspline_interpolate(xi, yi, x, axis=0, bc_type="not-a-knot", extrapolat def _interpolate_with_limit_area( - values: ArrayLike, method: str, limit: int | None, limit_area: str | None -) -> ArrayLike: + values: np.ndarray, method: str, limit: int | None, limit_area: str | None +) -> None: """ Apply interpolation and limit_area logic to values along a to-be-specified axis. Parameters ---------- - values: array-like + values: np.ndarray Input array. method: str Interpolation method. Could be "bfill" or "pad" @@ -703,10 +706,9 @@ def _interpolate_with_limit_area( limit_area: str Limit area for interpolation. Can be "inside" or "outside" - Returns - ------- - values: array-like - Interpolated array. + Notes + ----- + Modifies values in-place. """ invalid = isna(values) @@ -719,7 +721,7 @@ def _interpolate_with_limit_area( if last is None: last = len(values) - values = interpolate_2d( + interpolate_2d( values, method=method, limit=limit, @@ -732,23 +734,23 @@ def _interpolate_with_limit_area( values[invalid] = np.nan - return values + return def interpolate_2d( - values, + values: np.ndarray, method: str = "pad", axis: Axis = 0, limit: int | None = None, limit_area: str | None = None, -): +) -> None: """ Perform an actual interpolation of values, values will be make 2-d if needed fills inplace, returns the result. Parameters ---------- - values: array-like + values: np.ndarray Input array. method: str, default "pad" Interpolation method. Could be "bfill" or "pad" @@ -759,13 +761,12 @@ def interpolate_2d( limit_area: str, optional Limit area for interpolation. Can be "inside" or "outside" - Returns - ------- - values: array-like - Interpolated array. + Notes + ----- + Modifies values in-place. """ if limit_area is not None: - return np.apply_along_axis( + np.apply_along_axis( partial( _interpolate_with_limit_area, method=method, @@ -775,11 +776,11 @@ def interpolate_2d( axis, values, ) + return transf = (lambda x: x) if axis == 0 else (lambda x: x.T) # reshape a 1 dim if needed - ndim = values.ndim if values.ndim == 1: if axis != 0: # pragma: no cover raise AssertionError("cannot interpolate on a ndim == 1 with axis != 0") @@ -787,20 +788,19 @@ def interpolate_2d( method = clean_fill_method(method) tvalues = transf(values) + + # _pad_2d and _backfill_2d both modify tvalues inplace if method == "pad": - result, _ = _pad_2d(tvalues, limit=limit) + _pad_2d(tvalues, limit=limit) else: - result, _ = _backfill_2d(tvalues, limit=limit) - - result = transf(result) - # reshape back - if ndim == 1: - result = result[0] + _backfill_2d(tvalues, limit=limit) - return result + return -def _fillna_prep(values, mask: np.ndarray | None = None) -> np.ndarray: +def _fillna_prep( + values, mask: npt.NDArray[np.bool_] | None = None +) -> npt.NDArray[np.bool_]: # boilerplate for _pad_1d, _backfill_1d, _pad_2d, _backfill_2d if mask is None: @@ -834,8 +834,8 @@ def new_func(values, limit=None, mask=None): def _pad_1d( values: np.ndarray, limit: int | None = None, - mask: np.ndarray | None = None, -) -> tuple[np.ndarray, np.ndarray]: + mask: npt.NDArray[np.bool_] | None = None, +) -> tuple[np.ndarray, npt.NDArray[np.bool_]]: mask = _fillna_prep(values, mask) algos.pad_inplace(values, mask, limit=limit) return values, mask @@ -845,15 +845,15 @@ def _pad_1d( def _backfill_1d( values: np.ndarray, limit: int | None = None, - mask: np.ndarray | None = None, -) -> tuple[np.ndarray, np.ndarray]: + mask: npt.NDArray[np.bool_] | None = None, +) -> tuple[np.ndarray, npt.NDArray[np.bool_]]: mask = _fillna_prep(values, mask) algos.backfill_inplace(values, mask, limit=limit) return values, mask @_datetimelike_compat -def _pad_2d(values, limit=None, mask=None): +def _pad_2d(values: np.ndarray, limit=None, mask: npt.NDArray[np.bool_] | None = None): mask = _fillna_prep(values, mask) if np.all(values.shape): @@ -865,7 +865,7 @@ def _pad_2d(values, limit=None, mask=None): @_datetimelike_compat -def _backfill_2d(values, limit=None, mask=None): +def _backfill_2d(values, limit=None, mask: npt.NDArray[np.bool_] | None = None): mask = _fillna_prep(values, mask) if np.all(values.shape): @@ -890,7 +890,7 @@ def clean_reindex_fill_method(method): return clean_fill_method(method, allow_nearest=True) -def _interp_limit(invalid: np.ndarray, fw_limit, bw_limit): +def _interp_limit(invalid: npt.NDArray[np.bool_], fw_limit, bw_limit): """ Get indexers of values that won't be filled because they exceed the limits. @@ -955,7 +955,7 @@ def inner(invalid, limit): return f_idx & b_idx -def _rolling_window(a: np.ndarray, window: int): +def _rolling_window(a: npt.NDArray[np.bool_], window: int) -> npt.NDArray[np.bool_]: """ [True, True, False, True, False], 2 ->
- [ ] 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/44210
2021-10-27T21:57:11Z
2021-10-28T01:13:15Z
2021-10-28T01:13:15Z
2021-10-28T02:56:43Z
REF: Remove ArrowStringArray.fillna
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index a83cfa89c4728..4e3bd05d2cc8d 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -33,7 +33,6 @@ pa_version_under4p0, ) from pandas.util._decorators import doc -from pandas.util._validators import validate_fillna_kwargs from pandas.core.dtypes.common import ( is_array_like, @@ -48,7 +47,6 @@ ) from pandas.core.dtypes.missing import isna -from pandas.core import missing from pandas.core.arraylike import OpsMixin from pandas.core.arrays.base import ExtensionArray from pandas.core.arrays.boolean import BooleanDtype @@ -339,55 +337,6 @@ def _as_pandas_scalar(self, arrow_scalar: pa.Scalar): else: return scalar - def fillna(self, value=None, method=None, limit=None): - """ - Fill NA/NaN values using the specified method. - - Parameters - ---------- - value : scalar, array-like - If a scalar value is passed it is used to fill all missing values. - Alternatively, an array-like 'value' can be given. It's expected - that the array-like have the same length as 'self'. - method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None - Method to use for filling holes in reindexed Series - pad / ffill: propagate last valid observation forward to next valid - backfill / bfill: use NEXT valid observation to fill gap. - limit : int, default None - If method is specified, this is the maximum number of consecutive - NaN values to forward/backward fill. In other words, if there is - a gap with more than this number of consecutive NaNs, it will only - be partially filled. If method is not specified, this is the - maximum number of entries along the entire axis where NaNs will be - filled. - - Returns - ------- - ExtensionArray - With NA/NaN filled. - """ - value, method = validate_fillna_kwargs(value, method) - - mask = self.isna() - value = missing.check_value_size(value, mask, len(self)) - - if mask.any(): - if method is not None: - func = missing.get_fill_func(method) - new_values, _ = func( - self.to_numpy("object"), - limit=limit, - mask=mask, - ) - new_values = self._from_sequence(new_values) - else: - # fill with value - new_values = self.copy() - new_values[mask] = value - else: - new_values = self.copy() - return new_values - def _reduce(self, name: str, skipna: bool = True, **kwargs): if name in ["min", "max"]: return getattr(self, name)(skipna=skipna)
Equivalent to base class method.
https://api.github.com/repos/pandas-dev/pandas/pulls/44209
2021-10-27T21:51:27Z
2021-10-28T03:03:05Z
2021-10-28T03:03:05Z
2021-10-28T03:07:10Z
Backport PR #44204 on branch 1.3.x (CI: Python Dev build)
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index 4fe58ad4d60e9..96d5542451f06 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -17,7 +17,6 @@ env: PANDAS_CI: 1 PATTERN: "not slow and not network and not clipboard" COVERAGE: true - PYTEST_TARGET: pandas jobs: build: @@ -26,12 +25,13 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macOS-latest, windows-latest] + pytest_target: ["pandas/tests/[a-h]*", "pandas/tests/[i-z]*"] name: actions-310-dev - timeout-minutes: 60 + timeout-minutes: 80 concurrency: - group: ${{ github.ref }}-${{ matrix.os }}-dev + group: ${{ github.ref }}-${{ matrix.os }}-${{ matrix.pytest_target }}-dev cancel-in-progress: ${{github.event_name == 'pull_request'}} steps: @@ -63,6 +63,8 @@ jobs: python -c "import pandas; pandas.show_versions();" - name: Test with pytest + env: + PYTEST_TARGET: ${{ matrix.pytest_target }} shell: bash run: | ci/run_tests.sh
Backport PR #44204: CI: Python Dev build
https://api.github.com/repos/pandas-dev/pandas/pulls/44208
2021-10-27T21:32:34Z
2021-10-28T01:13:33Z
2021-10-28T01:13:33Z
2021-10-28T01:13:34Z
CLN: remove unused algos_common_helper functions
diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in index 4242a76dcc3b7..c6338216eb7a2 100644 --- a/pandas/_libs/algos_common_helper.pxi.in +++ b/pandas/_libs/algos_common_helper.pxi.in @@ -36,19 +36,19 @@ def ensure_object(object arr): # name, c_type, dtype dtypes = [('float64', 'FLOAT64', 'float64'), - ('float32', 'FLOAT32', 'float32'), + # ('float32', 'FLOAT32', 'float32'), # disabling bc unused ('int8', 'INT8', 'int8'), ('int16', 'INT16', 'int16'), ('int32', 'INT32', 'int32'), ('int64', 'INT64', 'int64'), - ('uint8', 'UINT8', 'uint8'), - ('uint16', 'UINT16', 'uint16'), - ('uint32', 'UINT32', 'uint32'), - ('uint64', 'UINT64', 'uint64'), - ('complex64', 'COMPLEX64', 'complex64'), - ('complex128', 'COMPLEX128', 'complex128') - # ('platform_int', 'INT', 'int_'), - # ('object', 'OBJECT', 'object_'), + # Disabling uint and complex dtypes because we do not use them + # (and compiling them increases wheel size) + # ('uint8', 'UINT8', 'uint8'), + # ('uint16', 'UINT16', 'uint16'), + # ('uint32', 'UINT32', 'uint32'), + # ('uint64', 'UINT64', 'uint64'), + # ('complex64', 'COMPLEX64', 'complex64'), + # ('complex128', 'COMPLEX128', 'complex128') ] def get_dispatch(dtypes): diff --git a/pandas/core/array_algos/take.py b/pandas/core/array_algos/take.py index e1a29f0dbe395..87d55702b33e0 100644 --- a/pandas/core/array_algos/take.py +++ b/pandas/core/array_algos/take.py @@ -284,6 +284,9 @@ def _get_take_nd_function_cached( if func is not None: return func + # We get here with string, uint, float16, and complex dtypes that could + # potentially be handled in algos_take_helper. + # Also a couple with (M8[ns], object) and (m8[ns], object) tup = (out_dtype.name, out_dtype.name) if ndim == 1: func = _take_1d_dict.get(tup, None) diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 2e8641c281661..0788ecdd8b4b5 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -65,7 +65,6 @@ _is_scipy_sparse = None ensure_float64 = algos.ensure_float64 -ensure_float32 = algos.ensure_float32 def ensure_float(arr): @@ -92,13 +91,10 @@ def ensure_float(arr): return arr -ensure_uint64 = algos.ensure_uint64 ensure_int64 = algos.ensure_int64 ensure_int32 = algos.ensure_int32 ensure_int16 = algos.ensure_int16 ensure_int8 = algos.ensure_int8 -ensure_complex64 = algos.ensure_complex64 -ensure_complex128 = algos.ensure_complex128 ensure_platform_int = algos.ensure_platform_int ensure_object = algos.ensure_object
- [ ] 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/44207
2021-10-27T20:18:02Z
2021-10-28T13:18:19Z
2021-10-28T13:18:19Z
2021-10-28T15:08:30Z
TST: enable 2D tests for Categorical
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c7f587b35f557..9c43e3714c332 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -6,7 +6,6 @@ from shutil import get_terminal_size from typing import ( TYPE_CHECKING, - Any, Hashable, Sequence, TypeVar, @@ -38,10 +37,6 @@ Dtype, NpDtype, Ordered, - PositionalIndexer2D, - PositionalIndexerTuple, - ScalarIndexer, - SequenceIndexer, Shape, npt, type_t, @@ -102,7 +97,10 @@ take_nd, unique1d, ) -from pandas.core.arrays._mixins import NDArrayBackedExtensionArray +from pandas.core.arrays._mixins import ( + NDArrayBackedExtensionArray, + ravel_compat, +) from pandas.core.base import ( ExtensionArray, NoNewAttributesMixin, @@ -113,7 +111,6 @@ extract_array, sanitize_array, ) -from pandas.core.indexers import deprecate_ndim_indexing from pandas.core.ops.common import unpack_zerodim_and_defer from pandas.core.sorting import nargsort from pandas.core.strings.object_array import ObjectStringArrayMixin @@ -1484,6 +1481,7 @@ def _validate_scalar(self, fill_value): # ------------------------------------------------------------- + @ravel_compat def __array__(self, dtype: NpDtype | None = None) -> np.ndarray: """ The numpy array interface. @@ -1934,7 +1932,10 @@ def __iter__(self): """ Returns an Iterator over the values of this Categorical. """ - return iter(self._internal_get_values().tolist()) + if self.ndim == 1: + return iter(self._internal_get_values().tolist()) + else: + return (self[n] for n in range(len(self))) def __contains__(self, key) -> bool: """ @@ -2053,27 +2054,6 @@ def __repr__(self) -> str: # ------------------------------------------------------------------ - @overload - def __getitem__(self, key: ScalarIndexer) -> Any: - ... - - @overload - def __getitem__( - self: CategoricalT, - key: SequenceIndexer | PositionalIndexerTuple, - ) -> CategoricalT: - ... - - def __getitem__(self: CategoricalT, key: PositionalIndexer2D) -> CategoricalT | Any: - """ - Return an item. - """ - result = super().__getitem__(key) - if getattr(result, "ndim", 0) > 1: - result = result._ndarray - deprecate_ndim_indexing(result) - return result - def _validate_listlike(self, value): # NB: here we assume scalar-like tuples have already been excluded value = extract_array(value, extract_numpy=True) @@ -2311,7 +2291,19 @@ def _concat_same_type( ) -> CategoricalT: from pandas.core.dtypes.concat import union_categoricals - return union_categoricals(to_concat) + result = union_categoricals(to_concat) + + # in case we are concatenating along axis != 0, we need to reshape + # the result from union_categoricals + first = to_concat[0] + if axis >= first.ndim: + raise ValueError + if axis == 1: + if not all(len(x) == len(first) for x in to_concat): + raise ValueError + # TODO: Will this get contiguity wrong? + result = result.reshape(-1, len(to_concat), order="F") + return result # ------------------------------------------------------------------ @@ -2699,6 +2691,11 @@ def _get_codes_for_values(values, categories: Index) -> np.ndarray: """ dtype_equal = is_dtype_equal(values.dtype, categories.dtype) + if values.ndim > 1: + flat = values.ravel() + codes = _get_codes_for_values(flat, categories) + return codes.reshape(values.shape) + if isinstance(categories.dtype, ExtensionDtype) and is_object_dtype(values): # Support inferring the correct extension dtype from an array of # scalar objects. e.g. diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index e9dc63e9bd903..6a1a9512bc036 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -303,3 +303,14 @@ def test_not_equal_with_na(self, categories): class TestParsing(base.BaseParsingTests): pass + + +class Test2DCompat(base.Dim2CompatTests): + def test_repr_2d(self, data): + # Categorical __repr__ doesn't include "Categorical", so we need + # to special-case + res = repr(data.reshape(1, -1)) + assert res.count("\nCategories") == 1 + + res = repr(data.reshape(-1, 1)) + assert res.count("\nCategories") == 1
- [ ] 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/44206
2021-10-27T20:17:32Z
2021-11-10T01:47:02Z
2021-11-10T01:47:02Z
2021-11-10T02:13:30Z
REF: de-special-case Block._maybe_downcast
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index bc9f5c3243705..151709301f71f 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -510,54 +510,24 @@ def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]: [blk.convert(datetime=True, numeric=False) for blk in blocks] ) - # no need to downcast our float - # unless indicated - if downcast is None and self.dtype.kind in ["f", "c", "m", "M"]: - # passing "infer" to maybe_downcast_to_dtype (via self.downcast) - # would be a no-op, so we can short-circuit + if downcast is None: + return blocks + if downcast is False: + # turn if off completely + # TODO: not reached, deprecate in favor of downcast=None return blocks - return extend_blocks([b.downcast(downcast) for b in blocks]) + return extend_blocks([b._downcast_2d(downcast) for b in blocks]) @final - def downcast(self, dtypes=None) -> list[Block]: - """try to downcast each item to the dict of dtypes if present""" - # turn it off completely - if dtypes is False: - return [self] - - values = self.values - - if self.ndim == 1: - - # try to cast all non-floats here - if dtypes is None: - dtypes = "infer" - - nv = maybe_downcast_to_dtype(values, dtypes) - return [self.make_block(nv)] - - # ndim > 1 - if dtypes is None: - return [self] - - if not (dtypes == "infer" or isinstance(dtypes, dict)): - raise ValueError( - "downcast must have a dictionary or 'infer' as its argument" - ) - elif dtypes != "infer": - raise AssertionError("dtypes as dict is not supported yet") - - return self._downcast_2d() - @maybe_split - def _downcast_2d(self) -> list[Block]: + def _downcast_2d(self, dtype) -> list[Block]: """ downcast specialized to 2D case post-validation. Refactored to allow use of maybe_split. """ - new_values = maybe_downcast_to_dtype(self.values, dtype="infer") + new_values = maybe_downcast_to_dtype(self.values, dtype=dtype) return [self.make_block(new_values)] @final @@ -1098,8 +1068,8 @@ def interpolate( **kwargs, ) - nbs = [self.make_block_same_class(interp_values)] - return self._maybe_downcast(nbs, downcast) + nb = self.make_block_same_class(interp_values) + return nb._maybe_downcast([nb], downcast) def take_nd( 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/44205
2021-10-27T19:46:35Z
2021-10-28T12:32:35Z
2021-10-28T12:32:35Z
2021-10-28T15:13:51Z
CI: Python Dev build
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index 4fe58ad4d60e9..96d5542451f06 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -17,7 +17,6 @@ env: PANDAS_CI: 1 PATTERN: "not slow and not network and not clipboard" COVERAGE: true - PYTEST_TARGET: pandas jobs: build: @@ -26,12 +25,13 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, macOS-latest, windows-latest] + pytest_target: ["pandas/tests/[a-h]*", "pandas/tests/[i-z]*"] name: actions-310-dev - timeout-minutes: 60 + timeout-minutes: 80 concurrency: - group: ${{ github.ref }}-${{ matrix.os }}-dev + group: ${{ github.ref }}-${{ matrix.os }}-${{ matrix.pytest_target }}-dev cancel-in-progress: ${{github.event_name == 'pull_request'}} steps: @@ -63,6 +63,8 @@ jobs: python -c "import pandas; pandas.show_versions();" - name: Test with pytest + env: + PYTEST_TARGET: ${{ matrix.pytest_target }} shell: bash run: | ci/run_tests.sh
xref #44173 Ref: https://github.com/pandas-dev/pandas/issues/44173#issuecomment-952289166 Means we will have 3 more jobs (hopefully can reduce this back..) - but all can run in parallel. https://github.com/pandas-dev/pandas/runs/4026818833?check_suite_focus=true
https://api.github.com/repos/pandas-dev/pandas/pulls/44204
2021-10-27T19:32:58Z
2021-10-27T21:32:06Z
2021-10-27T21:32:06Z
2021-11-07T16:41:10Z
DOCS: Update pyarrow version requirement in "What's new in 1.4.0"
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 254a004a37c40..003289037996d 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -95,7 +95,7 @@ Validation now for ``caption`` arg (:issue:`43368`) Multithreaded CSV reading with a new CSV Engine based on pyarrow ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -:func:`pandas.read_csv` now accepts ``engine="pyarrow"`` (requires at least ``pyarrow`` 0.17.0) as an argument, allowing for faster csv parsing on multicore machines +:func:`pandas.read_csv` now accepts ``engine="pyarrow"`` (requires at least ``pyarrow`` 1.0.1) as an argument, allowing for faster csv parsing on multicore machines with pyarrow installed. See the :doc:`I/O docs </user_guide/io>` for more info. (:issue:`23697`, :issue:`43706`) .. _whatsnew_140.enhancements.window_rank:
Updated the pyarrow version requirement from 0.17 to 1.0.1 in the "Multithreaded CSV reading" section, to make it in line with #44064. Docs only, no functional changes.
https://api.github.com/repos/pandas-dev/pandas/pulls/44202
2021-10-27T10:18:03Z
2021-10-27T11:53:26Z
2021-10-27T11:53:26Z
2021-10-27T11:53:31Z
BUG: Series[Interval[int64]] setitem Interval[float]
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 254a004a37c40..7b10ca64a9b3d 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -530,8 +530,10 @@ Indexing - Bug in :meth:`Series.__setitem__` with object dtype when setting an array with matching size and dtype='datetime64[ns]' or dtype='timedelta64[ns]' incorrectly converting the datetime/timedeltas to integers (:issue:`43868`) - Bug in :meth:`DataFrame.sort_index` where ``ignore_index=True`` was not being respected when the index was already sorted (:issue:`43591`) - Bug in :meth:`Index.get_indexer_non_unique` when index contains multiple ``np.datetime64("NaT")`` and ``np.timedelta64("NaT")`` (:issue:`43869`) +- Bug in setting a scalar :class:`Interval` value into a :class:`Series` with ``IntervalDtype`` when the scalar's sides are floats and the values' sides are integers (:issue:`44201`) - + Missing ^^^^^^^ - Bug in :meth:`DataFrame.fillna` with limit and no method ignores axis='columns' or ``axis = 1`` (:issue:`40989`) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index de612b367f78f..06ec02794e578 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -48,6 +48,7 @@ is_1d_only_ea_obj, is_dtype_equal, is_extension_array_dtype, + is_interval_dtype, is_list_like, is_sparse, is_string_dtype, @@ -1440,7 +1441,21 @@ def putmask(self, mask, new) -> list[Block]: # TODO(EA2D): unnecessary with 2D EAs mask = mask.reshape(new_values.shape) - new_values[mask] = new + try: + new_values[mask] = new + except TypeError: + if not is_interval_dtype(self.dtype): + # Discussion about what we want to support in the general + # case GH#39584 + raise + + blk = self.coerce_to_target_dtype(new) + if blk.dtype == _dtype_obj: + # For now at least, only support casting e.g. + # Interval[int64]->Interval[float64], + raise + return blk.putmask(mask, new) + nb = type(self)(new_values, placement=self._mgr_locs, ndim=self.ndim) return [nb] @@ -1477,12 +1492,8 @@ def setitem(self, indexer, value): be a compatible shape. """ if not self._can_hold_element(value): - # This is only relevant for DatetimeTZBlock, PeriodDtype, IntervalDtype, - # which has a non-trivial `_can_hold_element`. - # https://github.com/pandas-dev/pandas/issues/24020 - # Need a dedicated setitem until GH#24020 (type promotion in setitem - # for extension arrays) is designed and implemented. - return self.astype(_dtype_obj).setitem(indexer, value) + # see TestSetitemFloatIntervalWithIntIntervalValues + return self.coerce_to_target_dtype(value).setitem(indexer, value) if isinstance(indexer, tuple): # TODO(EA2D): not needed with 2D EAs @@ -1642,6 +1653,15 @@ def where(self, other, cond, errors="raise") -> list[Block]: # TODO: don't special-case raise + if is_interval_dtype(self.dtype): + # TestSetitemFloatIntervalWithIntIntervalValues + blk = self.coerce_to_target_dtype(other) + if blk.dtype == _dtype_obj: + # For now at least only support casting e.g. + # Interval[int64]->Interval[float64] + raise + return blk.where(other, cond, errors) + result = type(self.values)._from_sequence( np.where(cond, self.values, other), dtype=dtype ) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index fe3495abd2fb0..a922a937ce9d3 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -11,6 +11,7 @@ DataFrame, DatetimeIndex, Index, + Interval, IntervalIndex, MultiIndex, NaT, @@ -928,6 +929,38 @@ def is_inplace(self, obj): return obj.dtype.kind != "i" +class TestSetitemFloatIntervalWithIntIntervalValues(SetitemCastingEquivalents): + # GH#44201 Cast to shared IntervalDtype rather than object + + def test_setitem_example(self): + # Just a case here to make obvious what this test class is aimed at + idx = IntervalIndex.from_breaks(range(4)) + obj = Series(idx) + val = Interval(0.5, 1.5) + + obj[0] = val + assert obj.dtype == "Interval[float64, right]" + + @pytest.fixture + def obj(self): + idx = IntervalIndex.from_breaks(range(4)) + return Series(idx) + + @pytest.fixture + def val(self): + return Interval(0.5, 1.5) + + @pytest.fixture + def key(self): + return 0 + + @pytest.fixture + def expected(self, obj, val): + data = [val] + list(obj[1:]) + idx = IntervalIndex(data, dtype="Interval[float64]") + return Series(idx) + + def test_setitem_int_as_positional_fallback_deprecation(): # GH#42215 deprecated falling back to positional on __setitem__ with an # int not contained in the index
- [ ] 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 Cast to common dtype instead of object, match IntervalIndex behavior.
https://api.github.com/repos/pandas-dev/pandas/pulls/44201
2021-10-27T04:28:11Z
2021-10-27T18:24:06Z
2021-10-27T18:24:06Z
2021-10-27T19:49:25Z
CLN: remove no-op BlockManager.downcast
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c3ad87082c8ed..6895455a43160 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6359,9 +6359,6 @@ def fillna( raise NotImplementedError() result = self.T.fillna(method=method, limit=limit).T - # need to downcast here because of all of the transposes - result._mgr = result._mgr.downcast() - return result new_data = self._mgr.interpolate( @@ -6415,9 +6412,6 @@ def fillna( result = self.T.fillna(value=value, limit=limit).T - # need to downcast here because of all of the transposes - result._mgr = result._mgr.downcast() - new_data = result else: diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 9344aea8221d5..d1802afb7a2f1 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -388,9 +388,6 @@ def fillna(self: T, value, limit, inplace: bool, downcast) -> T: "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast ) - def downcast(self: T) -> T: - return self.apply_with_block("downcast") - def astype(self: T, dtype, copy: bool = False, errors: str = "raise") -> T: return self.apply(astype_array_safe, dtype=dtype, copy=copy, errors=errors) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index de612b367f78f..85d715f37a05b 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -511,8 +511,9 @@ def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]: # no need to downcast our float # unless indicated - if downcast is None and self.dtype.kind in ["f", "m", "M"]: - # TODO: complex? more generally, self._can_hold_na? + if downcast is None and self.dtype.kind in ["f", "c", "m", "M"]: + # passing "infer" to maybe_downcast_to_dtype (via self.downcast) + # would be a no-op, so we can short-circuit return blocks return extend_blocks([b.downcast(downcast) for b in blocks]) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 9b29216fa407b..991094f86c999 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -394,9 +394,6 @@ def fillna(self: T, value, limit, inplace: bool, downcast) -> T: "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast ) - def downcast(self: T) -> T: - return self.apply("downcast") - def astype(self: T, dtype, copy: bool = False, errors: str = "raise") -> T: return self.apply("astype", dtype=dtype, copy=copy, errors=errors) diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 3a307ebd702ca..186135f598235 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -164,19 +164,6 @@ def test_nonzero(self): with pytest.raises(ValueError, match=msg): not obj1 - def test_downcast(self): - # test close downcasting - - o = self._construct(shape=4, value=9, dtype=np.int64) - result = o.copy() - result._mgr = o._mgr.downcast() - self._compare(result, o) - - o = self._construct(shape=4, value=9.5) - result = o.copy() - result._mgr = o._mgr.downcast() - self._compare(result, o) - def test_constructor_compound_dtypes(self): # see gh-5191 # Compound dtypes should raise NotImplementedError.
- [ ] 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/44198
2021-10-26T22:48:35Z
2021-10-27T11:54:25Z
2021-10-27T11:54:25Z
2021-10-27T15:27:01Z
Backport PR #44192 on branch 1.3.x (PERF: read_csv GH#44106)
diff --git a/doc/source/whatsnew/v1.3.5.rst b/doc/source/whatsnew/v1.3.5.rst index 0f1997de2166a..ba9fcb5c1bfeb 100644 --- a/doc/source/whatsnew/v1.3.5.rst +++ b/doc/source/whatsnew/v1.3.5.rst @@ -14,7 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- +- Fixed performance regression in :func:`read_csv` (:issue:`44106`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index ae62cc3b45578..8aedfb9b26f38 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -206,9 +206,10 @@ def _set_noconvert_columns(self): """ assert self.orig_names is not None # error: Cannot determine type of 'names' - col_indices = [ - self.orig_names.index(x) for x in self.names # type: ignore[has-type] - ] + + # much faster than using orig_names.index(x) xref GH#44106 + names_dict = {x: i for i, x in enumerate(self.orig_names)} + col_indices = [names_dict[x] for x in self.names] # type: ignore[has-type] # error: Cannot determine type of 'names' noconvert_columns = self._set_noconvert_dtype_columns( col_indices,
Backport PR #44192: PERF: read_csv GH#44106
https://api.github.com/repos/pandas-dev/pandas/pulls/44197
2021-10-26T20:27:16Z
2021-10-27T01:25:34Z
2021-10-27T01:25:34Z
2021-10-27T01:25:34Z
Fix series with none equals float series
diff --git a/doc/source/whatsnew/v1.3.5.rst b/doc/source/whatsnew/v1.3.5.rst index ba9fcb5c1bfeb..589092c0dd7e3 100644 --- a/doc/source/whatsnew/v1.3.5.rst +++ b/doc/source/whatsnew/v1.3.5.rst @@ -14,6 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ +- Fixed regression in :meth:`Series.equals` when comparing floats with dtype object to None (:issue:`44190`) - Fixed performance regression in :func:`read_csv` (:issue:`44106`) - diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index 90f409d371e6b..b77db2aec4a08 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -67,7 +67,7 @@ cpdef bint is_matching_na(object left, object right, bint nan_matches_none=False elif left is NaT: return right is NaT elif util.is_float_object(left): - if nan_matches_none and right is None: + if nan_matches_none and right is None and util.is_nan(left): return True return ( util.is_nan(left) diff --git a/pandas/tests/series/methods/test_equals.py b/pandas/tests/series/methods/test_equals.py index 052aef4ac1bab..22e27c271df88 100644 --- a/pandas/tests/series/methods/test_equals.py +++ b/pandas/tests/series/methods/test_equals.py @@ -125,3 +125,18 @@ def test_equals_none_vs_nan(): assert ser.equals(ser2) assert Index(ser, dtype=ser.dtype).equals(Index(ser2, dtype=ser2.dtype)) assert ser.array.equals(ser2.array) + + +def test_equals_None_vs_float(): + # GH#44190 + left = Series([-np.inf, np.nan, -1.0, 0.0, 1.0, 10 / 3, np.inf], dtype=object) + right = Series([None] * len(left)) + + # these series were found to be equal due to a bug, check that they are correctly + # found to not equal + assert not left.equals(right) + assert not right.equals(left) + assert not left.to_frame().equals(right.to_frame()) + assert not right.to_frame().equals(left.to_frame()) + assert not Index(left, dtype="object").equals(Index(right, dtype="object")) + assert not Index(right, dtype="object").equals(Index(left, dtype="object"))
- [x] closes #44190 - [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/44195
2021-10-26T18:16:19Z
2021-10-29T13:17:25Z
2021-10-29T13:17:25Z
2021-10-29T13:17:58Z
DEPR: warn on checks retained for fastparquet
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 57f07313ebdc4..a0f116c1f8f88 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -31,6 +31,7 @@ npt, ) from pandas.util._decorators import cache_readonly +from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import ( @@ -268,8 +269,19 @@ def make_block_same_class( placement = self._mgr_locs if values.dtype.kind in ["m", "M"]: - # TODO: remove this once fastparquet has stopped relying on it - values = ensure_wrapped_if_datetimelike(values) + + new_values = ensure_wrapped_if_datetimelike(values) + if new_values is not values: + # TODO(2.0): remove once fastparquet has stopped relying on it + warnings.warn( + "In a future version, Block.make_block_same_class will " + "assume that datetime64 and timedelta64 ndarrays have " + "already been cast to DatetimeArray and TimedeltaArray, " + "respectively.", + DeprecationWarning, + stacklevel=find_stack_level(), + ) + values = new_values # We assume maybe_coerce_values has already been called return type(self)(values, placement=placement, ndim=self.ndim) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 991094f86c999..745cddee93479 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -27,6 +27,7 @@ ) from pandas.errors import PerformanceWarning from pandas.util._decorators import cache_readonly +from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import infer_dtype_from_scalar @@ -907,7 +908,15 @@ def __init__( f"number of axes ({self.ndim})" ) if isinstance(block, DatetimeTZBlock) and block.values.ndim == 1: - # TODO: remove once fastparquet no longer needs this + # TODO(2.0): remove once fastparquet no longer needs this + warnings.warn( + "In a future version, the BlockManager constructor " + "will assume that a DatetimeTZBlock with block.ndim==2 " + "has block.values.ndim == 2.", + DeprecationWarning, + stacklevel=find_stack_level(), + ) + # error: Incompatible types in assignment (expression has type # "Union[ExtensionArray, ndarray]", variable has type # "DatetimeArray")
- [ ] 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 cc @mdurant
https://api.github.com/repos/pandas-dev/pandas/pulls/44193
2021-10-26T16:06:04Z
2021-10-30T22:24:35Z
2021-10-30T22:24:35Z
2021-10-30T23:31:24Z
PERF: read_csv GH#44106
diff --git a/doc/source/whatsnew/v1.3.5.rst b/doc/source/whatsnew/v1.3.5.rst index 0f1997de2166a..ba9fcb5c1bfeb 100644 --- a/doc/source/whatsnew/v1.3.5.rst +++ b/doc/source/whatsnew/v1.3.5.rst @@ -14,7 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- +- Fixed performance regression in :func:`read_csv` (:issue:`44106`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index 7998fe57b58c8..32ca3aaeba6cc 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -205,9 +205,10 @@ def _set_noconvert_columns(self): """ assert self.orig_names is not None # error: Cannot determine type of 'names' - col_indices = [ - self.orig_names.index(x) for x in self.names # type: ignore[has-type] - ] + + # much faster than using orig_names.index(x) xref GH#44106 + names_dict = {x: i for i, x in enumerate(self.orig_names)} + col_indices = [names_dict[x] for x in self.names] # type: ignore[has-type] # error: Cannot determine type of 'names' noconvert_columns = self._set_noconvert_dtype_columns( col_indices,
- [x] closes #44106 - [ ] 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 - [x] whatsnew entry Using the example in #44106 I time 188.4s on master and 3.9s on this PR.
https://api.github.com/repos/pandas-dev/pandas/pulls/44192
2021-10-26T16:00:05Z
2021-10-26T20:26:51Z
2021-10-26T20:26:51Z
2021-10-26T23:48:20Z
Update generic.py, explanatory text of describe
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c3ad87082c8ed..b8e158b5f9e2e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9899,7 +9899,7 @@ def describe( from the result. To exclude numeric types submit ``numpy.number``. To exclude object columns submit the data type ``numpy.object``. Strings can also be used in the style of - ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To + ``select_dtypes`` (e.g. ``df.describe(exclude=['O'])``). To exclude pandas categorical columns, use ``'category'`` - None (default) : The result will exclude nothing. datetime_is_numeric : bool, default False
Usage of correct parameter ``exclude`` in description of ``exclude``-parameter of ``describe()``-function
https://api.github.com/repos/pandas-dev/pandas/pulls/44191
2021-10-26T13:18:10Z
2021-10-28T01:37:15Z
2021-10-28T01:37:15Z
2021-10-28T01:37:17Z
:white_check_mark: TST: Update sync flake8 tests
diff --git a/scripts/tests/test_sync_flake8_versions.py b/scripts/tests/test_sync_flake8_versions.py index d9b6dbe8c3f0a..21c3b743830ee 100644 --- a/scripts/tests/test_sync_flake8_versions.py +++ b/scripts/tests/test_sync_flake8_versions.py @@ -3,44 +3,6 @@ from ..sync_flake8_versions import get_revisions -def test_wrong_yesqa_flake8(capsys): - precommit_config = { - "repos": [ - { - "repo": "https://gitlab.com/pycqa/flake8", - "rev": "0.1.1", - "hooks": [ - { - "id": "flake8", - } - ], - }, - { - "repo": "https://github.com/asottile/yesqa", - "rev": "v1.2.2", - "hooks": [ - { - "id": "yesqa", - "additional_dependencies": [ - "flake8==0.4.2", - ], - } - ], - }, - ] - } - environment = { - "dependencies": [ - "flake8=0.1.1", - ] - } - with pytest.raises(SystemExit, match=None): - get_revisions(precommit_config, environment) - result, _ = capsys.readouterr() - expected = "flake8 in 'yesqa' does not match in 'flake8' from 'pre-commit'\n" - assert result == expected - - def test_wrong_env_flake8(capsys): precommit_config = { "repos": [ @@ -53,18 +15,6 @@ def test_wrong_env_flake8(capsys): } ], }, - { - "repo": "https://github.com/asottile/yesqa", - "rev": "v1.2.2", - "hooks": [ - { - "id": "yesqa", - "additional_dependencies": [ - "flake8==0.4.2", - ], - } - ], - }, ] } environment = { @@ -81,52 +31,6 @@ def test_wrong_env_flake8(capsys): assert result == expected -def test_wrong_yesqa_add_dep(capsys): - precommit_config = { - "repos": [ - { - "repo": "https://gitlab.com/pycqa/flake8", - "rev": "0.1.1", - "hooks": [ - { - "id": "flake8", - "additional_dependencies": [ - "flake8-bugs==1.1.1", - ], - } - ], - }, - { - "repo": "https://github.com/asottile/yesqa", - "rev": "v1.2.2", - "hooks": [ - { - "id": "yesqa", - "additional_dependencies": [ - "flake8==0.4.2", - "flake8-bugs>=1.1.1", - ], - } - ], - }, - ] - } - environment = { - "dependencies": [ - "flake8=1.5.6", - "flake8-bugs=1.1.1", - ] - } - with pytest.raises(SystemExit, match=None): - get_revisions(precommit_config, environment) - result, _ = capsys.readouterr() - expected = ( - "Mismatch of 'flake8-bugs' version between 'flake8' and 'yesqa' in " - "'.pre-commit-config.yaml'\n" - ) - assert result == expected - - def test_wrong_env_add_dep(capsys): precommit_config = { "repos": [
- [x] related to #44177 - [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 I sent a PR yesterday #44177 which was aimed at adding anchors to the `pre-commit-config.yaml` file However, somehow I forgot to also update the corresponding test so this PR should remove the references to `yesqa` dependencies checks
https://api.github.com/repos/pandas-dev/pandas/pulls/44189
2021-10-26T10:25:32Z
2021-10-26T11:06:16Z
2021-10-26T11:06:16Z
2021-10-26T12:02:28Z
ENH: implement EA._where
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 848e724949bc5..cbb029f62732a 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -320,7 +320,7 @@ def putmask(self, mask: np.ndarray, value) -> None: np.putmask(self._ndarray, mask, value) - def where( + def _where( self: NDArrayBackedExtensionArrayT, mask: np.ndarray, value ) -> NDArrayBackedExtensionArrayT: """ diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 5536a4665fd79..46b505e7384b4 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -1411,6 +1411,31 @@ def insert(self: ExtensionArrayT, loc: int, item) -> ExtensionArrayT: return type(self)._concat_same_type([self[:loc], item_arr, self[loc:]]) + def _where( + self: ExtensionArrayT, mask: npt.NDArray[np.bool_], value + ) -> ExtensionArrayT: + """ + Analogue to np.where(mask, self, value) + + Parameters + ---------- + mask : np.ndarray[bool] + value : scalar or listlike + + Returns + ------- + same type as self + """ + result = self.copy() + + if is_list_like(value): + val = value[~mask] + else: + val = value + + result[~mask] = val + return result + @classmethod def _empty(cls, shape: Shape, dtype: ExtensionDtype): """ diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 87fcf54ed684b..8260846ae7dc7 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -1305,6 +1305,13 @@ def to_dense(self) -> np.ndarray: _internal_get_values = to_dense + def _where(self, mask, value): + # NB: may not preserve dtype, e.g. result may be Sparse[float64] + # while self is Sparse[int64] + naive_implementation = np.where(mask, self, value) + result = type(self)._from_sequence(naive_implementation) + return result + # ------------------------------------------------------------------------ # IO # ------------------------------------------------------------------------ diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index bc9f5c3243705..3015df95f6e1b 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -50,7 +50,6 @@ is_extension_array_dtype, is_interval_dtype, is_list_like, - is_sparse, is_string_dtype, ) from pandas.core.dtypes.dtypes import ( @@ -1626,30 +1625,9 @@ def where(self, other, cond, errors="raise") -> list[Block]: # for the type other = self.dtype.na_value - if is_sparse(self.values): - # TODO(SparseArray.__setitem__): remove this if condition - # We need to re-infer the type of the data after doing the - # where, for cases where the subtypes don't match - dtype = None - else: - dtype = self.dtype - - result = self.values.copy() - icond = ~cond - if lib.is_scalar(other): - set_other = other - else: - set_other = other[icond] try: - result[icond] = set_other - except (NotImplementedError, TypeError): - # NotImplementedError for class not implementing `__setitem__` - # TypeError for SparseArray, which implements just to raise - # a TypeError - if isinstance(result, Categorical): - # TODO: don't special-case - raise - + result = self.values._where(cond, other) + except TypeError: if is_interval_dtype(self.dtype): # TestSetitemFloatIntervalWithIntIntervalValues blk = self.coerce_to_target_dtype(other) @@ -1658,10 +1636,7 @@ def where(self, other, cond, errors="raise") -> list[Block]: # Interval[int64]->Interval[float64] raise return blk.where(other, cond, errors) - - result = type(self.values)._from_sequence( - np.where(cond, self.values, other), dtype=dtype - ) + raise return [self.make_block_same_class(result)] @@ -1751,7 +1726,7 @@ def where(self, other, cond, errors="raise") -> list[Block]: cond = extract_bool_array(cond) try: - res_values = arr.T.where(cond, other).T + res_values = arr.T._where(cond, other).T except (ValueError, TypeError): return Block.where(self, other, cond, errors=errors) diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py index 798aa7188cb9a..6f8b18f449779 100644 --- a/pandas/tests/indexes/categorical/test_indexing.py +++ b/pandas/tests/indexes/categorical/test_indexing.py @@ -325,7 +325,7 @@ def test_where_non_categories(self): msg = "Cannot setitem on a Categorical with a new category" with pytest.raises(TypeError, match=msg): # Test the Categorical method directly - ci._data.where(mask, 2) + ci._data._where(mask, 2) class TestContains: diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index ed1ba11c5fd55..0adc1810a6c47 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -508,7 +508,7 @@ def test_where_datetimelike_categorical(tz_naive_fixture): tm.assert_index_equal(res, dr) # DatetimeArray.where - res = lvals._data.where(mask, rvals) + res = lvals._data._where(mask, rvals) tm.assert_datetime_array_equal(res, dr._data) # Series.where
The goal here is to avoid special-casing in ExtensionBlock.where
https://api.github.com/repos/pandas-dev/pandas/pulls/44187
2021-10-26T04:30:18Z
2021-10-28T12:32:47Z
2021-10-28T12:32:47Z
2021-10-28T15:10:55Z
ENH: added regex argument to Series.str.split
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2a718fdcf16e7..496bc6046a935 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -180,6 +180,7 @@ Other enhancements - :meth:`DataFrame.__pos__`, :meth:`DataFrame.__neg__` now retain ``ExtensionDtype`` dtypes (:issue:`43883`) - The error raised when an optional dependency can't be imported now includes the original exception, for easier investigation (:issue:`43882`) - Added :meth:`.ExponentialMovingWindow.sum` (:issue:`13297`) +- :meth:`Series.str.split` now supports a ``regex`` argument that explicitly specifies whether the pattern is a regular expression. Default is ``None`` (:issue:`43563`, :issue:`32835`, :issue:`25549`) - :meth:`DataFrame.dropna` now accepts a single label as ``subset`` along with array-like (:issue:`41021`) - diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index a62d701413bf1..9f163f77a2ae8 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -659,11 +659,11 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): Split strings around given separator/delimiter. Splits the string in the Series/Index from the %(side)s, - at the specified delimiter string. Equivalent to :meth:`str.%(method)s`. + at the specified delimiter string. Parameters ---------- - pat : str, optional + pat : str or compiled regex, optional String or regular expression to split on. If not specified, split on whitespace. n : int, default -1 (all) @@ -672,14 +672,30 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): expand : bool, default False Expand the split strings into separate columns. - * If ``True``, return DataFrame/MultiIndex expanding dimensionality. - * If ``False``, return Series/Index, containing lists of strings. + - If ``True``, return DataFrame/MultiIndex expanding dimensionality. + - If ``False``, return Series/Index, containing lists of strings. + + regex : bool, default None + Determines if the passed-in pattern is a regular expression: + + - If ``True``, assumes the passed-in pattern is a regular expression + - If ``False``, treats the pattern as a literal string. + - If ``None`` and `pat` length is 1, treats `pat` as a literal string. + - If ``None`` and `pat` length is not 1, treats `pat` as a regular expression. + - Cannot be set to False if `pat` is a compiled regex + + .. versionadded:: 1.4.0 Returns ------- Series, Index, DataFrame or MultiIndex Type matches caller unless ``expand=True`` (see Notes). + Raises + ------ + ValueError + * if `regex` is False and `pat` is a compiled regex + See Also -------- Series.str.split : Split strings around given separator/delimiter. @@ -702,6 +718,9 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): If using ``expand=True``, Series and Index callers return DataFrame and MultiIndex objects, respectively. + Use of `regex=False` with a `pat` as a compiled regex will raise + an error. + Examples -------- >>> s = pd.Series( @@ -776,22 +795,63 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): 1 https://docs.python.org/3/tutorial index.html 2 NaN NaN - Remember to escape special characters when explicitly using regular - expressions. + Remember to escape special characters when explicitly using regular expressions. - >>> s = pd.Series(["1+1=2"]) - >>> s - 0 1+1=2 - dtype: object - >>> s.str.split(r"\+|=", expand=True) - 0 1 2 - 0 1 1 2 + >>> s = pd.Series(["foo and bar plus baz"]) + >>> s.str.split(r"and|plus", expand=True) + 0 1 2 + 0 foo bar baz + + Regular expressions can be used to handle urls or file names. + When `pat` is a string and ``regex=None`` (the default), the given `pat` is compiled + as a regex only if ``len(pat) != 1``. + + >>> s = pd.Series(['foojpgbar.jpg']) + >>> s.str.split(r".", expand=True) + 0 1 + 0 foojpgbar jpg + + >>> s.str.split(r"\.jpg", expand=True) + 0 1 + 0 foojpgbar + + When ``regex=True``, `pat` is interpreted as a regex + + >>> s.str.split(r"\.jpg", regex=True, expand=True) + 0 1 + 0 foojpgbar + + A compiled regex can be passed as `pat` + + >>> import re + >>> s.str.split(re.compile(r"\.jpg"), expand=True) + 0 1 + 0 foojpgbar + + When ``regex=False``, `pat` is interpreted as the string itself + + >>> s.str.split(r"\.jpg", regex=False, expand=True) + 0 + 0 foojpgbar.jpg """ @Appender(_shared_docs["str_split"] % {"side": "beginning", "method": "split"}) @forbid_nonstring_types(["bytes"]) - def split(self, pat=None, n=-1, expand=False): - result = self._data.array._str_split(pat, n, expand) + def split( + self, + pat: str | re.Pattern | None = None, + n=-1, + expand=False, + *, + regex: bool | None = None, + ): + if regex is False and is_re(pat): + raise ValueError( + "Cannot use a compiled regex as replacement pattern with regex=False" + ) + if is_re(pat): + regex = True + result = self._data.array._str_split(pat, n, expand, regex) return self._wrap_result(result, returns_string=expand, expand=expand) @Appender(_shared_docs["str_split"] % {"side": "end", "method": "rsplit"}) diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 76ee55ef5f9ad..3081575f50700 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -308,21 +308,38 @@ def f(x): return self._str_map(f) - def _str_split(self, pat=None, n=-1, expand=False): + def _str_split( + self, + pat: str | re.Pattern | None = None, + n=-1, + expand=False, + regex: bool | None = None, + ): if pat is None: if n is None or n == 0: n = -1 f = lambda x: x.split(pat, n) else: - if len(pat) == 1: - if n is None or n == 0: - n = -1 - f = lambda x: x.split(pat, n) + new_pat: str | re.Pattern + if regex is True or isinstance(pat, re.Pattern): + new_pat = re.compile(pat) + elif regex is False: + new_pat = pat + # regex is None so link to old behavior #43563 else: + if len(pat) == 1: + new_pat = pat + else: + new_pat = re.compile(pat) + + if isinstance(new_pat, re.Pattern): if n is None or n == -1: n = 0 - regex = re.compile(pat) - f = lambda x: regex.split(x, maxsplit=n) + f = lambda x: new_pat.split(x, maxsplit=n) + else: + if n is None or n == 0: + n = -1 + f = lambda x: x.split(pat, n) return self._str_map(f, dtype=object) def _str_rsplit(self, pat=None, n=-1): diff --git a/pandas/tests/strings/test_split_partition.py b/pandas/tests/strings/test_split_partition.py index f3f5acd0d2f1c..01a397938db52 100644 --- a/pandas/tests/strings/test_split_partition.py +++ b/pandas/tests/strings/test_split_partition.py @@ -1,4 +1,5 @@ from datetime import datetime +import re import numpy as np import pytest @@ -35,6 +36,44 @@ def test_split(any_string_dtype): tm.assert_series_equal(result, exp) +def test_split_regex(any_string_dtype): + # GH 43563 + # explicit regex = True split + values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype) + result = values.str.split(r"\.jpg", regex=True) + exp = Series([["xxxjpgzzz", ""]]) + tm.assert_series_equal(result, exp) + + # explicit regex = True split with compiled regex + regex_pat = re.compile(r".jpg") + values = Series("xxxjpgzzz.jpg", dtype=any_string_dtype) + result = values.str.split(regex_pat) + exp = Series([["xx", "zzz", ""]]) + tm.assert_series_equal(result, exp) + + # explicit regex = False split + result = values.str.split(r"\.jpg", regex=False) + exp = Series([["xxxjpgzzz.jpg"]]) + tm.assert_series_equal(result, exp) + + # non explicit regex split, pattern length == 1 + result = values.str.split(r".") + exp = Series([["xxxjpgzzz", "jpg"]]) + tm.assert_series_equal(result, exp) + + # non explicit regex split, pattern length != 1 + result = values.str.split(r".jpg") + exp = Series([["xx", "zzz", ""]]) + tm.assert_series_equal(result, exp) + + # regex=False with pattern compiled regex raises error + with pytest.raises( + ValueError, + match="Cannot use a compiled regex as replacement pattern with regex=False", + ): + values.str.split(regex_pat, regex=False) + + def test_split_object_mixed(): mixed = Series(["a_b_c", np.nan, "d_e_f", True, datetime.today(), None, 1, 2.0]) result = mixed.str.split("_")
- [X] closes #43563 - [X] closes #32835 - [X] closes #25549 - [X] xref #37963 - [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 I've preserved current behavior, in which regex = None. Currently, it handles the pattern as a regex if the length of pattern is not 1. I believe that in the future, this may be worth considering deprecating.
https://api.github.com/repos/pandas-dev/pandas/pulls/44185
2021-10-26T02:13:17Z
2021-11-04T00:40:28Z
2021-11-04T00:40:27Z
2021-11-04T00:40:54Z
BUG: np.timedelta64 + Period
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index fc3eaec47431f..8221bc406521a 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -567,7 +567,7 @@ I/O Period ^^^^^^ -- +- Bug in adding a :class:`Period` object to a ``np.timedelta64`` object incorrectly raising ``TypeError`` (:issue:`44182`) - Plotting diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 0998cb7b0c21e..dcf4323bc8755 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -4,6 +4,7 @@ cimport numpy as cnp from cpython.object cimport ( Py_EQ, Py_NE, + PyObject_RichCompare, PyObject_RichCompareBool, ) from numpy cimport ( @@ -1594,6 +1595,9 @@ cdef class _Period(PeriodMixin): PeriodDtypeBase _dtype BaseOffset freq + # higher than np.ndarray, np.matrix, np.timedelta64 + __array_priority__ = 100 + dayofweek = _Period.day_of_week dayofyear = _Period.day_of_year @@ -1652,7 +1656,10 @@ cdef class _Period(PeriodMixin): return PyObject_RichCompareBool(self.ordinal, other.ordinal, op) elif other is NaT: return _nat_scalar_rules[op] - return NotImplemented # TODO: ndarray[object]? + elif util.is_array(other): + # in particular ndarray[object]; see test_pi_cmp_period + return np.array([PyObject_RichCompare(self, x, op) for x in other]) + return NotImplemented def __hash__(self): return hash((self.ordinal, self.freqstr)) diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 0c42be517b798..d7cb314743e86 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -185,6 +185,10 @@ def test_pi_cmp_period(self): exp = idx.values < idx.values[10] tm.assert_numpy_array_equal(result, exp) + # Tests Period.__richcmp__ against ndarray[object, ndim=2] + result = idx.values.reshape(10, 2) < idx[10] + tm.assert_numpy_array_equal(result, exp.reshape(10, 2)) + # TODO: moved from test_datetime64; de-duplicate with version below def test_parr_cmp_period_scalar2(self, box_with_array): xbox = get_expected_box(box_with_array) diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 9b2e0cac5de84..f1b8c1cfdd39b 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1287,20 +1287,8 @@ def test_add_offset(self): msg = "Input has different freq|Input cannot be converted to Period" with pytest.raises(IncompatibleFrequency, match=msg): p + o - - if isinstance(o, np.timedelta64): - msg = "cannot use operands with types" - with pytest.raises(TypeError, match=msg): - o + p - else: - msg = "|".join( - [ - "Input has different freq", - "Input cannot be converted to Period", - ] - ) - with pytest.raises(IncompatibleFrequency, match=msg): - o + p + with pytest.raises(IncompatibleFrequency, match=msg): + o + p for freq in ["M", "2M", "3M"]: p = Period("2011-03", freq=freq) @@ -1329,14 +1317,8 @@ def test_add_offset(self): with pytest.raises(IncompatibleFrequency, match=msg): p + o - - if isinstance(o, np.timedelta64): - td_msg = "cannot use operands with types" - with pytest.raises(TypeError, match=td_msg): - o + p - else: - with pytest.raises(IncompatibleFrequency, match=msg): - o + p + with pytest.raises(IncompatibleFrequency, match=msg): + o + p # freq is Tick for freq in ["D", "2D", "3D"]: @@ -1352,14 +1334,11 @@ def test_add_offset(self): exp = Period("2011-04-03", freq=freq) assert p + np.timedelta64(2, "D") == exp - msg = "cannot use operands with types" - with pytest.raises(TypeError, match=msg): - np.timedelta64(2, "D") + p + assert np.timedelta64(2, "D") + p == exp exp = Period("2011-04-02", freq=freq) assert p + np.timedelta64(3600 * 24, "s") == exp - with pytest.raises(TypeError, match=msg): - np.timedelta64(3600 * 24, "s") + p + assert np.timedelta64(3600 * 24, "s") + p == exp exp = Period("2011-03-30", freq=freq) assert p + timedelta(-2) == exp @@ -1385,14 +1364,8 @@ def test_add_offset(self): ]: with pytest.raises(IncompatibleFrequency, match=msg): p + o - - if isinstance(o, np.timedelta64): - td_msg = "cannot use operands with types" - with pytest.raises(TypeError, match=td_msg): - o + p - else: - with pytest.raises(IncompatibleFrequency, match=msg): - o + p + with pytest.raises(IncompatibleFrequency, match=msg): + o + p for freq in ["H", "2H", "3H"]: p = Period("2011-04-01 09:00", freq=freq) @@ -1408,13 +1381,11 @@ def test_add_offset(self): msg = "cannot use operands with types" exp = Period("2011-04-01 12:00", freq=freq) assert p + np.timedelta64(3, "h") == exp - with pytest.raises(TypeError, match=msg): - np.timedelta64(3, "h") + p + assert np.timedelta64(3, "h") + p == exp exp = Period("2011-04-01 10:00", freq=freq) assert p + np.timedelta64(3600, "s") == exp - with pytest.raises(TypeError, match=msg): - np.timedelta64(3600, "s") + p + assert np.timedelta64(3600, "s") + p == exp exp = Period("2011-04-01 11:00", freq=freq) assert p + timedelta(minutes=120) == exp @@ -1440,14 +1411,8 @@ def test_add_offset(self): ]: with pytest.raises(IncompatibleFrequency, match=msg): p + o - - if isinstance(o, np.timedelta64): - td_msg = "cannot use operands with types" - with pytest.raises(TypeError, match=td_msg): - o + p - else: - with pytest.raises(IncompatibleFrequency, match=msg): - o + p + with pytest.raises(IncompatibleFrequency, match=msg): + o + p def test_sub_offset(self): # freq is DateOffset
- [ ] 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/44182
2021-10-25T18:07:58Z
2021-10-28T13:19:18Z
2021-10-28T13:19:18Z
2021-11-02T01:57:49Z
Group by a categorical Series of unequal length
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 71d5c46b81ea0..5136051468ff8 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -784,6 +784,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`) +- 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`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index a05f8e581d12f..b3302233ce91f 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -887,12 +887,6 @@ def is_in_obj(gpr) -> bool: else: in_axis = False - if is_categorical_dtype(gpr) and len(gpr) != obj.shape[axis]: - raise ValueError( - f"Length of grouper ({len(gpr)}) and axis ({obj.shape[axis]}) " - "must be same length" - ) - # create the Grouping # allow us to passing the actual Grouping as the gpr ping = ( @@ -938,7 +932,7 @@ def _convert_grouper(axis: Index, grouper): return grouper.reindex(axis)._values elif isinstance(grouper, MultiIndex): return grouper._values - elif isinstance(grouper, (list, tuple, Series, Index, np.ndarray)): + elif isinstance(grouper, (list, tuple, Index, Categorical, np.ndarray)): if len(grouper) != len(axis): raise ValueError("Grouper and axis must be same length") diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 28128dee9da0f..585491f8664b3 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -664,11 +664,32 @@ def test_bins_unequal_len(): bins = pd.cut(series.dropna().values, 4) # len(bins) != len(series) here - msg = r"Length of grouper \(8\) and axis \(10\) must be same length" - with pytest.raises(ValueError, match=msg): + with pytest.raises(ValueError, match="Grouper and axis must be same length"): series.groupby(bins).mean() +@pytest.mark.parametrize( + ["series", "data"], + [ + # Group a series with length and index equal to those of the grouper. + (Series(range(4)), {"A": [0, 3], "B": [1, 2]}), + # Group a series with length equal to that of the grouper and index unequal to + # that of the grouper. + (Series(range(4)).rename(lambda idx: idx + 1), {"A": [2], "B": [0, 1]}), + # GH44179: Group a series with length unequal to that of the grouper. + (Series(range(7)), {"A": [0, 3], "B": [1, 2]}), + ], +) +def test_categorical_series(series, data): + # Group the given series by a series with categorical data type such that group A + # takes indices 0 and 3 and group B indices 1 and 2, obtaining the values mapped in + # the given data. + groupby = series.groupby(Series(list("ABBA"), dtype="category")) + result = groupby.aggregate(list) + expected = Series(data, index=CategoricalIndex(data.keys())) + tm.assert_series_equal(result, expected) + + def test_as_index(): # GH13204 df = DataFrame(
- [X] closes #44179 - [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 While this fix enables grouping by a `Series` that has a categorical data type and length unequal to the axis of grouping, it maintains the requirement (developed in #3017, #9741, and #18525) that the length of a `Categorical` object used for grouping must match that of the axis of grouping. Additionally, this fix checks that requirement consistently with other groupers whose lengths must match—namely `list`, `tuple`, `Index`, and `numpy.ndarray`—and produces the same exception message when the lengths differ.
https://api.github.com/repos/pandas-dev/pandas/pulls/44180
2021-10-25T14:17:49Z
2021-12-22T03:07:33Z
2021-12-22T03:07:32Z
2022-01-03T17:14:19Z
ENH: Use yaml anchors for pre-commit hooks additional dependencies
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2c76b682ee343..469c4066e2387 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -39,10 +39,11 @@ repos: rev: 3.9.2 hooks: - id: flake8 - additional_dependencies: - - flake8-comprehensions==3.1.0 - - flake8-bugbear==21.3.2 - - pandas-dev-flaker==0.2.0 + additional_dependencies: &flake8_dependencies + - flake8==3.9.2 + - flake8-comprehensions==3.1.0 + - flake8-bugbear==21.3.2 + - pandas-dev-flaker==0.2.0 - id: flake8 alias: flake8-cython name: flake8 (cython) @@ -76,11 +77,7 @@ repos: rev: v1.2.3 hooks: - id: yesqa - additional_dependencies: - - flake8==3.9.2 - - flake8-comprehensions==3.1.0 - - flake8-bugbear==21.3.2 - - pandas-dev-flaker==0.2.0 + additional_dependencies: *flake8_dependencies - repo: local hooks: - id: pyright diff --git a/scripts/sync_flake8_versions.py b/scripts/sync_flake8_versions.py index cb6bb1eb0986e..370924cdfa199 100644 --- a/scripts/sync_flake8_versions.py +++ b/scripts/sync_flake8_versions.py @@ -68,16 +68,9 @@ def _conda_to_pip_compat(dep): def _validate_additional_dependencies( flake8_additional_dependencies, - yesqa_additional_dependencies, environment_additional_dependencies, ) -> None: for dep in flake8_additional_dependencies: - if dep not in yesqa_additional_dependencies: - sys.stdout.write( - f"Mismatch of '{dep.name}' version between 'flake8' " - "and 'yesqa' in '.pre-commit-config.yaml'\n" - ) - sys.exit(1) if dep not in environment_additional_dependencies: sys.stdout.write( f"Mismatch of '{dep.name}' version between 'enviroment.yml' " @@ -94,13 +87,6 @@ def _validate_revisions(revisions): ) sys.exit(1) - if revisions.yesqa != revisions.pre_commit: - sys.stdout.write( - f"{revisions.name} in 'yesqa' does not match " - "in 'flake8' from 'pre-commit'\n" - ) - sys.exit(1) - def _process_dependencies(deps): for dep in deps: @@ -130,21 +116,12 @@ def get_revisions( else: flake8_additional_dependencies.append(dep) - _, yesqa_hook = _get_repo_hook(repos, "yesqa") - yesqa_additional_dependencies = [] - for dep in _process_dependencies(yesqa_hook.get("additional_dependencies", [])): - if dep.name == "flake8": - flake8_revisions.yesqa = dep - elif dep.name == "pandas-dev-flaker": - pandas_dev_flaker_revisions.yesqa = dep - else: - yesqa_additional_dependencies.append(dep) - environment_dependencies = environment["dependencies"] environment_additional_dependencies = [] for dep in _process_dependencies(environment_dependencies): if dep.name == "flake8": flake8_revisions.environment = dep + environment_additional_dependencies.append(dep) elif dep.name == "pandas-dev-flaker": pandas_dev_flaker_revisions.environment = dep else: @@ -152,7 +129,6 @@ def get_revisions( _validate_additional_dependencies( flake8_additional_dependencies, - yesqa_additional_dependencies, environment_additional_dependencies, )
- [x] closes #43282 - [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 This PR adds: - use of yaml anchors for the `flake8` and `yesqa` hooks - updates to `scripts/sync_flake8_versions.py` since now both `yesqa` and `flake8` hooks have the same additional dependencies declared through a reusable anchor there is no need to check for sync between these two PD. I am not sure this needs a `whatsnew` entry so I did not add it - unless y'all think there should be one
https://api.github.com/repos/pandas-dev/pandas/pulls/44177
2021-10-25T11:55:38Z
2021-10-25T14:04:54Z
2021-10-25T14:04:54Z
2021-10-25T14:08:51Z
PERF: Improve performance in rolling.mean(engine=numba)
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 254a004a37c40..fa4dadde13185 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -426,7 +426,7 @@ Performance improvements - :meth:`SparseArray.min` and :meth:`SparseArray.max` no longer require converting to a dense array (:issue:`43526`) - Indexing into a :class:`SparseArray` with a ``slice`` with ``step=1`` no longer requires converting to a dense array (:issue:`43777`) - Performance improvement in :meth:`SparseArray.take` with ``allow_fill=False`` (:issue:`43654`) -- Performance improvement in :meth:`.Rolling.mean` and :meth:`.Expanding.mean` with ``engine="numba"`` (:issue:`43612`) +- Performance improvement in :meth:`.Rolling.mean`, :meth:`.Expanding.mean`, :meth:`.Rolling.sum`, :meth:`.Expanding.sum` with ``engine="numba"`` (:issue:`43612`, :issue:`44176`) - Improved performance of :meth:`pandas.read_csv` with ``memory_map=True`` when file encoding is UTF-8 (:issue:`43787`) - Performance improvement in :meth:`RangeIndex.sort_values` overriding :meth:`Index.sort_values` (:issue:`43666`) - Performance improvement in :meth:`RangeIndex.insert` (:issue:`43988`) diff --git a/pandas/core/_numba/kernels/__init__.py b/pandas/core/_numba/kernels/__init__.py index eb43de1e0d979..23b0ec5c3d8aa 100644 --- a/pandas/core/_numba/kernels/__init__.py +++ b/pandas/core/_numba/kernels/__init__.py @@ -1,3 +1,4 @@ from pandas.core._numba.kernels.mean_ import sliding_mean +from pandas.core._numba.kernels.sum_ import sliding_sum -__all__ = ["sliding_mean"] +__all__ = ["sliding_mean", "sliding_sum"] diff --git a/pandas/core/_numba/kernels/mean_.py b/pandas/core/_numba/kernels/mean_.py index 32ea505513ed0..8f67dd9b51c06 100644 --- a/pandas/core/_numba/kernels/mean_.py +++ b/pandas/core/_numba/kernels/mean_.py @@ -1,5 +1,5 @@ """ -Numba 1D aggregation kernels that can be shared by +Numba 1D mean kernels that can be shared by * Dataframe / Series * groupby * rolling / expanding @@ -11,20 +11,7 @@ import numba import numpy as np - -@numba.jit(nopython=True, nogil=True, parallel=False) -def is_monotonic_increasing(bounds: np.ndarray) -> bool: - """Check if int64 values are monotonically increasing.""" - n = len(bounds) - if n < 2: - return True - prev = bounds[0] - for i in range(1, n): - cur = bounds[i] - if cur < prev: - return False - prev = cur - return True +from pandas.core._numba.kernels.shared import is_monotonic_increasing @numba.jit(nopython=True, nogil=True, parallel=False) diff --git a/pandas/core/_numba/kernels/shared.py b/pandas/core/_numba/kernels/shared.py new file mode 100644 index 0000000000000..d84e409ca879d --- /dev/null +++ b/pandas/core/_numba/kernels/shared.py @@ -0,0 +1,17 @@ +import numba +import numpy as np + + +@numba.jit(numba.boolean(numba.int64[:]), nopython=True, nogil=True, parallel=False) +def is_monotonic_increasing(bounds: np.ndarray) -> bool: + """Check if int64 values are monotonically increasing.""" + n = len(bounds) + if n < 2: + return True + prev = bounds[0] + for i in range(1, n): + cur = bounds[i] + if cur < prev: + return False + prev = cur + return True diff --git a/pandas/core/_numba/kernels/sum_.py b/pandas/core/_numba/kernels/sum_.py new file mode 100644 index 0000000000000..c2e81b4990ba9 --- /dev/null +++ b/pandas/core/_numba/kernels/sum_.py @@ -0,0 +1,98 @@ +""" +Numba 1D sum kernels that can be shared by +* Dataframe / Series +* groupby +* rolling / expanding + +Mirrors pandas/_libs/window/aggregation.pyx +""" +from __future__ import annotations + +import numba +import numpy as np + +from pandas.core._numba.kernels.shared import is_monotonic_increasing + + +@numba.jit(nopython=True, nogil=True, parallel=False) +def add_sum( + val: float, nobs: int, sum_x: float, compensation: float +) -> tuple[int, float, float]: + if not np.isnan(val): + nobs += 1 + y = val - compensation + t = sum_x + y + compensation = t - sum_x - y + sum_x = t + return nobs, sum_x, compensation + + +@numba.jit(nopython=True, nogil=True, parallel=False) +def remove_sum( + val: float, nobs: int, sum_x: float, compensation: float +) -> tuple[int, float, float]: + if not np.isnan(val): + nobs -= 1 + y = -val - compensation + t = sum_x + y + compensation = t - sum_x - y + sum_x = t + return nobs, sum_x, compensation + + +@numba.jit(nopython=True, nogil=True, parallel=False) +def sliding_sum( + values: np.ndarray, + start: np.ndarray, + end: np.ndarray, + min_periods: int, +) -> np.ndarray: + N = len(start) + nobs = 0 + sum_x = 0.0 + compensation_add = 0.0 + compensation_remove = 0.0 + + is_monotonic_increasing_bounds = is_monotonic_increasing( + start + ) and is_monotonic_increasing(end) + + output = np.empty(N, dtype=np.float64) + + for i in range(N): + s = start[i] + e = end[i] + if i == 0 or not is_monotonic_increasing_bounds: + for j in range(s, e): + val = values[j] + nobs, sum_x, compensation_add = add_sum( + val, nobs, sum_x, compensation_add + ) + else: + for j in range(start[i - 1], s): + val = values[j] + nobs, sum_x, compensation_remove = remove_sum( + val, nobs, sum_x, compensation_remove + ) + + for j in range(end[i - 1], e): + val = values[j] + nobs, sum_x, compensation_add = add_sum( + val, nobs, sum_x, compensation_add + ) + + if nobs == 0 == nobs: + result = 0.0 + elif nobs >= min_periods: + result = sum_x + else: + result = np.nan + + output[i] = result + + if not is_monotonic_increasing_bounds: + nobs = 0 + sum_x = 0.0 + compensation_remove = 0.0 + + return output diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 274c78c30aec4..b04aab3755b91 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1345,15 +1345,16 @@ def sum( if maybe_use_numba(engine): if self.method == "table": func = generate_manual_numpy_nan_agg_with_axis(np.nansum) + return self.apply( + func, + raw=True, + engine=engine, + engine_kwargs=engine_kwargs, + ) else: - func = np.nansum + from pandas.core._numba.kernels import sliding_sum - return self.apply( - func, - raw=True, - engine=engine, - engine_kwargs=engine_kwargs, - ) + return self._numba_apply(sliding_sum, "rolling_sum", engine_kwargs) window_func = window_aggregations.roll_sum return self._apply(window_func, name="sum", **kwargs) diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index d47b3e856cb25..9fd4bd422178a 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -59,7 +59,7 @@ def test_numba_vs_cython_rolling_methods( expected = getattr(roll, method)(engine="cython") # Check the cache - if method != "mean": + if method not in ("mean", "sum"): assert ( getattr(np, f"nan{method}"), "Rolling_apply_single", @@ -67,7 +67,9 @@ def test_numba_vs_cython_rolling_methods( tm.assert_equal(result, expected) - @pytest.mark.parametrize("data", [DataFrame(np.eye(5)), Series(range(5))]) + @pytest.mark.parametrize( + "data", [DataFrame(np.eye(5)), Series(range(5), name="foo")] + ) def test_numba_vs_cython_expanding_methods( self, data, nogil, parallel, nopython, arithmetic_numba_supported_operators ): @@ -82,7 +84,7 @@ def test_numba_vs_cython_expanding_methods( expected = getattr(expand, method)(engine="cython") # Check the cache - if method != "mean": + if method not in ("mean", "sum"): assert ( getattr(np, f"nan{method}"), "Expanding_apply_single",
- [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 This also starts to add a shared aggregation function (sum) that can shared between rolling/groupby/DataFrame when using the numba engine. ``` df = pd.DataFrame(np.ones((10000, 1000))) roll = df.rolling(10) roll.sum(engine="numba", engine_kwargs={"nopython": True, "nogil": True, "parallel": True}) %timeit roll.sum(engine="numba", engine_kwargs={"nopython": True, "nogil": True, "parallel": True}) 211 ms ± 12.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) <- PR 424 ms ± 9.23 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) <- master ```
https://api.github.com/repos/pandas-dev/pandas/pulls/44176
2021-10-25T04:43:08Z
2021-10-28T02:07:11Z
2021-10-28T02:07:11Z
2021-10-29T02:32:13Z
TST: tests using invalid_scalar fixture
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index bed64efc690ec..0e413f81834b2 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -56,6 +56,7 @@ is_datetime64tz_dtype, is_dtype_equal, is_integer, + is_list_like, is_object_dtype, is_scalar, is_string_dtype, @@ -927,6 +928,14 @@ def __getitem__( indices = np.arange(len(self), dtype=np.int32)[key] return self.take(indices) + elif not is_list_like(key): + # e.g. "foo" or 2.5 + # exception message copied from numpy + raise IndexError( + r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis " + r"(`None`) and integer or boolean arrays are valid indices" + ) + else: # TODO: I think we can avoid densifying when masking a # boolean SparseArray with another. Need to look at the diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 4e3bd05d2cc8d..58b4a0c9f9242 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -322,6 +322,13 @@ def __getitem__( elif item[1] is Ellipsis: item = item[0] + if is_scalar(item) and not is_integer(item): + # e.g. "foo" or 2.5 + # exception message copied from numpy + raise IndexError( + r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis " + r"(`None`) and integer or boolean arrays are valid indices" + ) # We are not an array indexer, so maybe e.g. a slice or integer # indexer. We dispatch to pyarrow. value = self._data[item] @@ -392,6 +399,11 @@ def _cmp_method(self, other, op): # TODO(ARROW-9429): Add a .to_numpy() to ChunkedArray return BooleanArray._from_sequence(result.to_pandas().values) + def insert(self, loc: int, item): + if not isinstance(item, str) and item is not libmissing.NA: + raise TypeError("Scalar must be NA or str") + return super().insert(loc, item) + def __setitem__(self, key: int | slice | np.ndarray, value: Any) -> None: """Set one or more values inplace. diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 7efd3bdb6920a..73bff29305f20 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -120,6 +120,33 @@ def test_getitem_scalar(self, data): result = pd.Series(data)[0] assert isinstance(result, data.dtype.type) + def test_getitem_invalid(self, data): + # TODO: box over scalar, [scalar], (scalar,)? + + msg = ( + r"only integers, slices \(`:`\), ellipsis \(`...`\), numpy.newaxis " + r"\(`None`\) and integer or boolean arrays are valid indices" + ) + with pytest.raises(IndexError, match=msg): + data["foo"] + with pytest.raises(IndexError, match=msg): + data[2.5] + + ub = len(data) + msg = "|".join( + [ + "list index out of range", # json + "index out of bounds", # pyarrow + "Out of bounds access", # Sparse + f"index {ub+1} is out of bounds for axis 0 with size {ub}", + f"index -{ub+1} is out of bounds for axis 0 with size {ub}", + ] + ) + with pytest.raises(IndexError, match=msg): + data[ub + 1] + with pytest.raises(IndexError, match=msg): + data[-ub - 1] + def test_getitem_scalar_na(self, data_missing, na_cmp, na_value): result = data_missing[0] assert na_cmp(result, na_value) diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index 0392ea794237c..a2d100db81a2c 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -367,3 +367,11 @@ def test_delitem_series(self, data): expected = ser[taker] del ser[1] self.assert_series_equal(ser, expected) + + def test_setitem_invalid(self, data, invalid_scalar): + msg = "" # messages vary by subclass, so we do not test it + with pytest.raises((ValueError, TypeError), match=msg): + data[0] = invalid_scalar + + with pytest.raises((ValueError, TypeError), match=msg): + data[:] = invalid_scalar diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 2eef828288e59..309d865bc7452 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -32,7 +32,10 @@ from pandas._typing import type_t from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike -from pandas.core.dtypes.common import pandas_dtype +from pandas.core.dtypes.common import ( + is_list_like, + pandas_dtype, +) import pandas as pd from pandas.api.extensions import ( @@ -103,6 +106,13 @@ def __getitem__(self, item): elif isinstance(item, slice): # slice return type(self)(self.data[item]) + elif not is_list_like(item): + # e.g. "foo" or 2.5 + # exception message copied from numpy + raise IndexError( + r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis " + r"(`None`) and integer or boolean arrays are valid indices" + ) else: item = pd.api.indexers.check_array_indexer(self, item) if is_bool_dtype(item.dtype): diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 0e3e26e7e9500..e60f7769270bd 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -363,6 +363,11 @@ def test_concat(self, data, in_frame): class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): + @skip_nested + def test_setitem_invalid(self, data, invalid_scalar): + # object dtype can hold anything, so doesn't raise + super().test_setitem_invalid(data, invalid_scalar) + @skip_nested def test_setitem_sequence_broadcasts(self, data, box_in_series): # ValueError: cannot set using a list-like indexer with a different diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index 06b07968f949e..af86c359c4c00 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -160,13 +160,6 @@ def test_value_counts(self, all_data, dropna): def test_value_counts_with_normalize(self, data): pass - def test_insert_invalid(self, data, invalid_scalar, request): - if data.dtype.storage == "pyarrow": - mark = pytest.mark.xfail(reason="casts invalid_scalar to string") - request.node.add_marker(mark) - - super().test_insert_invalid(data, invalid_scalar) - class TestCasting(base.BaseCastingTests): pass diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 7566c17eda9e6..ea76a4b4b1cfc 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -403,6 +403,33 @@ def test_insert_base(self, index): # test 0th element assert index[0:4].equals(result.insert(0, index[0])) + def test_insert_out_of_bounds(self, index): + # TypeError/IndexError matches what np.insert raises in these cases + + if len(index) > 0: + err = TypeError + else: + err = IndexError + if len(index) == 0: + # 0 vs 0.5 in error message varies with numpy version + msg = "index (0|0.5) is out of bounds for axis 0 with size 0" + else: + msg = "slice indices must be integers or None or have an __index__ method" + with pytest.raises(err, match=msg): + index.insert(0.5, "foo") + + msg = "|".join( + [ + r"index -?\d+ is out of bounds for axis 0 with size \d+", + "loc must be an integer between", + ] + ) + with pytest.raises(IndexError, match=msg): + index.insert(len(index) + 1, 1) + + with pytest.raises(IndexError, match=msg): + index.insert(-len(index) - 1, 1) + def test_delete_base(self, index): if not len(index): return
- [ ] 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/44175
2021-10-25T02:20:29Z
2021-10-30T23:52:25Z
2021-10-30T23:52:25Z
2021-10-31T16:18:48Z
CLN/TST: address TODOs/FIXMES #2
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 07cef290c8919..8a2ba69a61ed9 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1517,8 +1517,11 @@ def _cython_agg_general( if numeric_only: if is_ser and not is_numeric_dtype(self._selected_obj.dtype): # GH#41291 match Series behavior + kwd_name = "numeric_only" + if how in ["any", "all"]: + kwd_name = "bool_only" raise NotImplementedError( - f"{type(self).__name__}.{how} does not implement numeric_only." + f"{type(self).__name__}.{how} does not implement {kwd_name}." ) elif not is_ser: data = data.get_numeric_data(copy=False) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 8534d4f6c9e59..41ef824afc2a7 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -600,9 +600,7 @@ def _intersection(self, other: Index, sort=False): new_index = new_index[::-1] if sort is None: - # TODO: can revert to just `if sort is None` after GH#43666 - if new_index.step < 0: - new_index = new_index[::-1] + new_index = new_index.sort_values() return new_index diff --git a/pandas/core/series.py b/pandas/core/series.py index 20e68742e4075..9795e1f7141ee 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4169,7 +4169,7 @@ def map(self, arg, na_action=None) -> Series: 3 I am a rabbit dtype: object """ - new_values = super()._map_values(arg, na_action=na_action) + new_values = self._map_values(arg, na_action=na_action) return self._constructor(new_values, index=self.index).__finalize__( self, method="map" ) @@ -4396,8 +4396,11 @@ def _reduce( else: # dispatch to numpy arrays if numeric_only: + kwd_name = "numeric_only" + if name in ["any", "all"]: + kwd_name = "bool_only" raise NotImplementedError( - f"Series.{name} does not implement numeric_only." + f"Series.{name} does not implement {kwd_name}." ) with np.errstate(all="ignore"): return op(delegate, skipna=skipna, **kwds) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index e9b4ceafddfd5..461dbe5575022 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -1,5 +1,4 @@ import decimal -import math import operator import numpy as np @@ -70,54 +69,7 @@ def data_for_grouping(): return DecimalArray([b, b, na, na, a, a, b, c]) -class BaseDecimal: - @classmethod - def assert_series_equal(cls, left, right, *args, **kwargs): - def convert(x): - # need to convert array([Decimal(NaN)], dtype='object') to np.NaN - # because Series[object].isnan doesn't recognize decimal(NaN) as - # NA. - try: - return math.isnan(x) - except TypeError: - return False - - if left.dtype == "object": - left_na = left.apply(convert) - else: - left_na = left.isna() - if right.dtype == "object": - right_na = right.apply(convert) - else: - right_na = right.isna() - - tm.assert_series_equal(left_na, right_na) - return tm.assert_series_equal(left[~left_na], right[~right_na], *args, **kwargs) - - @classmethod - def assert_frame_equal(cls, left, right, *args, **kwargs): - # TODO(EA): select_dtypes - tm.assert_index_equal( - left.columns, - right.columns, - exact=kwargs.get("check_column_type", "equiv"), - check_names=kwargs.get("check_names", True), - check_exact=kwargs.get("check_exact", False), - check_categorical=kwargs.get("check_categorical", True), - obj=f"{kwargs.get('obj', 'DataFrame')}.columns", - ) - - decimals = (left.dtypes == "decimal").index - - for col in decimals: - cls.assert_series_equal(left[col], right[col], *args, **kwargs) - - left = left.drop(columns=decimals) - right = right.drop(columns=decimals) - tm.assert_frame_equal(left, right, *args, **kwargs) - - -class TestDtype(BaseDecimal, base.BaseDtypeTests): +class TestDtype(base.BaseDtypeTests): def test_hashable(self, dtype): pass @@ -129,19 +81,19 @@ def test_infer_dtype(self, data, data_missing, skipna): assert infer_dtype(data_missing, skipna=skipna) == "unknown-array" -class TestInterface(BaseDecimal, base.BaseInterfaceTests): +class TestInterface(base.BaseInterfaceTests): pass -class TestConstructors(BaseDecimal, base.BaseConstructorsTests): +class TestConstructors(base.BaseConstructorsTests): pass -class TestReshaping(BaseDecimal, base.BaseReshapingTests): +class TestReshaping(base.BaseReshapingTests): pass -class TestGetitem(BaseDecimal, base.BaseGetitemTests): +class TestGetitem(base.BaseGetitemTests): def test_take_na_value_other_decimal(self): arr = DecimalArray([decimal.Decimal("1.0"), decimal.Decimal("2.0")]) result = arr.take([0, -1], allow_fill=True, fill_value=decimal.Decimal("-1.0")) @@ -149,7 +101,7 @@ def test_take_na_value_other_decimal(self): self.assert_extension_array_equal(result, expected) -class TestMissing(BaseDecimal, base.BaseMissingTests): +class TestMissing(base.BaseMissingTests): pass @@ -175,7 +127,7 @@ class TestBooleanReduce(Reduce, base.BaseBooleanReduceTests): pass -class TestMethods(BaseDecimal, base.BaseMethodsTests): +class TestMethods(base.BaseMethodsTests): @pytest.mark.parametrize("dropna", [True, False]) def test_value_counts(self, all_data, dropna, request): all_data = all_data[:10] @@ -200,20 +152,20 @@ def test_value_counts_with_normalize(self, data): return super().test_value_counts_with_normalize(data) -class TestCasting(BaseDecimal, base.BaseCastingTests): +class TestCasting(base.BaseCastingTests): pass -class TestGroupby(BaseDecimal, base.BaseGroupbyTests): +class TestGroupby(base.BaseGroupbyTests): def test_groupby_agg_extension(self, data_for_grouping): super().test_groupby_agg_extension(data_for_grouping) -class TestSetitem(BaseDecimal, base.BaseSetitemTests): +class TestSetitem(base.BaseSetitemTests): pass -class TestPrinting(BaseDecimal, base.BasePrintingTests): +class TestPrinting(base.BasePrintingTests): def test_series_repr(self, data): # Overriding this base test to explicitly test that # the custom _formatter is used @@ -282,7 +234,7 @@ def test_astype_dispatches(frame): assert result.dtype.context.prec == ctx.prec -class TestArithmeticOps(BaseDecimal, base.BaseArithmeticOpsTests): +class TestArithmeticOps(base.BaseArithmeticOpsTests): def check_opname(self, s, op_name, other, exc=None): super().check_opname(s, op_name, other, exc=None) @@ -313,7 +265,7 @@ def _check_divmod_op(self, s, op, other, exc=NotImplementedError): super()._check_divmod_op(s, op, other, exc=None) -class TestComparisonOps(BaseDecimal, base.BaseComparisonOpsTests): +class TestComparisonOps(base.BaseComparisonOpsTests): def test_compare_scalar(self, data, all_compare_operators): op_name = all_compare_operators s = pd.Series(data) diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index 9df5f79aa7d19..d8511581f0e94 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -211,7 +211,7 @@ def test_shift_axis1_multiple_blocks_with_int_fill(self): @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_frame): - # TODO: remove this test when tshift deprecation is enforced + # TODO(2.0): remove this test when tshift deprecation is enforced # PeriodIndex ps = tm.makePeriodFrame() diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 704af61ee2390..1bb4b24266de0 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2508,7 +2508,7 @@ def check_views(): # TODO: we can call check_views if we stop consolidating # in setitem_with_indexer - # FIXME: until GH#35417, iloc.setitem into EA values does not preserve + # FIXME(GH#35417): until GH#35417, iloc.setitem into EA values does not preserve # view, so we have to check in the other direction # df.iloc[0, 2] = 0 # if not copy: @@ -2522,7 +2522,7 @@ def check_views(): else: assert a[0] == a.dtype.type(1) assert b[0] == b.dtype.type(3) - # FIXME: enable after GH#35417 + # FIXME(GH#35417): enable after GH#35417 # assert c[0] == 1 assert df.iloc[0, 2] == 1 else: diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index a7f6c47db916d..3a8ae03015628 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -929,13 +929,11 @@ def test_all_any_params(self): with tm.assert_produces_warning(FutureWarning): s.all(bool_only=True, level=0) - # bool_only is not implemented alone. - # TODO GH38810 change this error message to: - # "Series.any does not implement bool_only" - msg = "Series.any does not implement numeric_only" + # GH#38810 bool_only is not implemented alone. + msg = "Series.any does not implement bool_only" with pytest.raises(NotImplementedError, match=msg): s.any(bool_only=True) - msg = "Series.all does not implement numeric_only." + msg = "Series.all does not implement bool_only." with pytest.raises(NotImplementedError, match=msg): s.all(bool_only=True) diff --git a/pandas/tests/series/methods/test_rename.py b/pandas/tests/series/methods/test_rename.py index e00e9a894d340..2930c657eb3b2 100644 --- a/pandas/tests/series/methods/test_rename.py +++ b/pandas/tests/series/methods/test_rename.py @@ -22,11 +22,13 @@ def test_rename(self, datetime_series): renamed2 = ts.rename(rename_dict) tm.assert_series_equal(renamed, renamed2) + def test_rename_partial_dict(self): # partial dict - s = Series(np.arange(4), index=["a", "b", "c", "d"], dtype="int64") - renamed = s.rename({"b": "foo", "d": "bar"}) + ser = Series(np.arange(4), index=["a", "b", "c", "d"], dtype="int64") + renamed = ser.rename({"b": "foo", "d": "bar"}) tm.assert_index_equal(renamed.index, Index(["a", "foo", "c", "bar"])) + def test_rename_retain_index_name(self): # index with name renamer = Series( np.arange(4), index=Index(["a", "b", "c", "d"], name="name"), dtype="int64" @@ -35,38 +37,38 @@ def test_rename(self, datetime_series): assert renamed.index.name == renamer.index.name def test_rename_by_series(self): - s = Series(range(5), name="foo") + ser = Series(range(5), name="foo") renamer = Series({1: 10, 2: 20}) - result = s.rename(renamer) + result = ser.rename(renamer) expected = Series(range(5), index=[0, 10, 20, 3, 4], name="foo") tm.assert_series_equal(result, expected) def test_rename_set_name(self): - s = Series(range(4), index=list("abcd")) + ser = Series(range(4), index=list("abcd")) for name in ["foo", 123, 123.0, datetime(2001, 11, 11), ("foo",)]: - result = s.rename(name) + result = ser.rename(name) assert result.name == name - tm.assert_numpy_array_equal(result.index.values, s.index.values) - assert s.name is None + tm.assert_numpy_array_equal(result.index.values, ser.index.values) + assert ser.name is None def test_rename_set_name_inplace(self): - s = Series(range(3), index=list("abc")) + ser = Series(range(3), index=list("abc")) for name in ["foo", 123, 123.0, datetime(2001, 11, 11), ("foo",)]: - s.rename(name, inplace=True) - assert s.name == name + ser.rename(name, inplace=True) + assert ser.name == name exp = np.array(["a", "b", "c"], dtype=np.object_) - tm.assert_numpy_array_equal(s.index.values, exp) + tm.assert_numpy_array_equal(ser.index.values, exp) def test_rename_axis_supported(self): # Supporting axis for compatibility, detailed in GH-18589 - s = Series(range(5)) - s.rename({}, axis=0) - s.rename({}, axis="index") - # FIXME: dont leave commenred-out + ser = Series(range(5)) + ser.rename({}, axis=0) + ser.rename({}, axis="index") + # FIXME: dont leave commented-out # TODO: clean up shared index validation # with pytest.raises(ValueError, match="No axis named 5"): - # s.rename({}, axis=5) + # ser.rename({}, axis=5) def test_rename_inplace(self, datetime_series): renamer = lambda x: x.strftime("%Y%m%d") @@ -81,8 +83,8 @@ class MyIndexer: pass ix = MyIndexer() - s = Series([1, 2, 3]).rename(ix) - assert s.name is ix + ser = Series([1, 2, 3]).rename(ix) + assert ser.name is ix def test_rename_with_custom_indexer_inplace(self): # GH 27814 @@ -90,15 +92,15 @@ class MyIndexer: pass ix = MyIndexer() - s = Series([1, 2, 3]) - s.rename(ix, inplace=True) - assert s.name is ix + ser = Series([1, 2, 3]) + ser.rename(ix, inplace=True) + assert ser.name is ix def test_rename_callable(self): # GH 17407 - s = Series(range(1, 6), index=Index(range(2, 7), name="IntIndex")) - result = s.rename(str) - expected = s.rename(lambda i: str(i)) + ser = Series(range(1, 6), index=Index(range(2, 7), name="IntIndex")) + result = ser.rename(str) + expected = ser.rename(lambda i: str(i)) tm.assert_series_equal(result, expected) assert result.name == expected.name @@ -111,8 +113,8 @@ def test_rename_series_with_multiindex(self): ] index = MultiIndex.from_arrays(arrays, names=["first", "second"]) - s = Series(np.ones(5), index=index) - result = s.rename(index={"one": "yes"}, level="second", errors="raise") + ser = Series(np.ones(5), index=index) + result = ser.rename(index={"one": "yes"}, level="second", errors="raise") arrays_expected = [ ["bar", "baz", "baz", "foo", "qux"], diff --git a/pandas/tests/series/methods/test_shift.py b/pandas/tests/series/methods/test_shift.py index df270f3e0f85c..4fb378720d89d 100644 --- a/pandas/tests/series/methods/test_shift.py +++ b/pandas/tests/series/methods/test_shift.py @@ -202,7 +202,7 @@ def test_shift_dst(self): @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_series): - # TODO: remove this test when tshift deprecation is enforced + # TODO(2.0): remove this test when tshift deprecation is enforced # PeriodIndex ps = tm.makePeriodSeries() diff --git a/pandas/tests/strings/test_api.py b/pandas/tests/strings/test_api.py index 6cbf2dd606692..974ecc152f17b 100644 --- a/pandas/tests/strings/test_api.py +++ b/pandas/tests/strings/test_api.py @@ -71,7 +71,6 @@ def test_api_per_method( inferred_dtype, values = any_allowed_skipna_inferred_dtype method_name, args, kwargs = any_string_method - # TODO: get rid of these xfails reason = None if box is Index and values.size == 0: if method_name in ["partition", "rpartition"] and kwargs.get("expand", True):
- [ ] 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/44174
2021-10-25T00:38:44Z
2021-10-25T17:18:56Z
2021-10-25T17:18:55Z
2021-10-25T17:20:05Z
TST: Move a consistency ewm test to test_ewm.py
diff --git a/pandas/tests/window/moments/test_moments_consistency_ewm.py b/pandas/tests/window/moments/test_moments_consistency_ewm.py index b41d2ec23a52d..800ee2164693b 100644 --- a/pandas/tests/window/moments/test_moments_consistency_ewm.py +++ b/pandas/tests/window/moments/test_moments_consistency_ewm.py @@ -9,15 +9,6 @@ import pandas._testing as tm -@pytest.mark.parametrize("func", ["cov", "corr"]) -def test_ewm_pairwise_cov_corr(func, frame): - result = getattr(frame.ewm(span=10, min_periods=5), func)() - result = result.loc[(slice(None), 1), 5] - result.index = result.index.droplevel(1) - expected = getattr(frame[1].ewm(span=10, min_periods=5), func)(frame[5]) - tm.assert_series_equal(result, expected, check_names=False) - - def create_mock_weights(obj, com, adjust, ignore_na): if isinstance(obj, DataFrame): if not len(obj.columns): diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index 21c0099bbc0e6..23c3a0ef27fef 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -657,3 +657,12 @@ def test_ewm_alpha_arg(series): s.ewm(span=10.0, alpha=0.5) with pytest.raises(ValueError, match=msg): s.ewm(halflife=10.0, alpha=0.5) + + +@pytest.mark.parametrize("func", ["cov", "corr"]) +def test_ewm_pairwise_cov_corr(func, frame): + result = getattr(frame.ewm(span=10, min_periods=5), func)() + result = result.loc[(slice(None), 1), 5] + result.index = result.index.droplevel(1) + expected = getattr(frame[1].ewm(span=10, min_periods=5), func)(frame[5]) + tm.assert_series_equal(result, expected, check_names=False)
- [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 Since some tests are not running on windows/moments (#37535), moving a "consistency" ewm tests to the `test_ewm.py`.
https://api.github.com/repos/pandas-dev/pandas/pulls/44171
2021-10-24T22:08:32Z
2021-10-25T12:33:56Z
2021-10-25T12:33:56Z
2021-10-25T18:27:41Z
REF: share ExtensionIndex.insert-> Index.insert
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index f5fbd4cc4a7fc..38553bc1be8d6 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -37,6 +37,7 @@ needs_i8_conversion, ) from pandas.core.dtypes.dtypes import ( + CategoricalDtype, ExtensionDtype, IntervalDtype, PeriodDtype, @@ -641,5 +642,8 @@ def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool: elif isinstance(dtype, IntervalDtype): return lib.is_float(obj) or obj is None or obj is libmissing.NA + elif isinstance(dtype, CategoricalDtype): + return is_valid_na_for_dtype(obj, dtype.categories.dtype) + # fallback, default to allowing NaN, None, NA, NaT return not isinstance(obj, (np.datetime64, np.timedelta64, Decimal)) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 05047540c6ccd..e82bd61938f15 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6432,14 +6432,21 @@ def insert(self, loc: int, item) -> Index: if is_valid_na_for_dtype(item, self.dtype) and self.dtype != object: item = self._na_value + arr = self._values + try: - item = self._validate_fill_value(item) - except TypeError: + if isinstance(arr, ExtensionArray): + res_values = arr.insert(loc, item) + return type(self)._simple_new(res_values, name=self.name) + else: + item = self._validate_fill_value(item) + except (TypeError, ValueError): + # e.g. trying to insert an integer into a DatetimeIndex + # We cannot keep the same dtype, so cast to the (often object) + # minimal shared dtype before doing the insert. dtype = self._find_common_type_compat(item) return self.astype(dtype).insert(loc, item) - arr = self._values - if arr.dtype != object or not isinstance( item, (tuple, np.datetime64, np.timedelta64) ): diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index ccd18f54da327..7c7f1b267b5be 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -134,31 +134,6 @@ class ExtensionIndex(Index): # --------------------------------------------------------------------- - def insert(self, loc: int, item) -> Index: - """ - Make new Index inserting new item at location. Follows - Python list.append semantics for negative values. - - Parameters - ---------- - loc : int - item : object - - Returns - ------- - new_index : Index - """ - try: - result = self._data.insert(loc, item) - except (ValueError, TypeError): - # e.g. trying to insert an integer into a DatetimeIndex - # We cannot keep the same dtype, so cast to the (often object) - # minimal shared dtype before doing the insert. - dtype = self._find_common_type_compat(item) - return self.astype(dtype).insert(loc, item) - else: - return type(self)._simple_new(result, name=self.name) - def _validate_fill_value(self, value): """ Convert value to be insertable to underlying array. diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index bf68c4b79bcea..55d0e5e73418e 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -18,6 +18,7 @@ is_scalar, ) from pandas.core.dtypes.dtypes import ( + CategoricalDtype, DatetimeTZDtype, IntervalDtype, PeriodDtype, @@ -739,3 +740,11 @@ def test_is_valid_na_for_dtype_interval(self): dtype = IntervalDtype("datetime64[ns]", "both") assert not is_valid_na_for_dtype(NaT, dtype) + + def test_is_valid_na_for_dtype_categorical(self): + dtype = CategoricalDtype(categories=[0, 1, 2]) + assert is_valid_na_for_dtype(np.nan, dtype) + + assert not is_valid_na_for_dtype(NaT, dtype) + assert not is_valid_na_for_dtype(np.datetime64("NaT", "ns"), dtype) + assert not is_valid_na_for_dtype(np.timedelta64("NaT", "ns"), dtype)
- [ ] 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 Prelim to #43930
https://api.github.com/repos/pandas-dev/pandas/pulls/44170
2021-10-24T21:39:28Z
2021-10-24T23:26:20Z
2021-10-24T23:26:20Z
2021-10-25T00:06:42Z
WEB: Update institutional sponsors list
diff --git a/web/pandas/config.yml b/web/pandas/config.yml index 82eb023f185c8..9165456d55897 100644 --- a/web/pandas/config.yml +++ b/web/pandas/config.yml @@ -112,26 +112,21 @@ sponsors: url: https://numfocus.org/ logo: /static/img/partners/numfocus.svg kind: numfocus - - name: "Anaconda" - url: https://www.anaconda.com/ - logo: /static/img/partners/anaconda.svg - kind: partner - description: "Tom Augspurger, Brock Mendel" - name: "Two Sigma" url: https://www.twosigma.com/ logo: /static/img/partners/two_sigma.svg kind: partner description: "Phillip Cloud, Jeff Reback" - - name: "RStudio" - url: https://www.rstudio.com/ - logo: /static/img/partners/r_studio.svg - kind: partner - description: "Wes McKinney" - name: "Ursa Labs" url: https://ursalabs.org/ logo: /static/img/partners/ursa_labs.svg kind: partner description: "Wes McKinney, Joris Van den Bossche" + - name: "d-fine GmbH" + url: https://www.d-fine.com/en/ + logo: /static/img/partners/dfine.svg + kind: partner + description: "Patrick Hoefler" - name: "Tidelift" url: https://tidelift.com logo: /static/img/partners/tidelift.svg @@ -153,3 +148,12 @@ sponsors: - name: "Paris-Saclay Center for Data Science" url: https://www.datascience-paris-saclay.fr/ kind: partner + - name: "Anaconda" + url: https://www.anaconda.com/ + logo: /static/img/partners/anaconda.svg + kind: partner + - name: "RStudio" + url: https://www.rstudio.com/ + logo: /static/img/partners/r_studio.svg + kind: partner + description: "Wes McKinney" diff --git a/web/pandas/static/img/partners/dfine.svg b/web/pandas/static/img/partners/dfine.svg new file mode 100755 index 0000000000000..d892dded33322 --- /dev/null +++ b/web/pandas/static/img/partners/dfine.svg @@ -0,0 +1 @@ +<svg id="Ebene_1" data-name="Ebene 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 343.18 104.19"><defs><style>.cls-1,.cls-2{fill:#003e52;}.cls-1{fill-rule:evenodd;}</style></defs><title>dfine_dunkelblau_cmyk</title><path class="cls-1" d="M138.15,438.72c0-12.41,3.4-30,16-30,11.38,0,15.37,16,15.37,30,0,12.57-3.39,30-15.37,30-13.59,0-16-17.14-16-30Zm31.33,34H181V370l-22.76,3.55v2.51c4.29.44,11.23.89,11.23,9.61v29h-.29c-2.07-4.13-7.69-11.38-17-11.38-20.54,0-27.19,17.44-27.19,35.47s6.65,35.47,27.19,35.47c8.28,0,15.67-6.94,17-10.93h.29v9.42Z" transform="translate(-125 -370)"/><polygon class="cls-2" points="67.52 39.71 67.52 35.67 155.01 35.67 155.01 39.71 67.52 39.71 67.52 39.71"/><path class="cls-1" d="M314.28,472.68V403.25l-22.77,3.55v2.51c4.44.3,11.24.74,11.24,9.61v53.76Z" transform="translate(-125 -370)"/><path class="cls-2" d="M466.26,466.77v4.73c-3.54,1.33-8.56,2.66-17.58,2.66-22.9,0-35.75-12.56-35.75-37.38,0-21.57,8.72-33.54,30-33.54,13.3,0,25.26,7.39,25.26,24.53V431h-43c0,12.41,6.06,37.67,30.73,37.67,3.4,0,7.39-.44,10.34-1.92Zm-41.07-40.63H455c0-7.83-2.66-18-14-18s-15.81,12.56-15.81,18ZM343.5,472.68V418.9c0-8.86-6.95-9.3-11.23-9.6v-2.51L355,403.24v19.5h.3c2.06-5.46,8.71-19.5,23.34-19.5,15.66,0,17.14,8.57,17.14,22.31v47.13H384.27V428.8c0-12.7-.14-18.47-9.89-18.47-8.72,0-19.36,16.7-19.36,30.73v31.62Z" transform="translate(-125 -370)"/><path class="cls-2" d="M248.56,401.63v-3.4c0-19.51,5.32-28.23,27.93-28.23,7.24,0,16.26,2.81,16.26,8.87a6.74,6.74,0,0,1-7.1,7.09c-9.31,0-4.87-11.08-14.33-11.08-11.23,0-11.23,9.9-11.23,21v5.77Zm11.53,71.05H248.55V413.75h11.53v58.93Z" transform="translate(-125 -370)"/><path class="cls-2" d="M301.07,381a7.47,7.47,0,1,1,7.47,7.47,7.47,7.47,0,0,1-7.47-7.47Z" transform="translate(-125 -370)"/></svg> \ No newline at end of file
Makes the lists consistent with the governance docs and adds d-fine cc @MarcoGorelli Would you like to add gousto too?
https://api.github.com/repos/pandas-dev/pandas/pulls/44169
2021-10-24T20:47:32Z
2021-10-24T23:26:35Z
2021-10-24T23:26:35Z
2021-11-13T19:32:43Z
TST: Adding tests for checking Boolean series and df as indexes for series
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 6c3587c7eeada..d77f831bee8bc 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -377,3 +377,17 @@ def test_frozenset_index(): assert s[idx1] == 2 s[idx1] = 3 assert s[idx1] == 3 + + +def test_boolean_index(): + # GH18579 + s1 = Series([1, 2, 3], index=[4, 5, 6]) + s2 = Series([1, 3, 2], index=s1 == 2) + tm.assert_series_equal(Series([1, 3, 2], [False, True, False]), s2) + + +def test_index_ndim_gt_1_raises(): + # GH18579 + df = DataFrame([[1, 2], [3, 4], [5, 6]], index=[3, 6, 9]) + with pytest.raises(ValueError, match="Index data must be 1-dimensional"): + Series([1, 3, 2], index=df)
- [ ] closes #18579 - [ ] 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 - [ ] After discussion in #18579 the current tests were suggested
https://api.github.com/repos/pandas-dev/pandas/pulls/44165
2021-10-24T15:37:53Z
2021-10-24T22:07:43Z
2021-10-24T22:07:43Z
2021-10-24T22:07:47Z
TST: Move some consistency rolling tests to misc rolling functions
diff --git a/pandas/tests/window/moments/test_moments_consistency_rolling.py b/pandas/tests/window/moments/test_moments_consistency_rolling.py index 7ec5846ef4acf..bda8ba05d4024 100644 --- a/pandas/tests/window/moments/test_moments_consistency_rolling.py +++ b/pandas/tests/window/moments/test_moments_consistency_rolling.py @@ -1,17 +1,7 @@ -from datetime import datetime - import numpy as np import pytest -import pandas.util._test_decorators as td - -from pandas import ( - DataFrame, - DatetimeIndex, - Index, - MultiIndex, - Series, -) +from pandas import Series import pandas._testing as tm @@ -24,62 +14,6 @@ def _rolling_consistency_cases(): yield window, min_periods, center -# binary moments -def test_rolling_cov(series): - A = series - B = A + np.random.randn(len(A)) - - result = A.rolling(window=50, min_periods=25).cov(B) - tm.assert_almost_equal(result[-1], np.cov(A[-50:], B[-50:])[0, 1]) - - -def test_rolling_corr(series): - A = series - B = A + np.random.randn(len(A)) - - result = A.rolling(window=50, min_periods=25).corr(B) - tm.assert_almost_equal(result[-1], np.corrcoef(A[-50:], B[-50:])[0, 1]) - - # test for correct bias correction - a = tm.makeTimeSeries() - b = tm.makeTimeSeries() - a[:5] = np.nan - b[:10] = np.nan - - result = a.rolling(window=len(a), min_periods=1).corr(b) - tm.assert_almost_equal(result[-1], a.corr(b)) - - -@pytest.mark.parametrize("func", ["cov", "corr"]) -def test_rolling_pairwise_cov_corr(func, frame): - result = getattr(frame.rolling(window=10, min_periods=5), func)() - result = result.loc[(slice(None), 1), 5] - result.index = result.index.droplevel(1) - expected = getattr(frame[1].rolling(window=10, min_periods=5), func)(frame[5]) - tm.assert_series_equal(result, expected, check_names=False) - - -@pytest.mark.parametrize("method", ["corr", "cov"]) -def test_flex_binary_frame(method, frame): - series = frame[1] - - res = getattr(series.rolling(window=10), method)(frame) - res2 = getattr(frame.rolling(window=10), method)(series) - exp = frame.apply(lambda x: getattr(series.rolling(window=10), method)(x)) - - tm.assert_frame_equal(res, exp) - tm.assert_frame_equal(res2, exp) - - frame2 = frame.copy() - frame2.values[:] = np.random.randn(*frame2.shape) - - res3 = getattr(frame.rolling(window=10), method)(frame2) - exp = DataFrame( - {k: getattr(frame[k].rolling(window=10), method)(frame2[k]) for k in frame} - ) - tm.assert_frame_equal(res3, exp) - - @pytest.mark.parametrize( "window,min_periods,center", list(_rolling_consistency_cases()) ) @@ -123,375 +57,6 @@ def test_rolling_apply_consistency_sum_no_nans( tm.assert_equal(rolling_f_result, rolling_apply_f_result) -@pytest.mark.parametrize("window", range(7)) -def test_rolling_corr_with_zero_variance(window): - # GH 18430 - s = Series(np.zeros(20)) - other = Series(np.arange(20)) - - assert s.rolling(window=window).corr(other=other).isna().all() - - -def test_corr_sanity(): - # GH 3155 - df = DataFrame( - np.array( - [ - [0.87024726, 0.18505595], - [0.64355431, 0.3091617], - [0.92372966, 0.50552513], - [0.00203756, 0.04520709], - [0.84780328, 0.33394331], - [0.78369152, 0.63919667], - ] - ) - ) - - res = df[0].rolling(5, center=True).corr(df[1]) - assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res) - - df = DataFrame(np.random.rand(30, 2)) - res = df[0].rolling(5, center=True).corr(df[1]) - assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res) - - -def test_rolling_cov_diff_length(): - # GH 7512 - s1 = Series([1, 2, 3], index=[0, 1, 2]) - s2 = Series([1, 3], index=[0, 2]) - result = s1.rolling(window=3, min_periods=2).cov(s2) - expected = Series([None, None, 2.0]) - tm.assert_series_equal(result, expected) - - s2a = Series([1, None, 3], index=[0, 1, 2]) - result = s1.rolling(window=3, min_periods=2).cov(s2a) - tm.assert_series_equal(result, expected) - - -def test_rolling_corr_diff_length(): - # GH 7512 - s1 = Series([1, 2, 3], index=[0, 1, 2]) - s2 = Series([1, 3], index=[0, 2]) - result = s1.rolling(window=3, min_periods=2).corr(s2) - expected = Series([None, None, 1.0]) - tm.assert_series_equal(result, expected) - - s2a = Series([1, None, 3], index=[0, 1, 2]) - result = s1.rolling(window=3, min_periods=2).corr(s2a) - tm.assert_series_equal(result, expected) - - -@pytest.mark.parametrize( - "f", - [ - lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False), - lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False), - lambda x: x.rolling(window=10, min_periods=5).max(), - lambda x: x.rolling(window=10, min_periods=5).min(), - lambda x: x.rolling(window=10, min_periods=5).sum(), - lambda x: x.rolling(window=10, min_periods=5).mean(), - lambda x: x.rolling(window=10, min_periods=5).std(), - lambda x: x.rolling(window=10, min_periods=5).var(), - lambda x: x.rolling(window=10, min_periods=5).skew(), - lambda x: x.rolling(window=10, min_periods=5).kurt(), - lambda x: x.rolling(window=10, min_periods=5).quantile(quantile=0.5), - lambda x: x.rolling(window=10, min_periods=5).median(), - lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False), - lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True), - pytest.param( - lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(), - marks=td.skip_if_no_scipy, - ), - ], -) -def test_rolling_functions_window_non_shrinkage(f): - # GH 7764 - s = Series(range(4)) - s_expected = Series(np.nan, index=s.index) - df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]], columns=["A", "B"]) - df_expected = DataFrame(np.nan, index=df.index, columns=df.columns) - - s_result = f(s) - tm.assert_series_equal(s_result, s_expected) - - df_result = f(df) - tm.assert_frame_equal(df_result, df_expected) - - -@pytest.mark.parametrize( - "f", - [ - lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)), - lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)), - ], -) -def test_rolling_functions_window_non_shrinkage_binary(f): - - # corr/cov return a MI DataFrame - df = DataFrame( - [[1, 5], [3, 2], [3, 9], [-1, 0]], - columns=Index(["A", "B"], name="foo"), - index=Index(range(4), name="bar"), - ) - df_expected = DataFrame( - columns=Index(["A", "B"], name="foo"), - index=MultiIndex.from_product([df.index, df.columns], names=["bar", "foo"]), - dtype="float64", - ) - df_result = f(df) - tm.assert_frame_equal(df_result, df_expected) - - -def test_rolling_skew_edge_cases(): - - all_nan = Series([np.NaN] * 5) - - # yields all NaN (0 variance) - d = Series([1] * 5) - x = d.rolling(window=5).skew() - tm.assert_series_equal(all_nan, x) - - # yields all NaN (window too small) - d = Series(np.random.randn(5)) - x = d.rolling(window=2).skew() - tm.assert_series_equal(all_nan, x) - - # yields [NaN, NaN, NaN, 0.177994, 1.548824] - d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401]) - expected = Series([np.NaN, np.NaN, np.NaN, 0.177994, 1.548824]) - x = d.rolling(window=4).skew() - tm.assert_series_equal(expected, x) - - -def test_rolling_kurt_edge_cases(): - - all_nan = Series([np.NaN] * 5) - - # yields all NaN (0 variance) - d = Series([1] * 5) - x = d.rolling(window=5).kurt() - tm.assert_series_equal(all_nan, x) - - # yields all NaN (window too small) - d = Series(np.random.randn(5)) - x = d.rolling(window=3).kurt() - tm.assert_series_equal(all_nan, x) - - # yields [NaN, NaN, NaN, 1.224307, 2.671499] - d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401]) - expected = Series([np.NaN, np.NaN, np.NaN, 1.224307, 2.671499]) - x = d.rolling(window=4).kurt() - tm.assert_series_equal(expected, x) - - -def test_rolling_skew_eq_value_fperr(): - # #18804 all rolling skew for all equal values should return Nan - a = Series([1.1] * 15).rolling(window=10).skew() - assert np.isnan(a).all() - - -def test_rolling_kurt_eq_value_fperr(): - # #18804 all rolling kurt for all equal values should return Nan - a = Series([1.1] * 15).rolling(window=10).kurt() - assert np.isnan(a).all() - - -def test_rolling_max_gh6297(): - """Replicate result expected in GH #6297""" - indices = [datetime(1975, 1, i) for i in range(1, 6)] - # So that we can have 2 datapoints on one of the days - indices.append(datetime(1975, 1, 3, 6, 0)) - series = Series(range(1, 7), index=indices) - # Use floats instead of ints as values - series = series.map(lambda x: float(x)) - # Sort chronologically - series = series.sort_index() - - expected = Series( - [1.0, 2.0, 6.0, 4.0, 5.0], - index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), - ) - x = series.resample("D").max().rolling(window=1).max() - tm.assert_series_equal(expected, x) - - -def test_rolling_max_resample(): - - indices = [datetime(1975, 1, i) for i in range(1, 6)] - # So that we can have 3 datapoints on last day (4, 10, and 20) - indices.append(datetime(1975, 1, 5, 1)) - indices.append(datetime(1975, 1, 5, 2)) - series = Series(list(range(0, 5)) + [10, 20], index=indices) - # Use floats instead of ints as values - series = series.map(lambda x: float(x)) - # Sort chronologically - series = series.sort_index() - - # Default how should be max - expected = Series( - [0.0, 1.0, 2.0, 3.0, 20.0], - index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), - ) - x = series.resample("D").max().rolling(window=1).max() - tm.assert_series_equal(expected, x) - - # Now specify median (10.0) - expected = Series( - [0.0, 1.0, 2.0, 3.0, 10.0], - index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), - ) - x = series.resample("D").median().rolling(window=1).max() - tm.assert_series_equal(expected, x) - - # Now specify mean (4+10+20)/3 - v = (4.0 + 10.0 + 20.0) / 3.0 - expected = Series( - [0.0, 1.0, 2.0, 3.0, v], - index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), - ) - x = series.resample("D").mean().rolling(window=1).max() - tm.assert_series_equal(expected, x) - - -def test_rolling_min_resample(): - - indices = [datetime(1975, 1, i) for i in range(1, 6)] - # So that we can have 3 datapoints on last day (4, 10, and 20) - indices.append(datetime(1975, 1, 5, 1)) - indices.append(datetime(1975, 1, 5, 2)) - series = Series(list(range(0, 5)) + [10, 20], index=indices) - # Use floats instead of ints as values - series = series.map(lambda x: float(x)) - # Sort chronologically - series = series.sort_index() - - # Default how should be min - expected = Series( - [0.0, 1.0, 2.0, 3.0, 4.0], - index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), - ) - r = series.resample("D").min().rolling(window=1) - tm.assert_series_equal(expected, r.min()) - - -def test_rolling_median_resample(): - - indices = [datetime(1975, 1, i) for i in range(1, 6)] - # So that we can have 3 datapoints on last day (4, 10, and 20) - indices.append(datetime(1975, 1, 5, 1)) - indices.append(datetime(1975, 1, 5, 2)) - series = Series(list(range(0, 5)) + [10, 20], index=indices) - # Use floats instead of ints as values - series = series.map(lambda x: float(x)) - # Sort chronologically - series = series.sort_index() - - # Default how should be median - expected = Series( - [0.0, 1.0, 2.0, 3.0, 10], - index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), - ) - x = series.resample("D").median().rolling(window=1).median() - tm.assert_series_equal(expected, x) - - -def test_rolling_median_memory_error(): - # GH11722 - n = 20000 - Series(np.random.randn(n)).rolling(window=2, center=False).median() - Series(np.random.randn(n)).rolling(window=2, center=False).median() - - -@pytest.mark.parametrize( - "data_type", - [np.dtype(f"f{width}") for width in [4, 8]] - + [np.dtype(f"{sign}{width}") for width in [1, 2, 4, 8] for sign in "ui"], -) -def test_rolling_min_max_numeric_types(data_type): - # GH12373 - - # Just testing that these don't throw exceptions and that - # the return type is float64. Other tests will cover quantitative - # correctness - result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).max() - assert result.dtypes[0] == np.dtype("f8") - result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).min() - assert result.dtypes[0] == np.dtype("f8") - - -@pytest.mark.parametrize( - "f", - [ - lambda x: x.rolling(window=10, min_periods=0).count(), - lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False), - lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False), - lambda x: x.rolling(window=10, min_periods=5).max(), - lambda x: x.rolling(window=10, min_periods=5).min(), - lambda x: x.rolling(window=10, min_periods=5).sum(), - lambda x: x.rolling(window=10, min_periods=5).mean(), - lambda x: x.rolling(window=10, min_periods=5).std(), - lambda x: x.rolling(window=10, min_periods=5).var(), - lambda x: x.rolling(window=10, min_periods=5).skew(), - lambda x: x.rolling(window=10, min_periods=5).kurt(), - lambda x: x.rolling(window=10, min_periods=5).quantile(0.5), - lambda x: x.rolling(window=10, min_periods=5).median(), - lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False), - lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True), - pytest.param( - lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(), - marks=td.skip_if_no_scipy, - ), - ], -) -def test_moment_functions_zero_length(f): - # GH 8056 - s = Series(dtype=np.float64) - s_expected = s - df1 = DataFrame() - df1_expected = df1 - df2 = DataFrame(columns=["a"]) - df2["a"] = df2["a"].astype("float64") - df2_expected = df2 - - s_result = f(s) - tm.assert_series_equal(s_result, s_expected) - - df1_result = f(df1) - tm.assert_frame_equal(df1_result, df1_expected) - - df2_result = f(df2) - tm.assert_frame_equal(df2_result, df2_expected) - - -@pytest.mark.parametrize( - "f", - [ - lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)), - lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)), - ], -) -def test_moment_functions_zero_length_pairwise(f): - - df1 = DataFrame() - df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) - df2["a"] = df2["a"].astype("float64") - - df1_expected = DataFrame( - index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([]) - ) - df2_expected = DataFrame( - index=MultiIndex.from_product([df2.index, df2.columns], names=["bar", "foo"]), - columns=Index(["a"], name="foo"), - dtype="float64", - ) - - df1_result = f(df1) - tm.assert_frame_equal(df1_result, df1_expected) - - df2_result = f(df2) - tm.assert_frame_equal(df2_result, df2_expected) - - @pytest.mark.parametrize( "window,min_periods,center", list(_rolling_consistency_cases()) ) diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py index f43d7ec99e312..77ff6ae03d836 100644 --- a/pandas/tests/window/test_pairwise.py +++ b/pandas/tests/window/test_pairwise.py @@ -5,6 +5,7 @@ from pandas import ( DataFrame, + Index, MultiIndex, Series, date_range, @@ -13,6 +14,172 @@ from pandas.core.algorithms import safe_sort +def test_rolling_cov(series): + A = series + B = A + np.random.randn(len(A)) + + result = A.rolling(window=50, min_periods=25).cov(B) + tm.assert_almost_equal(result[-1], np.cov(A[-50:], B[-50:])[0, 1]) + + +def test_rolling_corr(series): + A = series + B = A + np.random.randn(len(A)) + + result = A.rolling(window=50, min_periods=25).corr(B) + tm.assert_almost_equal(result[-1], np.corrcoef(A[-50:], B[-50:])[0, 1]) + + # test for correct bias correction + a = tm.makeTimeSeries() + b = tm.makeTimeSeries() + a[:5] = np.nan + b[:10] = np.nan + + result = a.rolling(window=len(a), min_periods=1).corr(b) + tm.assert_almost_equal(result[-1], a.corr(b)) + + +@pytest.mark.parametrize("func", ["cov", "corr"]) +def test_rolling_pairwise_cov_corr(func, frame): + result = getattr(frame.rolling(window=10, min_periods=5), func)() + result = result.loc[(slice(None), 1), 5] + result.index = result.index.droplevel(1) + expected = getattr(frame[1].rolling(window=10, min_periods=5), func)(frame[5]) + tm.assert_series_equal(result, expected, check_names=False) + + +@pytest.mark.parametrize("method", ["corr", "cov"]) +def test_flex_binary_frame(method, frame): + series = frame[1] + + res = getattr(series.rolling(window=10), method)(frame) + res2 = getattr(frame.rolling(window=10), method)(series) + exp = frame.apply(lambda x: getattr(series.rolling(window=10), method)(x)) + + tm.assert_frame_equal(res, exp) + tm.assert_frame_equal(res2, exp) + + frame2 = frame.copy() + frame2.values[:] = np.random.randn(*frame2.shape) + + res3 = getattr(frame.rolling(window=10), method)(frame2) + exp = DataFrame( + {k: getattr(frame[k].rolling(window=10), method)(frame2[k]) for k in frame} + ) + tm.assert_frame_equal(res3, exp) + + +@pytest.mark.parametrize("window", range(7)) +def test_rolling_corr_with_zero_variance(window): + # GH 18430 + s = Series(np.zeros(20)) + other = Series(np.arange(20)) + + assert s.rolling(window=window).corr(other=other).isna().all() + + +def test_corr_sanity(): + # GH 3155 + df = DataFrame( + np.array( + [ + [0.87024726, 0.18505595], + [0.64355431, 0.3091617], + [0.92372966, 0.50552513], + [0.00203756, 0.04520709], + [0.84780328, 0.33394331], + [0.78369152, 0.63919667], + ] + ) + ) + + res = df[0].rolling(5, center=True).corr(df[1]) + assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res) + + df = DataFrame(np.random.rand(30, 2)) + res = df[0].rolling(5, center=True).corr(df[1]) + assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res) + + +def test_rolling_cov_diff_length(): + # GH 7512 + s1 = Series([1, 2, 3], index=[0, 1, 2]) + s2 = Series([1, 3], index=[0, 2]) + result = s1.rolling(window=3, min_periods=2).cov(s2) + expected = Series([None, None, 2.0]) + tm.assert_series_equal(result, expected) + + s2a = Series([1, None, 3], index=[0, 1, 2]) + result = s1.rolling(window=3, min_periods=2).cov(s2a) + tm.assert_series_equal(result, expected) + + +def test_rolling_corr_diff_length(): + # GH 7512 + s1 = Series([1, 2, 3], index=[0, 1, 2]) + s2 = Series([1, 3], index=[0, 2]) + result = s1.rolling(window=3, min_periods=2).corr(s2) + expected = Series([None, None, 1.0]) + tm.assert_series_equal(result, expected) + + s2a = Series([1, None, 3], index=[0, 1, 2]) + result = s1.rolling(window=3, min_periods=2).corr(s2a) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "f", + [ + lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)), + lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)), + ], +) +def test_rolling_functions_window_non_shrinkage_binary(f): + + # corr/cov return a MI DataFrame + df = DataFrame( + [[1, 5], [3, 2], [3, 9], [-1, 0]], + columns=Index(["A", "B"], name="foo"), + index=Index(range(4), name="bar"), + ) + df_expected = DataFrame( + columns=Index(["A", "B"], name="foo"), + index=MultiIndex.from_product([df.index, df.columns], names=["bar", "foo"]), + dtype="float64", + ) + df_result = f(df) + tm.assert_frame_equal(df_result, df_expected) + + +@pytest.mark.parametrize( + "f", + [ + lambda x: (x.rolling(window=10, min_periods=5).cov(x, pairwise=True)), + lambda x: (x.rolling(window=10, min_periods=5).corr(x, pairwise=True)), + ], +) +def test_moment_functions_zero_length_pairwise(f): + + df1 = DataFrame() + df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) + df2["a"] = df2["a"].astype("float64") + + df1_expected = DataFrame( + index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([]) + ) + df2_expected = DataFrame( + index=MultiIndex.from_product([df2.index, df2.columns], names=["bar", "foo"]), + columns=Index(["a"], name="foo"), + dtype="float64", + ) + + df1_result = f(df1) + tm.assert_frame_equal(df1_result, df1_expected) + + df2_result = f(df2) + tm.assert_frame_equal(df2_result, df2_expected) + + class TestPairwise: # GH 7738 diff --git a/pandas/tests/window/test_rolling_functions.py b/pandas/tests/window/test_rolling_functions.py index b25b3c3b17637..c788b3d88cb63 100644 --- a/pandas/tests/window/test_rolling_functions.py +++ b/pandas/tests/window/test_rolling_functions.py @@ -1,8 +1,13 @@ +from datetime import datetime + import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import ( DataFrame, + DatetimeIndex, Series, concat, isna, @@ -316,3 +321,207 @@ def test_center_reindex_frame(frame, roll_func, kwargs, minp, fill_value): if fill_value is not None: frame_xp = frame_xp.fillna(fill_value) tm.assert_frame_equal(frame_xp, frame_rs) + + +@pytest.mark.parametrize( + "f", + [ + lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False), + lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False), + lambda x: x.rolling(window=10, min_periods=5).max(), + lambda x: x.rolling(window=10, min_periods=5).min(), + lambda x: x.rolling(window=10, min_periods=5).sum(), + lambda x: x.rolling(window=10, min_periods=5).mean(), + lambda x: x.rolling(window=10, min_periods=5).std(), + lambda x: x.rolling(window=10, min_periods=5).var(), + lambda x: x.rolling(window=10, min_periods=5).skew(), + lambda x: x.rolling(window=10, min_periods=5).kurt(), + lambda x: x.rolling(window=10, min_periods=5).quantile(quantile=0.5), + lambda x: x.rolling(window=10, min_periods=5).median(), + lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False), + lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True), + pytest.param( + lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(), + marks=td.skip_if_no_scipy, + ), + ], +) +def test_rolling_functions_window_non_shrinkage(f): + # GH 7764 + s = Series(range(4)) + s_expected = Series(np.nan, index=s.index) + df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]], columns=["A", "B"]) + df_expected = DataFrame(np.nan, index=df.index, columns=df.columns) + + s_result = f(s) + tm.assert_series_equal(s_result, s_expected) + + df_result = f(df) + tm.assert_frame_equal(df_result, df_expected) + + +def test_rolling_max_gh6297(): + """Replicate result expected in GH #6297""" + indices = [datetime(1975, 1, i) for i in range(1, 6)] + # So that we can have 2 datapoints on one of the days + indices.append(datetime(1975, 1, 3, 6, 0)) + series = Series(range(1, 7), index=indices) + # Use floats instead of ints as values + series = series.map(lambda x: float(x)) + # Sort chronologically + series = series.sort_index() + + expected = Series( + [1.0, 2.0, 6.0, 4.0, 5.0], + index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), + ) + x = series.resample("D").max().rolling(window=1).max() + tm.assert_series_equal(expected, x) + + +def test_rolling_max_resample(): + + indices = [datetime(1975, 1, i) for i in range(1, 6)] + # So that we can have 3 datapoints on last day (4, 10, and 20) + indices.append(datetime(1975, 1, 5, 1)) + indices.append(datetime(1975, 1, 5, 2)) + series = Series(list(range(0, 5)) + [10, 20], index=indices) + # Use floats instead of ints as values + series = series.map(lambda x: float(x)) + # Sort chronologically + series = series.sort_index() + + # Default how should be max + expected = Series( + [0.0, 1.0, 2.0, 3.0, 20.0], + index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), + ) + x = series.resample("D").max().rolling(window=1).max() + tm.assert_series_equal(expected, x) + + # Now specify median (10.0) + expected = Series( + [0.0, 1.0, 2.0, 3.0, 10.0], + index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), + ) + x = series.resample("D").median().rolling(window=1).max() + tm.assert_series_equal(expected, x) + + # Now specify mean (4+10+20)/3 + v = (4.0 + 10.0 + 20.0) / 3.0 + expected = Series( + [0.0, 1.0, 2.0, 3.0, v], + index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), + ) + x = series.resample("D").mean().rolling(window=1).max() + tm.assert_series_equal(expected, x) + + +def test_rolling_min_resample(): + + indices = [datetime(1975, 1, i) for i in range(1, 6)] + # So that we can have 3 datapoints on last day (4, 10, and 20) + indices.append(datetime(1975, 1, 5, 1)) + indices.append(datetime(1975, 1, 5, 2)) + series = Series(list(range(0, 5)) + [10, 20], index=indices) + # Use floats instead of ints as values + series = series.map(lambda x: float(x)) + # Sort chronologically + series = series.sort_index() + + # Default how should be min + expected = Series( + [0.0, 1.0, 2.0, 3.0, 4.0], + index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), + ) + r = series.resample("D").min().rolling(window=1) + tm.assert_series_equal(expected, r.min()) + + +def test_rolling_median_resample(): + + indices = [datetime(1975, 1, i) for i in range(1, 6)] + # So that we can have 3 datapoints on last day (4, 10, and 20) + indices.append(datetime(1975, 1, 5, 1)) + indices.append(datetime(1975, 1, 5, 2)) + series = Series(list(range(0, 5)) + [10, 20], index=indices) + # Use floats instead of ints as values + series = series.map(lambda x: float(x)) + # Sort chronologically + series = series.sort_index() + + # Default how should be median + expected = Series( + [0.0, 1.0, 2.0, 3.0, 10], + index=DatetimeIndex([datetime(1975, 1, i, 0) for i in range(1, 6)], freq="D"), + ) + x = series.resample("D").median().rolling(window=1).median() + tm.assert_series_equal(expected, x) + + +def test_rolling_median_memory_error(): + # GH11722 + n = 20000 + Series(np.random.randn(n)).rolling(window=2, center=False).median() + Series(np.random.randn(n)).rolling(window=2, center=False).median() + + +@pytest.mark.parametrize( + "data_type", + [np.dtype(f"f{width}") for width in [4, 8]] + + [np.dtype(f"{sign}{width}") for width in [1, 2, 4, 8] for sign in "ui"], +) +def test_rolling_min_max_numeric_types(data_type): + # GH12373 + + # Just testing that these don't throw exceptions and that + # the return type is float64. Other tests will cover quantitative + # correctness + result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).max() + assert result.dtypes[0] == np.dtype("f8") + result = DataFrame(np.arange(20, dtype=data_type)).rolling(window=5).min() + assert result.dtypes[0] == np.dtype("f8") + + +@pytest.mark.parametrize( + "f", + [ + lambda x: x.rolling(window=10, min_periods=0).count(), + lambda x: x.rolling(window=10, min_periods=5).cov(x, pairwise=False), + lambda x: x.rolling(window=10, min_periods=5).corr(x, pairwise=False), + lambda x: x.rolling(window=10, min_periods=5).max(), + lambda x: x.rolling(window=10, min_periods=5).min(), + lambda x: x.rolling(window=10, min_periods=5).sum(), + lambda x: x.rolling(window=10, min_periods=5).mean(), + lambda x: x.rolling(window=10, min_periods=5).std(), + lambda x: x.rolling(window=10, min_periods=5).var(), + lambda x: x.rolling(window=10, min_periods=5).skew(), + lambda x: x.rolling(window=10, min_periods=5).kurt(), + lambda x: x.rolling(window=10, min_periods=5).quantile(0.5), + lambda x: x.rolling(window=10, min_periods=5).median(), + lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=False), + lambda x: x.rolling(window=10, min_periods=5).apply(sum, raw=True), + pytest.param( + lambda x: x.rolling(win_type="boxcar", window=10, min_periods=5).mean(), + marks=td.skip_if_no_scipy, + ), + ], +) +def test_moment_functions_zero_length(f): + # GH 8056 + s = Series(dtype=np.float64) + s_expected = s + df1 = DataFrame() + df1_expected = df1 + df2 = DataFrame(columns=["a"]) + df2["a"] = df2["a"].astype("float64") + df2_expected = df2 + + s_result = f(s) + tm.assert_series_equal(s_result, s_expected) + + df1_result = f(df1) + tm.assert_frame_equal(df1_result, df1_expected) + + df2_result = f(df2) + tm.assert_frame_equal(df2_result, df2_expected) diff --git a/pandas/tests/window/test_rolling_skew_kurt.py b/pandas/tests/window/test_rolling_skew_kurt.py index 34d5f686eb853..2c275ed6f4a28 100644 --- a/pandas/tests/window/test_rolling_skew_kurt.py +++ b/pandas/tests/window/test_rolling_skew_kurt.py @@ -168,3 +168,57 @@ def test_center_reindex_frame(frame, roll_func): ) frame_rs = getattr(frame.rolling(window=25, center=True), roll_func)() tm.assert_frame_equal(frame_xp, frame_rs) + + +def test_rolling_skew_edge_cases(): + + all_nan = Series([np.NaN] * 5) + + # yields all NaN (0 variance) + d = Series([1] * 5) + x = d.rolling(window=5).skew() + tm.assert_series_equal(all_nan, x) + + # yields all NaN (window too small) + d = Series(np.random.randn(5)) + x = d.rolling(window=2).skew() + tm.assert_series_equal(all_nan, x) + + # yields [NaN, NaN, NaN, 0.177994, 1.548824] + d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401]) + expected = Series([np.NaN, np.NaN, np.NaN, 0.177994, 1.548824]) + x = d.rolling(window=4).skew() + tm.assert_series_equal(expected, x) + + +def test_rolling_kurt_edge_cases(): + + all_nan = Series([np.NaN] * 5) + + # yields all NaN (0 variance) + d = Series([1] * 5) + x = d.rolling(window=5).kurt() + tm.assert_series_equal(all_nan, x) + + # yields all NaN (window too small) + d = Series(np.random.randn(5)) + x = d.rolling(window=3).kurt() + tm.assert_series_equal(all_nan, x) + + # yields [NaN, NaN, NaN, 1.224307, 2.671499] + d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401]) + expected = Series([np.NaN, np.NaN, np.NaN, 1.224307, 2.671499]) + x = d.rolling(window=4).kurt() + tm.assert_series_equal(expected, x) + + +def test_rolling_skew_eq_value_fperr(): + # #18804 all rolling skew for all equal values should return Nan + a = Series([1.1] * 15).rolling(window=10).skew() + assert np.isnan(a).all() + + +def test_rolling_kurt_eq_value_fperr(): + # #18804 all rolling kurt for all equal values should return Nan + a = Series([1.1] * 15).rolling(window=10).kurt() + assert np.isnan(a).all()
- [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 Since some tests are not running on windows/moments (#37535), moving the "consistency" rolling tests to the relevant files.
https://api.github.com/repos/pandas-dev/pandas/pulls/44164
2021-10-24T03:38:42Z
2021-10-24T22:04:52Z
2021-10-24T22:04:52Z
2021-10-24T22:05:30Z
TST: Move some consistency expanding tests to test_expanding
diff --git a/pandas/tests/window/moments/test_moments_consistency_expanding.py b/pandas/tests/window/moments/test_moments_consistency_expanding.py index df3e79fb79eca..d0fe7bf9fc2d2 100644 --- a/pandas/tests/window/moments/test_moments_consistency_expanding.py +++ b/pandas/tests/window/moments/test_moments_consistency_expanding.py @@ -1,171 +1,10 @@ import numpy as np import pytest -from pandas import ( - DataFrame, - Index, - MultiIndex, - Series, - isna, - notna, -) +from pandas import Series import pandas._testing as tm -def test_expanding_corr(series): - A = series.dropna() - B = (A + np.random.randn(len(A)))[:-5] - - result = A.expanding().corr(B) - - rolling_result = A.rolling(window=len(A), min_periods=1).corr(B) - - tm.assert_almost_equal(rolling_result, result) - - -def test_expanding_count(series): - result = series.expanding(min_periods=0).count() - tm.assert_almost_equal( - result, series.rolling(window=len(series), min_periods=0).count() - ) - - -def test_expanding_quantile(series): - result = series.expanding().quantile(0.5) - - rolling_result = series.rolling(window=len(series), min_periods=1).quantile(0.5) - - tm.assert_almost_equal(result, rolling_result) - - -def test_expanding_cov(series): - A = series - B = (A + np.random.randn(len(A)))[:-5] - - result = A.expanding().cov(B) - - rolling_result = A.rolling(window=len(A), min_periods=1).cov(B) - - tm.assert_almost_equal(rolling_result, result) - - -def test_expanding_cov_pairwise(frame): - result = frame.expanding().cov() - - rolling_result = frame.rolling(window=len(frame), min_periods=1).cov() - - tm.assert_frame_equal(result, rolling_result) - - -def test_expanding_corr_pairwise(frame): - result = frame.expanding().corr() - - rolling_result = frame.rolling(window=len(frame), min_periods=1).corr() - tm.assert_frame_equal(result, rolling_result) - - -@pytest.mark.parametrize( - "func,static_comp", - [("sum", np.sum), ("mean", np.mean), ("max", np.max), ("min", np.min)], - ids=["sum", "mean", "max", "min"], -) -def test_expanding_func(func, static_comp, frame_or_series): - data = frame_or_series(np.array(list(range(10)) + [np.nan] * 10)) - result = getattr(data.expanding(min_periods=1, axis=0), func)() - assert isinstance(result, frame_or_series) - - if frame_or_series is Series: - tm.assert_almost_equal(result[10], static_comp(data[:11])) - else: - tm.assert_series_equal( - result.iloc[10], static_comp(data[:11]), check_names=False - ) - - -@pytest.mark.parametrize( - "func,static_comp", - [("sum", np.sum), ("mean", np.mean), ("max", np.max), ("min", np.min)], - ids=["sum", "mean", "max", "min"], -) -def test_expanding_min_periods(func, static_comp): - ser = Series(np.random.randn(50)) - - result = getattr(ser.expanding(min_periods=30, axis=0), func)() - assert result[:29].isna().all() - tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50])) - - # min_periods is working correctly - result = getattr(ser.expanding(min_periods=15, axis=0), func)() - assert isna(result.iloc[13]) - assert notna(result.iloc[14]) - - ser2 = Series(np.random.randn(20)) - result = getattr(ser2.expanding(min_periods=5, axis=0), func)() - assert isna(result[3]) - assert notna(result[4]) - - # min_periods=0 - result0 = getattr(ser.expanding(min_periods=0, axis=0), func)() - result1 = getattr(ser.expanding(min_periods=1, axis=0), func)() - tm.assert_almost_equal(result0, result1) - - result = getattr(ser.expanding(min_periods=1, axis=0), func)() - tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50])) - - -def test_expanding_apply(engine_and_raw, frame_or_series): - engine, raw = engine_and_raw - data = frame_or_series(np.array(list(range(10)) + [np.nan] * 10)) - result = data.expanding(min_periods=1).apply( - lambda x: x.mean(), raw=raw, engine=engine - ) - assert isinstance(result, frame_or_series) - - if frame_or_series is Series: - tm.assert_almost_equal(result[9], np.mean(data[:11])) - else: - tm.assert_series_equal(result.iloc[9], np.mean(data[:11]), check_names=False) - - -def test_expanding_min_periods_apply(engine_and_raw): - engine, raw = engine_and_raw - ser = Series(np.random.randn(50)) - - result = ser.expanding(min_periods=30).apply( - lambda x: x.mean(), raw=raw, engine=engine - ) - assert result[:29].isna().all() - tm.assert_almost_equal(result.iloc[-1], np.mean(ser[:50])) - - # min_periods is working correctly - result = ser.expanding(min_periods=15).apply( - lambda x: x.mean(), raw=raw, engine=engine - ) - assert isna(result.iloc[13]) - assert notna(result.iloc[14]) - - ser2 = Series(np.random.randn(20)) - result = ser2.expanding(min_periods=5).apply( - lambda x: x.mean(), raw=raw, engine=engine - ) - assert isna(result[3]) - assert notna(result[4]) - - # min_periods=0 - result0 = ser.expanding(min_periods=0).apply( - lambda x: x.mean(), raw=raw, engine=engine - ) - result1 = ser.expanding(min_periods=1).apply( - lambda x: x.mean(), raw=raw, engine=engine - ) - tm.assert_almost_equal(result0, result1) - - result = ser.expanding(min_periods=1).apply( - lambda x: x.mean(), raw=raw, engine=engine - ) - tm.assert_almost_equal(result.iloc[-1], np.mean(ser[:50])) - - @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4]) @pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum]) def test_expanding_apply_consistency_sum_nans(consistency_data, min_periods, f): @@ -334,202 +173,3 @@ def test_expanding_consistency_var_debiasing_factors(consistency_data, min_perio x.expanding().count() - 1.0 ).replace(0.0, np.nan) tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x) - - -@pytest.mark.parametrize( - "f", - [ - lambda x: (x.expanding(min_periods=5).cov(x, pairwise=True)), - lambda x: (x.expanding(min_periods=5).corr(x, pairwise=True)), - ], -) -def test_moment_functions_zero_length_pairwise(f): - - df1 = DataFrame() - df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) - df2["a"] = df2["a"].astype("float64") - - df1_expected = DataFrame( - index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([]) - ) - df2_expected = DataFrame( - index=MultiIndex.from_product([df2.index, df2.columns], names=["bar", "foo"]), - columns=Index(["a"], name="foo"), - dtype="float64", - ) - - df1_result = f(df1) - tm.assert_frame_equal(df1_result, df1_expected) - - df2_result = f(df2) - tm.assert_frame_equal(df2_result, df2_expected) - - -@pytest.mark.parametrize( - "f", - [ - lambda x: x.expanding().count(), - lambda x: x.expanding(min_periods=5).cov(x, pairwise=False), - lambda x: x.expanding(min_periods=5).corr(x, pairwise=False), - lambda x: x.expanding(min_periods=5).max(), - lambda x: x.expanding(min_periods=5).min(), - lambda x: x.expanding(min_periods=5).sum(), - lambda x: x.expanding(min_periods=5).mean(), - lambda x: x.expanding(min_periods=5).std(), - lambda x: x.expanding(min_periods=5).var(), - lambda x: x.expanding(min_periods=5).skew(), - lambda x: x.expanding(min_periods=5).kurt(), - lambda x: x.expanding(min_periods=5).quantile(0.5), - lambda x: x.expanding(min_periods=5).median(), - lambda x: x.expanding(min_periods=5).apply(sum, raw=False), - lambda x: x.expanding(min_periods=5).apply(sum, raw=True), - ], -) -def test_moment_functions_zero_length(f): - # GH 8056 - s = Series(dtype=np.float64) - s_expected = s - df1 = DataFrame() - df1_expected = df1 - df2 = DataFrame(columns=["a"]) - df2["a"] = df2["a"].astype("float64") - df2_expected = df2 - - s_result = f(s) - tm.assert_series_equal(s_result, s_expected) - - df1_result = f(df1) - tm.assert_frame_equal(df1_result, df1_expected) - - df2_result = f(df2) - tm.assert_frame_equal(df2_result, df2_expected) - - -def test_expanding_apply_empty_series(engine_and_raw): - engine, raw = engine_and_raw - ser = Series([], dtype=np.float64) - tm.assert_series_equal( - ser, ser.expanding().apply(lambda x: x.mean(), raw=raw, engine=engine) - ) - - -def test_expanding_apply_min_periods_0(engine_and_raw): - # GH 8080 - engine, raw = engine_and_raw - s = Series([None, None, None]) - result = s.expanding(min_periods=0).apply(lambda x: len(x), raw=raw, engine=engine) - expected = Series([1.0, 2.0, 3.0]) - tm.assert_series_equal(result, expected) - - -def test_expanding_cov_diff_index(): - # GH 7512 - s1 = Series([1, 2, 3], index=[0, 1, 2]) - s2 = Series([1, 3], index=[0, 2]) - result = s1.expanding().cov(s2) - expected = Series([None, None, 2.0]) - tm.assert_series_equal(result, expected) - - s2a = Series([1, None, 3], index=[0, 1, 2]) - result = s1.expanding().cov(s2a) - tm.assert_series_equal(result, expected) - - s1 = Series([7, 8, 10], index=[0, 1, 3]) - s2 = Series([7, 9, 10], index=[0, 2, 3]) - result = s1.expanding().cov(s2) - expected = Series([None, None, None, 4.5]) - tm.assert_series_equal(result, expected) - - -def test_expanding_corr_diff_index(): - # GH 7512 - s1 = Series([1, 2, 3], index=[0, 1, 2]) - s2 = Series([1, 3], index=[0, 2]) - result = s1.expanding().corr(s2) - expected = Series([None, None, 1.0]) - tm.assert_series_equal(result, expected) - - s2a = Series([1, None, 3], index=[0, 1, 2]) - result = s1.expanding().corr(s2a) - tm.assert_series_equal(result, expected) - - s1 = Series([7, 8, 10], index=[0, 1, 3]) - s2 = Series([7, 9, 10], index=[0, 2, 3]) - result = s1.expanding().corr(s2) - expected = Series([None, None, None, 1.0]) - tm.assert_series_equal(result, expected) - - -def test_expanding_cov_pairwise_diff_length(): - # GH 7512 - df1 = DataFrame([[1, 5], [3, 2], [3, 9]], columns=Index(["A", "B"], name="foo")) - df1a = DataFrame( - [[1, 5], [3, 9]], index=[0, 2], columns=Index(["A", "B"], name="foo") - ) - df2 = DataFrame( - [[5, 6], [None, None], [2, 1]], columns=Index(["X", "Y"], name="foo") - ) - df2a = DataFrame( - [[5, 6], [2, 1]], index=[0, 2], columns=Index(["X", "Y"], name="foo") - ) - # TODO: xref gh-15826 - # .loc is not preserving the names - result1 = df1.expanding().cov(df2, pairwise=True).loc[2] - result2 = df1.expanding().cov(df2a, pairwise=True).loc[2] - result3 = df1a.expanding().cov(df2, pairwise=True).loc[2] - result4 = df1a.expanding().cov(df2a, pairwise=True).loc[2] - expected = DataFrame( - [[-3.0, -6.0], [-5.0, -10.0]], - columns=Index(["A", "B"], name="foo"), - index=Index(["X", "Y"], name="foo"), - ) - tm.assert_frame_equal(result1, expected) - tm.assert_frame_equal(result2, expected) - tm.assert_frame_equal(result3, expected) - tm.assert_frame_equal(result4, expected) - - -def test_expanding_corr_pairwise_diff_length(): - # GH 7512 - df1 = DataFrame( - [[1, 2], [3, 2], [3, 4]], columns=["A", "B"], index=Index(range(3), name="bar") - ) - df1a = DataFrame( - [[1, 2], [3, 4]], index=Index([0, 2], name="bar"), columns=["A", "B"] - ) - df2 = DataFrame( - [[5, 6], [None, None], [2, 1]], - columns=["X", "Y"], - index=Index(range(3), name="bar"), - ) - df2a = DataFrame( - [[5, 6], [2, 1]], index=Index([0, 2], name="bar"), columns=["X", "Y"] - ) - result1 = df1.expanding().corr(df2, pairwise=True).loc[2] - result2 = df1.expanding().corr(df2a, pairwise=True).loc[2] - result3 = df1a.expanding().corr(df2, pairwise=True).loc[2] - result4 = df1a.expanding().corr(df2a, pairwise=True).loc[2] - expected = DataFrame( - [[-1.0, -1.0], [-1.0, -1.0]], columns=["A", "B"], index=Index(["X", "Y"]) - ) - tm.assert_frame_equal(result1, expected) - tm.assert_frame_equal(result2, expected) - tm.assert_frame_equal(result3, expected) - tm.assert_frame_equal(result4, expected) - - -def test_expanding_apply_args_kwargs(engine_and_raw): - def mean_w_arg(x, const): - return np.mean(x) + const - - engine, raw = engine_and_raw - - df = DataFrame(np.random.rand(20, 3)) - - expected = df.expanding().apply(np.mean, engine=engine, raw=raw) + 20.0 - - result = df.expanding().apply(mean_w_arg, engine=engine, raw=raw, args=(20,)) - tm.assert_frame_equal(result, expected) - - result = df.expanding().apply(mean_w_arg, raw=raw, kwargs={"const": 20}) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py index 680ac3654222a..ad43a02724960 100644 --- a/pandas/tests/window/test_expanding.py +++ b/pandas/tests/window/test_expanding.py @@ -6,7 +6,11 @@ from pandas import ( DataFrame, DatetimeIndex, + Index, + MultiIndex, Series, + isna, + notna, ) import pandas._testing as tm from pandas.core.window import Expanding @@ -288,3 +292,356 @@ def test_rank(window, method, pct, ascending, test_data): result = ser.expanding(window).rank(method=method, pct=pct, ascending=ascending) tm.assert_series_equal(result, expected) + + +def test_expanding_corr(series): + A = series.dropna() + B = (A + np.random.randn(len(A)))[:-5] + + result = A.expanding().corr(B) + + rolling_result = A.rolling(window=len(A), min_periods=1).corr(B) + + tm.assert_almost_equal(rolling_result, result) + + +def test_expanding_count(series): + result = series.expanding(min_periods=0).count() + tm.assert_almost_equal( + result, series.rolling(window=len(series), min_periods=0).count() + ) + + +def test_expanding_quantile(series): + result = series.expanding().quantile(0.5) + + rolling_result = series.rolling(window=len(series), min_periods=1).quantile(0.5) + + tm.assert_almost_equal(result, rolling_result) + + +def test_expanding_cov(series): + A = series + B = (A + np.random.randn(len(A)))[:-5] + + result = A.expanding().cov(B) + + rolling_result = A.rolling(window=len(A), min_periods=1).cov(B) + + tm.assert_almost_equal(rolling_result, result) + + +def test_expanding_cov_pairwise(frame): + result = frame.expanding().cov() + + rolling_result = frame.rolling(window=len(frame), min_periods=1).cov() + + tm.assert_frame_equal(result, rolling_result) + + +def test_expanding_corr_pairwise(frame): + result = frame.expanding().corr() + + rolling_result = frame.rolling(window=len(frame), min_periods=1).corr() + tm.assert_frame_equal(result, rolling_result) + + +@pytest.mark.parametrize( + "func,static_comp", + [("sum", np.sum), ("mean", np.mean), ("max", np.max), ("min", np.min)], + ids=["sum", "mean", "max", "min"], +) +def test_expanding_func(func, static_comp, frame_or_series): + data = frame_or_series(np.array(list(range(10)) + [np.nan] * 10)) + result = getattr(data.expanding(min_periods=1, axis=0), func)() + assert isinstance(result, frame_or_series) + + if frame_or_series is Series: + tm.assert_almost_equal(result[10], static_comp(data[:11])) + else: + tm.assert_series_equal( + result.iloc[10], static_comp(data[:11]), check_names=False + ) + + +@pytest.mark.parametrize( + "func,static_comp", + [("sum", np.sum), ("mean", np.mean), ("max", np.max), ("min", np.min)], + ids=["sum", "mean", "max", "min"], +) +def test_expanding_min_periods(func, static_comp): + ser = Series(np.random.randn(50)) + + result = getattr(ser.expanding(min_periods=30, axis=0), func)() + assert result[:29].isna().all() + tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50])) + + # min_periods is working correctly + result = getattr(ser.expanding(min_periods=15, axis=0), func)() + assert isna(result.iloc[13]) + assert notna(result.iloc[14]) + + ser2 = Series(np.random.randn(20)) + result = getattr(ser2.expanding(min_periods=5, axis=0), func)() + assert isna(result[3]) + assert notna(result[4]) + + # min_periods=0 + result0 = getattr(ser.expanding(min_periods=0, axis=0), func)() + result1 = getattr(ser.expanding(min_periods=1, axis=0), func)() + tm.assert_almost_equal(result0, result1) + + result = getattr(ser.expanding(min_periods=1, axis=0), func)() + tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50])) + + +def test_expanding_apply(engine_and_raw, frame_or_series): + engine, raw = engine_and_raw + data = frame_or_series(np.array(list(range(10)) + [np.nan] * 10)) + result = data.expanding(min_periods=1).apply( + lambda x: x.mean(), raw=raw, engine=engine + ) + assert isinstance(result, frame_or_series) + + if frame_or_series is Series: + tm.assert_almost_equal(result[9], np.mean(data[:11])) + else: + tm.assert_series_equal(result.iloc[9], np.mean(data[:11]), check_names=False) + + +def test_expanding_min_periods_apply(engine_and_raw): + engine, raw = engine_and_raw + ser = Series(np.random.randn(50)) + + result = ser.expanding(min_periods=30).apply( + lambda x: x.mean(), raw=raw, engine=engine + ) + assert result[:29].isna().all() + tm.assert_almost_equal(result.iloc[-1], np.mean(ser[:50])) + + # min_periods is working correctly + result = ser.expanding(min_periods=15).apply( + lambda x: x.mean(), raw=raw, engine=engine + ) + assert isna(result.iloc[13]) + assert notna(result.iloc[14]) + + ser2 = Series(np.random.randn(20)) + result = ser2.expanding(min_periods=5).apply( + lambda x: x.mean(), raw=raw, engine=engine + ) + assert isna(result[3]) + assert notna(result[4]) + + # min_periods=0 + result0 = ser.expanding(min_periods=0).apply( + lambda x: x.mean(), raw=raw, engine=engine + ) + result1 = ser.expanding(min_periods=1).apply( + lambda x: x.mean(), raw=raw, engine=engine + ) + tm.assert_almost_equal(result0, result1) + + result = ser.expanding(min_periods=1).apply( + lambda x: x.mean(), raw=raw, engine=engine + ) + tm.assert_almost_equal(result.iloc[-1], np.mean(ser[:50])) + + +@pytest.mark.parametrize( + "f", + [ + lambda x: (x.expanding(min_periods=5).cov(x, pairwise=True)), + lambda x: (x.expanding(min_periods=5).corr(x, pairwise=True)), + ], +) +def test_moment_functions_zero_length_pairwise(f): + + df1 = DataFrame() + df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) + df2["a"] = df2["a"].astype("float64") + + df1_expected = DataFrame( + index=MultiIndex.from_product([df1.index, df1.columns]), columns=Index([]) + ) + df2_expected = DataFrame( + index=MultiIndex.from_product([df2.index, df2.columns], names=["bar", "foo"]), + columns=Index(["a"], name="foo"), + dtype="float64", + ) + + df1_result = f(df1) + tm.assert_frame_equal(df1_result, df1_expected) + + df2_result = f(df2) + tm.assert_frame_equal(df2_result, df2_expected) + + +@pytest.mark.parametrize( + "f", + [ + lambda x: x.expanding().count(), + lambda x: x.expanding(min_periods=5).cov(x, pairwise=False), + lambda x: x.expanding(min_periods=5).corr(x, pairwise=False), + lambda x: x.expanding(min_periods=5).max(), + lambda x: x.expanding(min_periods=5).min(), + lambda x: x.expanding(min_periods=5).sum(), + lambda x: x.expanding(min_periods=5).mean(), + lambda x: x.expanding(min_periods=5).std(), + lambda x: x.expanding(min_periods=5).var(), + lambda x: x.expanding(min_periods=5).skew(), + lambda x: x.expanding(min_periods=5).kurt(), + lambda x: x.expanding(min_periods=5).quantile(0.5), + lambda x: x.expanding(min_periods=5).median(), + lambda x: x.expanding(min_periods=5).apply(sum, raw=False), + lambda x: x.expanding(min_periods=5).apply(sum, raw=True), + ], +) +def test_moment_functions_zero_length(f): + # GH 8056 + s = Series(dtype=np.float64) + s_expected = s + df1 = DataFrame() + df1_expected = df1 + df2 = DataFrame(columns=["a"]) + df2["a"] = df2["a"].astype("float64") + df2_expected = df2 + + s_result = f(s) + tm.assert_series_equal(s_result, s_expected) + + df1_result = f(df1) + tm.assert_frame_equal(df1_result, df1_expected) + + df2_result = f(df2) + tm.assert_frame_equal(df2_result, df2_expected) + + +def test_expanding_apply_empty_series(engine_and_raw): + engine, raw = engine_and_raw + ser = Series([], dtype=np.float64) + tm.assert_series_equal( + ser, ser.expanding().apply(lambda x: x.mean(), raw=raw, engine=engine) + ) + + +def test_expanding_apply_min_periods_0(engine_and_raw): + # GH 8080 + engine, raw = engine_and_raw + s = Series([None, None, None]) + result = s.expanding(min_periods=0).apply(lambda x: len(x), raw=raw, engine=engine) + expected = Series([1.0, 2.0, 3.0]) + tm.assert_series_equal(result, expected) + + +def test_expanding_cov_diff_index(): + # GH 7512 + s1 = Series([1, 2, 3], index=[0, 1, 2]) + s2 = Series([1, 3], index=[0, 2]) + result = s1.expanding().cov(s2) + expected = Series([None, None, 2.0]) + tm.assert_series_equal(result, expected) + + s2a = Series([1, None, 3], index=[0, 1, 2]) + result = s1.expanding().cov(s2a) + tm.assert_series_equal(result, expected) + + s1 = Series([7, 8, 10], index=[0, 1, 3]) + s2 = Series([7, 9, 10], index=[0, 2, 3]) + result = s1.expanding().cov(s2) + expected = Series([None, None, None, 4.5]) + tm.assert_series_equal(result, expected) + + +def test_expanding_corr_diff_index(): + # GH 7512 + s1 = Series([1, 2, 3], index=[0, 1, 2]) + s2 = Series([1, 3], index=[0, 2]) + result = s1.expanding().corr(s2) + expected = Series([None, None, 1.0]) + tm.assert_series_equal(result, expected) + + s2a = Series([1, None, 3], index=[0, 1, 2]) + result = s1.expanding().corr(s2a) + tm.assert_series_equal(result, expected) + + s1 = Series([7, 8, 10], index=[0, 1, 3]) + s2 = Series([7, 9, 10], index=[0, 2, 3]) + result = s1.expanding().corr(s2) + expected = Series([None, None, None, 1.0]) + tm.assert_series_equal(result, expected) + + +def test_expanding_cov_pairwise_diff_length(): + # GH 7512 + df1 = DataFrame([[1, 5], [3, 2], [3, 9]], columns=Index(["A", "B"], name="foo")) + df1a = DataFrame( + [[1, 5], [3, 9]], index=[0, 2], columns=Index(["A", "B"], name="foo") + ) + df2 = DataFrame( + [[5, 6], [None, None], [2, 1]], columns=Index(["X", "Y"], name="foo") + ) + df2a = DataFrame( + [[5, 6], [2, 1]], index=[0, 2], columns=Index(["X", "Y"], name="foo") + ) + # TODO: xref gh-15826 + # .loc is not preserving the names + result1 = df1.expanding().cov(df2, pairwise=True).loc[2] + result2 = df1.expanding().cov(df2a, pairwise=True).loc[2] + result3 = df1a.expanding().cov(df2, pairwise=True).loc[2] + result4 = df1a.expanding().cov(df2a, pairwise=True).loc[2] + expected = DataFrame( + [[-3.0, -6.0], [-5.0, -10.0]], + columns=Index(["A", "B"], name="foo"), + index=Index(["X", "Y"], name="foo"), + ) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, expected) + tm.assert_frame_equal(result3, expected) + tm.assert_frame_equal(result4, expected) + + +def test_expanding_corr_pairwise_diff_length(): + # GH 7512 + df1 = DataFrame( + [[1, 2], [3, 2], [3, 4]], columns=["A", "B"], index=Index(range(3), name="bar") + ) + df1a = DataFrame( + [[1, 2], [3, 4]], index=Index([0, 2], name="bar"), columns=["A", "B"] + ) + df2 = DataFrame( + [[5, 6], [None, None], [2, 1]], + columns=["X", "Y"], + index=Index(range(3), name="bar"), + ) + df2a = DataFrame( + [[5, 6], [2, 1]], index=Index([0, 2], name="bar"), columns=["X", "Y"] + ) + result1 = df1.expanding().corr(df2, pairwise=True).loc[2] + result2 = df1.expanding().corr(df2a, pairwise=True).loc[2] + result3 = df1a.expanding().corr(df2, pairwise=True).loc[2] + result4 = df1a.expanding().corr(df2a, pairwise=True).loc[2] + expected = DataFrame( + [[-1.0, -1.0], [-1.0, -1.0]], columns=["A", "B"], index=Index(["X", "Y"]) + ) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, expected) + tm.assert_frame_equal(result3, expected) + tm.assert_frame_equal(result4, expected) + + +def test_expanding_apply_args_kwargs(engine_and_raw): + def mean_w_arg(x, const): + return np.mean(x) + const + + engine, raw = engine_and_raw + + df = DataFrame(np.random.rand(20, 3)) + + expected = df.expanding().apply(np.mean, engine=engine, raw=raw) + 20.0 + + result = df.expanding().apply(mean_w_arg, engine=engine, raw=raw, args=(20,)) + tm.assert_frame_equal(result, expected) + + result = df.expanding().apply(mean_w_arg, raw=raw, kwargs={"const": 20}) + tm.assert_frame_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 Since some tests are not running on windows/moments (#37535), moving the "consistency" expanding tests to `test_expanding.py`
https://api.github.com/repos/pandas-dev/pandas/pulls/44163
2021-10-24T03:03:08Z
2021-10-24T14:43:41Z
2021-10-24T14:43:41Z
2021-10-24T17:20:55Z
TST: Move remaining ewm tests to window/
diff --git a/pandas/tests/window/moments/test_moments_ewm.py b/pandas/tests/window/moments/test_moments_ewm.py deleted file mode 100644 index f87ff654e554a..0000000000000 --- a/pandas/tests/window/moments/test_moments_ewm.py +++ /dev/null @@ -1,64 +0,0 @@ -import pytest - -from pandas import ( - DataFrame, - Series, -) -import pandas._testing as tm - - -@pytest.mark.parametrize("name", ["var", "std", "mean"]) -def test_ewma_series(series, name): - series_result = getattr(series.ewm(com=10), name)() - assert isinstance(series_result, Series) - - -@pytest.mark.parametrize("name", ["var", "std", "mean"]) -def test_ewma_frame(frame, name): - frame_result = getattr(frame.ewm(com=10), name)() - assert isinstance(frame_result, DataFrame) - - -def test_ewma_span_com_args(series): - A = series.ewm(com=9.5).mean() - B = series.ewm(span=20).mean() - tm.assert_almost_equal(A, B) - msg = "comass, span, halflife, and alpha are mutually exclusive" - with pytest.raises(ValueError, match=msg): - series.ewm(com=9.5, span=20) - - msg = "Must pass one of comass, span, halflife, or alpha" - with pytest.raises(ValueError, match=msg): - series.ewm().mean() - - -def test_ewma_halflife_arg(series): - A = series.ewm(com=13.932726172912965).mean() - B = series.ewm(halflife=10.0).mean() - tm.assert_almost_equal(A, B) - msg = "comass, span, halflife, and alpha are mutually exclusive" - with pytest.raises(ValueError, match=msg): - series.ewm(span=20, halflife=50) - with pytest.raises(ValueError, match=msg): - series.ewm(com=9.5, halflife=50) - with pytest.raises(ValueError, match=msg): - series.ewm(com=9.5, span=20, halflife=50) - msg = "Must pass one of comass, span, halflife, or alpha" - with pytest.raises(ValueError, match=msg): - series.ewm() - - -def test_ewm_alpha_arg(series): - # GH 10789 - s = series - msg = "Must pass one of comass, span, halflife, or alpha" - with pytest.raises(ValueError, match=msg): - s.ewm() - - msg = "comass, span, halflife, and alpha are mutually exclusive" - with pytest.raises(ValueError, match=msg): - s.ewm(com=10.0, alpha=0.5) - with pytest.raises(ValueError, match=msg): - s.ewm(span=10.0, alpha=0.5) - with pytest.raises(ValueError, match=msg): - s.ewm(halflife=10.0, alpha=0.5) diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index 4ca090fba4955..21c0099bbc0e6 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -600,3 +600,60 @@ def test_different_input_array_raise_exception(name): # exception raised is Exception with pytest.raises(ValueError, match=msg): getattr(A.ewm(com=20, min_periods=5), name)(np.random.randn(50)) + + +@pytest.mark.parametrize("name", ["var", "std", "mean"]) +def test_ewma_series(series, name): + series_result = getattr(series.ewm(com=10), name)() + assert isinstance(series_result, Series) + + +@pytest.mark.parametrize("name", ["var", "std", "mean"]) +def test_ewma_frame(frame, name): + frame_result = getattr(frame.ewm(com=10), name)() + assert isinstance(frame_result, DataFrame) + + +def test_ewma_span_com_args(series): + A = series.ewm(com=9.5).mean() + B = series.ewm(span=20).mean() + tm.assert_almost_equal(A, B) + msg = "comass, span, halflife, and alpha are mutually exclusive" + with pytest.raises(ValueError, match=msg): + series.ewm(com=9.5, span=20) + + msg = "Must pass one of comass, span, halflife, or alpha" + with pytest.raises(ValueError, match=msg): + series.ewm().mean() + + +def test_ewma_halflife_arg(series): + A = series.ewm(com=13.932726172912965).mean() + B = series.ewm(halflife=10.0).mean() + tm.assert_almost_equal(A, B) + msg = "comass, span, halflife, and alpha are mutually exclusive" + with pytest.raises(ValueError, match=msg): + series.ewm(span=20, halflife=50) + with pytest.raises(ValueError, match=msg): + series.ewm(com=9.5, halflife=50) + with pytest.raises(ValueError, match=msg): + series.ewm(com=9.5, span=20, halflife=50) + msg = "Must pass one of comass, span, halflife, or alpha" + with pytest.raises(ValueError, match=msg): + series.ewm() + + +def test_ewm_alpha_arg(series): + # GH 10789 + s = series + msg = "Must pass one of comass, span, halflife, or alpha" + with pytest.raises(ValueError, match=msg): + s.ewm() + + msg = "comass, span, halflife, and alpha are mutually exclusive" + with pytest.raises(ValueError, match=msg): + s.ewm(com=10.0, alpha=0.5) + with pytest.raises(ValueError, match=msg): + s.ewm(span=10.0, alpha=0.5) + with pytest.raises(ValueError, match=msg): + s.ewm(halflife=10.0, alpha=0.5)
- [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 Since some tests are not running on windows/moments (#37535), moving the remaining tests to test_ewm.py
https://api.github.com/repos/pandas-dev/pandas/pulls/44161
2021-10-24T02:02:33Z
2021-10-24T14:42:33Z
2021-10-24T14:42:33Z
2021-10-24T17:20:46Z
TST: enable interval dtype feather test again
diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index ba8a9ed070236..97ebb3a0d39ba 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -89,9 +89,7 @@ def test_basic(self): ) df["periods"] = pd.period_range("2013", freq="M", periods=3) df["timedeltas"] = pd.timedelta_range("1 day", periods=3) - # TODO temporary disable due to regression in pyarrow 0.17.1 - # https://github.com/pandas-dev/pandas/issues/34255 - # df["intervals"] = pd.interval_range(0, 3, 3) + df["intervals"] = pd.interval_range(0, 3, 3) assert df.dttz.dtype.tz.zone == "US/Eastern" self.check_round_trip(df)
Closes #34255
https://api.github.com/repos/pandas-dev/pandas/pulls/44155
2021-10-23T14:57:40Z
2021-10-23T17:50:44Z
2021-10-23T17:50:44Z
2021-10-23T17:54:37Z