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
CI: Fix jedi upgrades causes deprecation warning
diff --git a/pandas/tests/arrays/categorical/test_warnings.py b/pandas/tests/arrays/categorical/test_warnings.py index f66c327e9967d..9e164a250cdb1 100644 --- a/pandas/tests/arrays/categorical/test_warnings.py +++ b/pandas/tests/arrays/categorical/test_warnings.py @@ -14,6 +14,16 @@ async def test_tab_complete_warning(self, ip): code = "import pandas as pd; c = Categorical([])" await ip.run_code(code) - with tm.assert_produces_warning(None): + + # GH 31324 newer jedi version raises Deprecation warning + import jedi + + if jedi.__version__ < "0.16.0": + warning = tm.assert_produces_warning(None) + else: + warning = tm.assert_produces_warning( + DeprecationWarning, check_stacklevel=False + ) + with warning: with provisionalcompleter("ignore"): list(ip.Completer.completions("c.", 1)) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index d40a2257771a2..e72963de09ab4 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2413,7 +2413,17 @@ async def test_tab_complete_warning(self, ip): code = "import pandas as pd; idx = pd.Index([1, 2])" await ip.run_code(code) - with tm.assert_produces_warning(None): + + # GH 31324 newer jedi version raises Deprecation warning + import jedi + + if jedi.__version__ < "0.16.0": + warning = tm.assert_produces_warning(None) + else: + warning = tm.assert_produces_warning( + DeprecationWarning, check_stacklevel=False + ) + with warning: with provisionalcompleter("ignore"): list(ip.Completer.completions("idx.", 4))
- [ ] closes #31324 - [ ] 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/31323
2020-01-26T09:45:14Z
2020-01-27T12:28:10Z
2020-01-27T12:28:10Z
2020-01-27T15:49:41Z
CLN: dont return anything from _validate_indexer; annotations
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 10d9552e6f5a7..ae427d3b914e6 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3117,7 +3117,8 @@ def _convert_scalar_indexer(self, key, kind=None): assert kind in ["loc", "getitem", "iloc", None] if kind == "iloc": - return self._validate_indexer("positional", key, kind) + self._validate_indexer("positional", key, "iloc") + return key if len(self) and not isinstance(self, ABCMultiIndex): @@ -3126,11 +3127,11 @@ def _convert_scalar_indexer(self, key, kind=None): # or label indexing if we are using a type able # to be represented in the index - if kind in ["getitem"] and is_float(key): + if kind == "getitem" and is_float(key): if not self.is_floating(): self._invalid_indexer("label", key) - elif kind in ["loc"] and is_float(key): + elif kind == "loc" and is_float(key): # we want to raise KeyError on string/mixed here # technically we *could* raise a TypeError @@ -3144,7 +3145,7 @@ def _convert_scalar_indexer(self, key, kind=None): ]: self._invalid_indexer("label", key) - elif kind in ["loc"] and is_integer(key): + elif kind == "loc" and is_integer(key): if not self.holds_integer(): self._invalid_indexer("label", key) @@ -3170,11 +3171,10 @@ def _convert_slice_indexer(self, key: slice, kind=None): # validate iloc if kind == "iloc": - return slice( - self._validate_indexer("slice", key.start, kind), - self._validate_indexer("slice", key.stop, kind), - self._validate_indexer("slice", key.step, kind), - ) + self._validate_indexer("slice", key.start, "iloc") + self._validate_indexer("slice", key.stop, "iloc") + self._validate_indexer("slice", key.step, "iloc") + return key # potentially cast the bounds to integers start, stop, step = key.start, key.stop, key.step @@ -3195,11 +3195,10 @@ def is_int(v): integers """ if self.is_integer() or is_index_slice: - return slice( - self._validate_indexer("slice", key.start, kind), - self._validate_indexer("slice", key.stop, kind), - self._validate_indexer("slice", key.step, kind), - ) + self._validate_indexer("slice", key.start, "getitem") + self._validate_indexer("slice", key.stop, "getitem") + self._validate_indexer("slice", key.step, "getitem") + return key # convert the slice to an indexer here @@ -3329,7 +3328,7 @@ def _convert_list_indexer(self, keyarr, kind=None): return None - def _invalid_indexer(self, form, key): + def _invalid_indexer(self, form: str_t, key): """ Consistent invalid indexer message. """ @@ -4987,20 +4986,19 @@ def _maybe_cast_indexer(self, key): pass return key - def _validate_indexer(self, form, key, kind: str_t): + def _validate_indexer(self, form: str_t, key, kind: str_t): """ If we are positional indexer, validate that we have appropriate typed bounds must be an integer. """ - assert kind in ["loc", "getitem", "iloc"] + assert kind in ["getitem", "iloc"] if key is None: pass elif is_integer(key): pass - elif kind in ["iloc", "getitem"]: + else: self._invalid_indexer(form, key) - return key _index_shared_docs[ "_maybe_cast_slice_bound" @@ -5025,7 +5023,7 @@ def _validate_indexer(self, form, key, kind: str_t): """ @Appender(_index_shared_docs["_maybe_cast_slice_bound"]) - def _maybe_cast_slice_bound(self, label, side, kind): + def _maybe_cast_slice_bound(self, label, side: str_t, kind): assert kind in ["loc", "getitem", None] # We are a plain index here (sub-class override this method if they @@ -5056,7 +5054,7 @@ def _searchsorted_monotonic(self, label, side="left"): raise ValueError("index must be monotonic increasing or decreasing") - def get_slice_bound(self, label, side, kind) -> int: + def get_slice_bound(self, label, side: str_t, kind) -> int: """ Calculate slice bound that corresponds to given label. @@ -5241,7 +5239,7 @@ def insert(self, loc: int, item): idx = np.concatenate((_self[:loc], item, _self[loc:])) return self._shallow_copy_with_infer(idx) - def drop(self, labels, errors="raise"): + def drop(self, labels, errors: str_t = "raise"): """ Make new Index with passed list of labels deleted. diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 1a53596fb5967..e5a3b52584675 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -851,12 +851,12 @@ def _concat_same_dtype(self, to_concat, name): result.name = name return result - def _delegate_property_get(self, name, *args, **kwargs): + def _delegate_property_get(self, name: str, *args, **kwargs): """ method delegation to the ._values """ prop = getattr(self._values, name) return prop # no wrapping for now - def _delegate_method(self, name, *args, **kwargs): + def _delegate_method(self, name: str, *args, **kwargs): """ method delegation to the ._values """ method = getattr(self._values, name) if "inplace" in kwargs: diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 3afd1ff35806d..8ecc149caa6c5 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -489,7 +489,7 @@ def snap(self, freq="S"): dta = DatetimeArray(snapped, dtype=self.dtype) return DatetimeIndex._simple_new(dta, name=self.name) - def _parsed_string_to_bounds(self, reso, parsed): + def _parsed_string_to_bounds(self, reso: str, parsed: datetime): """ Calculate datetime bounds for parsed time string and its resolution. @@ -581,7 +581,7 @@ def _parsed_string_to_bounds(self, reso, parsed): return start, end def _partial_date_slice( - self, reso: str, parsed, use_lhs: bool = True, use_rhs: bool = True + self, reso: str, parsed: datetime, use_lhs: bool = True, use_rhs: bool = True ): """ Parameters @@ -698,7 +698,7 @@ def get_loc(self, key, method=None, tolerance=None): return Index.get_loc(self, key, method, tolerance) - def _maybe_cast_for_get_loc(self, key): + def _maybe_cast_for_get_loc(self, key) -> Timestamp: # needed to localize naive datetimes key = Timestamp(key) if key.tzinfo is None: @@ -707,7 +707,7 @@ def _maybe_cast_for_get_loc(self, key): key = key.tz_convert(self.tz) return key - def _maybe_cast_slice_bound(self, label, side, kind): + def _maybe_cast_slice_bound(self, label, side: str, kind): """ If label is a string, cast it to datetime according to resolution. diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 6a10b3650293c..9eaddf2edeb6c 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -107,7 +107,7 @@ def wrapper(cls): return wrapper -def _make_wrapped_comparison_op(opname): +def _make_wrapped_comparison_op(opname: str): """ Create a comparison method that dispatches to ``._data``. """ @@ -127,7 +127,7 @@ def wrapper(self, other): return wrapper -def make_wrapped_arith_op(opname): +def make_wrapped_arith_op(opname: str): def method(self, other): meth = getattr(self._data, opname) result = meth(_maybe_unwrap_index(other)) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 26b64836172fd..8d7716f80ad17 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -216,6 +216,7 @@ class IntervalIndex(IntervalMixin, ExtensionIndex): # Immutable, so we are able to cache computations like isna in '_mask' _mask = None + _data: IntervalArray # -------------------------------------------------------------------- # Constructors @@ -394,11 +395,11 @@ def __contains__(self, key: Any) -> bool: return False @cache_readonly - def _multiindex(self): + def _multiindex(self) -> MultiIndex: return MultiIndex.from_arrays([self.left, self.right], names=["left", "right"]) @cache_readonly - def values(self): + def values(self) -> IntervalArray: """ Return the IntervalIndex's data as an IntervalArray. """ diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index aece294edc3e3..f7af82920adb1 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -393,7 +393,7 @@ def _convert_scalar_indexer(self, key, kind=None): assert kind in ["loc", "getitem", "iloc", None] if kind == "iloc": - return self._validate_indexer("positional", key, kind) + self._validate_indexer("positional", key, "iloc") return key diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 1e18c16d02784..188fb4f05857c 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -383,7 +383,7 @@ def __contains__(self, key: Any) -> bool: return False @cache_readonly - def _int64index(self): + def _int64index(self) -> Int64Index: return Int64Index._simple_new(self.asi8, name=self.name) # ------------------------------------------------------------------------ @@ -606,7 +606,7 @@ def get_loc(self, key, method=None, tolerance=None): except KeyError: raise KeyError(key) - def _maybe_cast_slice_bound(self, label, side, kind): + def _maybe_cast_slice_bound(self, label, side: str, kind: str): """ If label is a string or a datetime, cast it to Period.ordinal according to resolution. @@ -810,7 +810,7 @@ def _union(self, other, sort): # ------------------------------------------------------------------------ - def _apply_meta(self, rawarr): + def _apply_meta(self, rawarr) -> "PeriodIndex": if not isinstance(rawarr, PeriodIndex): if not isinstance(rawarr, PeriodArray): rawarr = PeriodArray(rawarr, freq=self.freq) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 22940f851ddb0..340397b69c624 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -400,7 +400,7 @@ def copy(self, name=None, deep=False, dtype=None, **kwargs): name = self.name return self.from_range(self._range, name=name) - def _minmax(self, meth): + def _minmax(self, meth: str): no_steps = len(self) - 1 if no_steps == -1: return np.nan @@ -409,13 +409,13 @@ def _minmax(self, meth): return self.start + self.step * no_steps - def min(self, axis=None, skipna=True, *args, **kwargs): + def min(self, axis=None, skipna=True, *args, **kwargs) -> int: """The minimum value of the RangeIndex""" nv.validate_minmax_axis(axis) nv.validate_min(args, kwargs) return self._minmax("min") - def max(self, axis=None, skipna=True, *args, **kwargs): + def max(self, axis=None, skipna=True, *args, **kwargs) -> int: """The maximum value of the RangeIndex""" nv.validate_minmax_axis(axis) nv.validate_max(args, kwargs) @@ -519,12 +519,12 @@ def intersection(self, other, sort=False): new_index = new_index.sort_values() return new_index - def _min_fitting_element(self, lower_limit): + def _min_fitting_element(self, lower_limit: int) -> int: """Returns the smallest element greater than or equal to the limit""" no_steps = -(-(lower_limit - self.start) // abs(self.step)) return self.start + abs(self.step) * no_steps - def _max_fitting_element(self, upper_limit): + def _max_fitting_element(self, upper_limit: int) -> int: """Returns the largest element smaller than or equal to the limit""" no_steps = (upper_limit - self.start) // abs(self.step) return self.start + abs(self.step) * no_steps diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 1257e410b4125..7cd328c51d39f 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -277,7 +277,7 @@ def get_loc(self, key, method=None, tolerance=None): return Index.get_loc(self, key, method, tolerance) - def _maybe_cast_slice_bound(self, label, side, kind): + def _maybe_cast_slice_bound(self, label, side: str, kind): """ If label is a string, cast it to timedelta according to resolution.
https://api.github.com/repos/pandas-dev/pandas/pulls/31321
2020-01-26T04:07:50Z
2020-01-31T03:41:02Z
2020-01-31T03:41:02Z
2020-01-31T04:15:16Z
Backport PR: Series rolling count ignores min_periods
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index a820ef132957a..9d5289ae8f2d0 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -1165,6 +1165,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.groupby` when using nunique on axis=1 (:issue:`30253`) - Bug in :meth:`GroupBy.quantile` with multiple list-like q value and integer column names (:issue:`30289`) - Bug in :meth:`GroupBy.pct_change` and :meth:`core.groupby.SeriesGroupBy.pct_change` causes ``TypeError`` when ``fill_method`` is ``None`` (:issue:`30463`) +- Bug in :meth:`Rolling.count` and :meth:`Expanding.count` argument where ``min_periods`` was ignored (:issue:`26996`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index f612826132fd7..c1e34757b45d4 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1182,17 +1182,13 @@ class _Rolling_and_Expanding(_Rolling): def count(self): blocks, obj = self._create_blocks() - - window = self._get_window() - window = min(window, len(obj)) if not self.center else window - results = [] for b in blocks: result = b.notna().astype(int) result = self._constructor( result, - window=window, - min_periods=0, + window=self._get_window(), + min_periods=self.min_periods or 0, center=self.center, axis=self.axis, closed=self.closed, @@ -1657,7 +1653,11 @@ def _get_cov(X, Y): mean = lambda x: x.rolling( window, self.min_periods, center=self.center ).mean(**kwargs) - count = (X + Y).rolling(window=window, center=self.center).count(**kwargs) + count = ( + (X + Y) + .rolling(window=window, min_periods=0, center=self.center) + .count(**kwargs) + ) bias_adj = count / (count - ddof) return (mean(X * Y) - mean(X) * mean(Y)) * bias_adj diff --git a/pandas/tests/window/moments/test_moments_expanding.py b/pandas/tests/window/moments/test_moments_expanding.py index 4596552d8f255..983aa30560688 100644 --- a/pandas/tests/window/moments/test_moments_expanding.py +++ b/pandas/tests/window/moments/test_moments_expanding.py @@ -38,9 +38,9 @@ def test_expanding_corr(self): tm.assert_almost_equal(rolling_result, result) def test_expanding_count(self): - result = self.series.expanding().count() + result = self.series.expanding(min_periods=0).count() tm.assert_almost_equal( - result, self.series.rolling(window=len(self.series)).count() + result, self.series.rolling(window=len(self.series), min_periods=0).count() ) def test_expanding_quantile(self): @@ -358,7 +358,7 @@ def test_expanding_consistency(self, min_periods): ) self._test_moments_consistency( min_periods=min_periods, - count=lambda x: x.expanding().count(), + count=lambda x: x.expanding(min_periods=min_periods).count(), mean=lambda x: x.expanding(min_periods=min_periods).mean(), corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y), var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(), diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py index 9acb4ffcb40b8..83e4ee25558b5 100644 --- a/pandas/tests/window/moments/test_moments_rolling.py +++ b/pandas/tests/window/moments/test_moments_rolling.py @@ -777,8 +777,8 @@ def get_result(obj, window, min_periods=None, center=False): series_result = get_result(series, window=win, min_periods=minp) frame_result = get_result(frame, window=win, min_periods=minp) else: - series_result = get_result(series, window=win) - frame_result = get_result(frame, window=win) + series_result = get_result(series, window=win, min_periods=0) + frame_result = get_result(frame, window=win, min_periods=0) last_date = series_result.index[-1] prev_date = last_date - 24 * offsets.BDay() @@ -835,8 +835,8 @@ def get_result(obj, window, min_periods=None, center=False): nan_mask = ~nan_mask tm.assert_almost_equal(result[nan_mask], expected[nan_mask]) else: - result = get_result(self.series, len(self.series) + 1) - expected = get_result(self.series, len(self.series)) + result = get_result(self.series, len(self.series) + 1, min_periods=0) + expected = get_result(self.series, len(self.series), min_periods=0) nan_mask = isna(result) tm.assert_series_equal(nan_mask, isna(expected)) @@ -851,10 +851,11 @@ def get_result(obj, window, min_periods=None, center=False): pd.concat([obj, Series([np.NaN] * 9)]), 20, min_periods=15 )[9:].reset_index(drop=True) else: - result = get_result(obj, 20, center=True) - expected = get_result(pd.concat([obj, Series([np.NaN] * 9)]), 20)[ - 9: - ].reset_index(drop=True) + result = get_result(obj, 20, min_periods=0, center=True) + print(result) + expected = get_result( + pd.concat([obj, Series([np.NaN] * 9)]), 20, min_periods=0 + )[9:].reset_index(drop=True) tm.assert_series_equal(result, expected) @@ -893,21 +894,27 @@ def get_result(obj, window, min_periods=None, center=False): else: series_xp = ( get_result( - self.series.reindex(list(self.series.index) + s), window=25 + self.series.reindex(list(self.series.index) + s), + window=25, + min_periods=0, ) .shift(-12) .reindex(self.series.index) ) frame_xp = ( get_result( - self.frame.reindex(list(self.frame.index) + s), window=25 + self.frame.reindex(list(self.frame.index) + s), + window=25, + min_periods=0, ) .shift(-12) .reindex(self.frame.index) ) - series_rs = get_result(self.series, window=25, center=True) - frame_rs = get_result(self.frame, window=25, center=True) + series_rs = get_result( + self.series, window=25, min_periods=0, center=True + ) + frame_rs = get_result(self.frame, window=25, min_periods=0, center=True) if fill_value is not None: series_xp = series_xp.fillna(fill_value) @@ -964,7 +971,11 @@ def test_rolling_consistency(self, window, min_periods, center): self._test_moments_consistency_is_constant( min_periods=min_periods, - count=lambda x: (x.rolling(window=window, center=center).count()), + count=lambda x: ( + x.rolling( + window=window, min_periods=min_periods, center=center + ).count() + ), mean=lambda x: ( x.rolling( window=window, min_periods=min_periods, center=center @@ -989,19 +1000,26 @@ def test_rolling_consistency(self, window, min_periods, center): ).var(ddof=0) ), var_debiasing_factors=lambda x: ( - x.rolling(window=window, center=center) + x.rolling(window=window, min_periods=min_periods, center=center) .count() .divide( - (x.rolling(window=window, center=center).count() - 1.0).replace( - 0.0, np.nan - ) + ( + x.rolling( + window=window, min_periods=min_periods, center=center + ).count() + - 1.0 + ).replace(0.0, np.nan) ) ), ) self._test_moments_consistency( min_periods=min_periods, - count=lambda x: (x.rolling(window=window, center=center).count()), + count=lambda x: ( + x.rolling( + window=window, min_periods=min_periods, center=center + ).count() + ), mean=lambda x: ( x.rolling( window=window, min_periods=min_periods, center=center @@ -1071,7 +1089,7 @@ def test_rolling_consistency(self, window, min_periods, center): if name == "count": rolling_f_result = rolling_f() rolling_apply_f_result = x.rolling( - window=window, min_periods=0, center=center + window=window, min_periods=min_periods, center=center ).apply(func=f, raw=True) else: if name in ["cov", "corr"]: diff --git a/pandas/tests/window/test_api.py b/pandas/tests/window/test_api.py index 5e70e13209de5..680237db0535b 100644 --- a/pandas/tests/window/test_api.py +++ b/pandas/tests/window/test_api.py @@ -237,10 +237,10 @@ def test_count_nonnumeric_types(self): columns=cols, ) - result = df.rolling(window=2).count() + result = df.rolling(window=2, min_periods=0).count() tm.assert_frame_equal(result, expected) - result = df.rolling(1).count() + result = df.rolling(1, min_periods=0).count() expected = df.notna().astype(float) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py index fc4bd50f25c73..6b6367fd80b26 100644 --- a/pandas/tests/window/test_expanding.py +++ b/pandas/tests/window/test_expanding.py @@ -113,3 +113,22 @@ def test_expanding_axis(self, axis_frame): result = df.expanding(3, axis=axis_frame).sum() tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("constructor", [Series, DataFrame]) +def test_expanding_count_with_min_periods(constructor): + # GH 26996 + result = constructor(range(5)).expanding(min_periods=3).count() + expected = constructor([np.nan, np.nan, 3.0, 4.0, 5.0]) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("constructor", [Series, DataFrame]) +def test_expanding_count_default_min_periods_with_null_values(constructor): + # GH 26996 + values = [1, 2, 3, np.nan, 4, 5, 6] + expected_counts = [1.0, 2.0, 3.0, 3.0, 4.0, 5.0, 6.0] + + result = constructor(values).expanding().count() + expected = constructor(expected_counts) + tm.assert_equal(result, expected) diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 04fab93b71c4a..80a732c6f88df 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -324,7 +324,7 @@ def test_rolling_axis_count(self, axis_frame): else: expected = DataFrame({"x": [1.0, 1.0, 1.0], "y": [2.0, 2.0, 2.0]}) - result = df.rolling(2, axis=axis_frame).count() + result = df.rolling(2, axis=axis_frame, min_periods=0).count() tm.assert_frame_equal(result, expected) def test_readonly_array(self): @@ -426,3 +426,22 @@ def test_min_periods1(): result = df["a"].rolling(3, center=True, min_periods=1).max() expected = pd.Series([1.0, 2.0, 2.0, 2.0, 1.0], name="a") tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("constructor", [Series, DataFrame]) +def test_rolling_count_with_min_periods(constructor): + # GH 26996 + result = constructor(range(5)).rolling(3, min_periods=3).count() + expected = constructor([np.nan, np.nan, 3.0, 3.0, 3.0]) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("constructor", [Series, DataFrame]) +def test_rolling_count_default_min_periods_with_null_values(constructor): + # GH 26996 + values = [1, 2, 3, np.nan, 4, 5, 6] + expected_counts = [1.0, 2.0, 3.0, 2.0, 2.0, 2.0, 3.0] + + result = constructor(values).rolling(3).count() + expected = constructor(expected_counts) + tm.assert_equal(result, expected)
This is a backport for #30923
https://api.github.com/repos/pandas-dev/pandas/pulls/31320
2020-01-26T02:46:14Z
2020-01-26T04:17:59Z
2020-01-26T04:17:59Z
2020-01-26T04:44:44Z
REF: make PeriodIndex.get_value wrap PeriodIndex.get_loc
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index fe6c1ba808f9a..ab6db7780b283 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 TYPE_CHECKING, Any import weakref import numpy as np @@ -20,6 +20,7 @@ is_integer_dtype, is_list_like, is_object_dtype, + is_scalar, pandas_dtype, ) @@ -33,6 +34,7 @@ import pandas.core.common as com import pandas.core.indexes.base as ibase from pandas.core.indexes.base import ( + InvalidIndexError, _index_shared_docs, ensure_index, maybe_extract_name, @@ -52,6 +54,8 @@ _index_doc_kwargs = dict(ibase._index_doc_kwargs) _index_doc_kwargs.update(dict(target_klass="PeriodIndex or list of Periods")) +if TYPE_CHECKING: + from pandas import Series # --- Period index sketch @@ -474,43 +478,16 @@ def inferred_type(self) -> str: # indexing return "period" - def get_value(self, series, key): + def get_value(self, series: "Series", key): """ Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ if is_integer(key): - return series.iat[key] - - if isinstance(key, str): - try: - loc = self._get_string_slice(key) - return series[loc] - except (TypeError, ValueError, OverflowError): - pass - - asdt, reso = parse_time_string(key, self.freq) - grp = resolution.Resolution.get_freq_group(reso) - freqn = resolution.get_freq_group(self.freq) - - # _get_string_slice will handle cases where grp < freqn - assert grp >= freqn - - if grp == freqn: - key = Period(asdt, freq=self.freq) - loc = self.get_loc(key) - return series.iloc[loc] - else: - raise KeyError(key) - - elif isinstance(key, Period) or key is NaT: - ordinal = key.ordinal if key is not NaT else NaT.value - loc = self._engine.get_loc(ordinal) - return series[loc] - - # slice, PeriodIndex, np.ndarray, List[Period] - value = Index.get_value(self, series, key) - return com.maybe_box(self, value, series, key) + loc = key + else: + loc = self.get_loc(key) + return self._get_values_for_loc(series, loc) @Appender(_index_shared_docs["get_indexer"] % _index_doc_kwargs) def get_indexer(self, target, method=None, limit=None, tolerance=None): @@ -566,6 +543,9 @@ def get_loc(self, key, method=None, tolerance=None): If key is listlike or otherwise not hashable. """ + if not is_scalar(key): + raise InvalidIndexError(key) + if isinstance(key, str): try: diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 4c1438915ab33..38514594efe09 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -1,4 +1,5 @@ from datetime import datetime, timedelta +import re import numpy as np import pytest @@ -8,6 +9,7 @@ import pandas as pd from pandas import DatetimeIndex, Period, PeriodIndex, Series, notna, period_range import pandas._testing as tm +from pandas.core.indexes.base import InvalidIndexError class TestGetItem: @@ -408,11 +410,7 @@ def test_get_loc(self): with pytest.raises(KeyError, match=r"^1\.1$"): idx0.get_loc(1.1) - msg = ( - r"'PeriodIndex\(\['2017-09-01', '2017-09-02', '2017-09-03'\], " - r"dtype='period\[D\]', freq='D'\)' is an invalid key" - ) - with pytest.raises(TypeError, match=msg): + with pytest.raises(InvalidIndexError, match=re.escape(str(idx0))): idx0.get_loc(idx0) # get the location of p1/p2 from @@ -433,11 +431,7 @@ def test_get_loc(self): with pytest.raises(KeyError, match=r"^1\.1$"): idx1.get_loc(1.1) - msg = ( - r"'PeriodIndex\(\['2017-09-02', '2017-09-02', '2017-09-03'\], " - r"dtype='period\[D\]', freq='D'\)' is an invalid key" - ) - with pytest.raises(TypeError, match=msg): + with pytest.raises(InvalidIndexError, match=re.escape(str(idx1))): idx1.get_loc(idx1) # get the location of p1/p2 from @@ -461,16 +455,46 @@ def test_get_loc_integer(self): with pytest.raises(KeyError, match="46"): pi2.get_loc(46) + @pytest.mark.parametrize("freq", ["H", "D"]) + def test_get_value_datetime_hourly(self, freq): + # get_loc and get_value should treat datetime objects symmetrically + dti = pd.date_range("2016-01-01", periods=3, freq="MS") + pi = dti.to_period(freq) + ser = pd.Series(range(7, 10), index=pi) + + ts = dti[0] + + assert pi.get_loc(ts) == 0 + assert pi.get_value(ser, ts) == 7 + assert ser[ts] == 7 + assert ser.loc[ts] == 7 + + ts2 = ts + pd.Timedelta(hours=3) + if freq == "H": + with pytest.raises(KeyError, match="2016-01-01 03:00"): + pi.get_loc(ts2) + with pytest.raises(KeyError, match="2016-01-01 03:00"): + pi.get_value(ser, ts2) + with pytest.raises(KeyError, match="2016-01-01 03:00"): + ser[ts2] + with pytest.raises(KeyError, match="2016-01-01 03:00"): + ser.loc[ts2] + else: + assert pi.get_loc(ts2) == 0 + assert pi.get_value(ser, ts2) == 7 + assert ser[ts2] == 7 + assert ser.loc[ts2] == 7 + def test_get_value_integer(self): dti = pd.date_range("2016-01-01", periods=3) pi = dti.to_period("D") ser = pd.Series(range(3), index=pi) - with pytest.raises(IndexError, match="is out of bounds for axis 0 with size 3"): + with pytest.raises(IndexError, match="index out of bounds"): pi.get_value(ser, 16801) pi2 = dti.to_period("Y") # duplicates, ordinals are all 46 ser2 = pd.Series(range(3), index=pi2) - with pytest.raises(IndexError, match="is out of bounds for axis 0 with size 3"): + with pytest.raises(IndexError, match="index out of bounds"): pi2.get_value(ser2, 46) def test_is_monotonic_increasing(self): @@ -544,25 +568,25 @@ def test_get_value(self): p2 = pd.Period("2017-09-03") idx0 = pd.PeriodIndex([p0, p1, p2]) - input0 = np.array([1, 2, 3]) + input0 = pd.Series(np.array([1, 2, 3]), index=idx0) expected0 = 2 result0 = idx0.get_value(input0, p1) assert result0 == expected0 idx1 = pd.PeriodIndex([p1, p1, p2]) - input1 = np.array([1, 2, 3]) - expected1 = np.array([1, 2]) + input1 = pd.Series(np.array([1, 2, 3]), index=idx1) + expected1 = input1.iloc[[0, 1]] result1 = idx1.get_value(input1, p1) - tm.assert_numpy_array_equal(result1, expected1) + tm.assert_series_equal(result1, expected1) idx2 = pd.PeriodIndex([p1, p2, p1]) - input2 = np.array([1, 2, 3]) - expected2 = np.array([1, 3]) + input2 = pd.Series(np.array([1, 2, 3]), index=idx2) + expected2 = input2.iloc[[0, 2]] result2 = idx2.get_value(input2, p1) - tm.assert_numpy_array_equal(result2, expected2) + tm.assert_series_equal(result2, expected2) def test_get_indexer(self): # GH 17717
AFAICT the only behavior this changes is in how datetime objects are treated. After this they are more consistent. ``` dti = pd.date_range("2016-01-01", periods=3, freq="MS") pi = dti.to_period("H") ser = pd.Series(range(7, 10), index=pi) key = dti[0] ``` master ``` >>> pi.get_loc(key) 0 >>> pi.get_value(ser, key) KeyError: Timestamp('2016-01-01 00:00:00', freq='MS') >>> ser.loc[key] 7 >>> ser[key] KeyError: Timestamp('2016-01-01 00:00:00', freq='MS') ``` Under this PR, the get_value and `__getitem__` calls both return 7.
https://api.github.com/repos/pandas-dev/pandas/pulls/31318
2020-01-26T01:34:53Z
2020-01-28T02:22:56Z
2020-01-28T02:22:55Z
2020-03-12T13:31:07Z
Move DataFrame.info() to live with similar functions
diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index dd2af6e2799c3..c7b1cc1c832be 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -28,6 +28,7 @@ Attributes and underlying data :toctree: api/ DataFrame.dtypes + DataFrame.info DataFrame.select_dtypes DataFrame.values DataFrame.axes @@ -347,7 +348,6 @@ Serialization / IO / conversion DataFrame.from_dict DataFrame.from_records - DataFrame.info DataFrame.to_parquet DataFrame.to_pickle DataFrame.to_csv
#31233 - [x ] closes #31233 (Not sure these are relevant for a doc change?) - [ ] tests added / passed - [ ] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/31317
2020-01-26T00:23:12Z
2020-01-26T01:15:23Z
2020-01-26T01:15:23Z
2020-01-29T04:39:19Z
CLN: internals.managers
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 847f543ebca4d..a3675a1a58fd3 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -3,7 +3,7 @@ import itertools import operator import re -from typing import List, Optional, Sequence, Tuple, Union +from typing import Dict, List, Optional, Sequence, Tuple, Union import numpy as np @@ -181,7 +181,7 @@ def set_axis(self, axis, new_labels): self.axes[axis] = new_labels - def rename_axis(self, mapper, axis, copy=True, level=None): + def rename_axis(self, mapper, axis, copy: bool = True, level=None): """ Rename one of axes. @@ -189,7 +189,7 @@ def rename_axis(self, mapper, axis, copy=True, level=None): ---------- mapper : unary callable axis : int - copy : boolean, default True + copy : bool, default True level : int, default None """ obj = self.copy(deep=copy) @@ -197,7 +197,7 @@ def rename_axis(self, mapper, axis, copy=True, level=None): return obj @property - def _is_single_block(self): + def _is_single_block(self) -> bool: if self.ndim == 1: return True @@ -441,9 +441,9 @@ def quantile( Parameters ---------- axis: reduction axis, default 0 - consolidate: boolean, default True. Join together blocks having same + consolidate: bool, default True. Join together blocks having same dtype - transposed: boolean, default False + transposed: bool, default False we are holding transposed data interpolation : type of interpolation, default 'linear' qs : a scalar or list of the quantiles to be computed @@ -525,7 +525,9 @@ def get_axe(block, qs, axes): values = values.take(indexer) return SingleBlockManager( - [make_block(values, ndim=1, placement=np.arange(len(values)))], axes[0] + make_block(values, ndim=1, placement=np.arange(len(values))), + axes[0], + fastpath=True, ) def isna(self, func): @@ -635,24 +637,24 @@ def _consolidate_check(self): self._known_consolidated = True @property - def is_mixed_type(self): + def is_mixed_type(self) -> bool: # Warning, consolidation needs to get checked upstairs self._consolidate_inplace() return len(self.blocks) > 1 @property - def is_numeric_mixed_type(self): + def is_numeric_mixed_type(self) -> bool: # Warning, consolidation needs to get checked upstairs self._consolidate_inplace() return all(block.is_numeric for block in self.blocks) @property - def any_extension_types(self): + def any_extension_types(self) -> bool: """Whether any of the blocks in this manager are extension blocks""" return any(block.is_extension for block in self.blocks) @property - def is_view(self): + def is_view(self) -> bool: """ return a boolean if we are a single block and are a view """ if len(self.blocks) == 1: return self.blocks[0].is_view @@ -666,21 +668,21 @@ def is_view(self): return False - def get_bool_data(self, copy=False): + def get_bool_data(self, copy: bool = False): """ Parameters ---------- - copy : boolean, default False + copy : bool, default False Whether to copy the blocks """ self._consolidate_inplace() return self.combine([b for b in self.blocks if b.is_bool], copy) - def get_numeric_data(self, copy=False): + def get_numeric_data(self, copy: bool = False): """ Parameters ---------- - copy : boolean, default False + copy : bool, default False Whether to copy the blocks """ self._consolidate_inplace() @@ -772,8 +774,8 @@ def as_array(self, transpose: bool = False) -> np.ndarray: Parameters ---------- - transpose : boolean, default False - If True, transpose the return array + transpose : bool, default False + If True, transpose the return array, Returns ------- @@ -825,13 +827,13 @@ def _interleave(self): return result - def to_dict(self, copy=True): + def to_dict(self, copy: bool = True): """ Return a dict of str(dtype) -> BlockManager Parameters ---------- - copy : boolean, default True + copy : bool, default True Returns ------- @@ -843,7 +845,7 @@ def to_dict(self, copy=True): """ self._consolidate_inplace() - bd = {} + bd: Dict[str, List[Block]] = {} for b in self.blocks: bd.setdefault(str(b.dtype), []).append(b) @@ -944,21 +946,18 @@ def get(self, item): def iget(self, i): """ - Return the data as a SingleBlockManager if possible - - Otherwise return as a ndarray + Return the data as a SingleBlockManager. """ block = self.blocks[self._blknos[i]] values = block.iget(self._blklocs[i]) # shortcut for select a single-dim from a 2-dim BM return SingleBlockManager( - [ - block.make_block_same_class( - values, placement=slice(0, len(values)), ndim=1 - ) - ], + block.make_block_same_class( + values, placement=slice(0, len(values)), ndim=1 + ), self.axes[1], + fastpath=True, ) def delete(self, item): @@ -1360,7 +1359,7 @@ def take(self, indexer, axis=1, verify=True, convert=True): new_axis=new_labels, indexer=indexer, axis=axis, allow_dups=True ) - def equals(self, other): + def equals(self, other) -> bool: self_axes, other_axes = self.axes, other.axes if len(self_axes) != len(other_axes): return False @@ -1385,7 +1384,8 @@ def canonicalize(block): ) def unstack(self, unstacker_func, fill_value): - """Return a blockmanager with all blocks unstacked. + """ + Return a BlockManager with all blocks unstacked.. Parameters ---------- @@ -1538,7 +1538,7 @@ def get_values(self): return np.array(self._block.to_dense(), copy=False) @property - def _can_hold_na(self): + def _can_hold_na(self) -> bool: return self._block._can_hold_na def is_consolidated(self): @@ -1567,7 +1567,7 @@ def fast_xs(self, loc): """ return self._block.values[loc] - def concat(self, to_concat, new_axis): + def concat(self, to_concat, new_axis) -> "SingleBlockManager": """ Concatenate a list of SingleBlockManagers into a single SingleBlockManager. @@ -1582,7 +1582,6 @@ def concat(self, to_concat, new_axis): Returns ------- SingleBlockManager - """ non_empties = [x for x in to_concat if len(x) > 0]
Mostly annotations, use fastpath for SingleBlockManager constructor where possible.
https://api.github.com/repos/pandas-dev/pandas/pulls/31316
2020-01-25T23:27:06Z
2020-01-26T00:14:20Z
2020-01-26T00:14:20Z
2020-01-26T00:32:50Z
REF: tighten what we accept in TimedeltaIndex._simple_new
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index d77a37ad355a7..a7b16fd86468e 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -195,9 +195,12 @@ def __init__(self, values, dtype=_TD_DTYPE, freq=None, copy=False): def _simple_new(cls, values, freq=None, dtype=_TD_DTYPE): assert dtype == _TD_DTYPE, dtype assert isinstance(values, np.ndarray), type(values) + if values.dtype != _TD_DTYPE: + assert values.dtype == "i8" + values = values.view(_TD_DTYPE) result = object.__new__(cls) - result._data = values.view(_TD_DTYPE) + result._data = values result._freq = to_offset(freq) result._dtype = _TD_DTYPE return result diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index b87dd0f02252f..7fa92596dc23b 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -570,7 +570,8 @@ def delete(self, loc): if loc.start in (0, None) or loc.stop in (len(self), None): freq = self.freq - return self._shallow_copy(new_i8s, freq=freq) + arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq) + return type(self)._simple_new(arr, name=self.name) class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): @@ -611,6 +612,14 @@ def _shallow_copy(self, values=None, **kwargs): if values is None: values = self._data + if isinstance(values, type(self)): + values = values._data + if isinstance(values, np.ndarray): + # TODO: We would rather not get here + if kwargs.get("freq") is not None: + raise ValueError(kwargs) + values = type(self._data)(values, dtype=self.dtype) + attributes = self._get_attributes_dict() if "freq" not in kwargs and self.freq is not None: @@ -789,7 +798,10 @@ def _union(self, other, sort): this, other = self._maybe_utc_convert(other) if this._can_fast_union(other): - return this._fast_union(other, sort=sort) + result = this._fast_union(other, sort=sort) + if result.freq is None: + result._set_freq("infer") + return result else: result = Index._union(this, other, sort=sort) if isinstance(result, type(self)): @@ -923,7 +935,8 @@ def insert(self, loc, item): new_i8s = np.concatenate( (self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8) ) - return self._shallow_copy(new_i8s, freq=freq) + arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq) + return type(self)._simple_new(arr, name=self.name) except (AttributeError, TypeError): # fall back to object index diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index e78714487f01e..67e730abd9911 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -185,22 +185,15 @@ def __new__( def _simple_new(cls, values, name=None, freq=None, dtype=_TD_DTYPE): # `dtype` is passed by _shallow_copy in corner cases, should always # be timedelta64[ns] if present - - if not isinstance(values, TimedeltaArray): - values = TimedeltaArray._simple_new(values, dtype=dtype, freq=freq) - else: - if freq is None: - freq = values.freq - assert isinstance(values, TimedeltaArray), type(values) assert dtype == _TD_DTYPE, dtype - assert values.dtype == "m8[ns]", values.dtype + assert isinstance(values, TimedeltaArray) + assert freq is None or values.freq == freq - tdarr = TimedeltaArray._simple_new(values._data, freq=freq) result = object.__new__(cls) - result._data = tdarr + result._data = values result._name = name # For groupby perf. See note in indexes/base about _index_data - result._index_data = tdarr._data + result._index_data = values._data result._reset_identity() return result diff --git a/pandas/core/resample.py b/pandas/core/resample.py index fb837409a00f5..94ff1f0056663 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -23,6 +23,7 @@ from pandas.core.groupby.groupby import GroupBy, _GroupBy, _pipe_template, get_groupby from pandas.core.groupby.grouper import Grouper from pandas.core.groupby.ops import BinGrouper +from pandas.core.indexes.api import Index from pandas.core.indexes.datetimes import DatetimeIndex, date_range from pandas.core.indexes.period import PeriodIndex, period_range from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range @@ -424,10 +425,7 @@ def _wrap_result(self, result): if isinstance(result, ABCSeries) and result.empty: obj = self.obj - if isinstance(obj.index, PeriodIndex): - result.index = obj.index.asfreq(self.freq) - else: - result.index = obj.index._shallow_copy(freq=self.freq) + result.index = _asfreq_compat(obj.index, freq=self.freq) result.name = getattr(obj, "name", None) return result @@ -1787,8 +1785,8 @@ def asfreq(obj, freq, method=None, how=None, normalize=False, fill_value=None): elif len(obj.index) == 0: new_obj = obj.copy() - new_obj.index = obj.index._shallow_copy(freq=to_offset(freq)) + new_obj.index = _asfreq_compat(obj.index, freq) else: dti = date_range(obj.index[0], obj.index[-1], freq=freq) dti.name = obj.index.name @@ -1797,3 +1795,28 @@ def asfreq(obj, freq, method=None, how=None, normalize=False, fill_value=None): new_obj.index = new_obj.index.normalize() return new_obj + + +def _asfreq_compat(index, freq): + """ + Helper to mimic asfreq on (empty) DatetimeIndex and TimedeltaIndex. + + Parameters + ---------- + index : PeriodIndex, DatetimeIndex, or TimedeltaIndex + freq : DateOffset + + Returns + ------- + same type as index + """ + if len(index) != 0: + # This should never be reached, always checked by the caller + raise ValueError( + "Can only set arbitrary freq for empty DatetimeIndex or TimedeltaIndex" + ) + if isinstance(index, PeriodIndex): + new_index = index.asfreq(freq=freq) + else: + new_index = Index([], dtype=index.dtype, freq=freq, name=index.name) + return new_index diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py index f8a1810e66219..c84a5bf653b0a 100644 --- a/pandas/tests/resample/test_base.py +++ b/pandas/tests/resample/test_base.py @@ -11,6 +11,7 @@ from pandas.core.indexes.datetimes import date_range from pandas.core.indexes.period import PeriodIndex, period_range from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range +from pandas.core.resample import _asfreq_compat # a fixture value can be overridden by the test parameter value. Note that the # value of the fixture can be overridden this way even if the test doesn't use @@ -103,10 +104,8 @@ def test_resample_empty_series(freq, empty_series, resample_method): result = getattr(s.resample(freq), resample_method)() expected = s.copy() - if isinstance(s.index, PeriodIndex): - expected.index = s.index.asfreq(freq=freq) - else: - expected.index = s.index._shallow_copy(freq=freq) + expected.index = _asfreq_compat(s.index, freq) + tm.assert_index_equal(result.index, expected.index) assert result.index.freq == expected.index.freq tm.assert_series_equal(result, expected, check_dtype=False) @@ -119,10 +118,8 @@ def test_resample_count_empty_series(freq, empty_series, resample_method): # GH28427 result = getattr(empty_series.resample(freq), resample_method)() - if isinstance(empty_series.index, PeriodIndex): - index = empty_series.index.asfreq(freq=freq) - else: - index = empty_series.index._shallow_copy(freq=freq) + index = _asfreq_compat(empty_series.index, freq) + expected = pd.Series([], dtype="int64", index=index, name=empty_series.name) tm.assert_series_equal(result, expected) @@ -141,10 +138,8 @@ def test_resample_empty_dataframe(empty_frame, freq, resample_method): # GH14962 expected = Series([], dtype=object) - if isinstance(df.index, PeriodIndex): - expected.index = df.index.asfreq(freq=freq) - else: - expected.index = df.index._shallow_copy(freq=freq) + expected.index = _asfreq_compat(df.index, freq) + tm.assert_index_equal(result.index, expected.index) assert result.index.freq == expected.index.freq tm.assert_almost_equal(result, expected, check_dtype=False) @@ -162,10 +157,8 @@ def test_resample_count_empty_dataframe(freq, empty_frame): result = empty_frame.resample(freq).count() - if isinstance(empty_frame.index, PeriodIndex): - index = empty_frame.index.asfreq(freq=freq) - else: - index = empty_frame.index._shallow_copy(freq=freq) + index = _asfreq_compat(empty_frame.index, freq) + expected = pd.DataFrame({"a": []}, dtype="int64", index=index) tm.assert_frame_equal(result, expected) @@ -181,10 +174,8 @@ def test_resample_size_empty_dataframe(freq, empty_frame): result = empty_frame.resample(freq).size() - if isinstance(empty_frame.index, PeriodIndex): - index = empty_frame.index.asfreq(freq=freq) - else: - index = empty_frame.index._shallow_copy(freq=freq) + index = _asfreq_compat(empty_frame.index, freq) + expected = pd.Series([], dtype="int64", index=index) tm.assert_series_equal(result, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/31315
2020-01-25T22:37:05Z
2020-02-09T15:01:20Z
2020-02-09T15:01:20Z
2020-02-09T15:40:34Z
REF: DatetimeIndex.get_value wrap DTI.get_loc
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index fbcca270b2be3..398d37cad9296 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -641,34 +641,10 @@ def get_value(self, series, key): Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ - if not is_scalar(key): - raise InvalidIndexError(key) - - if isinstance(key, (datetime, np.datetime64)): - return self.get_value_maybe_box(series, key) - - if isinstance(key, time): - locs = self.indexer_at_time(key) - return series.take(locs) - - if isinstance(key, str): - try: - loc = self._get_string_slice(key) - return series[loc] - except (TypeError, ValueError, KeyError): - pass - try: - stamp = self._maybe_cast_for_get_loc(key) - loc = self.get_loc(stamp) - return series[loc] - except (KeyError, ValueError): - raise KeyError(key) - - value = Index.get_value(self, series, key) - return com.maybe_box(self, value, series, key) - - def get_value_maybe_box(self, series, key): - loc = self.get_loc(key) + if is_integer(key): + loc = key + else: + loc = self.get_loc(key) return self._get_values_for_loc(series, loc) def get_loc(self, key, method=None, tolerance=None):
After this, DTI.get_value is identical to TDI.get_value. Separate PR to get PeriodIndex to match too, then de-duplicate.
https://api.github.com/repos/pandas-dev/pandas/pulls/31314
2020-01-25T22:33:42Z
2020-01-26T00:23:57Z
2020-01-26T00:23:57Z
2020-01-26T00:38:36Z
BUG: MultiIndex intersection with sort=False does not preserve order
diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py index 0e188c58012fa..793f0c7c03c77 100644 --- a/asv_bench/benchmarks/multiindex_object.py +++ b/asv_bench/benchmarks/multiindex_object.py @@ -160,4 +160,43 @@ def time_equals_non_object_index(self): self.mi_large_slow.equals(self.idx_non_object) +class SetOperations: + + params = [ + ("monotonic", "non_monotonic"), + ("datetime", "int", "string"), + ("intersection", "union", "symmetric_difference"), + ] + param_names = ["index_structure", "dtype", "method"] + + def setup(self, index_structure, dtype, method): + N = 10 ** 5 + level1 = range(1000) + + level2 = date_range(start="1/1/2000", periods=N // 1000) + dates_left = MultiIndex.from_product([level1, level2]) + + level2 = range(N // 1000) + int_left = MultiIndex.from_product([level1, level2]) + + level2 = tm.makeStringIndex(N // 1000).values + str_left = MultiIndex.from_product([level1, level2]) + + data = { + "datetime": dates_left, + "int": int_left, + "string": str_left, + } + + if index_structure == "non_monotonic": + data = {k: mi[::-1] for k, mi in data.items()} + + data = {k: {"left": mi, "right": mi[:-1]} for k, mi in data.items()} + self.left = data[dtype]["left"] + self.right = data[dtype]["right"] + + def time_operation(self, index_structure, dtype, method): + getattr(self.left, method)(self.right) + + from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 40abb8f83de2f..aeed59f5e80f2 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -175,6 +175,16 @@ MultiIndex index=[["a", "a", "b", "b"], [1, 2, 1, 2]]) # Rows are now ordered as the requested keys df.loc[(['b', 'a'], [2, 1]), :] + +- Bug in :meth:`MultiIndex.intersection` was not guaranteed to preserve order when ``sort=False``. (:issue:`31325`) + +.. ipython:: python + + left = pd.MultiIndex.from_arrays([["b", "a"], [2, 1]]) + right = pd.MultiIndex.from_arrays([["a", "b", "c"], [1, 2, 3]]) + # Common elements are now guaranteed to be ordered by the left side + left.intersection(right, sort=False) + - I/O diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 94d6564d372c7..4edfa078dd919 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -3314,9 +3314,23 @@ def intersection(self, other, sort=False): if self.equals(other): return self - self_tuples = self._ndarray_values - other_tuples = other._ndarray_values - uniq_tuples = set(self_tuples) & set(other_tuples) + lvals = self._ndarray_values + rvals = other._ndarray_values + + uniq_tuples = None # flag whether _inner_indexer was succesful + if self.is_monotonic and other.is_monotonic: + try: + uniq_tuples = self._inner_indexer(lvals, rvals)[0] + sort = False # uniq_tuples is already sorted + except TypeError: + pass + + if uniq_tuples is None: + other_uniq = set(rvals) + seen = set() + uniq_tuples = [ + x for x in lvals if x in other_uniq and not (x in seen or seen.add(x)) + ] if sort is None: uniq_tuples = sorted(uniq_tuples) diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index f949db537de67..627127f7b5b53 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -19,22 +19,20 @@ def test_set_ops_error_cases(idx, case, sort, method): @pytest.mark.parametrize("sort", [None, False]) -def test_intersection_base(idx, sort): - first = idx[:5] - second = idx[:3] - intersect = first.intersection(second, sort=sort) +@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list]) +def test_intersection_base(idx, sort, klass): + first = idx[2::-1] # first 3 elements reversed + second = idx[:5] - if sort is None: - tm.assert_index_equal(intersect, second.sort_values()) - assert tm.equalContents(intersect, second) + if klass is not MultiIndex: + second = klass(second.values) - # GH 10149 - cases = [klass(second.values) for klass in [np.array, Series, list]] - for case in cases: - result = first.intersection(case, sort=sort) - if sort is None: - tm.assert_index_equal(result, second.sort_values()) - assert tm.equalContents(result, second) + intersect = first.intersection(second, sort=sort) + if sort is None: + expected = first.sort_values() + else: + expected = first + tm.assert_index_equal(intersect, expected) msg = "other must be a MultiIndex or a list of tuples" with pytest.raises(TypeError, match=msg): @@ -42,22 +40,20 @@ def test_intersection_base(idx, sort): @pytest.mark.parametrize("sort", [None, False]) -def test_union_base(idx, sort): - first = idx[3:] +@pytest.mark.parametrize("klass", [MultiIndex, np.array, Series, list]) +def test_union_base(idx, sort, klass): + first = idx[::-1] second = idx[:5] - everything = idx + + if klass is not MultiIndex: + second = klass(second.values) + union = first.union(second, sort=sort) if sort is None: - tm.assert_index_equal(union, everything.sort_values()) - assert tm.equalContents(union, everything) - - # GH 10149 - cases = [klass(second.values) for klass in [np.array, Series, list]] - for case in cases: - result = first.union(case, sort=sort) - if sort is None: - tm.assert_index_equal(result, everything.sort_values()) - assert tm.equalContents(result, everything) + expected = first.sort_values() + else: + expected = first + tm.assert_index_equal(union, expected) msg = "other must be a MultiIndex or a list of tuples" with pytest.raises(TypeError, match=msg):
- [x] closes #31325 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry The intersection of 2 `MultiIndex` with `sort=False` does not preserve the order, whereas `Index. intersection()` does. This behavior does not seem to be intentional since the tests for `difference` and `symmetric_difference` are testing for order preservation. For example: ```python import pandas as pd arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) idx = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) left = idx[2::-1] print(left) #> MultiIndex([('baz', 'one'), #> ('bar', 'two'), #> ('bar', 'one')], #> names=['first', 'second']) right = idx[:5] print(right) #> MultiIndex([('bar', 'one'), #> ('bar', 'two'), #> ('baz', 'one'), #> ('baz', 'two'), #> ('foo', 'one')], #> names=['first', 'second']) # expected same order as left intersect = left.intersection(right, sort=False) print(intersect) #> MultiIndex([('bar', 'two'), #> ('baz', 'one'), #> ('bar', 'one')], #> names=['first', 'second']) ``` <sup>Created on 2020-01-25 by the [reprexpy package](https://github.com/crew102/reprexpy)</sup> I verified that my PR does not decrease performances. I also modified the test for `union`. The implementation was preserving the order with `sort=False` but the tests were not verifying it.
https://api.github.com/repos/pandas-dev/pandas/pulls/31312
2020-01-25T18:25:24Z
2020-02-12T16:04:23Z
2020-02-12T16:04:23Z
2020-02-12T16:04:32Z
xfail sparse warning; closes #31310
diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 22c4e38206df6..04fd4835469a9 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -198,6 +198,7 @@ def test_pickle_path_localpath(): tm.assert_frame_equal(df, result) +@pytest.mark.xfail(reason="GitHub issue #31310", strict=False) def test_legacy_sparse_warning(datapath): """
xref #31310
https://api.github.com/repos/pandas-dev/pandas/pulls/31311
2020-01-25T17:36:58Z
2020-01-26T00:26:02Z
2020-01-26T00:26:02Z
2020-01-26T00:26:20Z
Backport PR #31292 on branch 1.0.x (CI: Updated version of macos image)
diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 57032932b878c..d992c64073476 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -4,7 +4,7 @@ jobs: - template: ci/azure/posix.yml parameters: name: macOS - vmImage: xcode9-macos10.13 + vmImage: macOS-10.14 - template: ci/azure/posix.yml parameters:
Backport PR #31292: CI: Updated version of macos image
https://api.github.com/repos/pandas-dev/pandas/pulls/31309
2020-01-25T15:38:35Z
2020-01-25T16:08:09Z
2020-01-25T16:08:09Z
2020-01-25T16:08:09Z
Add test for multiindex json
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 638bcaa21bdf9..94d51589023c4 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1647,3 +1647,18 @@ def test_frame_int_overflow(self): expected = DataFrame({"col": ["31900441201190696999", "Text"]}) result = read_json(encoded_json) tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dataframe,expected", + [ + ( + pd.DataFrame({"x": [1, 2, 3], "y": ["a", "b", "c"]}), + '{"(0, \'x\')":1,"(0, \'y\')":"a","(1, \'x\')":2,' + '"(1, \'y\')":"b","(2, \'x\')":3,"(2, \'y\')":"c"}', + ) + ], + ) + def test_json_multiindex(self, dataframe, expected): + series = dataframe.stack() + result = series.to_json(orient="index") + assert result == expected
- [x] related to #31028 and adds test for #27618 - [x] tests added / passed - [x] passes `black pandas`
https://api.github.com/repos/pandas-dev/pandas/pulls/31307
2020-01-25T12:42:39Z
2020-01-25T16:19:06Z
2020-01-25T16:19:06Z
2020-01-31T09:03:28Z
REF: define _get_slice_axis in correct classes
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 6ac7876a809fc..4550be791b1ec 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1662,16 +1662,6 @@ def _convert_to_indexer(self, key, axis: int): return {"key": key} raise - def _get_slice_axis(self, slice_obj: slice, axis: int): - # caller is responsible for ensuring non-None axis - obj = self.obj - - if not need_slice(slice_obj): - return obj.copy(deep=False) - - indexer = self._convert_slice_indexer(slice_obj, axis) - return self._slice(indexer, axis=axis, kind="iloc") - class _LocationIndexer(_NDFrameIndexer): _takeable: bool = False @@ -1706,27 +1696,6 @@ def _getbool_axis(self, key, axis: int): inds = key.nonzero()[0] return self.obj.take(inds, axis=axis) - def _get_slice_axis(self, slice_obj: slice, axis: int): - """ - This is pretty simple as we just have to deal with labels. - """ - # caller is responsible for ensuring non-None axis - obj = self.obj - if not need_slice(slice_obj): - return obj.copy(deep=False) - - labels = obj._get_axis(axis) - indexer = labels.slice_indexer( - slice_obj.start, slice_obj.stop, slice_obj.step, kind=self.name - ) - - if isinstance(indexer, slice): - return self._slice(indexer, axis=axis, kind="iloc") - else: - # DatetimeIndex overrides Index.slice_indexer and may - # return a DatetimeIndex instead of a slice object. - return self.obj.take(indexer, axis=axis) - @Appender(IndexingMixin.loc.__doc__) class _LocIndexer(_LocationIndexer): @@ -1881,6 +1850,27 @@ def _getitem_axis(self, key, axis: int): self._validate_key(key, axis) return self._get_label(key, axis=axis) + def _get_slice_axis(self, slice_obj: slice, axis: int): + """ + This is pretty simple as we just have to deal with labels. + """ + # caller is responsible for ensuring non-None axis + obj = self.obj + if not need_slice(slice_obj): + return obj.copy(deep=False) + + labels = obj._get_axis(axis) + indexer = labels.slice_indexer( + slice_obj.start, slice_obj.stop, slice_obj.step, kind=self.name + ) + + if isinstance(indexer, slice): + return self._slice(indexer, axis=axis, kind="iloc") + else: + # DatetimeIndex overrides Index.slice_indexer and may + # return a DatetimeIndex instead of a slice object. + return self.obj.take(indexer, axis=axis) + @Appender(IndexingMixin.iloc.__doc__) class _iLocIndexer(_LocationIndexer): @@ -1888,7 +1878,6 @@ class _iLocIndexer(_LocationIndexer): "integer, integer slice (START point is INCLUDED, END " "point is EXCLUDED), listlike of integers, boolean array" ) - _get_slice_axis = _NDFrameIndexer._get_slice_axis _takeable = True def _validate_key(self, key, axis: int): @@ -2051,6 +2040,16 @@ def _getitem_axis(self, key, axis: int): return self._get_loc(key, axis=axis) + def _get_slice_axis(self, slice_obj: slice, axis: int): + # caller is responsible for ensuring non-None axis + obj = self.obj + + if not need_slice(slice_obj): + return obj.copy(deep=False) + + indexer = self._convert_slice_indexer(slice_obj, axis) + return self._slice(indexer, axis=axis, kind="iloc") + def _convert_to_indexer(self, key, axis: int): """ Much simpler as we only have to deal with our valid types.
Since ix has been removed, a bunch of _NDFrameIndexer methods are defined in now-weird places. This fixes the one that confused me today.
https://api.github.com/repos/pandas-dev/pandas/pulls/31304
2020-01-25T04:36:10Z
2020-01-26T00:40:31Z
2020-01-26T00:40:31Z
2020-01-26T00:46:49Z
CLN: remove _set_subtyp
diff --git a/pandas/core/dtypes/generic.py b/pandas/core/dtypes/generic.py index 4c3f8b7374465..435d80b2c4dfb 100644 --- a/pandas/core/dtypes/generic.py +++ b/pandas/core/dtypes/generic.py @@ -56,9 +56,7 @@ def _check(cls, inst) -> bool: ABCSeries = create_pandas_abc_type("ABCSeries", "_typ", ("series",)) ABCDataFrame = create_pandas_abc_type("ABCDataFrame", "_typ", ("dataframe",)) -ABCSparseArray = create_pandas_abc_type( - "ABCSparseArray", "_subtyp", ("sparse_array", "sparse_series") -) +ABCSparseArray = create_pandas_abc_type("ABCSparseArray", "_subtyp", ("sparse_array",)) ABCCategorical = create_pandas_abc_type("ABCCategorical", "_typ", ("categorical")) ABCDatetimeArray = create_pandas_abc_type("ABCDatetimeArray", "_typ", ("datetimearray")) ABCTimedeltaArray = create_pandas_abc_type( diff --git a/pandas/core/series.py b/pandas/core/series.py index de34b2b047851..e79404ccd9521 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -392,7 +392,7 @@ def _can_hold_na(self): _index = None - def _set_axis(self, axis, labels, fastpath=False) -> None: + def _set_axis(self, axis, labels, fastpath: bool = False) -> None: """ Override generic, we want to set the _typ here. """ @@ -413,18 +413,10 @@ def _set_axis(self, axis, labels, fastpath=False) -> None: # or not be a DatetimeIndex pass - self._set_subtyp(is_all_dates) - object.__setattr__(self, "_index", labels) if not fastpath: self._data.set_axis(axis, labels) - def _set_subtyp(self, is_all_dates): - if is_all_dates: - object.__setattr__(self, "_subtyp", "time_series") - else: - object.__setattr__(self, "_subtyp", "series") - def _update_inplace(self, result, **kwargs): # we want to call the generic version and not the IndexOpsMixin return generic.NDFrame._update_inplace(self, result, **kwargs)
its not used anywhere, apparently legacy leftover
https://api.github.com/repos/pandas-dev/pandas/pulls/31301
2020-01-25T02:37:01Z
2020-01-25T16:01:40Z
2020-01-25T16:01:40Z
2020-01-25T16:04:55Z
PERF: avoid copies if possible in fill_binop
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 9ed233cad65ce..76e90a26874fc 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -329,19 +329,25 @@ def fill_binop(left, right, fill_value): Notes ----- - Makes copies if fill_value is not None + Makes copies if fill_value is not None and NAs are present. """ - # TODO: can we make a no-copy implementation? if fill_value is not None: left_mask = isna(left) right_mask = isna(right) - left = left.copy() - right = right.copy() # one but not both mask = left_mask ^ right_mask - left[left_mask & mask] = fill_value - right[right_mask & mask] = fill_value + + if left_mask.any(): + # Avoid making a copy if we can + left = left.copy() + left[left_mask & mask] = fill_value + + if right_mask.any(): + # Avoid making a copy if we can + right = right.copy() + right[right_mask & mask] = fill_value + return left, right
This has a small perf bump, but more importantly is necessary for the blockwise frame-with-frame PR that is coming up. ``` import pandas as pd from pandas.core.ops import * arr = np.arange(10**6) df = pd.DataFrame({"A": arr}) ser = df["A"] %timeit result = df.add(df, fill_value=4) 7.77 ms ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) <-- master 5.46 ms ± 36.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) <-- PR %timeit result = ser.add(ser, fill_value=1) 6.79 ms ± 56.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) <-- master 4.65 ms ± 82.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) <-- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/31300
2020-01-25T02:01:57Z
2020-01-25T16:20:21Z
2020-01-25T16:20:21Z
2020-01-25T16:28:10Z
REF: pass str_rep through arithmetic ops more consistently
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index b74dea686a89f..c0fb959723127 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -836,7 +836,7 @@ def f(self, other, axis=default_axis, level=None): return _combine_series_frame(self, other, op, axis=axis) else: # in this case we always have `np.ndim(other) == 0` - new_data = dispatch_to_series(self, other, op) + new_data = dispatch_to_series(self, other, op, str_rep) return self._construct_result(new_data) f.__name__ = op_name @@ -860,13 +860,15 @@ def f(self, other): new_data = dispatch_to_series(self, other, op, str_rep) elif isinstance(other, ABCSeries): - new_data = dispatch_to_series(self, other, op, axis="columns") + new_data = dispatch_to_series( + self, other, op, str_rep=str_rep, axis="columns" + ) else: # straight boolean comparisons we want to allow all columns # (regardless of dtype to pass thru) See #4537 for discussion. - new_data = dispatch_to_series(self, other, op) + new_data = dispatch_to_series(self, other, op, str_rep) return self._construct_result(new_data)
This doesn't get all of the places where we fail to pass str_rep, still working out a couple of places where passing it breaks tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/31297
2020-01-24T23:11:03Z
2020-02-23T16:18:50Z
2020-02-23T16:18:50Z
2020-02-23T17:13:37Z
PERF: do DataFrame.op(series, axis=0) blockwise
diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py index d1e94f62967f4..5a8b109c21858 100644 --- a/asv_bench/benchmarks/arithmetic.py +++ b/asv_bench/benchmarks/arithmetic.py @@ -50,6 +50,36 @@ def time_frame_op_with_scalar(self, dtype, scalar, op): op(self.df, scalar) +class MixedFrameWithSeriesAxis0: + params = [ + [ + "eq", + "ne", + "lt", + "le", + "ge", + "gt", + "add", + "sub", + "div", + "floordiv", + "mul", + "pow", + ] + ] + param_names = ["opname"] + + def setup(self, opname): + arr = np.arange(10 ** 6).reshape(100, -1) + df = DataFrame(arr) + df["C"] = 1.0 + self.df = df + self.ser = df[0] + + def time_frame_op_with_series_axis0(self, opname): + getattr(self.df, opname)(self.ser, axis=0) + + class Ops: params = [[True, False], ["default", 1]] diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 44deab25db695..912da955c14f3 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -183,7 +183,7 @@ Performance improvements - Performance improvement in :class:`Timedelta` constructor (:issue:`30543`) - Performance improvement in :class:`Timestamp` constructor (:issue:`30543`) -- +- Performance improvement in flex arithmetic ops between :class:`DataFrame` and :class:`Series` with ``axis=0`` (:issue:`31296`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/ops.pyx b/pandas/_libs/ops.pyx index abe1484e3763d..c0971b91a2fa1 100644 --- a/pandas/_libs/ops.pyx +++ b/pandas/_libs/ops.pyx @@ -100,7 +100,7 @@ def scalar_compare(object[:] values, object val, object op): @cython.wraparound(False) @cython.boundscheck(False) -def vec_compare(object[:] left, object[:] right, object op): +def vec_compare(ndarray[object] left, ndarray[object] right, object op): """ Compare the elements of `left` with the elements of `right` pointwise, with the comparison operation described by `op`. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 61641bfb24293..76e2caeff0cca 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5212,20 +5212,6 @@ def _arith_op(left, right): return new_data - def _combine_match_index(self, other: Series, func): - # at this point we have `self.index.equals(other.index)` - - if ops.should_series_dispatch(self, other, func): - # operate column-wise; avoid costly object-casting in `.values` - new_data = ops.dispatch_to_series(self, other, func) - else: - # fastpath --> operate directly on values - other_vals = other.values.reshape(-1, 1) - with np.errstate(all="ignore"): - new_data = func(self.values, other_vals) - new_data = dispatch_fill_zeros(func, self.values, other_vals, new_data) - return new_data - def _construct_result(self, result) -> "DataFrame": """ Wrap the result of an arithmetic, comparison, or logical operation. diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index d0adf2da04db3..ed779c5da6d14 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -585,7 +585,7 @@ def flex_wrapper(self, other, level=None, fill_value=None, axis=0): # DataFrame -def _combine_series_frame(left, right, func, axis: int): +def _combine_series_frame(left, right, func, axis: int, str_rep: str): """ Apply binary operator `func` to self, other using alignment and fill conventions determined by the axis argument. @@ -596,6 +596,7 @@ def _combine_series_frame(left, right, func, axis: int): right : Series func : binary operator axis : {0, 1} + str_rep : str Returns ------- @@ -603,7 +604,17 @@ def _combine_series_frame(left, right, func, axis: int): """ # We assume that self.align(other, ...) has already been called if axis == 0: - new_data = left._combine_match_index(right, func) + values = right._values + if isinstance(values, np.ndarray): + # We can operate block-wise + values = values.reshape(-1, 1) + + array_op = get_array_op(func, str_rep=str_rep) + bm = left._data.apply(array_op, right=values.T) + return type(left)(bm) + + new_data = dispatch_to_series(left, right, func) + else: new_data = dispatch_to_series(left, right, func, axis="columns") @@ -791,7 +802,9 @@ def f(self, other, axis=default_axis, level=None, fill_value=None): raise NotImplementedError(f"fill_value {fill_value} not supported.") axis = self._get_axis_number(axis) if axis is not None else 1 - return _combine_series_frame(self, other, pass_op, axis=axis) + return _combine_series_frame( + self, other, pass_op, axis=axis, str_rep=str_rep + ) else: # in this case we always have `np.ndim(other) == 0` if fill_value is not None: @@ -826,7 +839,7 @@ def f(self, other, axis=default_axis, level=None): elif isinstance(other, ABCSeries): axis = self._get_axis_number(axis) if axis is not None else 1 - return _combine_series_frame(self, other, op, axis=axis) + return _combine_series_frame(self, other, op, axis=axis, str_rep=str_rep) else: # in this case we always have `np.ndim(other) == 0` new_data = dispatch_to_series(self, other, op, str_rep) diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 2c9105c52cf9b..e285c53d9813e 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -28,7 +28,6 @@ ABCDatetimeArray, ABCExtensionArray, ABCIndex, - ABCIndexClass, ABCSeries, ABCTimedeltaArray, ) @@ -53,13 +52,15 @@ def comp_method_OBJECT_ARRAY(op, x, y): if isinstance(y, (ABCSeries, ABCIndex)): y = y.values - result = libops.vec_compare(x.ravel(), y, op) + if x.shape != y.shape: + raise ValueError("Shapes must match", x.shape, y.shape) + result = libops.vec_compare(x.ravel(), y.ravel(), op) else: result = libops.scalar_compare(x.ravel(), y, op) return result.reshape(x.shape) -def masked_arith_op(x, y, op): +def masked_arith_op(x: np.ndarray, y, op): """ If the given arithmetic operation fails, attempt it again on only the non-null elements of the input array(s). @@ -78,10 +79,22 @@ def masked_arith_op(x, y, op): dtype = find_common_type([x.dtype, y.dtype]) result = np.empty(x.size, dtype=dtype) + if len(x) != len(y): + if not _can_broadcast(x, y): + raise ValueError(x.shape, y.shape) + + # Call notna on pre-broadcasted y for performance + ymask = notna(y) + y = np.broadcast_to(y, x.shape) + ymask = np.broadcast_to(ymask, x.shape) + + else: + ymask = notna(y) + # NB: ravel() is only safe since y is ndarray; for e.g. PeriodIndex # we would get int64 dtype, see GH#19956 yrav = y.ravel() - mask = notna(xrav) & notna(yrav) + mask = notna(xrav) & ymask.ravel() if yrav.shape != mask.shape: # FIXME: GH#5284, GH#5035, GH#19448 @@ -211,6 +224,51 @@ def arithmetic_op(left: ArrayLike, right: Any, op, str_rep: str): return res_values +def _broadcast_comparison_op(lvalues, rvalues, op) -> np.ndarray: + """ + Broadcast a comparison operation between two 2D arrays. + + Parameters + ---------- + lvalues : np.ndarray or ExtensionArray + rvalues : np.ndarray or ExtensionArray + + Returns + ------- + np.ndarray[bool] + """ + if isinstance(rvalues, np.ndarray): + rvalues = np.broadcast_to(rvalues, lvalues.shape) + result = comparison_op(lvalues, rvalues, op) + else: + result = np.empty(lvalues.shape, dtype=bool) + for i in range(len(lvalues)): + result[i, :] = comparison_op(lvalues[i], rvalues[:, 0], op) + return result + + +def _can_broadcast(lvalues, rvalues) -> bool: + """ + Check if we can broadcast rvalues to match the shape of lvalues. + + Parameters + ---------- + lvalues : np.ndarray or ExtensionArray + rvalues : np.ndarray or ExtensionArray + + Returns + ------- + bool + """ + # We assume that lengths dont match + if lvalues.ndim == rvalues.ndim == 2: + # See if we can broadcast unambiguously + if lvalues.shape[1] == rvalues.shape[-1]: + if rvalues.shape[0] == 1: + return True + return False + + def comparison_op( left: ArrayLike, right: Any, op, str_rep: Optional[str] = None, ) -> ArrayLike: @@ -237,12 +295,16 @@ def comparison_op( # TODO: same for tuples? rvalues = np.asarray(rvalues) - if isinstance(rvalues, (np.ndarray, ABCExtensionArray, ABCIndexClass)): + if isinstance(rvalues, (np.ndarray, ABCExtensionArray)): # TODO: make this treatment consistent across ops and classes. # We are not catching all listlikes here (e.g. frozenset, tuple) # The ambiguous case is object-dtype. See GH#27803 if len(lvalues) != len(rvalues): - raise ValueError("Lengths must match to compare") + if _can_broadcast(lvalues, rvalues): + return _broadcast_comparison_op(lvalues, rvalues, op) + raise ValueError( + "Lengths must match to compare", lvalues.shape, rvalues.shape + ) if should_extension_dispatch(lvalues, rvalues): res_values = dispatch_to_extension_op(op, lvalues, rvalues) diff --git a/pandas/tests/arithmetic/test_array_ops.py b/pandas/tests/arithmetic/test_array_ops.py index d8aaa3183a1c6..53cb10ba9fc5e 100644 --- a/pandas/tests/arithmetic/test_array_ops.py +++ b/pandas/tests/arithmetic/test_array_ops.py @@ -4,7 +4,7 @@ import pytest import pandas._testing as tm -from pandas.core.ops.array_ops import na_logical_op +from pandas.core.ops.array_ops import comparison_op, na_logical_op def test_na_logical_op_2d(): @@ -19,3 +19,18 @@ def test_na_logical_op_2d(): result = na_logical_op(left, right, operator.or_) expected = right tm.assert_numpy_array_equal(result, expected) + + +def test_object_comparison_2d(): + left = np.arange(9).reshape(3, 3).astype(object) + right = left.T + + result = comparison_op(left, right, operator.eq) + expected = np.eye(3).astype(bool) + tm.assert_numpy_array_equal(result, expected) + + # Ensure that cython doesn't raise on non-writeable arg, which + # we can get from np.broadcast_to + right.flags.writeable = False + result = comparison_op(left, right, operator.ne) + tm.assert_numpy_array_equal(result, ~expected) diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index e4be8a979a70f..92d86c8b602ff 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -348,6 +348,25 @@ def test_floordiv_axis0(self): result2 = df.floordiv(ser.values, axis=0) tm.assert_frame_equal(result2, expected) + @pytest.mark.slow + @pytest.mark.parametrize("opname", ["floordiv", "pow"]) + def test_floordiv_axis0_numexpr_path(self, opname): + # case that goes through numexpr and has to fall back to masked_arith_op + op = getattr(operator, opname) + + arr = np.arange(10 ** 6).reshape(100, -1) + df = pd.DataFrame(arr) + df["C"] = 1.0 + + ser = df[0] + result = getattr(df, opname)(ser, axis=0) + + expected = pd.DataFrame({col: op(df[col], ser) for col in df.columns}) + tm.assert_frame_equal(result, expected) + + result2 = getattr(df, opname)(ser.values, axis=0) + tm.assert_frame_equal(result2, expected) + def test_df_add_td64_columnwise(self): # GH 22534 Check that column-wise addition broadcasts correctly dti = pd.date_range("2016-01-01", periods=10)
Also fixes the same bug as #31271 (with the same test ported), so if this is accepted that will be closeable. ~2000x speedups for very-wide mixed-dtype cases. ``` arr = np.arange(10**6).reshape(100, -1) df = pd.DataFrame(arr) df["C"] = 1.0 ser = df[0] In [11]: %timeit df.eq(ser, axis=0) 1.58 s ± 20 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <-- master 595 µs ± 79.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) <-- PR In [12]: %timeit df.add(ser, axis=0) 2.06 s ± 52.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <-- master 1.04 ms ± 5.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # <-- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/31296
2020-01-24T22:57:15Z
2020-03-08T16:07:04Z
2020-03-08T16:07:04Z
2020-03-08T16:28:25Z
PERF: optimize is_scalar, is_iterator
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index acd74591134bc..9702eb4615909 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -11,6 +11,9 @@ from cython import Py_ssize_t from cpython.object cimport PyObject_RichCompareBool, Py_EQ from cpython.ref cimport Py_INCREF from cpython.tuple cimport PyTuple_SET_ITEM, PyTuple_New +from cpython.iterator cimport PyIter_Check +from cpython.sequence cimport PySequence_Check +from cpython.number cimport PyNumber_Check from cpython.datetime cimport (PyDateTime_Check, PyDate_Check, PyTime_Check, PyDelta_Check, @@ -156,7 +159,8 @@ def is_scalar(val: object) -> bool: True """ - return (cnp.PyArray_IsAnyScalar(val) + # Start with C-optimized checks + if (cnp.PyArray_IsAnyScalar(val) # PyArray_IsAnyScalar is always False for bytearrays on Py3 or PyDate_Check(val) or PyDelta_Check(val) @@ -164,14 +168,54 @@ def is_scalar(val: object) -> bool: # We differ from numpy, which claims that None is not scalar; # see np.isscalar or val is C_NA - or val is None - or isinstance(val, (Fraction, Number)) + or val is None): + return True + + # Next use C-optimized checks to exclude common non-scalars before falling + # back to non-optimized checks. + if PySequence_Check(val): + # e.g. list, tuple + # includes np.ndarray, Series which PyNumber_Check can return True for + return False + + # Note: PyNumber_Check check includes Decimal, Fraction, numbers.Number + return (PyNumber_Check(val) or util.is_period_object(val) - or is_decimal(val) or is_interval(val) or util.is_offset_object(val)) +def is_iterator(obj: object) -> bool: + """ + Check if the object is an iterator. + + This is intended for generators, not list-like objects. + + Parameters + ---------- + obj : The object to check + + Returns + ------- + is_iter : bool + Whether `obj` is an iterator. + + Examples + -------- + >>> is_iterator((x for x in [])) + True + >>> is_iterator([1, 2, 3]) + False + >>> is_iterator(datetime(2017, 1, 1)) + False + >>> is_iterator("foo") + False + >>> is_iterator(1) + False + """ + return PyIter_Check(obj) + + def item_from_zerodim(val: object) -> object: """ If the value is a zerodim array, return the item it contains. diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index 9e9278052e35d..37bca76802843 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -25,6 +25,8 @@ is_list_like = lib.is_list_like +is_iterator = lib.is_iterator + def is_number(obj) -> bool: """ @@ -93,40 +95,6 @@ def _iterable_not_string(obj) -> bool: return isinstance(obj, abc.Iterable) and not isinstance(obj, str) -def is_iterator(obj) -> bool: - """ - Check if the object is an iterator. - - For example, lists are considered iterators - but not strings or datetime objects. - - Parameters - ---------- - obj : The object to check - - Returns - ------- - is_iter : bool - Whether `obj` is an iterator. - - Examples - -------- - >>> is_iterator([1, 2, 3]) - True - >>> is_iterator(datetime(2017, 1, 1)) - False - >>> is_iterator("foo") - False - >>> is_iterator(1) - False - """ - - if not hasattr(obj, "__iter__"): - return False - - return hasattr(obj, "__next__") - - def is_file_like(obj) -> bool: """ Check if the object is a file-like object. diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 5eb85de2b90f5..48f9262ad3486 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1346,9 +1346,11 @@ def test_is_scalar_builtin_scalars(self): assert is_scalar(None) assert is_scalar(True) assert is_scalar(False) - assert is_scalar(Number()) assert is_scalar(Fraction()) assert is_scalar(0.0) + assert is_scalar(1) + assert is_scalar(complex(2)) + assert is_scalar(float("NaN")) assert is_scalar(np.nan) assert is_scalar("foobar") assert is_scalar(b"foobar") @@ -1357,6 +1359,7 @@ def test_is_scalar_builtin_scalars(self): assert is_scalar(time(12, 0)) assert is_scalar(timedelta(hours=1)) assert is_scalar(pd.NaT) + assert is_scalar(pd.NA) def test_is_scalar_builtin_nonscalars(self): assert not is_scalar({}) @@ -1371,6 +1374,7 @@ def test_is_scalar_numpy_array_scalars(self): assert is_scalar(np.int64(1)) assert is_scalar(np.float64(1.0)) assert is_scalar(np.int32(1)) + assert is_scalar(np.complex64(2)) assert is_scalar(np.object_("foobar")) assert is_scalar(np.str_("foobar")) assert is_scalar(np.unicode_("foobar")) @@ -1410,6 +1414,21 @@ def test_is_scalar_pandas_containers(self): assert not is_scalar(Index([])) assert not is_scalar(Index([1])) + def test_is_scalar_number(self): + # Number() is not recognied by PyNumber_Check, so by extension + # is not recognized by is_scalar, but instances of non-abstract + # subclasses are. + + class Numeric(Number): + def __init__(self, value): + self.value = value + + def __int__(self): + return self.value + + num = Numeric(1) + assert is_scalar(num) + def test_datetimeindex_from_empty_datetime64_array(): for unit in ["ms", "us", "ns"]:
While working on #30349 I noticed that `is_scalar` is pretty slow for non-scalar args, turns out we can get a 9-19x improvement for listlike cases, 5-10x improvement for Decimal/Period/DateOffset/Interval, with small improvements in nearly every other case while we're at it (the fractions.Fraction object is the only one where i found a small decrease in perf, within the margin of error) xref #31291, assuming this is the desired behavior for is_iterator, this closes that. Setup: ``` import pandas as pd from pandas.core.dtypes.common import * import decimal, fractions dec = decimal.Decimal(19.45678) frac = fractions.Fraction(1) i64 = np.int64(-1) arr = np.arange(5) ser = pd.Series(arr) idx = pd.Index(arr) interval = pd.Interval(0, 1) per = pd.Period("2017") offset = per - per iterator = (x for x in []) ``` Non-Scalar Cases ``` In [6]: %timeit is_scalar([]) 1.53 µs ± 36.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 79.7 ns ± 5.26 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [7]: %timeit is_scalar(arr) 1.58 µs ± 43.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 77.6 ns ± 5.02 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [8]: %timeit is_scalar(ser) 1.01 µs ± 51.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 92.3 ns ± 0.505 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [9]: %timeit is_scalar(idx) 876 ns ± 4.86 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 92.7 ns ± 1.47 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [10]: %timeit is_scalar(iterator) 2.08 µs ± 22.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) # <-- master 869 ns ± 20.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- PR ``` Non-Built-In Scalar Cases ``` In [10]: %timeit is_scalar(dec) 1.05 µs ± 9.75 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 79.5 ns ± 2.16 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [12]: %timeit is_scalar(interval) 748 ns ± 22.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 139 ns ± 5.38 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [13]: %timeit is_scalar(per) 706 ns ± 24.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 127 ns ± 14.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [14]: %timeit is_scalar(offset) 930 ns ± 40.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 211 ns ± 2.45 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- PR ``` Built-In Scalar Cases ``` In [3]: %timeit is_scalar(4) 60.1 ns ± 2.39 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- master 54.9 ns ± 1.15 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [4]: %timeit is_scalar(4.0) 53 ns ± 4.94 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- master 48.2 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [5]: %timeit is_scalar(i64) 58.5 ns ± 1.39 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- master 58.1 ns ± 5.88 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [11]: %timeit is_scalar(frac) 93.5 ns ± 2.05 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- master 94.1 ns ± 6.4 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR ``` is_iterator check ``` In [16] %timeit is_iterator(iterator) 283 ns ± 5.35 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 58.9 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [17] %timeit is_iterator(arr) 228 ns ± 3.98 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 55 ns ± 3.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [17] %timeit is_iterator("foo") 231 ns ± 15.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 49.4 ns ± 5.08 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/31294
2020-01-24T19:58:26Z
2020-01-26T00:34:33Z
2020-01-26T00:34:33Z
2020-05-11T13:56:13Z
CI: Updated version of macos image
diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 57032932b878c..d992c64073476 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -4,7 +4,7 @@ jobs: - template: ci/azure/posix.yml parameters: name: macOS - vmImage: xcode9-macos10.13 + vmImage: macOS-10.14 - template: ci/azure/posix.yml parameters:
- [x] closes #31281 - [ ] 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/31292
2020-01-24T18:22:05Z
2020-01-25T15:37:59Z
2020-01-25T15:37:59Z
2020-01-30T12:42:20Z
BUG: Handle IntegerArray in pd.cut
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 5a444d908b786..00a7645d0c7a5 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -14,7 +14,9 @@ is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, + is_extension_array_dtype, is_integer, + is_integer_dtype, is_list_like, is_scalar, is_timedelta64_dtype, @@ -205,6 +207,12 @@ def cut( x = _preprocess_for_cut(x) x, dtype = _coerce_to_type(x) + # To support cut(IntegerArray), we convert to object dtype with NaN + # Will properly support in the future. + # https://github.com/pandas-dev/pandas/pull/31290 + if is_extension_array_dtype(x.dtype) and is_integer_dtype(x.dtype): + x = x.to_numpy(dtype=object, na_value=np.nan) + if not np.iterable(bins): if is_scalar(bins) and bins < 1: raise ValueError("`bins` should be a positive integer.") diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index 96e676018a0d6..63e3c946df912 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -1061,6 +1061,19 @@ def test_value_counts_na(): tm.assert_series_equal(result, expected) +@pytest.mark.parametrize("bins", [3, [0, 5, 15]]) +@pytest.mark.parametrize("right", [True, False]) +@pytest.mark.parametrize("include_lowest", [True, False]) +def test_cut(bins, right, include_lowest): + a = np.random.randint(0, 10, size=50).astype(object) + a[::2] = np.nan + result = pd.cut( + pd.array(a, dtype="Int64"), bins, right=right, include_lowest=include_lowest + ) + expected = pd.cut(a, bins, right=right, include_lowest=include_lowest) + tm.assert_categorical_equal(result, expected) + + # TODO(jreback) - these need testing / are broken # shift
xref https://github.com/pandas-dev/pandas/issues/30944. I think this doesn't close it, since only the pd.cut compoment is fixed. cc @jorisvandenbossche @jreback. The changes here attempt to be extremely conservative, since we're backporting stuff. I'm trying to not change behavior for anything other than IntegerArray. In particular, I'm not trying to support arbitrary EAs in `pd.cut`. This leads to some code that's fairly ugly & specific to IntegerArray. I think we should attempt to clean that up in 1.1.
https://api.github.com/repos/pandas-dev/pandas/pulls/31290
2020-01-24T18:18:11Z
2020-01-28T01:52:09Z
2020-01-28T01:52:09Z
2020-01-28T12:41:00Z
REF: combine all alignment into _align_method_FRAME
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 012fb1d0c2eb7..6b1f8e7f1c6a5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5341,7 +5341,7 @@ def reorder_levels(self, order, axis=0) -> "DataFrame": # ---------------------------------------------------------------------- # Arithmetic / combination related - def _combine_frame(self, other, func, fill_value=None, level=None): + def _combine_frame(self, other: "DataFrame", func, fill_value=None): # at this point we have `self._indexed_same(other)` if fill_value is None: @@ -5368,7 +5368,7 @@ def _arith_op(left, right): return new_data - def _combine_match_index(self, other, func): + def _combine_match_index(self, other: Series, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c502adcdb09e0..2312a77e94465 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7197,7 +7197,7 @@ def _clip_with_one_bound(self, threshold, method, axis, inplace): if isinstance(self, ABCSeries): threshold = self._constructor(threshold, index=self.index) else: - threshold = _align_method_FRAME(self, threshold, axis) + threshold = _align_method_FRAME(self, threshold, axis, flex=None)[1] return self.where(subset, threshold, axis=axis, inplace=inplace) def clip( diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 9ed233cad65ce..393bb2f1900ff 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -5,12 +5,13 @@ """ import datetime import operator -from typing import Set, Tuple, Union +from typing import Optional, Set, Tuple, Union import numpy as np from pandas._libs import Timedelta, Timestamp, lib from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op # noqa:F401 +from pandas._typing import Level from pandas.util._decorators import Appender from pandas.core.dtypes.common import is_list_like, is_timedelta64_dtype @@ -609,8 +610,27 @@ def _combine_series_frame(left, right, func, axis: int): return left._construct_result(new_data) -def _align_method_FRAME(left, right, axis): - """ convert rhs to meet lhs dims if input is list, tuple or np.ndarray """ +def _align_method_FRAME( + left, right, axis, flex: Optional[bool] = False, level: Level = None +): + """ + Convert rhs to meet lhs dims if input is list, tuple or np.ndarray. + + Parameters + ---------- + left : DataFrame + right : Any + axis: int, str, or None + flex: bool or None, default False + Whether this is a flex op, in which case we reindex. + None indicates not to check for alignment. + level : int or level name, default None + + Returns + ------- + left : DataFrame + right : Any + """ def to_series(right): msg = "Unable to coerce to Series, length must be {req_len}: given {given_len}" @@ -661,7 +681,22 @@ def to_series(right): # GH17901 right = to_series(right) - return right + if flex is not None and isinstance(right, ABCDataFrame): + if not left._indexed_same(right): + if flex: + left, right = left.align(right, join="outer", level=level, copy=False) + else: + raise ValueError( + "Can only compare identically-labeled DataFrame objects" + ) + elif isinstance(right, ABCSeries): + # axis=1 is default for DataFrame-with-Series op + axis = left._get_axis_number(axis) if axis is not None else 1 + left, right = left.align( + right, join="outer", axis=axis, level=level, copy=False + ) + + return left, right def _arith_method_FRAME(cls, op, special): @@ -681,16 +716,15 @@ def _arith_method_FRAME(cls, op, special): @Appender(doc) def f(self, other, axis=default_axis, level=None, fill_value=None): - other = _align_method_FRAME(self, other, axis) + self, other = _align_method_FRAME(self, other, axis, flex=True, level=level) if isinstance(other, ABCDataFrame): # Another DataFrame pass_op = op if should_series_dispatch(self, other, op) else na_op pass_op = pass_op if not is_logical else op - left, right = self.align(other, join="outer", level=level, copy=False) - new_data = left._combine_frame(right, pass_op, fill_value) - return left._construct_result(new_data) + new_data = self._combine_frame(other, pass_op, fill_value) + return self._construct_result(new_data) elif isinstance(other, ABCSeries): # For these values of `axis`, we end up dispatching to Series op, @@ -702,9 +736,6 @@ def f(self, other, axis=default_axis, level=None, fill_value=None): raise NotImplementedError(f"fill_value {fill_value} not supported.") axis = self._get_axis_number(axis) if axis is not None else 1 - self, other = self.align( - other, join="outer", axis=axis, level=level, copy=False - ) return _combine_series_frame(self, other, pass_op, axis=axis) else: # in this case we always have `np.ndim(other) == 0` @@ -731,20 +762,15 @@ def _flex_comp_method_FRAME(cls, op, special): @Appender(doc) def f(self, other, axis=default_axis, level=None): - other = _align_method_FRAME(self, other, axis) + self, other = _align_method_FRAME(self, other, axis, flex=True, level=level) if isinstance(other, ABCDataFrame): # Another DataFrame - if not self._indexed_same(other): - self, other = self.align(other, "outer", level=level, copy=False) new_data = dispatch_to_series(self, other, op, str_rep) return self._construct_result(new_data) elif isinstance(other, ABCSeries): axis = self._get_axis_number(axis) if axis is not None else 1 - self, other = self.align( - other, join="outer", axis=axis, level=level, copy=False - ) return _combine_series_frame(self, other, op, axis=axis) else: # in this case we always have `np.ndim(other) == 0` @@ -763,21 +789,15 @@ def _comp_method_FRAME(cls, op, special): @Appender(f"Wrapper for comparison method {op_name}") def f(self, other): - other = _align_method_FRAME(self, other, axis=None) + self, other = _align_method_FRAME( + self, other, axis=None, level=None, flex=False + ) if isinstance(other, ABCDataFrame): # Another DataFrame - if not self._indexed_same(other): - raise ValueError( - "Can only compare identically-labeled DataFrame objects" - ) new_data = dispatch_to_series(self, other, op, str_rep) elif isinstance(other, ABCSeries): - # axis=1 is default for DataFrame-with-Series op - self, other = self.align( - other, join="outer", axis=1, level=None, copy=False - ) new_data = dispatch_to_series(self, other, op, axis="columns") else: diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index 55f1216a0efd7..162f3c114fa5d 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -864,10 +864,10 @@ def test_alignment_non_pandas(self): ]: tm.assert_series_equal( - align(df, val, "index"), Series([1, 2, 3], index=df.index) + align(df, val, "index")[1], Series([1, 2, 3], index=df.index) ) tm.assert_series_equal( - align(df, val, "columns"), Series([1, 2, 3], index=df.columns) + align(df, val, "columns")[1], Series([1, 2, 3], index=df.columns) ) # length mismatch @@ -882,10 +882,11 @@ def test_alignment_non_pandas(self): val = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) tm.assert_frame_equal( - align(df, val, "index"), DataFrame(val, index=df.index, columns=df.columns) + align(df, val, "index")[1], + DataFrame(val, index=df.index, columns=df.columns), ) tm.assert_frame_equal( - align(df, val, "columns"), + align(df, val, "columns")[1], DataFrame(val, index=df.index, columns=df.columns), )
This puts us within striking distance of de-duplicating _flex_comp_method_FRAME and _comp_method_FRAME, with _arith_method_FRAME not far behind
https://api.github.com/repos/pandas-dev/pandas/pulls/31288
2020-01-24T17:22:04Z
2020-01-31T03:36:34Z
2020-01-31T03:36:34Z
2020-01-31T04:23:10Z
Backport PR #30929: ENH: Implement convert_dtypes'
diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index 01aa6c60e3b2f..dd2af6e2799c3 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -43,6 +43,7 @@ Conversion :toctree: api/ DataFrame.astype + DataFrame.convert_dtypes DataFrame.infer_objects DataFrame.copy DataFrame.isna diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 4ad6a7b014532..1a69fa076dbf0 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -46,6 +46,7 @@ Conversion :toctree: api/ Series.astype + Series.convert_dtypes Series.infer_objects Series.copy Series.bool diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst index 0f55980b3d015..85f063f133dd9 100644 --- a/doc/source/user_guide/missing_data.rst +++ b/doc/source/user_guide/missing_data.rst @@ -806,7 +806,8 @@ dtype, it will use ``pd.NA``: Currently, pandas does not yet use those data types by default (when creating a DataFrame or Series, or when reading in data), so you need to specify -the dtype explicitly. +the dtype explicitly. An easy way to convert to those dtypes is explained +:ref:`here <missing_data.NA.conversion>`. Propagation in arithmetic and comparison operations --------------------------------------------------- @@ -942,3 +943,29 @@ work with ``NA``, and generally return ``NA``: in the future. See :ref:`dsintro.numpy_interop` for more on ufuncs. + +.. _missing_data.NA.conversion: + +Conversion +---------- + +If you have a DataFrame or Series using traditional types that have missing data +represented using ``np.nan``, there are convenience methods +:meth:`~Series.convert_dtypes` in Series and :meth:`~DataFrame.convert_dtypes` +in DataFrame that can convert data to use the newer dtypes for integers, strings and +booleans listed :ref:`here <basics.dtypes>`. This is especially helpful after reading +in data sets when letting the readers such as :meth:`read_csv` and :meth:`read_excel` +infer default dtypes. + +In this example, while the dtypes of all columns are changed, we show the results for +the first 10 columns. + +.. ipython:: python + + bb = pd.read_csv('data/baseball.csv', index_col='id') + bb[bb.columns[:10]].dtypes + +.. ipython:: python + + bbn = bb.convert_dtypes() + bbn[bbn.columns[:10]].dtypes diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 8c43b53f5cdfd..a820ef132957a 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -157,6 +157,36 @@ You can use the alias ``"boolean"`` as well. s = pd.Series([True, False, None], dtype="boolean") s +.. _whatsnew_100.convert_dtypes: + +``convert_dtypes`` method to ease use of supported extension dtypes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In order to encourage use of the extension dtypes ``StringDtype``, +``BooleanDtype``, ``Int64Dtype``, ``Int32Dtype``, etc., that support ``pd.NA``, the +methods :meth:`DataFrame.convert_dtypes` and :meth:`Series.convert_dtypes` +have been introduced. (:issue:`29752`) (:issue:`30929`) + +Example: + +.. ipython:: python + + df = pd.DataFrame({'x': ['abc', None, 'def'], + 'y': [1, 2, np.nan], + 'z': [True, False, True]}) + df + df.dtypes + +.. ipython:: python + + converted = df.convert_dtypes() + converted + converted.dtypes + +This is especially useful after reading in data using readers such as :func:`read_csv` +and :func:`read_excel`. +See :ref:`here <missing_data.NA.conversion>` for a description. + .. _whatsnew_100.numba_rolling_apply: Using Numba in ``rolling.apply`` diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 1dbdb8dbba48b..fa80e5c7b3700 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -7,6 +7,7 @@ from pandas._libs import lib, tslib, tslibs from pandas._libs.tslibs import NaT, OutOfBoundsDatetime, Period, iNaT from pandas._libs.tslibs.timezones import tz_compare +from pandas._typing import Dtype from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.common import ( @@ -34,6 +35,7 @@ is_float_dtype, is_integer, is_integer_dtype, + is_numeric_dtype, is_object_dtype, is_scalar, is_string_dtype, @@ -1018,6 +1020,80 @@ def soft_convert_objects( return values +def convert_dtypes( + input_array, + convert_string: bool = True, + convert_integer: bool = True, + convert_boolean: bool = True, +) -> Dtype: + """ + Convert objects to best possible type, and optionally, + to types supporting ``pd.NA``. + + Parameters + ---------- + input_array : ExtensionArray or PandasArray + convert_string : bool, default True + Whether object dtypes should be converted to ``StringDtype()``. + convert_integer : bool, default True + Whether, if possible, conversion can be done to integer extension types. + convert_boolean : bool, defaults True + Whether object dtypes should be converted to ``BooleanDtypes()``. + + Returns + ------- + dtype + new dtype + """ + + if convert_string or convert_integer or convert_boolean: + try: + inferred_dtype = lib.infer_dtype(input_array) + except ValueError: + # Required to catch due to Period. Can remove once GH 23553 is fixed + inferred_dtype = input_array.dtype + + if not convert_string and is_string_dtype(inferred_dtype): + inferred_dtype = input_array.dtype + + if convert_integer: + target_int_dtype = "Int64" + + if isinstance(inferred_dtype, str) and ( + inferred_dtype == "mixed-integer" + or inferred_dtype == "mixed-integer-float" + ): + inferred_dtype = target_int_dtype + if is_integer_dtype(input_array.dtype) and not is_extension_array_dtype( + input_array.dtype + ): + from pandas.core.arrays.integer import _dtypes + + inferred_dtype = _dtypes.get(input_array.dtype.name, target_int_dtype) + if not is_integer_dtype(input_array.dtype) and is_numeric_dtype( + input_array.dtype + ): + inferred_dtype = target_int_dtype + + else: + if is_integer_dtype(inferred_dtype): + inferred_dtype = input_array.dtype + + if convert_boolean: + if is_bool_dtype(input_array.dtype) and not is_extension_array_dtype( + input_array.dtype + ): + inferred_dtype = "boolean" + else: + if isinstance(inferred_dtype, str) and inferred_dtype == "boolean": + inferred_dtype = input_array.dtype + + else: + inferred_dtype = input_array.dtype + + return inferred_dtype + + def maybe_castable(arr) -> bool: # return False to force a non-fastpath diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0116207675889..93566b65d95eb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5879,6 +5879,7 @@ def infer_objects(self: FrameOrSeries) -> FrameOrSeries: to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. to_numeric : Convert argument to numeric type. + convert_dtypes : Convert argument to best possible dtype. Examples -------- @@ -5907,6 +5908,142 @@ def infer_objects(self: FrameOrSeries) -> FrameOrSeries: ) ).__finalize__(self) + def convert_dtypes( + self: FrameOrSeries, + infer_objects: bool_t = True, + convert_string: bool_t = True, + convert_integer: bool_t = True, + convert_boolean: bool_t = True, + ) -> FrameOrSeries: + """ + Convert columns to best possible dtypes using dtypes supporting ``pd.NA``. + + .. versionadded:: 1.0.0 + + Parameters + ---------- + infer_objects : bool, default True + Whether object dtypes should be converted to the best possible types. + convert_string : bool, default True + Whether object dtypes should be converted to ``StringDtype()``. + convert_integer : bool, default True + Whether, if possible, conversion can be done to integer extension types. + convert_boolean : bool, defaults True + Whether object dtypes should be converted to ``BooleanDtypes()``. + + Returns + ------- + Series or DataFrame + Copy of input object with new dtype. + + See Also + -------- + infer_objects : Infer dtypes of objects. + to_datetime : Convert argument to datetime. + to_timedelta : Convert argument to timedelta. + to_numeric : Convert argument to a numeric type. + + Notes + ----- + + By default, ``convert_dtypes`` will attempt to convert a Series (or each + Series in a DataFrame) to dtypes that support ``pd.NA``. By using the options + ``convert_string``, ``convert_integer``, and ``convert_boolean``, it is + possible to turn off individual conversions to ``StringDtype``, the integer + extension types or ``BooleanDtype``, respectively. + + For object-dtyped columns, if ``infer_objects`` is ``True``, use the inference + rules as during normal Series/DataFrame construction. Then, if possible, + convert to ``StringDtype``, ``BooleanDtype`` or an appropriate integer extension + type, otherwise leave as ``object``. + + If the dtype is integer, convert to an appropriate integer extension type. + + If the dtype is numeric, and consists of all integers, convert to an + appropriate integer extension type. + + In the future, as new dtypes are added that support ``pd.NA``, the results + of this method will change to support those new dtypes. + + Examples + -------- + >>> df = pd.DataFrame( + ... { + ... "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")), + ... "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")), + ... "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")), + ... "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")), + ... "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")), + ... "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")), + ... } + ... ) + + Start with a DataFrame with default dtypes. + + >>> df + a b c d e f + 0 1 x True h 10.0 NaN + 1 2 y False i NaN 100.5 + 2 3 z NaN NaN 20.0 200.0 + + >>> df.dtypes + a int32 + b object + c object + d object + e float64 + f float64 + dtype: object + + Convert the DataFrame to use best possible dtypes. + + >>> dfn = df.convert_dtypes() + >>> dfn + a b c d e f + 0 1 x True h 10 NaN + 1 2 y False i <NA> 100.5 + 2 3 z <NA> <NA> 20 200.0 + + >>> dfn.dtypes + a Int32 + b string + c boolean + d string + e Int64 + f float64 + dtype: object + + Start with a Series of strings and missing data represented by ``np.nan``. + + >>> s = pd.Series(["a", "b", np.nan]) + >>> s + 0 a + 1 b + 2 NaN + dtype: object + + Obtain a Series with dtype ``StringDtype``. + + >>> s.convert_dtypes() + 0 a + 1 b + 2 <NA> + dtype: string + """ + if self.ndim == 1: + return self._convert_dtypes( + infer_objects, convert_string, convert_integer, convert_boolean + ) + else: + results = [ + col._convert_dtypes( + infer_objects, convert_string, convert_integer, convert_boolean + ) + for col_name, col in self.items() + ] + result = pd.concat(results, axis=1, copy=False) + return result + # ---------------------------------------------------------------------- # Filling NA's diff --git a/pandas/core/series.py b/pandas/core/series.py index 270b97af9bdfb..9f8f94fe93ad8 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -16,6 +16,7 @@ from pandas.util._decorators import Appender, Substitution from pandas.util._validators import validate_bool_kwarg, validate_percentile +from pandas.core.dtypes.cast import convert_dtypes from pandas.core.dtypes.common import ( _is_unorderable_exception, ensure_platform_int, @@ -4352,6 +4353,34 @@ def between(self, left, right, inclusive=True): return lmask & rmask + # ---------------------------------------------------------------------- + # Convert to types that support pd.NA + + def _convert_dtypes( + self: ABCSeries, + infer_objects: bool = True, + convert_string: bool = True, + convert_integer: bool = True, + convert_boolean: bool = True, + ) -> "Series": + input_series = self + if infer_objects: + input_series = input_series.infer_objects() + if is_object_dtype(input_series): + input_series = input_series.copy() + + if convert_string or convert_integer or convert_boolean: + inferred_dtype = convert_dtypes( + input_series._values, convert_string, convert_integer, convert_boolean + ) + try: + result = input_series.astype(inferred_dtype) + except TypeError: + result = input_series.copy() + else: + result = input_series.copy() + return result + @Appender(generic._shared_docs["isna"] % _shared_doc_kwargs) def isna(self): return super().isna() diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index cfa42d764ee44..8c2be7092c37d 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -629,6 +629,7 @@ def to_datetime( -------- DataFrame.astype : Cast argument to a specified dtype. to_timedelta : Convert argument to timedelta. + convert_dtypes : Convert dtypes. Examples -------- diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py index e59ed247bd87b..4939cbfc9cc96 100644 --- a/pandas/core/tools/numeric.py +++ b/pandas/core/tools/numeric.py @@ -70,6 +70,7 @@ def to_numeric(arg, errors="raise", downcast=None): to_datetime : Convert argument to datetime. to_timedelta : Convert argument to timedelta. numpy.ndarray.astype : Cast a numpy array to a specified type. + convert_dtypes : Convert dtypes. Examples -------- diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 3e185feaea38e..3f0cfce39f6f9 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -49,6 +49,7 @@ def to_timedelta(arg, unit="ns", errors="raise"): -------- DataFrame.astype : Cast argument to a specified dtype. to_datetime : Convert argument to datetime. + convert_dtypes : Convert dtypes. Examples -------- diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 06bb040224455..2d3db3a1eff51 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -1072,6 +1072,27 @@ def test_str_to_small_float_conversion_type(self): expected = pd.DataFrame(col_data, columns=["A"], dtype=float) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "convert_integer, expected", [(False, np.dtype("int32")), (True, "Int32")] + ) + def test_convert_dtypes(self, convert_integer, expected): + # Specific types are tested in tests/series/test_dtypes.py + # Just check that it works for DataFrame here + df = pd.DataFrame( + { + "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")), + "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")), + } + ) + result = df.convert_dtypes(True, True, convert_integer, False) + expected = pd.DataFrame( + { + "a": pd.Series([1, 2, 3], dtype=expected), + "b": pd.Series(["x", "y", "z"], dtype="string"), + } + ) + tm.assert_frame_equal(result, expected) + class TestDataFrameDatetimeWithTZ: def test_interleave(self, timezone_frame): diff --git a/pandas/tests/series/test_convert_dtypes.py b/pandas/tests/series/test_convert_dtypes.py new file mode 100644 index 0000000000000..923b5a94c5f41 --- /dev/null +++ b/pandas/tests/series/test_convert_dtypes.py @@ -0,0 +1,248 @@ +from itertools import product + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +class TestSeriesConvertDtypes: + # The answerdict has keys that have 4 tuples, corresponding to the arguments + # infer_objects, convert_string, convert_integer, convert_boolean + # This allows all 16 possible combinations to be tested. Since common + # combinations expect the same answer, this provides an easy way to list + # all the possibilities + @pytest.mark.parametrize( + "data, maindtype, answerdict", + [ + ( + [1, 2, 3], + np.dtype("int32"), + { + ((True, False), (True, False), (True,), (True, False)): "Int32", + ((True, False), (True, False), (False,), (True, False)): np.dtype( + "int32" + ), + }, + ), + ( + [1, 2, 3], + np.dtype("int64"), + { + ((True, False), (True, False), (True,), (True, False)): "Int64", + ((True, False), (True, False), (False,), (True, False)): np.dtype( + "int64" + ), + }, + ), + ( + ["x", "y", "z"], + np.dtype("O"), + { + ( + (True, False), + (True,), + (True, False), + (True, False), + ): pd.StringDtype(), + ((True, False), (False,), (True, False), (True, False)): np.dtype( + "O" + ), + }, + ), + ( + [True, False, np.nan], + np.dtype("O"), + { + ( + (True, False), + (True, False), + (True, False), + (True,), + ): pd.BooleanDtype(), + ((True, False), (True, False), (True, False), (False,)): np.dtype( + "O" + ), + }, + ), + ( + ["h", "i", np.nan], + np.dtype("O"), + { + ( + (True, False), + (True,), + (True, False), + (True, False), + ): pd.StringDtype(), + ((True, False), (False,), (True, False), (True, False)): np.dtype( + "O" + ), + }, + ), + ( + [10, np.nan, 20], + np.dtype("float"), + { + ((True, False), (True, False), (True,), (True, False)): "Int64", + ((True, False), (True, False), (False,), (True, False)): np.dtype( + "float" + ), + }, + ), + ( + [np.nan, 100.5, 200], + np.dtype("float"), + { + ( + (True, False), + (True, False), + (True, False), + (True, False), + ): np.dtype("float"), + }, + ), + ( + [3, 4, 5], + "Int8", + {((True, False), (True, False), (True, False), (True, False)): "Int8"}, + ), + ( + [[1, 2], [3, 4], [5]], + None, + { + ( + (True, False), + (True, False), + (True, False), + (True, False), + ): np.dtype("O"), + }, + ), + ( + [4, 5, 6], + np.dtype("uint32"), + { + ((True, False), (True, False), (True,), (True, False)): "UInt32", + ((True, False), (True, False), (False,), (True, False)): np.dtype( + "uint32" + ), + }, + ), + ( + [-10, 12, 13], + np.dtype("i1"), + { + ((True, False), (True, False), (True,), (True, False)): "Int8", + ((True, False), (True, False), (False,), (True, False)): np.dtype( + "i1" + ), + }, + ), + ( + [1, 2.0], + object, + { + ((True, False), (True, False), (True,), (True, False)): "Int64", + ((True,), (True, False), (False,), (True, False)): np.dtype( + "float" + ), + ((False,), (True, False), (False,), (True, False)): np.dtype( + "object" + ), + }, + ), + ( + ["a", "b"], + pd.CategoricalDtype(), + { + ( + (True, False), + (True, False), + (True, False), + (True, False), + ): pd.CategoricalDtype(), + }, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]), + pd.DatetimeTZDtype(tz="UTC"), + { + ( + (True, False), + (True, False), + (True, False), + (True, False), + ): pd.DatetimeTZDtype(tz="UTC"), + }, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]), + "datetime64[ns]", + { + ( + (True, False), + (True, False), + (True, False), + (True, False), + ): np.dtype("datetime64[ns]"), + }, + ), + ( + pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]), + object, + { + ((True,), (True, False), (True, False), (True, False),): np.dtype( + "datetime64[ns]" + ), + ((False,), (True, False), (True, False), (True, False),): np.dtype( + "O" + ), + }, + ), + ( + pd.period_range("1/1/2011", freq="M", periods=3), + None, + { + ( + (True, False), + (True, False), + (True, False), + (True, False), + ): pd.PeriodDtype("M"), + }, + ), + ( + pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)]), + None, + { + ( + (True, False), + (True, False), + (True, False), + (True, False), + ): pd.IntervalDtype("int64"), + }, + ), + ], + ) + @pytest.mark.parametrize("params", product(*[(True, False)] * 4)) + def test_convert_dtypes(self, data, maindtype, params, answerdict): + if maindtype is not None: + series = pd.Series(data, dtype=maindtype) + else: + series = pd.Series(data) + answers = {k: a for (kk, a) in answerdict.items() for k in product(*kk)} + + ns = series.convert_dtypes(*params) + expected_dtype = answers[tuple(params)] + expected = pd.Series(series.values, dtype=expected_dtype) + tm.assert_series_equal(ns, expected) + + # Test that it is a copy + copy = series.copy(deep=True) + ns[ns.notna()] = np.nan + + # Make sure original not changed + tm.assert_series_equal(series, copy)
https://api.github.com/repos/pandas-dev/pandas/pulls/31282
2020-01-24T14:36:45Z
2020-01-24T15:34:14Z
2020-01-24T15:34:14Z
2020-01-24T15:34:18Z
Fixes non-existent doc/source/api.rst issue
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 9599dc5bd1412..a9237c239701b 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -410,7 +410,7 @@ Some other important things to know about the docs: doc build. This approach means that code examples will always be up to date, but it does make the doc building a bit more complex. -* Our API documentation in ``doc/source/api.rst`` houses the auto-generated +* Our API documentation files in ``doc/source/reference`` house the auto-generated documentation from the docstrings. For classes, there are a few subtleties around controlling which methods and attributes have pages auto-generated. @@ -428,7 +428,8 @@ Some other important things to know about the docs: ``Methods`` section in the class docstring. See ``CategoricalIndex`` for an example. - Every method should be included in a ``toctree`` in ``api.rst``, else Sphinx + Every method should be included in a ``toctree`` in one of the documentation files in + ``doc/source/reference``, else Sphinx will emit a warning. .. note:: @@ -444,11 +445,11 @@ Some other important things to know about the docs: The utility script ``scripts/validate_docstrings.py`` can be used to get a csv summary of the API documentation. And also validate common errors in the docstring of a specific class, function or method. The summary also compares the list of -methods documented in ``doc/source/api.rst`` (which is used to generate +methods documented in the files in ``doc/source/reference`` (which is used to generate the `API Reference <https://pandas.pydata.org/pandas-docs/stable/api.html>`_ page) and the actual public methods. -This will identify methods documented in ``doc/source/api.rst`` that are not actually -class methods, and existing methods that are not documented in ``doc/source/api.rst``. +This will identify methods documented in ``doc/source/reference`` that are not actually +class methods, and existing methods that are not documented in ``doc/source/reference``. Updating a *pandas* docstring
Modified the path doc/source/api.rst
https://api.github.com/repos/pandas-dev/pandas/pulls/31280
2020-01-24T13:57:14Z
2020-01-25T04:28:33Z
2020-01-25T04:28:33Z
2020-01-25T06:00:03Z
DOC: move convert_dtypes whatsnew to 1.0
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 087265858e850..94e537b4a997f 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -157,6 +157,36 @@ You can use the alias ``"boolean"`` as well. s = pd.Series([True, False, None], dtype="boolean") s +.. _whatsnew_100.convert_dtypes: + +``convert_dtypes`` method to ease use of supported extension dtypes +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In order to encourage use of the extension dtypes ``StringDtype``, +``BooleanDtype``, ``Int64Dtype``, ``Int32Dtype``, etc., that support ``pd.NA``, the +methods :meth:`DataFrame.convert_dtypes` and :meth:`Series.convert_dtypes` +have been introduced. (:issue:`29752`) (:issue:`30929`) + +Example: + +.. ipython:: python + + df = pd.DataFrame({'x': ['abc', None, 'def'], + 'y': [1, 2, np.nan], + 'z': [True, False, True]}) + df + df.dtypes + +.. ipython:: python + + converted = df.convert_dtypes() + converted + converted.dtypes + +This is especially useful after reading in data using readers such as :func:`read_csv` +and :func:`read_excel`. +See :ref:`here <missing_data.NA.conversion>` for a description. + .. _whatsnew_100.numba_rolling_apply: Using Numba in ``rolling.apply`` and ``expanding.apply`` diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index d0cf92b60fe0d..b41fbe880a65d 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -13,36 +13,6 @@ including other versions of pandas. Enhancements ~~~~~~~~~~~~ -.. _whatsnew_100.convert_dtypes: - -``convert_dtypes`` method to ease use of supported extension dtypes -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -In order to encourage use of the extension dtypes ``StringDtype``, -``BooleanDtype``, ``Int64Dtype``, ``Int32Dtype``, etc., that support ``pd.NA``, the -methods :meth:`DataFrame.convert_dtypes` and :meth:`Series.convert_dtypes` -have been introduced. (:issue:`29752`) (:issue:`30929`) - -Example: - -.. ipython:: python - - df = pd.DataFrame({'x': ['abc', None, 'def'], - 'y': [1, 2, np.nan], - 'z': [True, False, True]}) - df - df.dtypes - -.. ipython:: python - - converted = df.convert_dtypes() - converted - converted.dtypes - -This is especially useful after reading in data using readers such as :func:`read_csv` -and :func:`read_excel`. -See :ref:`here <missing_data.NA.conversion>` for a description. - .. _whatsnew_110.period_index_partial_string_slicing: Nonmonotonic PeriodIndex Partial String Slicing diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c502adcdb09e0..ca89c3f7209ca 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5741,7 +5741,7 @@ def convert_dtypes( """ Convert columns to best possible dtypes using dtypes supporting ``pd.NA``. - .. versionadded:: 1.1.0 + .. versionadded:: 1.0.0 Parameters ----------
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry - moved whatsnew entry from 1.1 to 1.0 Per comment here from @jreback: https://github.com/pandas-dev/pandas/pull/30929#issuecomment-577989924
https://api.github.com/repos/pandas-dev/pandas/pulls/31279
2020-01-24T13:45:32Z
2020-01-24T14:29:06Z
2020-01-24T14:29:06Z
2020-01-24T16:00:05Z
BUG: 27453 right merge order
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 8cb80c7c92f8e..e0d60e56796dd 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -168,6 +168,32 @@ key and type of :class:`Index`. These now consistently raise ``KeyError`` (:iss ... KeyError: Timestamp('1970-01-01 00:00:00') +:meth:`DataFrame.merge` preserves right frame's row order +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +:meth:`DataFrame.merge` now preserves right frame's row order when executing a right merge (:issue:`27453`) + +.. ipython:: python + + left_df = pd.DataFrame({'animal': ['dog', 'pig'], 'max_speed': [40, 11]}) + right_df = pd.DataFrame({'animal': ['quetzal', 'pig'], 'max_speed': [80, 11]}) + left_df + right_df + +*Previous behavior*: + +.. code-block:: python + + >>> left_df.merge(right_df, on=['animal', 'max_speed'], how="right") + animal max_speed + 0 pig 11 + 1 quetzal 80 + +*New behavior*: + +.. ipython:: python + + left_df.merge(right_df, on=['animal', 'max_speed'], how="right") + .. --------------------------------------------------------------------------- .. _whatsnew_110.api_breaking.assignment_to_multiple_columns: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 3b3802875b36b..6e024560ea2e4 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -6,14 +6,14 @@ import datetime from functools import partial import string -from typing import TYPE_CHECKING, Optional, Tuple, Union +from typing import TYPE_CHECKING, Optional, Tuple, Union, cast import warnings import numpy as np from pandas._libs import Timedelta, hashtable as libhashtable, lib import pandas._libs.join as libjoin -from pandas._typing import FrameOrSeries +from pandas._typing import ArrayLike, FrameOrSeries from pandas.errors import MergeError from pandas.util._decorators import Appender, Substitution @@ -24,6 +24,7 @@ is_array_like, is_bool, is_bool_dtype, + is_categorical, is_categorical_dtype, is_datetime64tz_dtype, is_dtype_equal, @@ -1271,7 +1272,7 @@ def _get_join_indexers( # get left & right join labels and num. of levels at each location mapped = ( - _factorize_keys(left_keys[n], right_keys[n], sort=sort) + _factorize_keys(left_keys[n], right_keys[n], sort=sort, how=how) for n in range(len(left_keys)) ) zipped = zip(*mapped) @@ -1283,8 +1284,8 @@ def _get_join_indexers( # factorize keys to a dense i8 space # `count` is the num. of unique keys # set(lkey) | set(rkey) == range(count) - lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort) + lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort, how=how) # preserve left frame order if how == 'left' and sort == False kwargs = copy.copy(kwargs) if how == "left": @@ -1822,7 +1823,59 @@ def _right_outer_join(x, y, max_groups): return left_indexer, right_indexer -def _factorize_keys(lk, rk, sort=True): +def _factorize_keys( + lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner" +) -> Tuple[np.array, np.array, int]: + """ + Encode left and right keys as enumerated types. + + This is used to get the join indexers to be used when merging DataFrames. + + Parameters + ---------- + lk : array-like + Left key. + rk : array-like + Right key. + sort : bool, defaults to True + If True, the encoding is done such that the unique elements in the + keys are sorted. + how : {‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’ + Type of merge. + + Returns + ------- + array + Left (resp. right if called with `key='right'`) labels, as enumerated type. + array + Right (resp. left if called with `key='right'`) labels, as enumerated type. + int + Number of unique elements in union of left and right labels. + + See Also + -------- + merge : Merge DataFrame or named Series objects + with a database-style join. + algorithms.factorize : Encode the object as an enumerated type + or categorical variable. + + Examples + -------- + >>> lk = np.array(["a", "c", "b"]) + >>> rk = np.array(["a", "c"]) + + Here, the unique values are `'a', 'b', 'c'`. With the default + `sort=True`, the encoding will be `{0: 'a', 1: 'b', 2: 'c'}`: + + >>> pd.core.reshape.merge._factorize_keys(lk, rk) + (array([0, 2, 1]), array([0, 2]), 3) + + With the `sort=False`, the encoding will correspond to the order + in which the unique elements first appear: `{0: 'a', 1: 'c', 2: 'b'}`: + + >>> pd.core.reshape.merge._factorize_keys(lk, rk, sort=False) + (array([0, 1, 2]), array([0, 1]), 3) + """ # Some pre-processing for non-ndarray lk / rk lk = extract_array(lk, extract_numpy=True) rk = extract_array(rk, extract_numpy=True) @@ -1834,8 +1887,11 @@ def _factorize_keys(lk, rk, sort=True): rk, _ = rk._values_for_factorize() elif ( - is_categorical_dtype(lk) and is_categorical_dtype(rk) and lk.is_dtype_equal(rk) + is_categorical_dtype(lk) and is_categorical_dtype(rk) and is_dtype_equal(lk, rk) ): + assert is_categorical(lk) and is_categorical(rk) + lk = cast(Categorical, lk) + rk = cast(Categorical, rk) if lk.categories.equals(rk.categories): # if we exactly match in categories, allow us to factorize on codes rk = rk.codes @@ -1892,6 +1948,8 @@ def _factorize_keys(lk, rk, sort=True): np.putmask(rlab, rmask, count) count += 1 + if how == "right": + return rlab, llab, count return llab, rlab, count diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 51e6f80df657d..a6a76a1078667 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1286,17 +1286,17 @@ def test_merge_on_index_with_more_values(self, how, index, expected_index): # GH 24212 # pd.merge gets [0, 1, 2, -1, -1, -1] as left_indexer, ensure that # -1 is interpreted as a missing value instead of the last element - df1 = pd.DataFrame({"a": [1, 2, 3], "key": [0, 2, 2]}, index=index) - df2 = pd.DataFrame({"b": [1, 2, 3, 4, 5]}) + df1 = pd.DataFrame({"a": [0, 1, 2], "key": [0, 1, 2]}, index=index) + df2 = pd.DataFrame({"b": [0, 1, 2, 3, 4, 5]}) result = df1.merge(df2, left_on="key", right_index=True, how=how) expected = pd.DataFrame( [ - [1.0, 0, 1], - [2.0, 2, 3], - [3.0, 2, 3], - [np.nan, 1, 2], - [np.nan, 3, 4], - [np.nan, 4, 5], + [0, 0, 0], + [1, 1, 1], + [2, 2, 2], + [np.nan, 3, 3], + [np.nan, 4, 4], + [np.nan, 5, 5], ], columns=["a", "key", "b"], ) @@ -1318,6 +1318,20 @@ def test_merge_right_index_right(self): result = left.merge(right, left_on="key", right_index=True, how="right") tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize("how", ["left", "right"]) + def test_merge_preserves_row_order(self, how): + # GH 27453 + left_df = pd.DataFrame({"animal": ["dog", "pig"], "max_speed": [40, 11]}) + right_df = pd.DataFrame({"animal": ["quetzal", "pig"], "max_speed": [80, 11]}) + result = left_df.merge(right_df, on=["animal", "max_speed"], how=how) + if how == "right": + expected = pd.DataFrame( + {"animal": ["quetzal", "pig"], "max_speed": [80, 11]} + ) + else: + expected = pd.DataFrame({"animal": ["dog", "pig"], "max_speed": [40, 11]}) + tm.assert_frame_equal(result, expected) + def test_merge_take_missing_values_from_index_of_other_dtype(self): # GH 24212 left = pd.DataFrame(
Resurrection of #27762 I fixed the NameError in the test, and also changed the example given in the whatsnew entry (I couldn't see a difference between the outputs of 0.25.x and 1.0.0 in the original) - [x] closes #27453 - [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/31278
2020-01-24T12:08:57Z
2020-03-26T12:45:39Z
2020-03-26T12:45:38Z
2020-03-26T12:49:31Z
ASV: add benchmarks for Series.array and extract_array
diff --git a/asv_bench/benchmarks/attrs_caching.py b/asv_bench/benchmarks/attrs_caching.py index 501e27b9078ec..9c7b107b478d4 100644 --- a/asv_bench/benchmarks/attrs_caching.py +++ b/asv_bench/benchmarks/attrs_caching.py @@ -1,5 +1,6 @@ import numpy as np +import pandas as pd from pandas import DataFrame try: @@ -7,6 +8,11 @@ except ImportError: from pandas.util.decorators import cache_readonly +try: + from pandas.core.construction import extract_array +except ImportError: + extract_array = None + class DataFrameAttributes: def setup(self): @@ -20,6 +26,33 @@ def time_set_index(self): self.df.index = self.cur_index +class SeriesArrayAttribute: + + params = [["numeric", "object", "category", "datetime64", "datetime64tz"]] + param_names = ["dtype"] + + def setup(self, dtype): + if dtype == "numeric": + self.series = pd.Series([1, 2, 3]) + elif dtype == "object": + self.series = pd.Series(["a", "b", "c"], dtype=object) + elif dtype == "category": + self.series = pd.Series(["a", "b", "c"], dtype="category") + elif dtype == "datetime64": + self.series = pd.Series(pd.date_range("2013", periods=3)) + elif dtype == "datetime64tz": + self.series = pd.Series(pd.date_range("2013", periods=3, tz="UTC")) + + def time_array(self, dtype): + self.series.array + + def time_extract_array(self, dtype): + extract_array(self.series) + + def time_extract_array_numpy(self, dtype): + extract_array(self.series, extract_numpy=True) + + class CacheReadonly: def setup(self): class Foo:
Just thought it would be useful to have a benchmark for `.array` (now the performance regression of https://github.com/pandas-dev/pandas/pull/31037 was caught indirectly through an indexing benchmark)
https://api.github.com/repos/pandas-dev/pandas/pulls/31277
2020-01-24T09:14:35Z
2020-01-24T13:09:50Z
2020-01-24T13:09:50Z
2020-01-24T13:11:28Z
Backport PR #31037: PERF: improve access of .array
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 4db3d3010adaf..075096f6cfb54 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -43,7 +43,6 @@ class PandasDtype(ExtensionDtype): def __init__(self, dtype): dtype = np.dtype(dtype) self._dtype = dtype - self._name = dtype.name self._type = dtype.type def __repr__(self) -> str: @@ -56,7 +55,7 @@ def numpy_dtype(self): @property def name(self): - return self._name + return self._dtype.name @property def type(self): diff --git a/pandas/core/base.py b/pandas/core/base.py index 66d7cd59dcfa4..5acf1a28bb4b6 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -18,13 +18,11 @@ from pandas.core.dtypes.cast import is_nested_object from pandas.core.dtypes.common import ( is_categorical_dtype, - is_datetime64_ns_dtype, is_dict_like, is_extension_array_dtype, is_list_like, is_object_dtype, is_scalar, - is_timedelta64_ns_dtype, needs_i8_conversion, ) from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries @@ -747,26 +745,7 @@ def array(self) -> ExtensionArray: [a, b, a] Categories (2, object): [a, b] """ - # As a mixin, we depend on the mixing class having _values. - # Special mixin syntax may be developed in the future: - # https://github.com/python/typing/issues/246 - result = self._values # type: ignore - - if is_datetime64_ns_dtype(result.dtype): - from pandas.arrays import DatetimeArray - - result = DatetimeArray(result) - elif is_timedelta64_ns_dtype(result.dtype): - from pandas.arrays import TimedeltaArray - - result = TimedeltaArray(result) - - elif not is_extension_array_dtype(result.dtype): - from pandas.core.arrays.numpy_ import PandasArray - - result = PandasArray(result) - - return result + raise AbstractMethodError(self) def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs): """ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index ca929b188dc33..875bbbd355ad6 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3640,6 +3640,16 @@ def values(self): """ return self._data.view(np.ndarray) + @cache_readonly + @Appender(IndexOpsMixin.array.__doc__) # type: ignore + def array(self) -> ExtensionArray: + array = self._data + if isinstance(array, np.ndarray): + from pandas.core.arrays.numpy_ import PandasArray + + array = PandasArray(array) + return array + @property def _values(self) -> Union[ExtensionArray, ABCIndexClass, np.ndarray]: # TODO(EA): remove index types as they become extension arrays diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 0732eda5f1f6e..a8a3b896f7b31 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -66,7 +66,14 @@ ) import pandas.core.algorithms as algos -from pandas.core.arrays import Categorical, DatetimeArray, PandasDtype, TimedeltaArray +from pandas.core.arrays import ( + Categorical, + DatetimeArray, + ExtensionArray, + PandasArray, + PandasDtype, + TimedeltaArray, +) from pandas.core.base import PandasObject import pandas.core.common as com from pandas.core.construction import extract_array @@ -193,7 +200,14 @@ def is_categorical_astype(self, dtype): return False def external_values(self, dtype=None): - """ return an outside world format, currently just the ndarray """ + """ + The array that Series.values returns (public attribute). + + This has some historical constraints, and is overridden in block + subclasses to return the correct array (e.g. period returns + object ndarray and datetimetz a datetime64[ns] ndarray instead of + proper extension array). + """ return self.values def internal_values(self, dtype=None): @@ -202,6 +216,12 @@ def internal_values(self, dtype=None): """ return self.values + def array_values(self) -> ExtensionArray: + """ + The array that Series.array returns. Always an ExtensionArray. + """ + return PandasArray(self.values) + def get_values(self, dtype=None): """ return an internal format, currently just the ndarray @@ -1770,6 +1790,9 @@ def get_values(self, dtype=None): values = values.reshape((1,) + values.shape) return values + def array_values(self) -> ExtensionArray: + return self.values + def to_dense(self): return np.asarray(self.values) @@ -2233,6 +2256,9 @@ def set(self, locs, values): def external_values(self): return np.asarray(self.values.astype("datetime64[ns]", copy=False)) + def array_values(self) -> ExtensionArray: + return DatetimeArray._simple_new(self.values) + class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): """ implement a datetime64 block with a tz attribute """ @@ -2490,6 +2516,9 @@ def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): def external_values(self, dtype=None): return np.asarray(self.values.astype("timedelta64[ns]", copy=False)) + def array_values(self) -> ExtensionArray: + return TimedeltaArray._simple_new(self.values) + class BoolBlock(NumericBlock): __slots__ = () diff --git a/pandas/core/series.py b/pandas/core/series.py index 33da47eefde20..270b97af9bdfb 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -479,10 +479,43 @@ def values(self): @property def _values(self): """ - Return the internal repr of this data. + Return the internal repr of this data (defined by Block.interval_values). + This are the values as stored in the Block (ndarray or ExtensionArray + depending on the Block class). + + Differs from the public ``.values`` for certain data types, because of + historical backwards compatibility of the public attribute (e.g. period + returns object ndarray and datetimetz a datetime64[ns] ndarray for + ``.values`` while it returns an ExtensionArray for ``._values`` in those + cases). + + Differs from ``.array`` in that this still returns the numpy array if + the Block is backed by a numpy array, while ``.array`` ensures to always + return an ExtensionArray. + + Differs from ``._ndarray_values``, as that ensures to always return a + numpy array (it will call ``_ndarray_values`` on the ExtensionArray, if + the Series was backed by an ExtensionArray). + + Overview: + + dtype | values | _values | array | _ndarray_values | + ----------- | ------------- | ------------- | ------------- | --------------- | + Numeric | ndarray | ndarray | PandasArray | ndarray | + Category | Categorical | Categorical | Categorical | ndarray[int] | + dt64[ns] | ndarray[M8ns] | ndarray[M8ns] | DatetimeArray | ndarray[M8ns] | + dt64[ns tz] | ndarray[M8ns] | DatetimeArray | DatetimeArray | ndarray[M8ns] | + Period | ndarray[obj] | PeriodArray | PeriodArray | ndarray[int] | + Nullable | EA | EA | EA | ndarray | + """ return self._data.internal_values() + @Appender(base.IndexOpsMixin.array.__doc__) # type: ignore + @property + def array(self) -> ExtensionArray: + return self._data._block.array_values() + def _internal_get_values(self): """ Same as values (but handles sparseness conversions); is a view.
https://github.com/pandas-dev/pandas/pull/31037
https://api.github.com/repos/pandas-dev/pandas/pulls/31275
2020-01-24T08:32:43Z
2020-01-24T09:06:31Z
2020-01-24T09:06:31Z
2020-01-24T09:06:39Z
BUG: DataFrame.floordiv(ser, axis=0) not matching column-wise bheavior
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index b41fbe880a65d..266eed8a50ceb 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -119,6 +119,7 @@ Timezones Numeric ^^^^^^^ +- Bug in :meth:`DataFrame.floordiv` with ``axis=0`` not treating division-by-zero like :meth:`Series.floordiv` (:issue:`31271`) - - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 012fb1d0c2eb7..9ff3f8c2316f1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5341,7 +5341,7 @@ def reorder_levels(self, order, axis=0) -> "DataFrame": # ---------------------------------------------------------------------- # Arithmetic / combination related - def _combine_frame(self, other, func, fill_value=None, level=None): + def _combine_frame(self, other: "DataFrame", func, fill_value=None): # at this point we have `self._indexed_same(other)` if fill_value is None: @@ -5368,7 +5368,7 @@ def _arith_op(left, right): return new_data - def _combine_match_index(self, other, func): + def _combine_match_index(self, other: Series, func): # at this point we have `self.index.equals(other.index)` if ops.should_series_dispatch(self, other, func): @@ -5376,8 +5376,10 @@ def _combine_match_index(self, other, func): new_data = ops.dispatch_to_series(self, other, func) else: # fastpath --> operate directly on values + other_vals = other.values.reshape(-1, 1) with np.errstate(all="ignore"): - new_data = func(self.values.T, other.values).T + new_data = func(self.values, other_vals) + new_data = dispatch_fill_zeros(func, self.values, other_vals, new_data) return new_data def _construct_result(self, result) -> "DataFrame": diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py index 5039ffab33fbd..854d6072eea36 100644 --- a/pandas/core/ops/missing.py +++ b/pandas/core/ops/missing.py @@ -109,26 +109,23 @@ def mask_zero_div_zero(x, y, result): return result if zmask.any(): - shape = result.shape # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask - nan_mask = (zmask & (x == 0)).ravel() + nan_mask = zmask & (x == 0) with np.errstate(invalid="ignore"): - neginf_mask = ((zpos_mask & (x < 0)) | (zneg_mask & (x > 0))).ravel() - posinf_mask = ((zpos_mask & (x > 0)) | (zneg_mask & (x < 0))).ravel() + neginf_mask = (zpos_mask & (x < 0)) | (zneg_mask & (x > 0)) + posinf_mask = (zpos_mask & (x > 0)) | (zneg_mask & (x < 0)) if nan_mask.any() or neginf_mask.any() or posinf_mask.any(): # Fill negative/0 with -inf, positive/0 with +inf, 0/0 with NaN - result = result.astype("float64", copy=False).ravel() - - np.putmask(result, nan_mask, np.nan) - np.putmask(result, posinf_mask, np.inf) - np.putmask(result, neginf_mask, -np.inf) + result = result.astype("float64", copy=False) - result = result.reshape(shape) + result[nan_mask] = np.nan + result[posinf_mask] = np.inf + result[neginf_mask] = -np.inf return result diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 659b55756c4b6..c6eacf2bbcd84 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -332,6 +332,21 @@ def test_df_flex_cmp_constant_return_types_empty(self, opname): class TestFrameFlexArithmetic: + def test_floordiv_axis0(self): + # make sure we df.floordiv(ser, axis=0) matches column-wise result + arr = np.arange(3) + ser = pd.Series(arr) + df = pd.DataFrame({"A": ser, "B": ser}) + + result = df.floordiv(ser, axis=0) + + expected = pd.DataFrame({col: df[col] // ser for col in df.columns}) + + tm.assert_frame_equal(result, expected) + + result2 = df.floordiv(ser.values, axis=0) + tm.assert_frame_equal(result2, expected) + def test_df_add_td64_columnwise(self): # GH 22534 Check that column-wise addition broadcasts correctly dti = pd.date_range("2016-01-01", periods=10)
We're pretty close to being able to combine _combine_frame and _combine_match_index (and hopefully get rid of them both before long)
https://api.github.com/repos/pandas-dev/pandas/pulls/31271
2020-01-24T05:30:30Z
2020-01-26T00:37:02Z
2020-01-26T00:37:02Z
2020-01-26T00:55:47Z
BUG: passing TDA and wrong freq to TimedeltaIndex
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index d0a31b68250ad..e78714487f01e 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -163,7 +163,7 @@ def __new__( "represent unambiguous timedelta values durations." ) - if isinstance(data, TimedeltaArray): + if isinstance(data, TimedeltaArray) and freq is None: if copy: data = data.copy() return cls._simple_new(data, name=name, freq=freq) diff --git a/pandas/tests/indexes/timedeltas/test_constructors.py b/pandas/tests/indexes/timedeltas/test_constructors.py index 39abbf59d1e56..32e6821e87f05 100644 --- a/pandas/tests/indexes/timedeltas/test_constructors.py +++ b/pandas/tests/indexes/timedeltas/test_constructors.py @@ -47,6 +47,12 @@ def test_infer_from_tdi_mismatch(self): # GH#23789 TimedeltaArray(tdi, freq="D") + with pytest.raises(ValueError, match=msg): + TimedeltaIndex(tdi._data, freq="D") + + with pytest.raises(ValueError, match=msg): + TimedeltaArray(tdi._data, freq="D") + def test_dt64_data_invalid(self): # GH#23539 # passing tz-aware DatetimeIndex raises, naive or ndarray[datetime64]
Caught while working towards making TimedeltaArray._simple_new more strict about its inputs. - [ ] closes #xxxx - [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/31268
2020-01-24T04:56:03Z
2020-01-25T16:18:11Z
2020-01-25T16:18:11Z
2020-01-25T16:31:07Z
Backport PR #31036 on branch 1.0.x (BUG: AssertionError on Series.append(DataFrame) fix #30975 )
diff --git a/pandas/tests/series/methods/test_append.py b/pandas/tests/series/methods/test_append.py index dc0fca4bba067..4d64b5b397981 100644 --- a/pandas/tests/series/methods/test_append.py +++ b/pandas/tests/series/methods/test_append.py @@ -61,6 +61,16 @@ def test_append_tuples(self): tm.assert_series_equal(expected, result) + def test_append_dataframe_regression(self): + # GH 30975 + df = pd.DataFrame({"A": [1, 2]}) + result = df.A.append([df]) + expected = pd.DataFrame( + {0: [1.0, 2.0, None, None], "A": [None, None, 1.0, 2.0]}, index=[0, 1, 0, 1] + ) + + tm.assert_frame_equal(expected, result) + class TestSeriesAppendWithDatetimeIndex: def test_append(self):
Backport PR #31036: BUG: AssertionError on Series.append(DataFrame) fix #30975
https://api.github.com/repos/pandas-dev/pandas/pulls/31267
2020-01-24T03:38:02Z
2020-01-24T04:34:47Z
2020-01-24T04:34:47Z
2020-01-24T04:34:47Z
REF: do alignment before _combine_series_frame
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 1355060efd097..9ed233cad65ce 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -584,33 +584,23 @@ def flex_wrapper(self, other, level=None, fill_value=None, axis=0): # DataFrame -def _combine_series_frame(self, other, func, fill_value=None, axis=None, level=None): +def _combine_series_frame(left, right, func, axis: int): """ Apply binary operator `func` to self, other using alignment and fill - conventions determined by the fill_value, axis, and level kwargs. + conventions determined by the axis argument. Parameters ---------- - self : DataFrame - other : Series + left : DataFrame + right : Series func : binary operator - fill_value : object, default None - axis : {0, 1, 'columns', 'index', None}, default None - level : int or None, default None + axis : {0, 1} Returns ------- result : DataFrame """ - if fill_value is not None: - raise NotImplementedError(f"fill_value {fill_value} not supported.") - - if axis is None: - # default axis is columns - axis = 1 - - axis = self._get_axis_number(axis) - left, right = self.align(other, join="outer", axis=axis, level=level, copy=False) + # We assume that self.align(other, ...) has already been called if axis == 0: new_data = left._combine_match_index(right, func) else: @@ -707,9 +697,15 @@ def f(self, other, axis=default_axis, level=None, fill_value=None): # so do not want the masked op. pass_op = op if axis in [0, "columns", None] else na_op pass_op = pass_op if not is_logical else op - return _combine_series_frame( - self, other, pass_op, fill_value=fill_value, axis=axis, level=level + + if fill_value is not None: + raise NotImplementedError(f"fill_value {fill_value} not supported.") + + axis = self._get_axis_number(axis) if axis is not None else 1 + self, other = self.align( + other, join="outer", axis=axis, level=level, copy=False ) + return _combine_series_frame(self, other, pass_op, axis=axis) else: # in this case we always have `np.ndim(other) == 0` if fill_value is not None: @@ -745,9 +741,11 @@ def f(self, other, axis=default_axis, level=None): return self._construct_result(new_data) elif isinstance(other, ABCSeries): - return _combine_series_frame( - self, other, op, fill_value=None, axis=axis, level=level + axis = self._get_axis_number(axis) if axis is not None else 1 + self, other = self.align( + other, join="outer", axis=axis, level=level, copy=False ) + return _combine_series_frame(self, other, op, axis=axis) else: # in this case we always have `np.ndim(other) == 0` new_data = dispatch_to_series(self, other, op) @@ -774,18 +772,21 @@ def f(self, other): "Can only compare identically-labeled DataFrame objects" ) new_data = dispatch_to_series(self, other, op, str_rep) - return self._construct_result(new_data) elif isinstance(other, ABCSeries): - return _combine_series_frame( - self, other, op, fill_value=None, axis=None, level=None + # axis=1 is default for DataFrame-with-Series op + self, other = self.align( + other, join="outer", axis=1, level=None, copy=False ) + new_data = dispatch_to_series(self, other, op, axis="columns") + else: # straight boolean comparisons we want to allow all columns # (regardless of dtype to pass thru) See #4537 for discussion. new_data = dispatch_to_series(self, other, op) - return self._construct_result(new_data) + + return self._construct_result(new_data) f.__name__ = op_name
This will allow us to de-duplicate _construct_result calls (this does so for _comp_method_FRAME) and ultimately move all of the alignment into _align_method_FRAME
https://api.github.com/repos/pandas-dev/pandas/pulls/31266
2020-01-24T01:55:49Z
2020-01-24T03:52:08Z
2020-01-24T03:52:08Z
2020-01-24T04:32:56Z
Backport PR #31249 on branch 1.0.x (TST: Fix timestamp comparison test)
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index f1fcf46a936fd..2f3175598d592 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -751,7 +751,7 @@ def test_asm8(self): def test_class_ops_pytz(self): def compare(x, y): - assert int(Timestamp(x).value / 1e9) == int(Timestamp(y).value / 1e9) + assert int((Timestamp(x).value - Timestamp(y).value) / 1e9) == 0 compare(Timestamp.now(), datetime.now()) compare(Timestamp.now("UTC"), datetime.now(timezone("UTC"))) @@ -775,8 +775,12 @@ def compare(x, y): def test_class_ops_dateutil(self): def compare(x, y): - assert int(np.round(Timestamp(x).value / 1e9)) == int( - np.round(Timestamp(y).value / 1e9) + assert ( + int( + np.round(Timestamp(x).value / 1e9) + - np.round(Timestamp(y).value / 1e9) + ) + == 0 ) compare(Timestamp.now(), datetime.now())
Backport PR #31249: TST: Fix timestamp comparison test
https://api.github.com/repos/pandas-dev/pandas/pulls/31265
2020-01-23T23:10:32Z
2020-01-23T23:52:52Z
2020-01-23T23:52:52Z
2020-01-23T23:52:52Z
BUG: na_logical_op with 2D inputs
diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index b84d468fff736..cb7b8a5987b96 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -277,7 +277,7 @@ def na_logical_op(x: np.ndarray, y, op): assert not (is_bool_dtype(x.dtype) and is_bool_dtype(y.dtype)) x = ensure_object(x) y = ensure_object(y) - result = libops.vec_binop(x, y, op) + result = libops.vec_binop(x.ravel(), y.ravel(), op) else: # let null fall thru assert lib.is_scalar(y) @@ -298,7 +298,7 @@ def na_logical_op(x: np.ndarray, y, op): f"and scalar of type [{typ}]" ) - return result + return result.reshape(x.shape) def logical_op( diff --git a/pandas/tests/arithmetic/test_array_ops.py b/pandas/tests/arithmetic/test_array_ops.py new file mode 100644 index 0000000000000..d8aaa3183a1c6 --- /dev/null +++ b/pandas/tests/arithmetic/test_array_ops.py @@ -0,0 +1,21 @@ +import operator + +import numpy as np +import pytest + +import pandas._testing as tm +from pandas.core.ops.array_ops import na_logical_op + + +def test_na_logical_op_2d(): + left = np.arange(8).reshape(4, 2) + right = left.astype(object) + right[0, 0] = np.nan + + # Check that we fall back to the vec_binop branch + with pytest.raises(TypeError, match="unsupported operand type"): + operator.or_(left, right) + + result = na_logical_op(left, right, operator.or_) + expected = right + tm.assert_numpy_array_equal(result, expected)
Broken off from a branch implementing block-wise ops for op(dataframe, dataframe)
https://api.github.com/repos/pandas-dev/pandas/pulls/31263
2020-01-23T22:31:18Z
2020-01-24T03:53:17Z
2020-01-24T03:53:17Z
2020-01-24T17:44:19Z
PLT: Color attributes of medianprops etc are lost in df.boxplot and df.plot.boxplot
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 40abb8f83de2f..02fb4b3a619d7 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -192,6 +192,8 @@ Plotting - :func:`.plot` for line/bar now accepts color by dictonary (:issue:`8193`). - +- Bug in :meth:`DataFrame.boxplot` and :meth:`DataFrame.plot.boxplot` lost color attributes of ``medianprops``, ``whiskerprops``, ``capprops`` and ``medianprops`` (:issue:`30346`) + Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index deeeb0016142c..e36696dc23a87 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -107,10 +107,16 @@ def maybe_color_bp(self, bp): medians = self.color or self._medians_c caps = self.color or self._caps_c - setp(bp["boxes"], color=boxes, alpha=1) - setp(bp["whiskers"], color=whiskers, alpha=1) - setp(bp["medians"], color=medians, alpha=1) - setp(bp["caps"], color=caps, alpha=1) + # GH 30346, when users specifying those arguments explicitly, our defaults + # for these four kwargs should be overridden; if not, use Pandas settings + if not self.kwds.get("boxprops"): + setp(bp["boxes"], color=boxes, alpha=1) + if not self.kwds.get("whiskerprops"): + setp(bp["whiskers"], color=whiskers, alpha=1) + if not self.kwds.get("medianprops"): + setp(bp["medians"], color=medians, alpha=1) + if not self.kwds.get("capprops"): + setp(bp["caps"], color=caps, alpha=1) def _make_plot(self): if self.subplots: @@ -275,11 +281,17 @@ def _get_colors(): return result - def maybe_color_bp(bp): - setp(bp["boxes"], color=colors[0], alpha=1) - setp(bp["whiskers"], color=colors[1], alpha=1) - setp(bp["medians"], color=colors[2], alpha=1) - setp(bp["caps"], color=colors[3], alpha=1) + def maybe_color_bp(bp, **kwds): + # GH 30346, when users specifying those arguments explicitly, our defaults + # for these four kwargs should be overridden; if not, use Pandas settings + if not kwds.get("boxprops"): + setp(bp["boxes"], color=colors[0], alpha=1) + if not kwds.get("whiskerprops"): + setp(bp["whiskers"], color=colors[1], alpha=1) + if not kwds.get("medianprops"): + setp(bp["medians"], color=colors[2], alpha=1) + if not kwds.get("capprops"): + setp(bp["caps"], color=colors[3], alpha=1) def plot_group(keys, values, ax): keys = [pprint_thing(x) for x in keys] @@ -291,7 +303,7 @@ def plot_group(keys, values, ax): ax.set_xticklabels(keys, rotation=rot) else: ax.set_yticklabels(keys, rotation=rot) - maybe_color_bp(bp) + maybe_color_bp(bp, **kwds) # Return axes in multiplot case, maybe revisit later # 985 if return_type == "dict": diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 8ee279f0e1f38..b84fcffe26991 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -203,6 +203,23 @@ def test_color_kwd_errors(self, dict_colors, msg): with pytest.raises(ValueError, match=msg): df.boxplot(color=dict_colors, return_type="dict") + @pytest.mark.parametrize( + "props, expected", + [ + ("boxprops", "boxes"), + ("whiskerprops", "whiskers"), + ("capprops", "caps"), + ("medianprops", "medians"), + ], + ) + def test_specified_props_kwd(self, props, expected): + # GH 30346 + df = DataFrame({k: np.random.random(100) for k in "ABC"}) + kwd = {props: dict(color="C1")} + result = df.boxplot(return_type="dict", **kwd) + + assert result[expected][0].get_color() == "C1" + @td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase): diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 1c429bafa9a19..ffbd135466709 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -2352,6 +2352,23 @@ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None): # Color contains invalid key results in ValueError df.plot.box(color=dict(boxes="red", xxxx="blue")) + @pytest.mark.parametrize( + "props, expected", + [ + ("boxprops", "boxes"), + ("whiskerprops", "whiskers"), + ("capprops", "caps"), + ("medianprops", "medians"), + ], + ) + def test_specified_props_kwd_plot_box(self, props, expected): + # GH 30346 + df = DataFrame({k: np.random.random(100) for k in "ABC"}) + kwd = {props: dict(color="C1")} + result = df.plot.box(return_type="dict", **kwd) + + assert result[expected][0].get_color() == "C1" + def test_default_color_cycle(self): import matplotlib.pyplot as plt import cycler
- [x] closes #30346 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Found out that not only `medianprops` info is lost, so is `whiskerprops`, `capprops` and `boxprops`, so I also added them alongside. Since this is a visualization PR, so add a screenshot to show what it looks like after the change <img width="587" alt="Screen Shot 2020-01-24 at 4 16 26 PM" src="https://user-images.githubusercontent.com/9269816/73079678-eb468180-3ec4-11ea-9628-5ab13e73f15c.png">
https://api.github.com/repos/pandas-dev/pandas/pulls/31262
2020-01-23T21:32:22Z
2020-02-11T21:27:08Z
2020-02-11T21:27:07Z
2020-07-03T16:15:11Z
Backport PR #31159 on branch 1.0.x (ENH: Implement _from_sequence_of_strings for BooleanArray)
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 99918aef7fd08..8c43b53f5cdfd 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -144,7 +144,7 @@ type dedicated to boolean data that can hold missing values. The default ``bool`` data type based on a bool-dtype NumPy array, the column can only hold ``True`` or ``False``, and not missing values. This new :class:`~arrays.BooleanArray` can store missing values as well by keeping track of this in a separate mask. -(:issue:`29555`, :issue:`30095`) +(:issue:`29555`, :issue:`30095`, :issue:`31131`) .. ipython:: python diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index eaa17df1235d3..7b12f3348e7e7 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -1,5 +1,5 @@ import numbers -from typing import TYPE_CHECKING, Any, Tuple, Type +from typing import TYPE_CHECKING, Any, List, Tuple, Type import warnings import numpy as np @@ -286,6 +286,23 @@ def _from_sequence(cls, scalars, dtype=None, copy: bool = False): values, mask = coerce_to_array(scalars, copy=copy) return BooleanArray(values, mask) + @classmethod + def _from_sequence_of_strings( + cls, strings: List[str], dtype=None, copy: bool = False + ): + def map_string(s): + if isna(s): + return s + elif s in ["True", "TRUE", "true"]: + return True + elif s in ["False", "FALSE", "false"]: + return False + else: + raise ValueError(f"{s} cannot be cast to bool") + + scalars = [map_string(x) for x in strings] + return cls._from_sequence(scalars, dtype, copy) + def _values_for_factorize(self) -> Tuple[np.ndarray, Any]: data = self._data.astype("int8") data[self._mask] = -1 diff --git a/pandas/tests/arrays/test_boolean.py b/pandas/tests/arrays/test_boolean.py index 6e361b2810d54..200446f79af8a 100644 --- a/pandas/tests/arrays/test_boolean.py +++ b/pandas/tests/arrays/test_boolean.py @@ -251,6 +251,22 @@ def test_coerce_to_numpy_array(): np.array(arr, dtype="bool") +def test_to_boolean_array_from_strings(): + result = BooleanArray._from_sequence_of_strings( + np.array(["True", "False", np.nan], dtype=object) + ) + expected = BooleanArray( + np.array([True, False, False]), np.array([False, False, True]) + ) + + tm.assert_extension_array_equal(result, expected) + + +def test_to_boolean_array_from_strings_invalid_string(): + with pytest.raises(ValueError, match="cannot be cast"): + BooleanArray._from_sequence_of_strings(["donkey"]) + + def test_repr(): df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")}) expected = " A\n0 True\n1 False\n2 <NA>" diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py index d08c86bf2ae75..11dcf7f04f76b 100644 --- a/pandas/tests/io/parser/test_dtypes.py +++ b/pandas/tests/io/parser/test_dtypes.py @@ -550,3 +550,35 @@ def test_numeric_dtype(all_parsers, dtype): result = parser.read_csv(StringIO(data), header=None, dtype=dtype) tm.assert_frame_equal(expected, result) + + +def test_boolean_dtype(all_parsers): + parser = all_parsers + data = "\n".join( + [ + "a", + "True", + "TRUE", + "true", + "False", + "FALSE", + "false", + "NaN", + "nan", + "NA", + "null", + "NULL", + ] + ) + + result = parser.read_csv(StringIO(data), dtype="boolean") + expected = pd.DataFrame( + { + "a": pd.array( + [True, True, True, False, False, False, None, None, None, None, None], + dtype="boolean", + ) + } + ) + + tm.assert_frame_equal(result, expected)
Backport PR #31159: ENH: Implement _from_sequence_of_strings for BooleanArray
https://api.github.com/repos/pandas-dev/pandas/pulls/31261
2020-01-23T20:56:14Z
2020-01-23T21:31:19Z
2020-01-23T21:31:19Z
2020-01-23T21:31:20Z
DOC fix truncated documentation for Series.unstack(), Series.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6c04212e26924..15904769957ac 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7371,7 +7371,7 @@ def at_time( self: FrameOrSeries, time, asof: bool_t = False, axis=None ) -> FrameOrSeries: """ - Select values at particular time of day (e.g. 9:30AM). + Select values at particular time of day (e.g., 9:30AM). Parameters ---------- diff --git a/pandas/core/series.py b/pandas/core/series.py index ffe0642f799fa..c275591d67c22 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3432,7 +3432,7 @@ def explode(self) -> "Series": def unstack(self, level=-1, fill_value=None): """ - Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. + Unstack, also known as pivot, Series with MultiIndex to produce DataFrame. The level involved will automatically get sorted. Parameters
fixes https://github.com/pandas-dev/pandas/issues/31235 Changed "e.g. " to "e.g., " Changed "a.k.a. " to "also known as" This helps avoid the truncation caused in the docstring
https://api.github.com/repos/pandas-dev/pandas/pulls/31260
2020-01-23T20:37:29Z
2020-01-24T17:49:59Z
2020-01-24T17:49:58Z
2020-01-24T19:30:59Z
REF: avoid calling engine for EA values
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5d802e8a6a77f..3b69dae785534 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2892,14 +2892,17 @@ def _get_value(self, index, col, takeable: bool = False): engine = self.index._engine try: - return engine.get_value(series._values, index) + if isinstance(series._values, np.ndarray): + # i.e. not EA, we can use engine + return engine.get_value(series._values, index) + else: + loc = series.index.get_loc(index) + return series._values[loc] except KeyError: # GH 20629 if self.index.nlevels > 1: # partial indexing forbidden raise - except (TypeError, ValueError): - pass # we cannot handle direct indexing # use positional diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 722fe152e6a85..075380f410220 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2101,8 +2101,7 @@ def __setitem__(self, key, value): if len(key) != self.ndim: raise ValueError("Not enough indexers for scalar access (setting)!") key = list(self._convert_key(key, is_setter=True)) - key.append(value) - self.obj._set_value(*key, takeable=self._takeable) + self.obj._set_value(*key, value=value, takeable=self._takeable) @Appender(IndexingMixin.at.__doc__) diff --git a/pandas/core/series.py b/pandas/core/series.py index e4883c4f0c38d..2af41393078cb 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1060,9 +1060,12 @@ def _set_value(self, label, value, takeable: bool = False): try: if takeable: self._values[label] = value - else: + elif isinstance(self._values, np.ndarray): + # i.e. not EA, so we can use _engine self.index._engine.set_value(self._values, label, value) - except (KeyError, TypeError): + else: + self.loc[label] = value + except KeyError: # set using a non-recursive method self.loc[label] = value
https://api.github.com/repos/pandas-dev/pandas/pulls/31258
2020-01-23T20:06:07Z
2020-01-23T23:01:08Z
2020-01-23T23:01:08Z
2020-01-23T23:12:57Z
BUG: DatetimeIndex.get_loc/get_value raise InvalidIndexError
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 0b89e702c9867..f0c6eedf5cee4 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -27,6 +27,7 @@ from pandas.core.groupby import ops from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex +from pandas.core.indexes.base import InvalidIndexError from pandas.core.series import Series from pandas.io.formats.printing import pprint_thing @@ -565,7 +566,7 @@ def is_in_axis(key) -> bool: items = obj._data.items try: items.get_loc(key) - except (KeyError, TypeError): + except (KeyError, TypeError, InvalidIndexError): # TypeError shows up here if we pass e.g. Int64Index return False diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index b1463f52333a1..fbcca270b2be3 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -27,7 +27,7 @@ validate_tz_from_dtype, ) import pandas.core.common as com -from pandas.core.indexes.base import Index, maybe_extract_name +from pandas.core.indexes.base import Index, InvalidIndexError, maybe_extract_name from pandas.core.indexes.datetimelike import ( DatetimelikeDelegateMixin, DatetimeTimedeltaMixin, @@ -641,6 +641,8 @@ def get_value(self, series, key): Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ + if not is_scalar(key): + raise InvalidIndexError(key) if isinstance(key, (datetime, np.datetime64)): return self.get_value_maybe_box(series, key) @@ -677,6 +679,9 @@ def get_loc(self, key, method=None, tolerance=None): ------- loc : int """ + if not is_scalar(key): + raise InvalidIndexError(key) + if is_valid_nat_for_dtype(key, self.dtype): key = NaT diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index a26a01ab7be21..704430fbb4c9d 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2778,7 +2778,7 @@ def maybe_mi_droplevels(indexer, levels, drop_level: bool): indexer = self._get_level_indexer(key, level=level) new_index = maybe_mi_droplevels(indexer, [0], drop_level) return indexer, new_index - except TypeError: + except (TypeError, InvalidIndexError): pass if not any(isinstance(k, slice) for k in key): diff --git a/pandas/core/series.py b/pandas/core/series.py index 2af41393078cb..7dadf5186f228 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -947,6 +947,9 @@ def __setitem__(self, key, value): self[:] = value else: self.loc[key] = value + except InvalidIndexError: + # e.g. slice + self._set_with(key, value) except TypeError as e: if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 26d99da42cd2b..2f954117f48d7 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -7,6 +7,7 @@ import pandas as pd from pandas import DatetimeIndex, Index, Timestamp, date_range, notna import pandas._testing as tm +from pandas.core.indexes.base import InvalidIndexError from pandas.tseries.offsets import BDay, CDay @@ -697,7 +698,7 @@ def test_get_loc(self): with pytest.raises(KeyError, match="'foobar'"): idx.get_loc("foobar") - with pytest.raises(TypeError): + with pytest.raises(InvalidIndexError, match=r"slice\(None, 2, None\)"): idx.get_loc(slice(2)) idx = pd.to_datetime(["2000-01-01", "2000-01-04"])
almost done with the get_value/get_loc methods
https://api.github.com/repos/pandas-dev/pandas/pulls/31257
2020-01-23T19:57:39Z
2020-01-24T00:23:33Z
2020-01-24T00:23:33Z
2020-01-24T00:31:20Z
Backport PR #31025 on branch 1.0.x (ENH: Handle extension arrays in algorithms.diff)
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index aac5c7e02f681..99918aef7fd08 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -727,6 +727,7 @@ Deprecations - Support for multi-dimensional indexing (e.g. ``index[:, None]``) on a :class:`Index` is deprecated and will be removed in a future version, convert to a numpy array before indexing instead (:issue:`30588`) - The ``pandas.np`` submodule is now deprecated. Import numpy directly instead (:issue:`30296`) - The ``pandas.datetime`` class is now deprecated. Import from ``datetime`` instead (:issue:`30610`) +- :class:`~DataFrame.diff` will raise a ``TypeError`` rather than implicitly losing the dtype of extension types in the future. Convert to the correct dtype before calling ``diff`` instead (:issue:`31025`) **Selecting Columns from a Grouped DataFrame** @@ -1018,6 +1019,8 @@ Numeric - Bug in :meth:`DataFrame.round` where a :class:`DataFrame` with a :class:`CategoricalIndex` of :class:`IntervalIndex` columns would incorrectly raise a ``TypeError`` (:issue:`30063`) - Bug in :meth:`Series.pct_change` and :meth:`DataFrame.pct_change` when there are duplicated indices (:issue:`30463`) - Bug in :class:`DataFrame` cumulative operations (e.g. cumsum, cummax) incorrect casting to object-dtype (:issue:`19296`) +- Bug in :class:`~DataFrame.diff` losing the dtype for extension types (:issue:`30889`) +- Bug in :class:`DataFrame.diff` raising an ``IndexError`` when one of the columns was a nullable integer dtype (:issue:`30967`) Conversion ^^^^^^^^^^ @@ -1158,7 +1161,7 @@ Sparse ^^^^^^ - Bug in :class:`SparseDataFrame` arithmetic operations incorrectly casting inputs to float (:issue:`28107`) - Bug in ``DataFrame.sparse`` returning a ``Series`` when there was a column named ``sparse`` rather than the accessor (:issue:`30758`) -- +- Fixed :meth:`operator.xor` with a boolean-dtype ``SparseArray``. Now returns a sparse result, rather than object dtype (:issue:`31025`) ExtensionArray ^^^^^^^^^^^^^^ diff --git a/pandas/_libs/sparse_op_helper.pxi.in b/pandas/_libs/sparse_op_helper.pxi.in index 62ea477167b72..996da4ca2f92b 100644 --- a/pandas/_libs/sparse_op_helper.pxi.in +++ b/pandas/_libs/sparse_op_helper.pxi.in @@ -84,7 +84,8 @@ def get_op(tup): 'ge': '{0} >= {1}', 'and': '{0} & {1}', # logical op - 'or': '{0} | {1}'} + 'or': '{0} | {1}', + 'xor': '{0} ^ {1}'} return ops_dict[opname].format(lval, rval) @@ -94,7 +95,7 @@ def get_dispatch(dtypes): ops_list = ['add', 'sub', 'mul', 'div', 'mod', 'truediv', 'floordiv', 'pow', 'eq', 'ne', 'lt', 'gt', 'le', 'ge', - 'and', 'or'] + 'and', 'or', 'xor'] for opname in ops_list: for dtype, arith_comp_group, logical_group in dtypes: @@ -104,13 +105,13 @@ def get_dispatch(dtypes): elif opname in ('eq', 'ne', 'lt', 'gt', 'le', 'ge'): # comparison op rdtype = 'uint8' - elif opname in ('and', 'or'): + elif opname in ('and', 'or', 'xor'): # logical op rdtype = 'uint8' else: rdtype = dtype - if opname in ('and', 'or'): + if opname in ('and', 'or', 'xor'): if logical_group: yield opname, dtype, rdtype else: diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 39e8e9008a844..431aa56eafe5f 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -2,6 +2,7 @@ Generic data algorithms. This module is experimental at the moment and not intended for public consumption """ +import operator from textwrap import dedent from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union from warnings import catch_warnings, simplefilter, warn @@ -1812,7 +1813,7 @@ def searchsorted(arr, value, side="left", sorter=None): _diff_special = {"float64", "float32", "int64", "int32", "int16", "int8"} -def diff(arr, n: int, axis: int = 0): +def diff(arr, n: int, axis: int = 0, stacklevel=3): """ difference of n between self, analogous to s-s.shift(n) @@ -1824,16 +1825,42 @@ def diff(arr, n: int, axis: int = 0): number of periods axis : int axis to shift on + stacklevel : int + The stacklevel for the lost dtype warning. Returns ------- shifted """ + from pandas.core.arrays import PandasDtype n = int(n) na = np.nan dtype = arr.dtype + if dtype.kind == "b": + op = operator.xor + else: + op = operator.sub + + if isinstance(dtype, PandasDtype): + # PandasArray cannot necessarily hold shifted versions of itself. + arr = np.asarray(arr) + dtype = arr.dtype + + if is_extension_array_dtype(dtype): + if hasattr(arr, f"__{op.__name__}__"): + return op(arr, arr.shift(n)) + else: + warn( + "dtype lost in 'diff()'. In the future this will raise a " + "TypeError. Convert to a suitable dtype prior to calling 'diff'.", + FutureWarning, + stacklevel=stacklevel, + ) + arr = np.asarray(arr) + dtype = arr.dtype + is_timedelta = False is_bool = False if needs_i8_conversion(arr): diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index e2562a375515d..75dd603aa6c7b 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -141,7 +141,7 @@ def _sparse_array_op( left, right = right, left name = name[1:] - if name in ("and", "or") and dtype == "bool": + if name in ("and", "or", "xor") and dtype == "bool": opname = f"sparse_{name}_uint8" # to make template simple, cast here left_sp_values = left.sp_values.view(np.uint8) @@ -1459,6 +1459,7 @@ def _add_unary_ops(cls): def _add_comparison_ops(cls): cls.__and__ = cls._create_comparison_method(operator.and_) cls.__or__ = cls._create_comparison_method(operator.or_) + cls.__xor__ = cls._create_arithmetic_method(operator.xor) super()._add_comparison_ops() # ---------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index aedc10c02d60f..b5f82da326497 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6533,6 +6533,11 @@ def diff(self, periods=1, axis=0) -> "DataFrame": DataFrame.shift: Shift index by desired number of periods with an optional time freq. + Notes + ----- + For boolean dtypes, this uses :meth:`operator.xor` rather than + :meth:`operator.sub`. + Examples -------- Difference with previous row diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index f74033924f64e..0732eda5f1f6e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1270,7 +1270,10 @@ def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): def diff(self, n: int, axis: int = 1) -> List["Block"]: """ return block for the diff of the values """ - new_values = algos.diff(self.values, n, axis=axis) + new_values = algos.diff(self.values, n, axis=axis, stacklevel=7) + # We use block_shape for ExtensionBlock subclasses, which may call here + # via a super. + new_values = _block_shape(new_values, ndim=self.ndim) return [self.make_block(values=new_values)] def shift(self, periods, axis=0, fill_value=None): @@ -1850,6 +1853,12 @@ def interpolate( placement=self.mgr_locs, ) + def diff(self, n: int, axis: int = 1) -> List["Block"]: + if axis == 1: + # we are by definition 1D. + axis = 0 + return super().diff(n, axis) + def shift( self, periods: int, diff --git a/pandas/core/series.py b/pandas/core/series.py index 3e1f011fde51a..33da47eefde20 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2264,6 +2264,11 @@ def diff(self, periods=1): optional time freq. DataFrame.diff: First discrete difference of object. + Notes + ----- + For boolean dtypes, this uses :meth:`operator.xor` rather than + :meth:`operator.sub`. + Examples -------- Difference with previous row @@ -2300,7 +2305,7 @@ def diff(self, periods=1): 5 NaN dtype: float64 """ - result = algorithms.diff(com.values_from_object(self), periods) + result = algorithms.diff(self.array, periods) return self._constructor(result, index=self.index).__finalize__(self) def autocorr(self, lag=1): diff --git a/pandas/tests/arrays/categorical/test_algos.py b/pandas/tests/arrays/categorical/test_algos.py index 5ff0bb8ef0d78..835aa87a7c21b 100644 --- a/pandas/tests/arrays/categorical/test_algos.py +++ b/pandas/tests/arrays/categorical/test_algos.py @@ -90,6 +90,21 @@ def test_isin_empty(empty): tm.assert_numpy_array_equal(expected, result) +def test_diff(): + s = pd.Series([1, 2, 3], dtype="category") + with tm.assert_produces_warning(FutureWarning): + result = s.diff() + expected = pd.Series([np.nan, 1, 1]) + tm.assert_series_equal(result, expected) + + expected = expected.to_frame(name="A") + df = s.to_frame(name="A") + with tm.assert_produces_warning(FutureWarning): + result = df.diff() + + tm.assert_frame_equal(result, expected) + + class TestTake: # https://github.com/pandas-dev/pandas/issues/20664 diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py index 76442a63ccb0f..73652da78654f 100644 --- a/pandas/tests/arrays/sparse/test_arithmetics.py +++ b/pandas/tests/arrays/sparse/test_arithmetics.py @@ -388,6 +388,14 @@ def test_mixed_array_comparison(self, kind): assert b.dtype == SparseDtype(rdtype, fill_value=2) self._check_comparison_ops(a, b, values, rvalues) + def test_xor(self): + s = SparseArray([True, True, False, False]) + t = SparseArray([True, False, True, False]) + result = s ^ t + sp_index = pd.core.arrays.sparse.IntIndex(4, np.array([0, 1, 2], dtype="int32")) + expected = SparseArray([False, True, True], sparse_index=sp_index) + tm.assert_sp_array_equal(result, expected) + @pytest.mark.parametrize("op", [operator.eq, operator.add]) def test_with_list(op): diff --git a/pandas/tests/arrays/test_boolean.py b/pandas/tests/arrays/test_boolean.py index cc8d0cdcb518d..6e361b2810d54 100644 --- a/pandas/tests/arrays/test_boolean.py +++ b/pandas/tests/arrays/test_boolean.py @@ -879,3 +879,19 @@ def test_value_counts_na(): result = arr.value_counts(dropna=True) expected = pd.Series([1, 1], index=[True, False], dtype="Int64") tm.assert_series_equal(result, expected) + + +def test_diff(): + a = pd.array( + [True, True, False, False, True, None, True, None, False], dtype="boolean" + ) + result = pd.core.algorithms.diff(a, 1) + expected = pd.array( + [None, False, True, False, True, None, None, None, None], dtype="boolean" + ) + tm.assert_extension_array_equal(result, expected) + + s = pd.Series(a) + result = s.diff() + expected = pd.Series(expected) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 1e427c6319cab..24ab7fe3fc845 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -1,6 +1,10 @@ +import operator + import numpy as np import pytest +from pandas.core.dtypes.common import is_bool_dtype + import pandas as pd import pandas._testing as tm from pandas.core.sorting import nargsort @@ -231,6 +235,32 @@ def test_container_shift(self, data, frame, periods, indices): compare(result, expected) + @pytest.mark.parametrize("periods", [1, -2]) + def test_diff(self, data, periods): + data = data[:5] + if is_bool_dtype(data.dtype): + op = operator.xor + else: + op = operator.sub + try: + # does this array implement ops? + op(data, data) + except Exception: + pytest.skip(f"{type(data)} does not support diff") + s = pd.Series(data) + result = s.diff(periods) + expected = pd.Series(op(data, data.shift(periods))) + self.assert_series_equal(result, expected) + + df = pd.DataFrame({"A": data, "B": [1.0] * 5}) + result = df.diff(periods) + if periods == 1: + b = [np.nan, 0, 0, 0, 0] + else: + b = [0, 0, 0, np.nan, np.nan] + expected = pd.DataFrame({"A": expected, "B": b}) + self.assert_frame_equal(result, expected) + @pytest.mark.parametrize( "periods, indices", [[-4, [-1, -1]], [-1, [1, -1]], [0, [0, 1]], [1, [-1, 0]], [4, [-1, -1]]], diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 7db38f41d4573..8a820c8746857 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -248,6 +248,10 @@ def test_repeat(self, data, repeats, as_series, use_numpy): # Fails creating expected super().test_repeat(data, repeats, as_series, use_numpy) + @pytest.mark.xfail(reason="PandasArray.diff may fail on dtype") + def test_diff(self, data, periods): + return super().test_diff(data, periods) + @skip_nested class TestArithmetics(BaseNumPyTests, base.BaseArithmeticOpsTests):
Backport PR #31025: ENH: Handle extension arrays in algorithms.diff
https://api.github.com/repos/pandas-dev/pandas/pulls/31255
2020-01-23T19:03:08Z
2020-01-23T19:33:19Z
2020-01-23T19:33:19Z
2020-01-23T19:33:20Z
Backport PR #31187 on branch 1.0.x (BUG: IntegerArray.astype(boolean))
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 67036761bc62a..022e6a7322872 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -19,6 +19,7 @@ is_list_like, is_object_dtype, is_scalar, + pandas_dtype, ) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.missing import isna @@ -440,11 +441,17 @@ def astype(self, dtype, copy=True): if incompatible type with an IntegerDtype, equivalent of same_kind casting """ + from pandas.core.arrays.boolean import BooleanArray, BooleanDtype + + dtype = pandas_dtype(dtype) # if we are astyping to an existing IntegerDtype we can fastpath if isinstance(dtype, _IntegerDtype): result = self._data.astype(dtype.numpy_dtype, copy=False) return type(self)(result, mask=self._mask, copy=False) + elif isinstance(dtype, BooleanDtype): + result = self._data.astype("bool", copy=False) + return BooleanArray(result, mask=self._mask, copy=False) # coerce if is_float_dtype(dtype): diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index f1a7cc741603d..3e9b880c01e91 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -680,6 +680,13 @@ def test_astype_str(self): tm.assert_numpy_array_equal(a.astype(str), expected) tm.assert_numpy_array_equal(a.astype("str"), expected) + def test_astype_boolean(self): + # https://github.com/pandas-dev/pandas/issues/31102 + a = pd.array([1, 0, -1, 2, None], dtype="Int64") + result = a.astype("boolean") + expected = pd.array([True, False, True, True, None], dtype="boolean") + tm.assert_extension_array_equal(result, expected) + def test_frame_repr(data_missing):
Backport PR #31187: BUG: IntegerArray.astype(boolean)
https://api.github.com/repos/pandas-dev/pandas/pulls/31254
2020-01-23T19:02:18Z
2020-01-23T19:32:25Z
2020-01-23T19:32:25Z
2020-01-23T19:32:25Z
TST: Fix timestamp comparison test
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index f1fcf46a936fd..2f3175598d592 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -751,7 +751,7 @@ def test_asm8(self): def test_class_ops_pytz(self): def compare(x, y): - assert int(Timestamp(x).value / 1e9) == int(Timestamp(y).value / 1e9) + assert int((Timestamp(x).value - Timestamp(y).value) / 1e9) == 0 compare(Timestamp.now(), datetime.now()) compare(Timestamp.now("UTC"), datetime.now(timezone("UTC"))) @@ -775,8 +775,12 @@ def compare(x, y): def test_class_ops_dateutil(self): def compare(x, y): - assert int(np.round(Timestamp(x).value / 1e9)) == int( - np.round(Timestamp(y).value / 1e9) + assert ( + int( + np.round(Timestamp(x).value / 1e9) + - np.round(Timestamp(y).value / 1e9) + ) + == 0 ) compare(Timestamp.now(), datetime.now())
- [x] closes #31175 - [x] tests added / passed - tests/scalar/timestamp/test_timestamp.py - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry - Not needed for fixing a test
https://api.github.com/repos/pandas-dev/pandas/pulls/31249
2020-01-23T15:52:37Z
2020-01-23T23:10:18Z
2020-01-23T23:10:17Z
2020-01-24T16:00:07Z
ENH: Implement DataFrame.value_counts
diff --git a/doc/source/getting_started/basics.rst b/doc/source/getting_started/basics.rst index 277080006cb3c..c6d9a48fcf8ed 100644 --- a/doc/source/getting_started/basics.rst +++ b/doc/source/getting_started/basics.rst @@ -689,6 +689,17 @@ of a 1D array of values. It can also be used as a function on regular arrays: s.value_counts() pd.value_counts(data) +.. versionadded:: 1.1.0 + +The :meth:`~DataFrame.value_counts` method can be used to count combinations across multiple columns. +By default all columns are used but a subset can be selected using the ``subset`` argument. + +.. ipython:: python + + data = {"a": [1, 2, 3, 4], "b": ["x", "x", "y", "y"]} + frame = pd.DataFrame(data) + frame.value_counts() + Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame: .. ipython:: python diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index c7b1cc1c832be..b326bbb5a465e 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -170,6 +170,7 @@ Computations / descriptive stats DataFrame.std DataFrame.var DataFrame.nunique + DataFrame.value_counts Reindexing / selection / label manipulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 705c335acfb48..1414abe13bcf1 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -55,6 +55,7 @@ Other API changes - :meth:`Series.describe` will now show distribution percentiles for ``datetime`` dtypes, statistics ``first`` and ``last`` will now be ``min`` and ``max`` to match with numeric dtypes in :meth:`DataFrame.describe` (:issue:`30164`) +- Added :meth:`DataFrame.value_counts` (:issue:`5377`) - :meth:`Groupby.groups` now returns an abbreviated representation when called on large dataframes (:issue:`1135`) - ``loc`` lookups with an object-dtype :class:`Index` and an integer key will now raise ``KeyError`` instead of ``TypeError`` when key is missing (:issue:`31905`) - diff --git a/pandas/core/base.py b/pandas/core/base.py index 56d3596f71813..85424e35fa0e0 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1196,6 +1196,7 @@ def value_counts( -------- Series.count: Number of non-NA elements in a Series. DataFrame.count: Number of non-NA elements in a DataFrame. + DataFrame.value_counts: Equivalent method on DataFrames. Examples -------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7efb4fbb878d6..3fc10444ee064 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -111,7 +111,7 @@ from pandas.core.indexes import base as ibase from pandas.core.indexes.api import Index, ensure_index, ensure_index_from_sequences from pandas.core.indexes.datetimes import DatetimeIndex -from pandas.core.indexes.multi import maybe_droplevels +from pandas.core.indexes.multi import MultiIndex, maybe_droplevels from pandas.core.indexes.period import PeriodIndex from pandas.core.indexing import check_bool_indexer, convert_to_index_sliceable from pandas.core.internals import BlockManager @@ -4569,6 +4569,10 @@ def drop_duplicates( ------- DataFrame DataFrame with duplicates removed or None if ``inplace=True``. + + See Also + -------- + DataFrame.value_counts: Count unique combinations of columns. """ if self.empty: return self.copy() @@ -4814,6 +4818,102 @@ def sort_index( else: return self._constructor(new_data).__finalize__(self) + def value_counts( + self, + subset: Optional[Sequence[Label]] = None, + normalize: bool = False, + sort: bool = True, + ascending: bool = False, + ): + """ + Return a Series containing counts of unique rows in the DataFrame. + + .. versionadded:: 1.1.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. + + Returns + ------- + Series + + See Also + -------- + Series.value_counts: Equivalent method on Series. + + Notes + ----- + The returned Series will have a MultiIndex with one level per input + column. By default, rows that contain any NA values are omitted from + the result. By default, the resulting Series will be in descending + order so that the first element is the most frequently-occurring row. + + Examples + -------- + >>> df = pd.DataFrame({'num_legs': [2, 4, 4, 6], + ... 'num_wings': [2, 0, 0, 0]}, + ... index=['falcon', 'dog', 'cat', 'ant']) + >>> df + num_legs num_wings + falcon 2 2 + dog 4 0 + cat 4 0 + ant 6 0 + + >>> df.value_counts() + num_legs num_wings + 4 0 2 + 6 0 1 + 2 2 1 + dtype: int64 + + >>> df.value_counts(sort=False) + num_legs num_wings + 2 2 1 + 4 0 2 + 6 0 1 + dtype: int64 + + >>> df.value_counts(ascending=True) + num_legs num_wings + 2 2 1 + 6 0 1 + 4 0 2 + dtype: int64 + + >>> df.value_counts(normalize=True) + num_legs num_wings + 4 0 0.50 + 6 0 0.25 + 2 2 0.25 + dtype: float64 + """ + if subset is None: + subset = self.columns.tolist() + + counts = self.groupby(subset).size() + + if sort: + counts = counts.sort_values(ascending=ascending) + if normalize: + counts /= counts.sum() + + # Force MultiIndex for single column + if len(subset) == 1: + counts.index = MultiIndex.from_arrays( + [counts.index], names=[counts.index.name] + ) + + return counts + def nlargest(self, n, columns, keep="first") -> "DataFrame": """ Return the first `n` rows ordered by `columns` in descending order. diff --git a/pandas/tests/frame/methods/test_value_counts.py b/pandas/tests/frame/methods/test_value_counts.py new file mode 100644 index 0000000000000..c409b0bbe6fa9 --- /dev/null +++ b/pandas/tests/frame/methods/test_value_counts.py @@ -0,0 +1,102 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +def test_data_frame_value_counts_unsorted(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts(sort=False) + expected = pd.Series( + data=[1, 2, 1], + index=pd.MultiIndex.from_arrays( + [(2, 4, 6), (2, 0, 0)], names=["num_legs", "num_wings"] + ), + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_ascending(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts(ascending=True) + expected = pd.Series( + data=[1, 1, 2], + index=pd.MultiIndex.from_arrays( + [(2, 6, 4), (2, 0, 0)], names=["num_legs", "num_wings"] + ), + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_default(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts() + expected = pd.Series( + data=[2, 1, 1], + index=pd.MultiIndex.from_arrays( + [(4, 6, 2), (0, 0, 2)], names=["num_legs", "num_wings"] + ), + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_normalize(): + df = pd.DataFrame( + {"num_legs": [2, 4, 4, 6], "num_wings": [2, 0, 0, 0]}, + index=["falcon", "dog", "cat", "ant"], + ) + + result = df.value_counts(normalize=True) + expected = pd.Series( + data=[0.5, 0.25, 0.25], + index=pd.MultiIndex.from_arrays( + [(4, 6, 2), (0, 0, 2)], names=["num_legs", "num_wings"] + ), + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_single_col_default(): + df = pd.DataFrame({"num_legs": [2, 4, 4, 6]}) + + result = df.value_counts() + expected = pd.Series( + data=[2, 1, 1], + index=pd.MultiIndex.from_arrays([[4, 6, 2]], names=["num_legs"]), + ) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_empty(): + df_no_cols = pd.DataFrame() + + result = df_no_cols.value_counts() + expected = pd.Series([], dtype=np.int64) + + tm.assert_series_equal(result, expected) + + +def test_data_frame_value_counts_empty_normalize(): + df_no_cols = pd.DataFrame() + + result = df_no_cols.value_counts(normalize=True) + expected = pd.Series([], dtype=np.float64) + + tm.assert_series_equal(result, expected)
- [x] closes #5377 - [x] tests added / passed - [x] passes `black pandas` - [x] whatsnew entry This is picking up where https://github.com/pandas-dev/pandas/pull/27350 left off because I think it'd be a nice feature to have. At least one thing that still needs to be done is implementing `bins` when we have only a single column in `subset`, in which case maybe we can just delegate to `Series.value_counts`.
https://api.github.com/repos/pandas-dev/pandas/pulls/31247
2020-01-23T14:39:35Z
2020-02-26T02:20:44Z
2020-02-26T02:20:44Z
2020-02-26T02:24:35Z
Backport PR #31232 on branch 1.0.x (REGR: Fix IntervalIndex.map when result is object dtype)
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index c4dac9d1c4a11..c98b4f21dbb92 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -164,22 +164,6 @@ def __contains__(self, key): except (KeyError, TypeError, ValueError): return False - # Try to run function on index first, and then on elements of index - # Especially important for group-by functionality - def map(self, mapper, na_action=None): - try: - result = mapper(self) - - # Try to use this result if we can - if isinstance(result, np.ndarray): - result = Index(result) - - if not isinstance(result, Index): - raise TypeError("The map function must return an Index object") - return result - except Exception: - return self.astype(object).map(mapper) - def sort_values(self, return_indexer=False, ascending=True): """ Return sorted copy of Index. diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index db35cdb72979f..9ddc5c01030b1 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -232,6 +232,23 @@ def _get_unique_index(self, dropna=False): result = result[~result.isna()] return self._shallow_copy(result) + @Appender(Index.map.__doc__) + def map(self, mapper, na_action=None): + # Try to run function on index first, and then on elements of index + # Especially important for group-by functionality + try: + result = mapper(self) + + # Try to use this result if we can + if isinstance(result, np.ndarray): + result = Index(result) + + if not isinstance(result, Index): + raise TypeError("The map function must return an Index object") + return result + except Exception: + return self.astype(object).map(mapper) + @Appender(Index.astype.__doc__) def astype(self, dtype, copy=True): if is_dtype_equal(self.dtype, dtype) and copy is False: diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index e027641288bb9..c69c1f3f386a9 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -981,3 +981,20 @@ def test_getitem_2d_deprecated(self): idx = self.create_index() with pytest.raises(ValueError, match="cannot mask with array containing NA"): idx[:, None] + + @pytest.mark.parametrize( + "data, categories", + [ + (list("abcbca"), list("cab")), + (pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)), + ], + ids=["string", "interval"], + ) + def test_map_str(self, data, categories, ordered_fixture): + # GH 31202 - override base class since we want to maintain categorical/ordered + index = CategoricalIndex(data, categories=categories, ordered=ordered_fixture) + result = index.map(str) + expected = CategoricalIndex( + map(str, data), categories=map(str, categories), ordered=ordered_fixture + ) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index a16017b0e12c0..cbffb9d375cb1 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -808,6 +808,13 @@ def test_map_dictlike(self, mapper): result = index.map(mapper(expected, index)) tm.assert_index_equal(result, expected) + def test_map_str(self): + # GH 31202 + index = self.create_index() + result = index.map(str) + expected = Index([str(x) for x in index], dtype=object) + tm.assert_index_equal(result, expected) + def test_putmask_with_wrong_mask(self): # GH18368 index = self.create_index()
Backport PR #31232: REGR: Fix IntervalIndex.map when result is object dtype
https://api.github.com/repos/pandas-dev/pandas/pulls/31246
2020-01-23T14:16:12Z
2020-01-23T15:23:12Z
2020-01-23T15:23:12Z
2020-01-23T15:56:52Z
Backport PR #31167 on branch 1.0.x (DOC: fix DataFrame.plot docs )
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index dd907457f7c32..c239f11d5c6a1 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -374,7 +374,6 @@ def hist_frame( <class 'numpy.ndarray'> """ - _backend_doc = """\ backend : str, default None Backend to use instead of the backend specified in the option @@ -847,6 +846,8 @@ def __call__(self, *args, **kwargs): return plot_backend.plot(data, kind=kind, **kwargs) + __call__.__doc__ = __doc__ + def line(self, x=None, y=None, **kwargs): """ Plot Series or DataFrame as lines.
Backport PR #31167: DOC: fix DataFrame.plot docs
https://api.github.com/repos/pandas-dev/pandas/pulls/31244
2020-01-23T12:35:26Z
2020-01-23T13:25:57Z
2020-01-23T13:25:57Z
2020-01-23T15:56:21Z
ENH: add use_nullable_dtypes option in read_parquet
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 5d36c52da9f0d..d37aaaf1fb040 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -241,6 +241,10 @@ Other enhancements - Calling a binary-input NumPy ufunc on multiple ``DataFrame`` objects now aligns, matching the behavior of binary operations and ufuncs on ``Series`` (:issue:`23743`). - Where possible :meth:`RangeIndex.difference` and :meth:`RangeIndex.symmetric_difference` will return :class:`RangeIndex` instead of :class:`Int64Index` (:issue:`36564`) - :meth:`DataFrame.to_parquet` now supports :class:`MultiIndex` for columns in parquet format (:issue:`34777`) +- :func:`read_parquet` gained a ``use_nullable_dtypes=True`` option to use + nullable dtypes that use ``pd.NA`` as missing value indicator where possible + for the resulting DataFrame (default is False, and only applicable for + ``engine="pyarrow"``) (:issue:`31242`) - Added :meth:`.Rolling.sem` and :meth:`Expanding.sem` to compute the standard error of the mean (:issue:`26476`) - :meth:`.Rolling.var` and :meth:`.Rolling.std` use Kahan summation and Welford's Method to avoid numerical issues (:issue:`37051`) - :meth:`DataFrame.corr` and :meth:`DataFrame.cov` use Welford's Method to avoid numerical issues (:issue:`37448`) diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index a19b132a7891d..8b1184df92eaf 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -1,5 +1,6 @@ """ parquet compat """ +from distutils.version import LooseVersion import io import os from typing import Any, AnyStr, Dict, List, Optional, Tuple @@ -177,10 +178,39 @@ def write( handles.close() def read( - self, path, columns=None, storage_options: StorageOptions = None, **kwargs + self, + path, + columns=None, + use_nullable_dtypes=False, + storage_options: StorageOptions = None, + **kwargs, ): kwargs["use_pandas_metadata"] = True + to_pandas_kwargs = {} + if use_nullable_dtypes: + if LooseVersion(self.api.__version__) >= "0.16": + import pandas as pd + + mapping = { + self.api.int8(): pd.Int8Dtype(), + self.api.int16(): pd.Int16Dtype(), + self.api.int32(): pd.Int32Dtype(), + self.api.int64(): pd.Int64Dtype(), + self.api.uint8(): pd.UInt8Dtype(), + self.api.uint16(): pd.UInt16Dtype(), + self.api.uint32(): pd.UInt32Dtype(), + self.api.uint64(): pd.UInt64Dtype(), + self.api.bool_(): pd.BooleanDtype(), + self.api.string(): pd.StringDtype(), + } + to_pandas_kwargs["types_mapper"] = mapping.get + else: + raise ValueError( + "'use_nullable_dtypes=True' is only supported for pyarrow >= 0.16 " + f"({self.api.__version__} is installed" + ) + path_or_handle, handles, kwargs["filesystem"] = _get_path_or_handle( path, kwargs.pop("filesystem", None), @@ -190,7 +220,7 @@ def read( try: return self.api.parquet.read_table( path_or_handle, columns=columns, **kwargs - ).to_pandas() + ).to_pandas(**to_pandas_kwargs) finally: if handles is not None: handles.close() @@ -258,6 +288,12 @@ def write( def read( self, path, columns=None, storage_options: StorageOptions = None, **kwargs ): + use_nullable_dtypes = kwargs.pop("use_nullable_dtypes", False) + if use_nullable_dtypes: + raise ValueError( + "The 'use_nullable_dtypes' argument is not supported for the " + "fastparquet engine" + ) path = stringify_path(path) parquet_kwargs = {} handles = None @@ -368,7 +404,13 @@ def to_parquet( return None -def read_parquet(path, engine: str = "auto", columns=None, **kwargs): +def read_parquet( + path, + engine: str = "auto", + columns=None, + use_nullable_dtypes: bool = False, + **kwargs, +): """ Load a parquet object from the file path, returning a DataFrame. @@ -397,6 +439,15 @@ def read_parquet(path, engine: str = "auto", columns=None, **kwargs): 'pyarrow' is unavailable. columns : list, default=None If not None, only these columns will be read from the file. + use_nullable_dtypes : bool, default False + If True, use dtypes that use ``pd.NA`` as missing value indicator + for the resulting DataFrame (only applicable for ``engine="pyarrow"``). + As new dtypes are added that support ``pd.NA`` in the future, the + output with this option will change to use those dtypes. + Note: this is an experimental option, and behaviour (e.g. additional + support dtypes) may change without notice. + + .. versionadded:: 1.2.0 **kwargs Any additional kwargs are passed to the engine. @@ -405,4 +456,6 @@ def read_parquet(path, engine: str = "auto", columns=None, **kwargs): DataFrame """ impl = get_engine(engine) - return impl.read(path, columns=columns, **kwargs) + return impl.read( + path, columns=columns, use_nullable_dtypes=use_nullable_dtypes, **kwargs + ) diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 3b83eed69c723..7e1d7fb17c8ed 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -828,6 +828,35 @@ def test_additional_extension_types(self, pa): ) check_round_trip(df, pa) + @td.skip_if_no("pyarrow", min_version="0.16") + def test_use_nullable_dtypes(self, pa): + import pyarrow.parquet as pq + + table = pyarrow.table( + { + "a": pyarrow.array([1, 2, 3, None], "int64"), + "b": pyarrow.array([1, 2, 3, None], "uint8"), + "c": pyarrow.array(["a", "b", "c", None]), + "d": pyarrow.array([True, False, True, None]), + } + ) + with tm.ensure_clean() as path: + # write manually with pyarrow to write integers + pq.write_table(table, path) + result1 = read_parquet(path) + result2 = read_parquet(path, use_nullable_dtypes=True) + + assert result1["a"].dtype == np.dtype("float64") + expected = pd.DataFrame( + { + "a": pd.array([1, 2, 3, None], dtype="Int64"), + "b": pd.array([1, 2, 3, None], dtype="UInt8"), + "c": pd.array(["a", "b", "c", None], dtype="string"), + "d": pd.array([True, False, True, None], dtype="boolean"), + } + ) + tm.assert_frame_equal(result2, expected) + @td.skip_if_no("pyarrow", min_version="0.14") def test_timestamp_nanoseconds(self, pa): # with version 2.0, pyarrow defaults to writing the nanoseconds, so @@ -1001,3 +1030,11 @@ def test_timezone_aware_index(self, fp, timezone_aware_date_list): expected = df.copy() expected.index.name = "index" check_round_trip(df, fp, expected=expected) + + def test_use_nullable_dtypes_not_supported(self, fp): + df = pd.DataFrame({"a": [1, 2]}) + + with tm.ensure_clean() as path: + df.to_parquet(path) + with pytest.raises(ValueError, match="not supported for the fastparquet"): + read_parquet(path, engine="fastparquet", use_nullable_dtypes=True)
xref #29752, #30929 Using some work I am doing in pyarrow (https://github.com/apache/arrow/pull/6189), we are able to provide an option in `read_parquet` to directly use new nullable dtypes instead of first using the default conversion (eg which gives floats for ints with nulls) and doing the conversion afterwards
https://api.github.com/repos/pandas-dev/pandas/pulls/31242
2020-01-23T10:51:32Z
2020-11-29T16:10:19Z
2020-11-29T16:10:19Z
2020-11-29T16:15:15Z
TST: add tzaware case to indices fixture
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index f3ebe8313d0c6..dbfa39ef690f5 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -6,6 +6,7 @@ from pandas._libs.tslib import iNaT +from pandas.core.dtypes.common import is_datetime64tz_dtype from pandas.core.dtypes.dtypes import CategoricalDtype import pandas as pd @@ -301,6 +302,9 @@ def test_ensure_copied_data(self, indices): index_type = type(indices) result = index_type(indices.values, copy=True, **init_kwargs) + if is_datetime64tz_dtype(indices.dtype): + result = result.tz_localize("UTC").tz_convert(indices.tz) + tm.assert_index_equal(indices, result) tm.assert_numpy_array_equal( indices._ndarray_values, result._ndarray_values, check_same="copy" @@ -464,6 +468,11 @@ def test_intersection_base(self, indices): intersect = first.intersection(second) assert tm.equalContents(intersect, second) + if is_datetime64tz_dtype(indices.dtype): + # The second.values below will drop tz, so the rest of this test + # is not applicable. + return + # GH 10149 cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: @@ -482,6 +491,11 @@ def test_union_base(self, indices): union = first.union(second) assert tm.equalContents(union, everything) + if is_datetime64tz_dtype(indices.dtype): + # The second.values below will drop tz, so the rest of this test + # is not applicable. + return + # GH 10149 cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: diff --git a/pandas/tests/indexes/conftest.py b/pandas/tests/indexes/conftest.py index b1dcf0ed9b44b..8e0366138f71e 100644 --- a/pandas/tests/indexes/conftest.py +++ b/pandas/tests/indexes/conftest.py @@ -7,6 +7,7 @@ "unicode": tm.makeUnicodeIndex(100), "string": tm.makeStringIndex(100), "datetime": tm.makeDateIndex(100), + "datetime-tz": tm.makeDateIndex(100, tz="US/Pacific"), "period": tm.makePeriodIndex(100), "timedelta": tm.makeTimedeltaIndex(100), "int": tm.makeIntIndex(100), diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 583556656ac87..7051f2b02fe03 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -81,6 +81,9 @@ def test_numpy_ufuncs_other(indices, func): idx = indices if isinstance(idx, (DatetimeIndex, TimedeltaIndex)): + if isinstance(idx, DatetimeIndex) and idx.tz is not None: + if func in [np.isfinite, np.isnan, np.isinf]: + pytest.xfail(reason="__array_ufunc__ is not defined") if not _np_version_under1p18 and func in [np.isfinite, np.isinf, np.isnan]: # numpy 1.18(dev) changed isinf and isnan to not raise on dt64/tfd64
Much easier alternative to #31236.
https://api.github.com/repos/pandas-dev/pandas/pulls/31241
2020-01-23T05:36:36Z
2020-01-24T00:59:33Z
2020-01-24T00:59:33Z
2020-01-24T01:07:21Z
Backport PR #31211 on branch 1.0.x (BUG: Fixed upcast dtype for datetime64 in merge)
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index c6f30ef65e9d5..c75373b82305c 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -350,7 +350,7 @@ def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: - return np.dtype("M8[ns]"), tslibs.iNaT + return np.dtype("M8[ns]"), np.datetime64("NaT", "ns") elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns") else: # pragma diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 8e0c4766056d3..8465e2ca49d67 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -2153,3 +2153,20 @@ def test_merge_multiindex_columns(): expected["id"] = "" tm.assert_frame_equal(result, expected) + + +def test_merge_datetime_upcast_dtype(): + # https://github.com/pandas-dev/pandas/issues/31208 + df1 = pd.DataFrame({"x": ["a", "b", "c"], "y": ["1", "2", "4"]}) + df2 = pd.DataFrame( + {"y": ["1", "2", "3"], "z": pd.to_datetime(["2000", "2001", "2002"])} + ) + result = pd.merge(df1, df2, how="left", on="y") + expected = pd.DataFrame( + { + "x": ["a", "b", "c"], + "y": ["1", "2", "4"], + "z": pd.to_datetime(["2000", "2001", "NaT"]), + } + ) + tm.assert_frame_equal(result, expected)
Backport PR #31211: BUG: Fixed upcast dtype for datetime64 in merge
https://api.github.com/repos/pandas-dev/pandas/pulls/31240
2020-01-23T04:26:44Z
2020-01-23T08:46:12Z
2020-01-23T08:46:12Z
2020-01-23T09:42:21Z
REGR: Prevent indexes that aren't directly backed by numpy from entering libreduction code paths
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index ca1be3154757a..9947866a76e3f 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -14,7 +14,7 @@ is_list_like, is_sequence, ) -from pandas.core.dtypes.generic import ABCMultiIndex, ABCSeries +from pandas.core.dtypes.generic import ABCSeries from pandas.core.construction import create_series_with_explicit_dtype @@ -278,9 +278,8 @@ def apply_standard(self): if ( self.result_type in ["reduce", None] and not self.dtypes.apply(is_extension_array_dtype).any() - # Disallow complex_internals since libreduction shortcut - # cannot handle MultiIndex - and not isinstance(self.agg_axis, ABCMultiIndex) + # Disallow complex_internals since libreduction shortcut raises a TypeError + and not self.agg_axis._has_complex_internals ): values = self.values diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 37067a1897a52..679d3668523c2 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -164,8 +164,8 @@ def apply(self, f, data: FrameOrSeries, axis: int = 0): com.get_callable_name(f) not in base.plotting_methods and isinstance(splitter, FrameSplitter) and axis == 0 - # apply_frame_axis0 doesn't allow MultiIndex - and not isinstance(sdata.index, MultiIndex) + # fast_apply/libreduction doesn't allow non-numpy backed indexes + and not sdata.index._has_complex_internals ): try: result_values, mutated = splitter.fast_apply(f, group_keys) @@ -616,8 +616,8 @@ def agg_series(self, obj: Series, func): # TODO: can we get a performant workaround for EAs backed by ndarray? return self._aggregate_series_pure_python(obj, func) - elif isinstance(obj.index, MultiIndex): - # MultiIndex; Pre-empt TypeError in _aggregate_series_fast + elif obj.index._has_complex_internals: + # Pre-empt TypeError in _aggregate_series_fast return self._aggregate_series_pure_python(obj, func) try: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index bab3d2d1b5431..00f0984d43578 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4109,6 +4109,14 @@ def _assert_can_do_op(self, value): if not is_scalar(value): raise TypeError(f"'value' must be a scalar, passed: {type(value).__name__}") + @property + def _has_complex_internals(self): + """ + Indicates if an index is not directly backed by a numpy array + """ + # used to avoid libreduction code paths, which raise or require conversion + return False + def _is_memory_usage_qualified(self) -> bool: """ Return a boolean if we need a qualified .info display. diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 268ab9ba4e4c4..36ba86bdc9f07 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -378,6 +378,11 @@ def values(self): """ return the underlying data, which is a Categorical """ return self._data + @property + def _has_complex_internals(self): + # used to avoid libreduction code paths, which raise or require conversion + return True + def _wrap_setop_result(self, other, result): name = get_op_result_name(self, other) # We use _shallow_copy rather than the Index implementation diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index a756900ff9ae5..89db2b4a7a379 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -411,6 +411,11 @@ def values(self): """ return self._data + @property + def _has_complex_internals(self): + # used to avoid libreduction code paths, which raise or require conversion + return True + def __array_wrap__(self, result, context=None): # we don't want the superclass implementation return result diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 488f3617f2c3c..2aa7a00707f24 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1346,6 +1346,11 @@ def values(self): self._tuples = lib.fast_zip(values) return self._tuples + @property + def _has_complex_internals(self): + # used to avoid libreduction code paths, which raise or require conversion + return True + @cache_readonly def is_monotonic_increasing(self) -> bool: """ diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index fe6c1ba808f9a..106aaeec4f8be 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -255,6 +255,11 @@ def _simple_new(cls, values, name=None, freq=None, **kwargs): def values(self): return np.asarray(self) + @property + def _has_complex_internals(self): + # used to avoid libreduction code paths, which raise or require conversion + return True + def _shallow_copy(self, values=None, **kwargs): # TODO: simplify, figure out type of values if values is None: diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 0a7272bbc131c..67bdcc246579e 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -360,6 +360,23 @@ def test_func_duplicates_raises(): df.groupby("A").agg(["min", "min"]) +@pytest.mark.parametrize( + "index", + [ + pd.CategoricalIndex(list("abc")), + pd.interval_range(0, 3), + pd.period_range("2020", periods=3, freq="D"), + pd.MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]), + ], +) +def test_agg_index_has_complex_internals(index): + # GH 31223 + df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index) + result = df.groupby("group").agg({"value": Series.nunique}) + expected = DataFrame({"group": [1, 2], "value": [2, 1]}).set_index("group") + tm.assert_frame_equal(result, expected) + + class TestNamedAggregationSeries: def test_series_named_agg(self): df = pd.Series([1, 2, 3, 4]) diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index fc7b9f56002d8..c18ef73203914 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -811,3 +811,19 @@ def test_groupby_apply_datetime_result_dtypes(): index=["observation", "color", "mood", "intensity", "score"], ) tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "index", + [ + pd.CategoricalIndex(list("abc")), + pd.interval_range(0, 3), + pd.period_range("2020", periods=3, freq="D"), + pd.MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]), + ], +) +def test_apply_index_has_complex_internals(index): + # GH 31248 + df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index) + result = df.groupby("group").apply(lambda x: x) + tm.assert_frame_equal(result, df)
- [X] closes #31223 - [X] closes #31248 - [X] tests added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` No whatsnew since this is a regression.
https://api.github.com/repos/pandas-dev/pandas/pulls/31238
2020-01-23T02:38:37Z
2020-01-28T01:57:19Z
2020-01-28T01:57:19Z
2020-01-30T09:59:53Z
CI: Fix Assign CI not working with quotes
diff --git a/.github/workflows/assign.yml b/.github/workflows/assign.yml index 019ecfc484ca5..a6d3f1f383751 100644 --- a/.github/workflows/assign.yml +++ b/.github/workflows/assign.yml @@ -7,9 +7,8 @@ jobs: one: runs-on: ubuntu-latest steps: - - name: - run: | - if [[ "${{ github.event.comment.body }}" == "take" ]]; then - echo "Assigning issue ${{ github.event.issue.number }} to ${{ github.event.comment.user.login }}" - curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -d '{"assignees": ["${{ github.event.comment.user.login }}"]}' https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/assignees - fi + - if: github.event.comment.body == 'take' + name: + run: | + echo "Assigning issue ${{ github.event.issue.number }} to ${{ github.event.comment.user.login }}" + curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -d '{"assignees": ["${{ github.event.comment.user.login }}"]}' https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/assignees
- [x] closes #29768 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Examples(all three passed) ![image](https://user-images.githubusercontent.com/47963215/72952081-a6481100-3d45-11ea-8845-338f2a2f17a4.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/31237
2020-01-23T02:28:50Z
2020-01-25T03:17:39Z
2020-01-25T03:17:39Z
2020-01-25T03:19:51Z
REGR: Fix IntervalIndex.map when result is object dtype
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 1bfec9fbad0ed..e50d752f910e0 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -164,22 +164,6 @@ def __contains__(self, key: Any) -> bool: is_scalar(res) or isinstance(res, slice) or (is_list_like(res) and len(res)) ) - # Try to run function on index first, and then on elements of index - # Especially important for group-by functionality - def map(self, mapper, na_action=None): - try: - result = mapper(self) - - # Try to use this result if we can - if isinstance(result, np.ndarray): - result = Index(result) - - if not isinstance(result, Index): - raise TypeError("The map function must return an Index object") - return result - except Exception: - return self.astype(object).map(mapper) - def sort_values(self, return_indexer=False, ascending=True): """ Return sorted copy of Index. diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index db35cdb72979f..9ddc5c01030b1 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -232,6 +232,23 @@ def _get_unique_index(self, dropna=False): result = result[~result.isna()] return self._shallow_copy(result) + @Appender(Index.map.__doc__) + def map(self, mapper, na_action=None): + # Try to run function on index first, and then on elements of index + # Especially important for group-by functionality + try: + result = mapper(self) + + # Try to use this result if we can + if isinstance(result, np.ndarray): + result = Index(result) + + if not isinstance(result, Index): + raise TypeError("The map function must return an Index object") + return result + except Exception: + return self.astype(object).map(mapper) + @Appender(Index.astype.__doc__) def astype(self, dtype, copy=True): if is_dtype_equal(self.dtype, dtype) and copy is False: diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index e027641288bb9..c69c1f3f386a9 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -981,3 +981,20 @@ def test_getitem_2d_deprecated(self): idx = self.create_index() with pytest.raises(ValueError, match="cannot mask with array containing NA"): idx[:, None] + + @pytest.mark.parametrize( + "data, categories", + [ + (list("abcbca"), list("cab")), + (pd.interval_range(0, 3).repeat(3), pd.interval_range(0, 3)), + ], + ids=["string", "interval"], + ) + def test_map_str(self, data, categories, ordered_fixture): + # GH 31202 - override base class since we want to maintain categorical/ordered + index = CategoricalIndex(data, categories=categories, ordered=ordered_fixture) + result = index.map(str) + expected = CategoricalIndex( + map(str, data), categories=map(str, categories), ordered=ordered_fixture + ) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index f3ebe8313d0c6..74731fa13b629 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -808,6 +808,13 @@ def test_map_dictlike(self, mapper): result = index.map(mapper(expected, index)) tm.assert_index_equal(result, expected) + def test_map_str(self): + # GH 31202 + index = self.create_index() + result = index.map(str) + expected = Index([str(x) for x in index], dtype=object) + tm.assert_index_equal(result, expected) + def test_putmask_with_wrong_mask(self): # GH18368 index = self.create_index()
- [X] closes #31202 - [X] tests added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` No whatnew since this is a regression.
https://api.github.com/repos/pandas-dev/pandas/pulls/31232
2020-01-23T01:22:55Z
2020-01-23T14:16:00Z
2020-01-23T14:16:00Z
2020-02-24T18:13:47Z
Backport PR #31229 on branch 1.0.x ((Fixes CI) Replaced set comprehension with a generator)
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index b8d66874bc660..b7164477c31f2 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -205,7 +205,7 @@ def test_read_csv_chunked_download(self, s3_resource, caplog): with caplog.at_level(logging.DEBUG, logger="s3fs"): read_csv("s3://pandas-test/large-file.csv", nrows=5) # log of fetch_range (start, stop) - assert (0, 5505024) in {x.args[-2:] for x in caplog.records} + assert (0, 5505024) in (x.args[-2:] for x in caplog.records) def test_read_s3_with_hash_in_key(self, tips_df): # GH 25945
Backport PR #31229: (Fixes CI) Replaced set comprehension with a generator
https://api.github.com/repos/pandas-dev/pandas/pulls/31231
2020-01-23T00:50:26Z
2020-01-23T03:07:15Z
2020-01-23T03:07:15Z
2020-01-23T03:07:15Z
make TDI.get_value use get_loc, fix wrong-dtype NaT
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 516a271042c9b..d77a37ad355a7 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -44,10 +44,6 @@ from pandas.tseries.offsets import Tick -def _is_convertible_to_td(key): - return isinstance(key, (Tick, timedelta, np.timedelta64, str)) - - def _field_accessor(name, alias, docstring=None): def f(self): values = self.asi8 diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 1dd5c065ec216..d0a31b68250ad 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -1,5 +1,4 @@ """ implement the TimedeltaIndex """ -from datetime import datetime import numpy as np @@ -10,19 +9,23 @@ _TD_DTYPE, is_float, is_integer, - is_list_like, is_scalar, is_timedelta64_dtype, is_timedelta64_ns_dtype, pandas_dtype, ) -from pandas.core.dtypes.missing import isna +from pandas.core.dtypes.missing import is_valid_nat_for_dtype from pandas.core.accessor import delegate_names from pandas.core.arrays import datetimelike as dtl -from pandas.core.arrays.timedeltas import TimedeltaArray, _is_convertible_to_td +from pandas.core.arrays.timedeltas import TimedeltaArray import pandas.core.common as com -from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name +from pandas.core.indexes.base import ( + Index, + InvalidIndexError, + _index_shared_docs, + maybe_extract_name, +) from pandas.core.indexes.datetimelike import ( DatetimeIndexOpsMixin, DatetimelikeDelegateMixin, @@ -236,22 +239,10 @@ def get_value(self, series, key): Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you're doing """ - - if isinstance(key, str): - try: - key = Timedelta(key) - except ValueError: - raise KeyError(key) - - if isinstance(key, self._data._recognized_scalars) or key is NaT: - key = Timedelta(key) - return self.get_value_maybe_box(series, key) - - value = Index.get_value(self, series, key) - return com.maybe_box(self, value, series, key) - - def get_value_maybe_box(self, series, key: Timedelta): - loc = self.get_loc(key) + if is_integer(key): + loc = key + else: + loc = self.get_loc(key) return self._get_values_for_loc(series, loc) def get_loc(self, key, method=None, tolerance=None): @@ -260,27 +251,31 @@ def get_loc(self, key, method=None, tolerance=None): Returns ------- - loc : int + loc : int, slice, or ndarray[int] """ - if is_list_like(key) or (isinstance(key, datetime) and key is not NaT): - # GH#20464 datetime check here is to ensure we don't allow - # datetime objects to be incorrectly treated as timedelta - # objects; NaT is a special case because it plays a double role - # as Not-A-Timedelta - raise TypeError - - if isna(key): + if not is_scalar(key): + raise InvalidIndexError(key) + + if is_valid_nat_for_dtype(key, self.dtype): key = NaT + elif isinstance(key, str): + try: + key = Timedelta(key) + except ValueError: + raise KeyError(key) + + elif isinstance(key, self._data._recognized_scalars) or key is NaT: + key = Timedelta(key) + + else: + raise KeyError(key) + if tolerance is not None: # try converting tolerance now, so errors don't get swallowed by # the try/except clauses below tolerance = self._convert_tolerance(tolerance, np.asarray(key)) - if _is_convertible_to_td(key) or key is NaT: - key = Timedelta(key) - return Index.get_loc(self, key, method, tolerance) - return Index.get_loc(self, key, method, tolerance) def _maybe_cast_slice_bound(self, label, side, kind): diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 63a86792082da..0b67ae902b075 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1608,19 +1608,22 @@ def _convert_to_indexer(self, obj, axis: int, raise_missing: bool = False): is_int_index = labels.is_integer() is_int_positional = is_integer(obj) and not is_int_index - # if we are a label return me - try: - return labels.get_loc(obj) - except LookupError: - if isinstance(obj, tuple) and isinstance(labels, ABCMultiIndex): - if len(obj) == labels.nlevels: - return {"key": obj} - raise - except TypeError: - pass - except ValueError: - if not is_int_positional: - raise + if is_scalar(obj) or isinstance(labels, ABCMultiIndex): + # Otherwise get_loc will raise InvalidIndexError + + # if we are a label return me + try: + return labels.get_loc(obj) + except LookupError: + if isinstance(obj, tuple) and isinstance(labels, ABCMultiIndex): + if len(obj) == labels.nlevels: + return {"key": obj} + raise + except TypeError: + pass + except ValueError: + if not is_int_positional: + raise # a positional if is_int_positional: diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index e8665ee1a3555..14fff6f9c85b5 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -1,4 +1,5 @@ from datetime import datetime, timedelta +import re import numpy as np import pytest @@ -48,12 +49,19 @@ def test_getitem(self): @pytest.mark.parametrize( "key", - [pd.Timestamp("1970-01-01"), pd.Timestamp("1970-01-02"), datetime(1970, 1, 1)], + [ + pd.Timestamp("1970-01-01"), + pd.Timestamp("1970-01-02"), + datetime(1970, 1, 1), + pd.Timestamp("1970-01-03").to_datetime64(), + # non-matching NA values + np.datetime64("NaT"), + ], ) def test_timestamp_invalid_key(self, key): # GH#20464 tdi = pd.timedelta_range(0, periods=10) - with pytest.raises(TypeError): + with pytest.raises(KeyError, match=re.escape(repr(key))): tdi.get_loc(key)
the wrong-dtype NaT is a bug, the DTI analogue is fixed in #31163. The refactor to make get_value is get_loc is basically what we want all of them index subclasses to do (at which point we de-duplicate and possibly get rid of get_value altogether) cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/31230
2020-01-23T00:30:46Z
2020-01-23T14:27:36Z
2020-01-23T14:27:35Z
2020-01-23T17:29:18Z
(Fixes CI) Replaced set comprehension with a generator
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index b8d66874bc660..b7164477c31f2 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -205,7 +205,7 @@ def test_read_csv_chunked_download(self, s3_resource, caplog): with caplog.at_level(logging.DEBUG, logger="s3fs"): read_csv("s3://pandas-test/large-file.csv", nrows=5) # log of fetch_range (start, stop) - assert (0, 5505024) in {x.args[-2:] for x in caplog.records} + assert (0, 5505024) in (x.args[-2:] for x in caplog.records) def test_read_s3_with_hash_in_key(self, tips_df): # GH 25945
- [x] closes #31149 - [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/31229
2020-01-23T00:14:58Z
2020-01-23T00:49:55Z
2020-01-23T00:49:55Z
2020-01-24T12:18:37Z
TST: parametrize tests
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 656b274aa1a9e..a240e6cef5930 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -573,45 +573,39 @@ def test_series_negate(self): result = pd.eval(expr, engine=self.engine, parser=self.parser) tm.assert_series_equal(expect, result) - def test_frame_pos(self): + @pytest.mark.parametrize( + "lhs", + [ + # Float + DataFrame(randn(5, 2)), + # Int + DataFrame(randint(5, size=(5, 2))), + # bool doesn't work with numexpr but works elsewhere + DataFrame(rand(5, 2) > 0.5), + ], + ) + def test_frame_pos(self, lhs): expr = self.ex("+") - - # float - lhs = DataFrame(randn(5, 2)) expect = lhs - result = pd.eval(expr, engine=self.engine, parser=self.parser) - tm.assert_frame_equal(expect, result) - # int - lhs = DataFrame(randint(5, size=(5, 2))) - expect = lhs - result = pd.eval(expr, engine=self.engine, parser=self.parser) - tm.assert_frame_equal(expect, result) - - # bool doesn't work with numexpr but works elsewhere - lhs = DataFrame(rand(5, 2) > 0.5) - expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) tm.assert_frame_equal(expect, result) - def test_series_pos(self): + @pytest.mark.parametrize( + "lhs", + [ + # Float + Series(randn(5)), + # Int + Series(randint(5, size=5)), + # bool doesn't work with numexpr but works elsewhere + Series(rand(5) > 0.5), + ], + ) + def test_series_pos(self, lhs): expr = self.ex("+") - - # float - lhs = Series(randn(5)) - expect = lhs - result = pd.eval(expr, engine=self.engine, parser=self.parser) - tm.assert_series_equal(expect, result) - - # int - lhs = Series(randint(5, size=5)) expect = lhs - result = pd.eval(expr, engine=self.engine, parser=self.parser) - tm.assert_series_equal(expect, result) - # bool doesn't work with numexpr but works elsewhere - lhs = Series(rand(5) > 0.5) - expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) tm.assert_series_equal(expect, result)
- [ ] closes #xxxx - [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/31228
2020-01-23T00:03:11Z
2020-01-23T15:55:56Z
2020-01-23T15:55:56Z
2020-01-24T12:19:57Z
CLN: unused kwarg, poorly named obj->key
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 0b67ae902b075..722fe152e6a85 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1577,7 +1577,7 @@ def _validate_read_indexer( "https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike" # noqa:E501 ) - def _convert_to_indexer(self, obj, axis: int, raise_missing: bool = False): + def _convert_to_indexer(self, key, axis: int): """ Convert indexing key into something we can use to do actual fancy indexing on a ndarray. @@ -1594,30 +1594,30 @@ def _convert_to_indexer(self, obj, axis: int, raise_missing: bool = False): """ labels = self.obj._get_axis(axis) - if isinstance(obj, slice): - return self._convert_slice_indexer(obj, axis) + if isinstance(key, slice): + return self._convert_slice_indexer(key, axis) # try to find out correct indexer, if not type correct raise try: - obj = self._convert_scalar_indexer(obj, axis) + key = self._convert_scalar_indexer(key, axis) except TypeError: # but we will allow setting pass # see if we are positional in nature is_int_index = labels.is_integer() - is_int_positional = is_integer(obj) and not is_int_index + is_int_positional = is_integer(key) and not is_int_index - if is_scalar(obj) or isinstance(labels, ABCMultiIndex): + if is_scalar(key) or isinstance(labels, ABCMultiIndex): # Otherwise get_loc will raise InvalidIndexError # if we are a label return me try: - return labels.get_loc(obj) + return labels.get_loc(key) except LookupError: - if isinstance(obj, tuple) and isinstance(labels, ABCMultiIndex): - if len(obj) == labels.nlevels: - return {"key": obj} + if isinstance(key, tuple) and isinstance(labels, ABCMultiIndex): + if len(key) == labels.nlevels: + return {"key": key} raise except TypeError: pass @@ -1633,33 +1633,33 @@ def _convert_to_indexer(self, obj, axis: int, raise_missing: bool = False): if self.name == "loc": # always valid - return {"key": obj} + return {"key": key} - if obj >= self.obj.shape[axis] and not isinstance(labels, ABCMultiIndex): + if key >= self.obj.shape[axis] and not isinstance(labels, ABCMultiIndex): # a positional raise ValueError("cannot set by positional indexing with enlargement") - return obj + return key - if is_nested_tuple(obj, labels): - return labels.get_locs(obj) + if is_nested_tuple(key, labels): + return labels.get_locs(key) - elif is_list_like_indexer(obj): + elif is_list_like_indexer(key): - if com.is_bool_indexer(obj): - obj = check_bool_indexer(labels, obj) - (inds,) = obj.nonzero() + if com.is_bool_indexer(key): + key = check_bool_indexer(labels, key) + (inds,) = key.nonzero() return inds else: # When setting, missing keys are not allowed, even with .loc: - return self._get_listlike_indexer(obj, axis, raise_missing=True)[1] + return self._get_listlike_indexer(key, axis, raise_missing=True)[1] else: try: - return labels.get_loc(obj) + return labels.get_loc(key) except LookupError: # allow a not found key only if we are a setter - if not is_list_like_indexer(obj): - return {"key": obj} + if not is_list_like_indexer(key): + return {"key": key} raise def _get_slice_axis(self, slice_obj: slice, axis: int): @@ -2051,21 +2051,20 @@ def _getitem_axis(self, key, axis: int): return self._get_loc(key, axis=axis) - # raise_missing is included for compat with the parent class signature - def _convert_to_indexer(self, obj, axis: int, raise_missing: bool = False): + def _convert_to_indexer(self, key, axis: int): """ Much simpler as we only have to deal with our valid types. """ # make need to convert a float key - if isinstance(obj, slice): - return self._convert_slice_indexer(obj, axis) + if isinstance(key, slice): + return self._convert_slice_indexer(key, axis) - elif is_float(obj): - return self._convert_scalar_indexer(obj, axis) + elif is_float(key): + return self._convert_scalar_indexer(key, axis) try: - self._validate_key(obj, axis) - return obj + self._validate_key(key, axis) + return key except ValueError: raise ValueError(f"Can only index by location with a [{self._valid_types}]")
elsehwere we use `obj = self.obj` which is either a Series or DataFrame, better to call this `key` like we do elsewhere
https://api.github.com/repos/pandas-dev/pandas/pulls/31226
2020-01-22T23:21:17Z
2020-01-23T17:53:24Z
2020-01-23T17:53:24Z
2020-01-23T17:53:27Z
REF/TST: collect misplaced tests
diff --git a/pandas/tests/indexes/multi/test_compat.py b/pandas/tests/indexes/multi/test_compat.py index d92cff1e10496..545a7ddef29bb 100644 --- a/pandas/tests/indexes/multi/test_compat.py +++ b/pandas/tests/indexes/multi/test_compat.py @@ -112,10 +112,6 @@ def test_ndarray_compat_properties(idx, compat_props): idx.values.nbytes -def test_compat(indices): - assert indices.tolist() == list(indices) - - def test_pickle_compat_construction(holder): # this is testing for pickle compat # need an object to create with diff --git a/pandas/tests/indexes/multi/test_conversion.py b/pandas/tests/indexes/multi/test_conversion.py index 8956e6ed4996f..bfc432a18458a 100644 --- a/pandas/tests/indexes/multi/test_conversion.py +++ b/pandas/tests/indexes/multi/test_conversion.py @@ -142,17 +142,6 @@ def test_roundtrip_pickle_with_tz(): assert index.equal_levels(unpickled) -def test_pickle(indices): - return # FIXME: this can't be right? - - unpickled = tm.round_trip_pickle(indices) - assert indices.equals(unpickled) - original_name, indices.name = indices.name, "foo" - unpickled = tm.round_trip_pickle(indices) - assert indices.equals(unpickled) - indices.name = original_name - - def test_to_series(idx): # assert that we are creating a copy of the index diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py index f2ec15e0af88c..fd150bb4d57a2 100644 --- a/pandas/tests/indexes/multi/test_integrity.py +++ b/pandas/tests/indexes/multi/test_integrity.py @@ -250,25 +250,6 @@ def test_rangeindex_fallback_coercion_bug(): tm.assert_index_equal(result, expected) -def test_hash_error(indices): - index = indices - with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"): - hash(indices) - - -def test_mutability(indices): - if not len(indices): - return - msg = "Index does not support mutable operations" - with pytest.raises(TypeError, match=msg): - indices[0] = indices[0] - - -def test_wrong_number_names(indices): - with pytest.raises(ValueError, match="^Length"): - indices.names = ["apple", "banana", "carrot"] - - def test_memory_usage(idx): result = idx.memory_usage() if len(idx): diff --git a/pandas/tests/indexes/multi/test_monotonic.py b/pandas/tests/indexes/multi/test_monotonic.py index b5c73d5e97745..ca1cb0932f63d 100644 --- a/pandas/tests/indexes/multi/test_monotonic.py +++ b/pandas/tests/indexes/multi/test_monotonic.py @@ -1,9 +1,7 @@ import numpy as np -import pytest import pandas as pd -from pandas import Index, IntervalIndex, MultiIndex -from pandas.api.types import is_scalar +from pandas import Index, MultiIndex def test_is_monotonic_increasing(): @@ -176,55 +174,3 @@ def test_is_strictly_monotonic_decreasing(): ) assert idx.is_monotonic_decreasing is True assert idx._is_strictly_monotonic_decreasing is False - - -def test_searchsorted_monotonic(indices): - # GH17271 - # not implemented for tuple searches in MultiIndex - # or Intervals searches in IntervalIndex - if isinstance(indices, (MultiIndex, IntervalIndex)): - return - - # nothing to test if the index is empty - if indices.empty: - return - value = indices[0] - - # determine the expected results (handle dupes for 'right') - expected_left, expected_right = 0, (indices == value).argmin() - if expected_right == 0: - # all values are the same, expected_right should be length - expected_right = len(indices) - - # test _searchsorted_monotonic in all cases - # test searchsorted only for increasing - if indices.is_monotonic_increasing: - ssm_left = indices._searchsorted_monotonic(value, side="left") - assert is_scalar(ssm_left) - assert expected_left == ssm_left - - ssm_right = indices._searchsorted_monotonic(value, side="right") - assert is_scalar(ssm_right) - assert expected_right == ssm_right - - ss_left = indices.searchsorted(value, side="left") - assert is_scalar(ss_left) - assert expected_left == ss_left - - ss_right = indices.searchsorted(value, side="right") - assert is_scalar(ss_right) - assert expected_right == ss_right - - elif indices.is_monotonic_decreasing: - ssm_left = indices._searchsorted_monotonic(value, side="left") - assert is_scalar(ssm_left) - assert expected_left == ssm_left - - ssm_right = indices._searchsorted_monotonic(value, side="right") - assert is_scalar(ssm_right) - assert expected_right == ssm_right - - else: - # non-monotonic should raise. - with pytest.raises(ValueError): - indices._searchsorted_monotonic(value, side="left") diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py index 277bd79cfe953..50242c1cac549 100644 --- a/pandas/tests/indexes/multi/test_sorting.py +++ b/pandas/tests/indexes/multi/test_sorting.py @@ -66,11 +66,6 @@ def test_sortlevel_deterministic(): assert sorted_idx.equals(expected[::-1]) -def test_sort(indices): - with pytest.raises(TypeError): - indices.sort() - - def test_numpy_argsort(idx): result = np.argsort(idx) expected = idx.argsort() diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py new file mode 100644 index 0000000000000..0db63f615c4f8 --- /dev/null +++ b/pandas/tests/indexes/test_any_index.py @@ -0,0 +1,34 @@ +""" +Tests that can be parametrized over _any_ Index object. + +TODO: consider using hypothesis for these. +""" +import pytest + + +def test_sort(indices): + with pytest.raises(TypeError): + indices.sort() + + +def test_hash_error(indices): + index = indices + with pytest.raises(TypeError, match=f"unhashable type: '{type(index).__name__}'"): + hash(indices) + + +def test_mutability(indices): + if not len(indices): + return + msg = "Index does not support mutable operations" + with pytest.raises(TypeError, match=msg): + indices[0] = indices[0] + + +def test_wrong_number_names(indices): + with pytest.raises(ValueError, match="^Length"): + indices.names = ["apple", "banana", "carrot"] + + +def test_tolist_matches_list(indices): + assert indices.tolist() == list(indices)
ATM we are mixing/matching pytest vs UnitTest idioms, which is confusing for me because I have to track down both inheritance and fixtures. So I'm trying to clean this up, leading to some yak shaving.
https://api.github.com/repos/pandas-dev/pandas/pulls/31224
2020-01-22T22:49:36Z
2020-01-23T14:25:31Z
2020-01-23T14:25:31Z
2020-01-23T17:20:01Z
Backport PR #31215 on branch 1.0.x (Follow-up: XLSB Support)
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index b5c512cdc8328..8f5900a2a1ba6 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -264,7 +264,7 @@ pyarrow 0.12.0 Parquet, ORC (requires 0.13.0), and pymysql 0.7.11 MySQL engine for sqlalchemy pyreadstat SPSS files (.sav) reading pytables 3.4.2 HDF5 reading / writing -pyxlsb 1.0.5 Reading for xlsb files +pyxlsb 1.0.6 Reading for xlsb files qtpy Clipboard I/O s3fs 0.3.0 Amazon S3 access tabulate 0.8.3 Printing in Markdown-friendly format (see `tabulate`_) diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index d561ab9a10548..cd711bcace013 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -19,7 +19,7 @@ "pyarrow": "0.13.0", "pytables": "3.4.2", "pytest": "5.0.1", - "pyxlsb": "1.0.5", + "pyxlsb": "1.0.6", "s3fs": "0.3.0", "scipy": "0.19.0", "sqlalchemy": "1.1.4", diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index f8ff3567b8b64..8d00ef1b7fe3e 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -562,11 +562,6 @@ def test_bad_engine_raises(self, read_ext): @tm.network def test_read_from_http_url(self, read_ext): - if read_ext == ".xlsb": - pytest.xfail("xlsb files not present in master repo yet") - if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") - url = ( "https://raw.githubusercontent.com/pandas-dev/pandas/master/" "pandas/tests/io/data/excel/test1" + read_ext
Backport PR #31215: Follow-up: XLSB Support
https://api.github.com/repos/pandas-dev/pandas/pulls/31221
2020-01-22T20:11:35Z
2020-01-22T21:08:55Z
2020-01-22T21:08:55Z
2020-01-23T09:40:20Z
DOC: fixup whatsnew
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 59c90534beefd..c8e811ce82b1f 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -17,6 +17,7 @@ Enhancements Nonmonotonic PeriodIndex Partial String Slicing ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + :class:`PeriodIndex` now supports partial string slicing for non-monotonic indexes, mirroring :class:`DatetimeIndex` behavior (:issue:`31096`) For example: @@ -31,6 +32,7 @@ For example: ser .. ipython:: python + ser["2014"] ser.loc["May 2015"]
The lack of newline below the ipython directive may be causing issues.
https://api.github.com/repos/pandas-dev/pandas/pulls/31217
2020-01-22T19:09:30Z
2020-01-22T19:37:57Z
2020-01-22T19:37:57Z
2020-01-22T19:38:00Z
Follow-up: XLSB Support
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index b5c512cdc8328..8f5900a2a1ba6 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -264,7 +264,7 @@ pyarrow 0.12.0 Parquet, ORC (requires 0.13.0), and pymysql 0.7.11 MySQL engine for sqlalchemy pyreadstat SPSS files (.sav) reading pytables 3.4.2 HDF5 reading / writing -pyxlsb 1.0.5 Reading for xlsb files +pyxlsb 1.0.6 Reading for xlsb files qtpy Clipboard I/O s3fs 0.3.0 Amazon S3 access tabulate 0.8.3 Printing in Markdown-friendly format (see `tabulate`_) diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index d561ab9a10548..cd711bcace013 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -19,7 +19,7 @@ "pyarrow": "0.13.0", "pytables": "3.4.2", "pytest": "5.0.1", - "pyxlsb": "1.0.5", + "pyxlsb": "1.0.6", "s3fs": "0.3.0", "scipy": "0.19.0", "sqlalchemy": "1.1.4", diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index f8ff3567b8b64..8d00ef1b7fe3e 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -562,11 +562,6 @@ def test_bad_engine_raises(self, read_ext): @tm.network def test_read_from_http_url(self, read_ext): - if read_ext == ".xlsb": - pytest.xfail("xlsb files not present in master repo yet") - if pd.read_excel.keywords["engine"] == "pyxlsb": - pytest.xfail("Sheets containing datetimes not supported by pyxlsb") - url = ( "https://raw.githubusercontent.com/pandas-dev/pandas/master/" "pandas/tests/io/data/excel/test1" + read_ext
Updated min version for `pyxlsb` to 1.0.6 and removed the now unnecessary xfail for read from url. Turns out the other xfail is actually unnecessary so I've removed it. Question: is my name supposed to show up in the contributors list? - [X] closes #8540 - [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/31215
2020-01-22T18:38:45Z
2020-01-22T20:11:24Z
2020-01-22T20:11:24Z
2020-02-01T20:33:13Z
BUG: Fixed upcast dtype for datetime64 in merge
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index c6f30ef65e9d5..c75373b82305c 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -350,7 +350,7 @@ def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: - return np.dtype("M8[ns]"), tslibs.iNaT + return np.dtype("M8[ns]"), np.datetime64("NaT", "ns") elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns") else: # pragma diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 30c440035d48e..f9acf5b60a3cd 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -2152,3 +2152,20 @@ def test_merge_multiindex_columns(): expected["id"] = "" tm.assert_frame_equal(result, expected) + + +def test_merge_datetime_upcast_dtype(): + # https://github.com/pandas-dev/pandas/issues/31208 + df1 = pd.DataFrame({"x": ["a", "b", "c"], "y": ["1", "2", "4"]}) + df2 = pd.DataFrame( + {"y": ["1", "2", "3"], "z": pd.to_datetime(["2000", "2001", "2002"])} + ) + result = pd.merge(df1, df2, how="left", on="y") + expected = pd.DataFrame( + { + "x": ["a", "b", "c"], + "y": ["1", "2", "4"], + "z": pd.to_datetime(["2000", "2001", "NaT"]), + } + ) + tm.assert_frame_equal(result, expected)
Closes https://github.com/pandas-dev/pandas/issues/31208
https://api.github.com/repos/pandas-dev/pandas/pulls/31211
2020-01-22T15:34:12Z
2020-01-23T04:26:33Z
2020-01-23T04:26:32Z
2020-01-23T20:57:16Z
Backport PR #31203 on branch 1.0.x (numpydev ragged array dtype warning)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index ed99c4eb46e48..b89ead2fe7b47 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2058,7 +2058,7 @@ def drop(self, codes, level=None, errors="raise"): if not isinstance(codes, (np.ndarray, Index)): try: - codes = com.index_labels_to_array(codes) + codes = com.index_labels_to_array(codes, dtype=object) except ValueError: pass diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 4bcf2943e3d6e..18c7504f2c2f8 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -79,7 +79,7 @@ def cat_core(list_of_columns: List, sep: str): return np.sum(arr_of_cols, axis=0) list_with_sep = [sep] * (2 * len(list_of_columns) - 1) list_with_sep[::2] = list_of_columns - arr_with_sep = np.asarray(list_with_sep) + arr_with_sep = np.asarray(list_with_sep, dtype=object) return np.sum(arr_with_sep, axis=0) diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 70a23e9748dd1..cfba3da354d44 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -605,6 +605,6 @@ def test_constructor_imaginary(self): @pytest.mark.skipif(_np_version_under1p16, reason="Skipping for NumPy <1.16") def test_constructor_string_and_tuples(self): # GH 21416 - c = pd.Categorical(["c", ("a", "b"), ("b", "a"), "c"]) + c = pd.Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object)) expected_index = pd.Index([("a", "b"), ("b", "a"), "c"]) assert c.categories.equals(expected_index) diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py index 211bf091ee17d..8889f45a84237 100644 --- a/pandas/tests/arrays/categorical/test_missing.py +++ b/pandas/tests/arrays/categorical/test_missing.py @@ -77,7 +77,7 @@ def test_fillna_iterable_category(self, named): Point = collections.namedtuple("Point", "x y") else: Point = lambda *args: args # tuple - cat = Categorical([Point(0, 0), Point(0, 1), None]) + cat = Categorical(np.array([Point(0, 0), Point(0, 1), None], dtype=object)) result = cat.fillna(Point(0, 0)) expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)]) diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index dc1f62c4c97c5..e0f3a4754221f 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -245,7 +245,9 @@ def test_take_non_na_fill_value(self, data_missing): fill_value = data_missing[1] # valid na = data_missing[0] - array = data_missing._from_sequence([na, fill_value, na]) + array = data_missing._from_sequence( + [na, fill_value, na], dtype=data_missing.dtype + ) result = array.take([-1, 1], fill_value=fill_value, allow_fill=True) expected = array.take([1, 1]) self.assert_extension_array_equal(result, expected) @@ -293,10 +295,12 @@ def test_reindex_non_na_fill_value(self, data_missing): valid = data_missing[1] na = data_missing[0] - array = data_missing._from_sequence([na, valid]) + array = data_missing._from_sequence([na, valid], dtype=data_missing.dtype) ser = pd.Series(array) result = ser.reindex([0, 1, 2], fill_value=valid) - expected = pd.Series(data_missing._from_sequence([na, valid, valid])) + expected = pd.Series( + data_missing._from_sequence([na, valid, valid], dtype=data_missing.dtype) + ) self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 17bc2773aad19..a065c33689c78 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -113,6 +113,11 @@ def __setitem__(self, key, value): def __len__(self) -> int: return len(self.data) + def __array__(self, dtype=None): + if dtype is None: + dtype = object + return np.asarray(self.data, dtype=dtype) + @property def nbytes(self) -> int: return sys.getsizeof(self.data) diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 4d3145109e3c2..dc03a1f1dcf72 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -163,10 +163,6 @@ def test_unstack(self, data, index): # this matches otherwise return super().test_unstack(data, index) - @pytest.mark.xfail(reason="Inconsistent sizes.") - def test_transpose(self, data): - super().test_transpose(data) - class TestGetitem(BaseJSON, base.BaseGetitemTests): pass
Backport PR #31203: numpydev ragged array dtype warning
https://api.github.com/repos/pandas-dev/pandas/pulls/31209
2020-01-22T15:10:17Z
2020-01-22T21:06:16Z
2020-01-22T21:06:16Z
2020-01-23T09:41:02Z
BUG: no longer raise user warning when plotting tz aware time series
diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst index 16d9d341f785d..6e053208f7692 100644 --- a/doc/source/whatsnew/v1.0.1.rst +++ b/doc/source/whatsnew/v1.0.1.rst @@ -97,7 +97,7 @@ I/O Plotting ^^^^^^^^ -- +- Plotting tz-aware timeseries no longer gives UserWarning (:issue:`31205`) - Groupby/resample/rolling diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index dd048114142f3..3abce690cbe6b 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -251,7 +251,7 @@ def _maybe_convert_index(ax, data): freq = frequencies.get_period_alias(freq) if isinstance(data.index, ABCDatetimeIndex): - data = data.to_period(freq=freq) + data = data.tz_localize(None).to_period(freq=freq) elif isinstance(data.index, ABCPeriodIndex): data.index = data.index.asfreq(freq=freq) return data diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 84d298cd7c6fe..dbe728f5238c7 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -43,19 +43,14 @@ def setup_method(self, method): def teardown_method(self, method): tm.close() - # Ignore warning - # ``` - # Converting to PeriodArray/Index representation will drop timezone information. - # ``` - # which occurs for UTC-like timezones. @pytest.mark.slow - @pytest.mark.filterwarnings("ignore:msg:UserWarning") def test_ts_plot_with_tz(self, tz_aware_fixture): - # GH2877, GH17173 + # GH2877, GH17173, GH31205 tz = tz_aware_fixture index = date_range("1/1/2011", periods=2, freq="H", tz=tz) ts = Series([188.5, 328.25], index=index) - _check_plot_works(ts.plot) + with tm.assert_produces_warning(None): + _check_plot_works(ts.plot) def test_fontsize_set_correctly(self): # For issue #8765
- [x] closes #31205 - [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/31207
2020-01-22T14:35:16Z
2020-02-03T07:36:36Z
2020-02-03T07:36:36Z
2020-02-05T18:54:49Z
Backport PR #31017 on branch 1.0.x (REG: restore format_type attr)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d61d1cf7f0257..4f12c0225bd2d 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2474,6 +2474,7 @@ class Fixed: """ pandas_kind: str + format_type: str = "fixed" # GH#30962 needed by dask obj_type: Type[Union[DataFrame, Series]] ndim: int encoding: str @@ -3132,6 +3133,7 @@ class Table(Fixed): """ pandas_kind = "wide_table" + format_type: str = "table" # GH#30962 needed by dask table_type: str levels = 1 is_table = True diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 64c4ad800f49d..f56d042093886 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -64,6 +64,16 @@ @pytest.mark.single class TestHDFStore: + def test_format_type(self, setup_path): + df = pd.DataFrame({"A": [1, 2]}) + with ensure_clean_path(setup_path) as path: + with HDFStore(path) as store: + store.put("a", df, format="fixed") + store.put("b", df, format="table") + + assert store.get_storer("a").format_type == "fixed" + assert store.get_storer("b").format_type == "table" + def test_format_kwarg_in_constructor(self, setup_path): # GH 13291
Backport PR #31017: REG: restore format_type attr
https://api.github.com/repos/pandas-dev/pandas/pulls/31206
2020-01-22T14:17:27Z
2020-01-22T21:08:28Z
2020-01-22T21:08:27Z
2020-01-23T09:41:34Z
numpydev ragged array dtype warning
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index b684908c25fe5..a26a01ab7be21 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2058,7 +2058,7 @@ def drop(self, codes, level=None, errors="raise"): if not isinstance(codes, (np.ndarray, Index)): try: - codes = com.index_labels_to_array(codes) + codes = com.index_labels_to_array(codes, dtype=object) except ValueError: pass diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 4bcf2943e3d6e..18c7504f2c2f8 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -79,7 +79,7 @@ def cat_core(list_of_columns: List, sep: str): return np.sum(arr_of_cols, axis=0) list_with_sep = [sep] * (2 * len(list_of_columns) - 1) list_with_sep[::2] = list_of_columns - arr_with_sep = np.asarray(list_with_sep) + arr_with_sep = np.asarray(list_with_sep, dtype=object) return np.sum(arr_with_sep, axis=0) diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 70a23e9748dd1..cfba3da354d44 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -605,6 +605,6 @@ def test_constructor_imaginary(self): @pytest.mark.skipif(_np_version_under1p16, reason="Skipping for NumPy <1.16") def test_constructor_string_and_tuples(self): # GH 21416 - c = pd.Categorical(["c", ("a", "b"), ("b", "a"), "c"]) + c = pd.Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object)) expected_index = pd.Index([("a", "b"), ("b", "a"), "c"]) assert c.categories.equals(expected_index) diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py index 211bf091ee17d..8889f45a84237 100644 --- a/pandas/tests/arrays/categorical/test_missing.py +++ b/pandas/tests/arrays/categorical/test_missing.py @@ -77,7 +77,7 @@ def test_fillna_iterable_category(self, named): Point = collections.namedtuple("Point", "x y") else: Point = lambda *args: args # tuple - cat = Categorical([Point(0, 0), Point(0, 1), None]) + cat = Categorical(np.array([Point(0, 0), Point(0, 1), None], dtype=object)) result = cat.fillna(Point(0, 0)) expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)]) diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index dc1f62c4c97c5..e0f3a4754221f 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -245,7 +245,9 @@ def test_take_non_na_fill_value(self, data_missing): fill_value = data_missing[1] # valid na = data_missing[0] - array = data_missing._from_sequence([na, fill_value, na]) + array = data_missing._from_sequence( + [na, fill_value, na], dtype=data_missing.dtype + ) result = array.take([-1, 1], fill_value=fill_value, allow_fill=True) expected = array.take([1, 1]) self.assert_extension_array_equal(result, expected) @@ -293,10 +295,12 @@ def test_reindex_non_na_fill_value(self, data_missing): valid = data_missing[1] na = data_missing[0] - array = data_missing._from_sequence([na, valid]) + array = data_missing._from_sequence([na, valid], dtype=data_missing.dtype) ser = pd.Series(array) result = ser.reindex([0, 1, 2], fill_value=valid) - expected = pd.Series(data_missing._from_sequence([na, valid, valid])) + expected = pd.Series( + data_missing._from_sequence([na, valid, valid], dtype=data_missing.dtype) + ) self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 17bc2773aad19..a065c33689c78 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -113,6 +113,11 @@ def __setitem__(self, key, value): def __len__(self) -> int: return len(self.data) + def __array__(self, dtype=None): + if dtype is None: + dtype = object + return np.asarray(self.data, dtype=dtype) + @property def nbytes(self) -> int: return sys.getsizeof(self.data) diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 4d3145109e3c2..dc03a1f1dcf72 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -163,10 +163,6 @@ def test_unstack(self, data, index): # this matches otherwise return super().test_unstack(data, index) - @pytest.mark.xfail(reason="Inconsistent sizes.") - def test_transpose(self, data): - super().test_transpose(data) - class TestGetitem(BaseJSON, base.BaseGetitemTests): pass
Closes #31201 There are still two failures in the Categorical constructor I'm looking into. Not sure what's best yet. ```python In [2]: pd.Categorical(['a', ('a', 'b')]) /Users/taugspurger/sandbox/pandas/pandas/core/dtypes/cast.py:1066: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray v = np.array(v, copy=False) Out[2]: [a, (a, b)] Categories (2, object): [(a, b), a] ``` I think that perhaps the user should see this warning, but have an option to pass through a `dtype` to silence it... Not sure yet. Tagged for backport to keep the CI passing on that branch.
https://api.github.com/repos/pandas-dev/pandas/pulls/31203
2020-01-22T12:41:36Z
2020-01-22T14:46:59Z
2020-01-22T14:46:58Z
2020-01-22T17:48:55Z
DOC Remove Python 2 specific comments from documentation
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index b5c512cdc8328..25b499a46ffaf 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -146,7 +146,6 @@ Installing using your Linux distribution's package manager. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The commands in this table will install pandas for Python 3 from your distribution. -To install pandas for Python 2, you may need to use the ``python-pandas`` package. .. csv-table:: :header: "Distribution", "Status", "Download / Repository Link", "Install method" diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst index 2df5b9d82dcc3..22ef4ccd6f07f 100644 --- a/doc/source/user_guide/enhancingperf.rst +++ b/doc/source/user_guide/enhancingperf.rst @@ -78,11 +78,6 @@ four calls) using the `prun ipython magic function <http://ipython.org/ipython-d By far the majority of time is spend inside either ``integrate_f`` or ``f``, hence we'll concentrate our efforts cythonizing these two functions. -.. note:: - - In Python 2 replacing the ``range`` with its generator counterpart (``xrange``) - would mean the ``range`` line would vanish. In Python 3 ``range`` is already a generator. - .. _enhancingperf.plain: Plain Cython diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index d0780e4ab8dba..22bf34c40abc5 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -41,8 +41,7 @@ The pandas I/O API is a set of top level ``reader`` functions accessed like .. note:: For examples that use the ``StringIO`` class, make sure you import it - according to your Python version, i.e. ``from StringIO import StringIO`` for - Python 2 and ``from io import StringIO`` for Python 3. + with ``from io import StringIO`` for Python 3. .. _io.read_csv_table: @@ -912,16 +911,6 @@ data columns: significantly faster, ~20x has been observed. -.. note:: - - When passing a dict as the `parse_dates` argument, the order of - the columns prepended is not guaranteed, because `dict` objects do not impose - an ordering on their keys. On Python 2.7+ you may use `collections.OrderedDict` - instead of a regular `dict` if this matters to you. Because of this, when using a - dict for 'parse_dates' in conjunction with the `index_col` argument, it's best to - specify `index_col` as a column label rather then as an index on the resulting frame. - - Date parsing functions ++++++++++++++++++++++ @@ -2453,7 +2442,7 @@ Specify a number of rows to skip: dfs = pd.read_html(url, skiprows=0) -Specify a number of rows to skip using a list (``xrange`` (Python 2 only) works +Specify a number of rows to skip using a list (``range`` works as well): .. code-block:: python @@ -3124,11 +3113,7 @@ Pandas supports writing Excel files to buffer-like objects such as ``StringIO`` .. code-block:: python - # Safe import for either Python 2.x or 3.x - try: - from io import BytesIO - except ImportError: - from cStringIO import StringIO as BytesIO + from io import BytesIO bio = BytesIO()
A few minor fixes to remove Python 2 specific comments from the documentation, since 1.0 does not support Python 2.
https://api.github.com/repos/pandas-dev/pandas/pulls/31198
2020-01-22T09:45:56Z
2020-01-26T02:31:18Z
2020-01-26T02:31:18Z
2020-01-26T09:42:56Z
TST: More regression tests
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 55b987a599670..f7b49ccb1a72d 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -258,6 +258,36 @@ def test_read_excel_parse_dates(self, ext): ) tm.assert_frame_equal(df, res) + def test_multiindex_interval_datetimes(self, ext): + # GH 30986 + midx = pd.MultiIndex.from_arrays( + [ + range(4), + pd.interval_range( + start=pd.Timestamp("2020-01-01"), periods=4, freq="6M" + ), + ] + ) + df = pd.DataFrame(range(4), index=midx) + with tm.ensure_clean(ext) as pth: + df.to_excel(pth) + result = pd.read_excel(pth, index_col=[0, 1]) + expected = pd.DataFrame( + range(4), + pd.MultiIndex.from_arrays( + [ + range(4), + [ + "(2020-01-31, 2020-07-31]", + "(2020-07-31, 2021-01-31]", + "(2021-01-31, 2021-07-31]", + "(2021-07-31, 2022-01-31]", + ], + ] + ), + ) + tm.assert_frame_equal(result, expected) + @td.skip_if_no("xlrd") @pytest.mark.parametrize( diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index efb95a0cb2a42..91b204ed41ebc 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -3,7 +3,7 @@ import numpy as np import pytest -from pandas import DataFrame, Index, json_normalize +from pandas import DataFrame, Index, Series, json_normalize import pandas._testing as tm from pandas.io.json._normalize import nested_to_record @@ -728,3 +728,24 @@ def test_deprecated_import(self): recs = [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}] json_normalize(recs) + + def test_series_non_zero_index(self): + # GH 19020 + data = { + 0: {"id": 1, "name": "Foo", "elements": {"a": 1}}, + 1: {"id": 2, "name": "Bar", "elements": {"b": 2}}, + 2: {"id": 3, "name": "Baz", "elements": {"c": 3}}, + } + s = Series(data) + s.index = [1, 2, 3] + result = json_normalize(s) + expected = DataFrame( + { + "id": [1, 2, 3], + "name": ["Foo", "Bar", "Baz"], + "elements.a": [1.0, np.nan, np.nan], + "elements.b": [np.nan, 2.0, np.nan], + "elements.c": [np.nan, np.nan, 3.0], + } + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 955f8c7482937..ff303b808f6f5 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -870,3 +870,15 @@ def test_get_period_range_edges(self, first, last, offset, exp_first, exp_last): result = _get_period_range_edges(first, last, offset) expected = (exp_first, exp_last) assert result == expected + + def test_sum_min_count(self): + # GH 19974 + index = pd.date_range(start="2018", freq="M", periods=6) + data = np.ones(6) + data[3:6] = np.nan + s = pd.Series(data, index).to_period() + result = s.resample("Q").sum(min_count=1) + expected = pd.Series( + [3.0, np.nan], index=PeriodIndex(["2018Q1", "2018Q2"], freq="Q-DEC") + ) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index ed9d0cffe2304..640cd8faf6811 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -891,6 +891,31 @@ def manual_compare_stacked(df, df_stacked, lev0, lev1): ) manual_compare_stacked(df, df.stack(0), 0, 1) + def test_stack_unstack_unordered_multiindex(self): + # GH 18265 + values = np.arange(5) + data = np.vstack( + [ + ["b{}".format(x) for x in values], # b0, b1, .. + ["a{}".format(x) for x in values], + ] + ) # a0, a1, .. + df = pd.DataFrame(data.T, columns=["b", "a"]) + df.columns.name = "first" + second_level_dict = {"x": df} + multi_level_df = pd.concat(second_level_dict, axis=1) + multi_level_df.columns.names = ["second", "first"] + df = multi_level_df.reindex(sorted(multi_level_df.columns), axis=1) + result = df.stack(["first", "second"]).unstack(["first", "second"]) + expected = DataFrame( + [["a0", "b0"], ["a1", "b1"], ["a2", "b2"], ["a3", "b3"], ["a4", "b4"]], + index=[0, 1, 2, 3, 4], + columns=MultiIndex.from_tuples( + [("a", "x"), ("b", "x")], names=["first", "second"] + ), + ) + tm.assert_frame_equal(result, expected) + def test_groupby_corner(self): midx = MultiIndex( levels=[["foo"], ["bar"], ["baz"]],
- [x] closes #30986 - [x] closes #19020 - [x] closes #19974 - [x] closes #18265 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/31196
2020-01-22T05:20:27Z
2020-01-24T19:04:56Z
2020-01-24T19:04:55Z
2020-01-24T19:12:23Z
Backport PR #43274 on branch 1.3.x (PERF: indexing)
diff --git a/doc/source/whatsnew/v1.3.3.rst b/doc/source/whatsnew/v1.3.3.rst index 9aac0a9ad9681..7c1a414c1f37d 100644 --- a/doc/source/whatsnew/v1.3.3.rst +++ b/doc/source/whatsnew/v1.3.3.rst @@ -21,6 +21,16 @@ Fixed regressions .. --------------------------------------------------------------------------- +.. _whatsnew_133.performance: + +Performance improvements +~~~~~~~~~~~~~~~~~~~~~~~~ +- Performance improvement for :meth:`DataFrame.__setitem__` when the key or value is not a :class:`DataFrame`, or key is not list-like (:issue:`43274`) +- +- + +.. --------------------------------------------------------------------------- + .. _whatsnew_133.bug_fixes: Bug fixes diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 21e90e5bc507d..4d4b90be908e9 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3597,9 +3597,11 @@ def __setitem__(self, key, value): self._setitem_array(key, value) elif isinstance(value, DataFrame): self._set_item_frame_value(key, value) - elif is_list_like(value) and 1 < len( - self.columns.get_indexer_for([key]) - ) == len(value): + elif ( + is_list_like(value) + and not self.columns.is_unique + and 1 < len(self.columns.get_indexer_for([key])) == len(value) + ): # Column to set is duplicated self._setitem_array([key], value) else:
Backport PR #43274: PERF: indexing
https://api.github.com/repos/pandas-dev/pandas/pulls/43303
2021-08-30T15:49:24Z
2021-08-30T18:13:45Z
2021-08-30T18:13:45Z
2021-08-30T18:13:46Z
BUG: Solves errors when calling series methods in DataFrame.query with numexpr
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index f6e90a3341424..0eae3c4c8cc83 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -426,6 +426,7 @@ Indexing - Bug in :meth:`Index.get_indexer_non_unique` when index contains multiple ``np.nan`` (:issue:`35392`) - Bug in :meth:`DataFrame.query` did not handle the degree sign in a backticked column name, such as \`Temp(°C)\`, used in an expression to query a dataframe (:issue:`42826`) - Bug in :meth:`DataFrame.drop` where the error message did not show missing labels with commas when raising ``KeyError`` (:issue:`42881`) +- Bug in :meth:`DataFrame.query` where method calls in query strings led to errors when the ``numexpr`` package was installed. (:issue:`22435`) - Bug in :meth:`DataFrame.nlargest` and :meth:`Series.nlargest` where sorted result did not count indexes containing ``np.nan`` (:issue:`28984`) diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index d495f89970348..2a959f4e9d653 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -702,7 +702,8 @@ def visit_Call(self, node, side=None, **kwargs): if key.arg: kwargs[key.arg] = self.visit(key.value).value - return self.const_type(res(*new_args, **kwargs), self.env) + name = self.env.add_tmp(res(*new_args, **kwargs)) + return self.term_type(name=name, env=self.env) def translate_In(self, op): return op diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index fdbf8a93ddddf..bc71b0c2048f8 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -731,6 +731,26 @@ def test_check_tz_aware_index_query(self, tz_aware_fixture): result = df.reset_index().query('"2018-01-03 00:00:00+00" < time') tm.assert_frame_equal(result, expected) + def test_method_calls_in_query(self): + # https://github.com/pandas-dev/pandas/issues/22435 + n = 10 + df = DataFrame({"a": 2 * np.random.rand(n), "b": np.random.rand(n)}) + expected = df[df["a"].astype("int") == 0] + result = df.query( + "a.astype('int') == 0", engine=self.engine, parser=self.parser + ) + tm.assert_frame_equal(result, expected) + + df = DataFrame( + { + "a": np.where(np.random.rand(n) < 0.5, np.nan, np.random.randn(n)), + "b": np.random.randn(n), + } + ) + expected = df[df["a"].notnull()] + result = df.query("a.notnull()", engine=self.engine, parser=self.parser) + tm.assert_frame_equal(result, expected) + @td.skip_if_no_ne class TestDataFrameQueryNumExprPython(TestDataFrameQueryNumExprPandas):
- [x] closes #22435 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry The initial issue #22435 (check that there is no conflicting names failing) was actually hiding a deeper one leading to a failure when calling `numexpr.evaluate()`. The commit proposed here solves both issues by adding a temporary variable to the scope for the results of function / method calls when using numexpr engine.
https://api.github.com/repos/pandas-dev/pandas/pulls/43301
2021-08-30T12:19:11Z
2021-09-25T15:31:04Z
2021-09-25T15:31:03Z
2021-09-25T15:31:09Z
TST: added test for to_string when max_rows is zero (GH35394)
diff --git a/pandas/tests/io/formats/test_to_string.py b/pandas/tests/io/formats/test_to_string.py index 1d3804a955433..5e7aeb7f226de 100644 --- a/pandas/tests/io/formats/test_to_string.py +++ b/pandas/tests/io/formats/test_to_string.py @@ -315,3 +315,26 @@ def test_to_string_na_rep_and_float_format(na_rep): 1 A {na_rep}""" ) assert result == expected + + +@pytest.mark.parametrize( + "data,expected", + [ + ( + {"col1": [1, 2], "col2": [3, 4]}, + " col1 col2\n0 1 3\n1 2 4", + ), + ( + {"col1": ["Abc", 0.756], "col2": [np.nan, 4.5435]}, + " col1 col2\n0 Abc NaN\n1 0.756 4.5435", + ), + ( + {"col1": [np.nan, "a"], "col2": [0.009, 3.543], "col3": ["Abc", 23]}, + " col1 col2 col3\n0 NaN 0.009 Abc\n1 a 3.543 23", + ), + ], +) +def test_to_string_max_rows_zero(data, expected): + # GH35394 + result = DataFrame(data=data).to_string(max_rows=0) + assert result == expected
- [x] closes #35394 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Provided tests for `to_string` when `max_rows=0`. Tests and linter pass locally.
https://api.github.com/repos/pandas-dev/pandas/pulls/43300
2021-08-30T10:20:01Z
2021-09-01T18:08:25Z
2021-09-01T18:08:24Z
2021-09-01T18:08:28Z
BUG: Fixes to FixedForwardWindowIndexer and GroupbyIndexer (#43267)
diff --git a/doc/source/whatsnew/v1.3.4.rst b/doc/source/whatsnew/v1.3.4.rst index b6ee2d57a0965..f36c0afac763e 100644 --- a/doc/source/whatsnew/v1.3.4.rst +++ b/doc/source/whatsnew/v1.3.4.rst @@ -33,6 +33,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ +- Fixed bug in :meth:`pandas.DataFrame.groupby.rolling` and :class:`pandas.api.indexers.FixedForwardWindowIndexer` leading to segfaults and window endpoints being mixed across groups (:issue:`43267`) - Fixed bug in :meth:`.GroupBy.mean` with datetimelike values including ``NaT`` values returning incorrect results (:issue:`43132`) - Fixed bug in :meth:`Series.aggregate` not passing the first ``args`` to the user supplied ``func`` in certain cases (:issue:`43357`) - Fixed memory leaks in :meth:`Series.rolling.quantile` and :meth:`Series.rolling.median` (:issue:`43339`) diff --git a/pandas/core/indexers/objects.py b/pandas/core/indexers/objects.py index cef023a647d7f..c4156f214ca68 100644 --- a/pandas/core/indexers/objects.py +++ b/pandas/core/indexers/objects.py @@ -266,9 +266,9 @@ def get_window_bounds( ) start = np.arange(num_values, dtype="int64") - end_s = start[: -self.window_size] + self.window_size - end_e = np.full(self.window_size, num_values, dtype="int64") - end = np.concatenate([end_s, end_e]) + end = start + self.window_size + if self.window_size: + end[-self.window_size :] = num_values return start, end @@ -279,8 +279,8 @@ class GroupbyIndexer(BaseIndexer): def __init__( self, index_array: np.ndarray | None = None, - window_size: int = 0, - groupby_indicies: dict | None = None, + window_size: int | BaseIndexer = 0, + groupby_indices: dict | None = None, window_indexer: type[BaseIndexer] = BaseIndexer, indexer_kwargs: dict | None = None, **kwargs, @@ -292,9 +292,9 @@ def __init__( np.ndarray of the index of the original object that we are performing a chained groupby operation over. This index has been pre-sorted relative to the groups - window_size : int + window_size : int or BaseIndexer window size during the windowing operation - groupby_indicies : dict or None + groupby_indices : dict or None dict of {group label: [positional index of rows belonging to the group]} window_indexer : BaseIndexer BaseIndexer class determining the start and end bounds of each group @@ -303,11 +303,13 @@ def __init__( **kwargs : keyword arguments that will be available when get_window_bounds is called """ - self.groupby_indicies = groupby_indicies or {} + self.groupby_indices = groupby_indices or {} self.window_indexer = window_indexer - self.indexer_kwargs = indexer_kwargs or {} + self.indexer_kwargs = indexer_kwargs.copy() if indexer_kwargs else {} super().__init__( - index_array, self.indexer_kwargs.pop("window_size", window_size), **kwargs + index_array=index_array, + window_size=self.indexer_kwargs.pop("window_size", window_size), + **kwargs, ) @Appender(get_window_bounds_doc) @@ -323,8 +325,8 @@ def get_window_bounds( # 3) Append the window bounds in group order start_arrays = [] end_arrays = [] - window_indicies_start = 0 - for key, indices in self.groupby_indicies.items(): + window_indices_start = 0 + for key, indices in self.groupby_indices.items(): index_array: np.ndarray | None if self.index_array is not None: @@ -341,18 +343,21 @@ def get_window_bounds( ) start = start.astype(np.int64) end = end.astype(np.int64) - # Cannot use groupby_indicies as they might not be monotonic with the object + assert len(start) == len( + end + ), "these should be equal in length from get_window_bounds" + # Cannot use groupby_indices as they might not be monotonic with the object # we're rolling over - window_indicies = np.arange( - window_indicies_start, window_indicies_start + len(indices) + window_indices = np.arange( + window_indices_start, window_indices_start + len(indices) ) - window_indicies_start += len(indices) + window_indices_start += len(indices) # Extend as we'll be slicing window like [start, end) - window_indicies = np.append( - window_indicies, [window_indicies[-1] + 1] - ).astype(np.int64) - start_arrays.append(window_indicies.take(ensure_platform_int(start))) - end_arrays.append(window_indicies.take(ensure_platform_int(end))) + window_indices = np.append(window_indices, [window_indices[-1] + 1]).astype( + np.int64, copy=False + ) + start_arrays.append(window_indices.take(ensure_platform_int(start))) + end_arrays.append(window_indices.take(ensure_platform_int(end))) start = np.concatenate(start_arrays) end = np.concatenate(end_arrays) return start, end diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index d769f846b3bdc..c697db9ea313e 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -798,7 +798,7 @@ def _get_window_indexer(self) -> GroupbyIndexer: GroupbyIndexer """ window_indexer = GroupbyIndexer( - groupby_indicies=self._grouper.indices, + groupby_indices=self._grouper.indices, window_indexer=ExponentialMovingWindowIndexer, ) return window_indexer diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 03f16259c66a2..58662e44b9887 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -760,7 +760,7 @@ def _get_window_indexer(self) -> GroupbyIndexer: GroupbyIndexer """ window_indexer = GroupbyIndexer( - groupby_indicies=self._grouper.indices, + groupby_indices=self._grouper.indices, window_indexer=ExpandingIndexer, ) return window_indexer diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 2b8ed3c97d026..89be1f4206939 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -311,8 +311,10 @@ def __iter__(self): center=self.center, closed=self.closed, ) - # From get_window_bounds, those two should be equal in length of array - assert len(start) == len(end) + + assert len(start) == len( + end + ), "these should be equal in length from get_window_bounds" for s, e in zip(start, end): result = obj.iloc[slice(s, e)] @@ -563,6 +565,10 @@ def calc(x): center=self.center, closed=self.closed, ) + assert len(start) == len( + end + ), "these should be equal in length from get_window_bounds" + return func(x, start, end, min_periods, *numba_args) with np.errstate(all="ignore"): @@ -1501,6 +1507,11 @@ def cov_func(x, y): center=self.center, closed=self.closed, ) + + assert len(start) == len( + end + ), "these should be equal in length from get_window_bounds" + with np.errstate(all="ignore"): mean_x_y = window_aggregations.roll_mean( x_array * y_array, start, end, min_periods @@ -1540,6 +1551,11 @@ def corr_func(x, y): center=self.center, closed=self.closed, ) + + assert len(start) == len( + end + ), "these should be equal in length from get_window_bounds" + with np.errstate(all="ignore"): mean_x_y = window_aggregations.roll_mean( x_array * y_array, start, end, min_periods @@ -2490,11 +2506,11 @@ def _get_window_indexer(self) -> GroupbyIndexer: index_array = self._index_array if isinstance(self.window, BaseIndexer): rolling_indexer = type(self.window) - indexer_kwargs = self.window.__dict__ + indexer_kwargs = self.window.__dict__.copy() assert isinstance(indexer_kwargs, dict) # for mypy # We'll be using the index of each group later indexer_kwargs.pop("index_array", None) - window = 0 + window = self.window elif self._win_freq_i8 is not None: rolling_indexer = VariableWindowIndexer window = self._win_freq_i8 @@ -2504,7 +2520,7 @@ def _get_window_indexer(self) -> GroupbyIndexer: window_indexer = GroupbyIndexer( index_array=index_array, window_size=window, - groupby_indicies=self._grouper.indices, + groupby_indices=self._grouper.indices, window_indexer=rolling_indexer, indexer_kwargs=indexer_kwargs, ) diff --git a/pandas/tests/groupby/test_missing.py b/pandas/tests/groupby/test_missing.py index 525bba984fca5..76da8dfe0607b 100644 --- a/pandas/tests/groupby/test_missing.py +++ b/pandas/tests/groupby/test_missing.py @@ -146,7 +146,7 @@ def test_min_count(func, min_count, value): tm.assert_frame_equal(result, expected) -def test_indicies_with_missing(): +def test_indices_with_missing(): # GH 9304 df = DataFrame({"a": [1, 1, np.nan], "b": [2, 3, 4], "c": [5, 6, 7]}) g = df.groupby(["a", "b"]) diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py index 89c4b0cfdb4aa..df4666d16ace0 100644 --- a/pandas/tests/window/test_base_indexer.py +++ b/pandas/tests/window/test_base_indexer.py @@ -3,7 +3,9 @@ from pandas import ( DataFrame, + MultiIndex, Series, + concat, date_range, ) import pandas._testing as tm @@ -13,6 +15,7 @@ ) from pandas.core.indexers.objects import ( ExpandingIndexer, + FixedWindowIndexer, VariableOffsetWindowIndexer, ) @@ -293,3 +296,159 @@ def get_window_bounds(self, num_values, min_periods, center, closed): result = getattr(df.rolling(indexer), func)(*args) expected = DataFrame({"values": values}) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "indexer_class", [FixedWindowIndexer, FixedForwardWindowIndexer, ExpandingIndexer] +) +@pytest.mark.parametrize("window_size", [1, 2, 12]) +@pytest.mark.parametrize( + "df_data", + [ + {"a": [1, 1], "b": [0, 1]}, + {"a": [1, 2], "b": [0, 1]}, + {"a": [1] * 16, "b": [np.nan, 1, 2, np.nan] + list(range(4, 16))}, + ], +) +def test_indexers_are_reusable_after_groupby_rolling( + indexer_class, window_size, df_data +): + # GH 43267 + df = DataFrame(df_data) + num_trials = 3 + indexer = indexer_class(window_size=window_size) + original_window_size = indexer.window_size + for i in range(num_trials): + df.groupby("a")["b"].rolling(window=indexer, min_periods=1).mean() + assert indexer.window_size == original_window_size + + +@pytest.mark.parametrize( + "window_size, num_values, expected_start, expected_end", + [ + (1, 1, [0], [1]), + (1, 2, [0, 1], [1, 2]), + (2, 1, [0], [1]), + (2, 2, [0, 1], [2, 2]), + (5, 12, range(12), list(range(5, 12)) + [12] * 5), + (12, 5, range(5), [5] * 5), + (0, 0, np.array([]), np.array([])), + (1, 0, np.array([]), np.array([])), + (0, 1, [0], [0]), + ], +) +def test_fixed_forward_indexer_bounds( + window_size, num_values, expected_start, expected_end +): + # GH 43267 + indexer = FixedForwardWindowIndexer(window_size=window_size) + start, end = indexer.get_window_bounds(num_values=num_values) + + tm.assert_numpy_array_equal(start, np.array(expected_start), check_dtype=False) + tm.assert_numpy_array_equal(end, np.array(expected_end), check_dtype=False) + assert len(start) == len(end) + + +@pytest.mark.parametrize( + "df, window_size, expected", + [ + ( + DataFrame({"b": [0, 1, 2], "a": [1, 2, 2]}), + 2, + Series( + [0, 1.5, 2.0], + index=MultiIndex.from_arrays([[1, 2, 2], range(3)], names=["a", None]), + name="b", + dtype=np.float64, + ), + ), + ( + DataFrame( + { + "b": [np.nan, 1, 2, np.nan] + list(range(4, 18)), + "a": [1] * 7 + [2] * 11, + "c": range(18), + } + ), + 12, + Series( + [ + 3.6, + 3.6, + 4.25, + 5.0, + 5.0, + 5.5, + 6.0, + 12.0, + 12.5, + 13.0, + 13.5, + 14.0, + 14.5, + 15.0, + 15.5, + 16.0, + 16.5, + 17.0, + ], + index=MultiIndex.from_arrays( + [[1] * 7 + [2] * 11, range(18)], names=["a", None] + ), + name="b", + dtype=np.float64, + ), + ), + ], +) +def test_rolling_groupby_with_fixed_forward_specific(df, window_size, expected): + # GH 43267 + indexer = FixedForwardWindowIndexer(window_size=window_size) + result = df.groupby("a")["b"].rolling(window=indexer, min_periods=1).mean() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "group_keys", + [ + (1,), + (1, 2), + (2, 1), + (1, 1, 2), + (1, 2, 1), + (1, 1, 2, 2), + (1, 2, 3, 2, 3), + (1, 1, 2) * 4, + (1, 2, 3) * 5, + ], +) +@pytest.mark.parametrize("window_size", [1, 2, 3, 4, 5, 8, 20]) +def test_rolling_groupby_with_fixed_forward_many(group_keys, window_size): + # GH 43267 + df = DataFrame( + { + "a": np.array(list(group_keys)), + "b": np.arange(len(group_keys), dtype=np.float64) + 17, + "c": np.arange(len(group_keys), dtype=np.int64), + } + ) + + indexer = FixedForwardWindowIndexer(window_size=window_size) + result = df.groupby("a")["b"].rolling(window=indexer, min_periods=1).sum() + result.index.names = ["a", "c"] + + groups = df.groupby("a")[["a", "b"]] + manual = concat( + [ + g.assign( + b=[ + g["b"].iloc[i : i + window_size].sum(min_count=1) + for i in range(len(g)) + ] + ) + for _, g in groups + ] + ) + manual = manual.set_index(["a", "c"])["b"] + + tm.assert_series_equal(result, manual)
- [x] closes https://github.com/pandas-dev/pandas/issues/43267 This PR addresses three issues, two major and one minor: (1) If you repeated the use of a FixedForwardWindowIndexer, the indexer would be mutated and a window_size of 0 would be used. This would lead to an empty end array which unsurprisingly led to segfaults on the second run. Similar issues could be produced with other BaseIndexer subclasses, this one was simply the loudest. (2) The end array generated by FixedForwardWindowIndexer.get_window_bounds was the wrong length, leading to longer arrays than necessary. When there was only one involved, it didn't matter much: the extra ones were simply ignored. But in the case of a groupby, these end arrays were concatenated, meaning that end values for the first group could leak into the second, and so on. (3) There were some typos for "indices".
https://api.github.com/repos/pandas-dev/pandas/pulls/43291
2021-08-30T01:02:42Z
2021-10-16T20:26:52Z
2021-10-16T20:26:52Z
2021-10-16T20:39:23Z
PERF: Styler 2
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 68a7b12d37339..31e10534d853a 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1023,12 +1023,13 @@ def _update_ctx(self, attrs: DataFrame) -> None: ) for cn in attrs.columns: + j = self.columns.get_loc(cn) ser = attrs[cn] for rn, c in ser.items(): if not c or pd.isna(c): continue css_list = maybe_convert_css_to_tuples(c) - i, j = self.index.get_loc(rn), self.columns.get_loc(cn) + i = self.index.get_loc(rn) self.ctx[(i, j)].extend(css_list) def _update_ctx_header(self, attrs: DataFrame, axis: int) -> None: @@ -1048,7 +1049,8 @@ def _update_ctx_header(self, attrs: DataFrame, axis: int) -> None: Identifies whether the ctx object being updated is the index or columns """ for j in attrs.columns: - for i, c in attrs[[j]].itertuples(): + ser = attrs[j] + for i, c in ser.items(): if not c: continue css_list = maybe_convert_css_to_tuples(c)
extends the idea pushed by @jbrockmendel in #43285 ```python >>> df = pd.DataFrame(np.random.randn(10000, 1)) >>> % timeit df.style.applymap_index(lambda v: "color: blue;")._compute() 29.7 ms ± 396 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # Master 24.4 ms ± 347 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/43287
2021-08-29T17:07:11Z
2021-08-30T22:58:12Z
2021-08-30T22:58:11Z
2021-08-31T04:48:29Z
PERF: Styler
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 5d523f59a46f8..3e5bf6f47ca82 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1023,7 +1023,8 @@ def _update_ctx(self, attrs: DataFrame) -> None: ) for cn in attrs.columns: - for rn, c in attrs[[cn]].itertuples(): + ser = attrs[cn] + for rn, c in ser.items(): if not c or pd.isna(c): continue css_list = maybe_convert_css_to_tuples(c)
``` from asv_bench.benchmarks.io.style import * self = Render() self.setup(36, 12) %timeit self.setup(36, 12); self.time_apply_render(36, 12) 29.2 ms ± 1.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <- master 9.98 ms ± 706 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) # <- PR ``` cc @attack68
https://api.github.com/repos/pandas-dev/pandas/pulls/43285
2021-08-29T14:35:11Z
2021-08-30T13:10:30Z
2021-08-30T13:10:30Z
2021-08-30T14:42:34Z
ENH: `styler.latex` options
diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst index 00da304ec9516..1ba7ea21d6c8c 100644 --- a/doc/source/user_guide/options.rst +++ b/doc/source/user_guide/options.rst @@ -502,6 +502,10 @@ styler.format.escape None Whether to escape "html" or styler.html.mathjax True If set to False will render specific CSS classes to table attributes that will prevent Mathjax from rendering in Jupyter Notebook. +styler.latex.multicol_align r Alignment of headers in a merged column due to sparsification. Can be in {"r", "c", "l"}. +styler.latex.multirow_align c Alignment of index labels in a merged row due to sparsification. Can be in {"c", "t", "b"}. +styler.latex.environment None If given will replace the default ``\\begin{table}`` environment. If "longtable" is specified + this will render with a specific "longtable" template with longtable features. ======================================= ============ ================================== diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index b60d020de6201..ef7b6ec92f175 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -75,7 +75,7 @@ Styler - :meth:`.Styler.to_latex` introduces keyword argument ``environment``, which also allows a specific "longtable" entry through a separate jinja2 template (:issue:`41866`). - :meth:`.Styler.to_html` introduces keyword arguments ``sparse_index``, ``sparse_columns``, ``bold_headers``, ``caption`` (:issue:`41946`, :issue:`43149`). - Keyword argument ``level`` is added to :meth:`.Styler.hide_index` and :meth:`.Styler.hide_columns` for optionally controlling hidden levels in a MultiIndex (:issue:`25475`) - - Global options have been extended to configure default ``Styler`` properties including formatting and encoding and mathjax options (:issue:`41395`) + - Global options have been extended to configure default ``Styler`` properties including formatting and encoding and mathjax options and LaTeX (:issue:`41395`) Formerly Styler relied on ``display.html.use_mathjax``, which has now been replaced by ``styler.html.mathjax``. diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index cbe75e914981b..b048eaee4aee1 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -793,6 +793,22 @@ def register_converter_cb(key): A formatter object to be used as default within ``Styler.format``. """ +styler_multirow_align = """ +: {"c", "t", "b"} + The specifier for vertical alignment of sparsified LaTeX multirows. +""" + +styler_multicol_align = """ +: {"r", "c", "l"} + The specifier for horizontal alignment of sparsified LaTeX multicolumns. +""" + +styler_environment = """ +: str + The environment to replace ``\\begin{table}``. If "longtable" is used results + in a specific longtable environment format. +""" + styler_encoding = """ : str The encoding used for output HTML and LaTeX files. @@ -855,3 +871,24 @@ def register_converter_cb(key): ) cf.register_option("html.mathjax", True, styler_mathjax, validator=is_bool) + + cf.register_option( + "latex.multirow_align", + "c", + styler_multirow_align, + validator=is_one_of_factory(["c", "t", "b"]), + ) + + cf.register_option( + "latex.multicol_align", + "r", + styler_multicol_align, + validator=is_one_of_factory(["r", "c", "l"]), + ) + + cf.register_option( + "latex.environment", + None, + styler_environment, + validator=is_instance_factory([type(None), str]), + ) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index ddafd8369ddd5..2fcac77e81cf3 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -458,8 +458,8 @@ def to_latex( caption: str | tuple | None = None, sparse_index: bool | None = None, sparse_columns: bool | None = None, - multirow_align: str = "c", - multicol_align: str = "r", + multirow_align: str | None = None, + multicol_align: str | None = None, siunitx: bool = False, environment: str | None = None, encoding: str | None = None, @@ -512,18 +512,21 @@ def to_latex( Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each column. Defaults to ``pandas.options.styler.sparse.columns`` value. - multirow_align : {"c", "t", "b"} + multirow_align : {"c", "t", "b"}, optional If sparsifying hierarchical MultiIndexes whether to align text centrally, - at the top or bottom. - multicol_align : {"r", "c", "l"} + at the top or bottom. If not given defaults to + ``pandas.options.styler.latex.multirow_align`` + multicol_align : {"r", "c", "l"}, optional If sparsifying hierarchical MultiIndex columns whether to align text at - the left, centrally, or at the right. + the left, centrally, or at the right. If not given defaults to + ``pandas.options.styler.latex.multicol_align`` siunitx : bool, default False Set to ``True`` to structure LaTeX compatible with the {siunitx} package. environment : str, optional If given, the environment that will replace 'table' in ``\\begin{table}``. If 'longtable' is specified then a more suitable template is - rendered. + rendered. If not given defaults to + ``pandas.options.styler.latex.environment``. .. versionadded:: 1.4.0 encoding : str, optional @@ -840,7 +843,9 @@ def to_latex( sparse_index = get_option("styler.sparse.index") if sparse_columns is None: sparse_columns = get_option("styler.sparse.columns") - + environment = environment or get_option("styler.latex.environment") + multicol_align = multicol_align or get_option("styler.latex.multicol_align") + multirow_align = multirow_align or get_option("styler.latex.multirow_align") latex = obj._render_latex( sparse_index=sparse_index, sparse_columns=sparse_columns, diff --git a/pandas/tests/io/formats/style/test_to_latex.py b/pandas/tests/io/formats/style/test_to_latex.py index ac164f2de9fb2..914eeff97c0fe 100644 --- a/pandas/tests/io/formats/style/test_to_latex.py +++ b/pandas/tests/io/formats/style/test_to_latex.py @@ -276,6 +276,30 @@ def test_multiindex_row_and_col(df): assert s.to_latex(sparse_index=False, sparse_columns=False) == expected +def test_multi_options(df): + cidx = MultiIndex.from_tuples([("Z", "a"), ("Z", "b"), ("Y", "c")]) + ridx = MultiIndex.from_tuples([("A", "a"), ("A", "b"), ("B", "c")]) + df.loc[2, :] = [2, -2.22, "de"] + df = df.astype({"A": int}) + df.index, df.columns = ridx, cidx + styler = df.style.format(precision=2) + + expected = dedent( + """\ + {} & {} & \\multicolumn{2}{r}{Z} & {Y} \\\\ + {} & {} & {a} & {b} & {c} \\\\ + \\multirow[c]{2}{*}{A} & a & 0 & -0.61 & ab \\\\ + """ + ) + assert expected in styler.to_latex() + + with option_context("styler.latex.multicol_align", "l"): + assert "{} & {} & \\multicolumn{2}{l}{Z} & {Y} \\\\" in styler.to_latex() + + with option_context("styler.latex.multirow_align", "b"): + assert "\\multirow[b]{2}{*}{A} & a & 0 & -0.61 & ab \\\\" in styler.to_latex() + + def test_multiindex_columns_hidden(): df = DataFrame([[1, 2, 3, 4]]) df.columns = MultiIndex.from_tuples([("A", 1), ("A", 2), ("A", 3), ("B", 1)]) @@ -376,6 +400,12 @@ def test_comprehensive(df, environment): assert s.format(precision=2).to_latex(environment=environment) == expected +def test_environment_option(styler): + with option_context("styler.latex.environment", "bar-env"): + assert "\\begin{bar-env}" in styler.to_latex() + assert "\\begin{foo-env}" in styler.to_latex(environment="foo-env") + + def test_parse_latex_table_styles(styler): styler.set_table_styles( [
adds item to #41395 - [x] added to config - [x] method and docstrings added - [x] options.rst docs - [x] adds tests - [x] whatsnew entry will update user guide as a follow on after all options added.
https://api.github.com/repos/pandas-dev/pandas/pulls/43284
2021-08-29T10:49:31Z
2021-09-01T19:36:08Z
2021-09-01T19:36:08Z
2021-09-01T21:50:56Z
ENH: `styler.html.mathjax` option
diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst index c415616affcd5..00da304ec9516 100644 --- a/doc/source/user_guide/options.rst +++ b/doc/source/user_guide/options.rst @@ -499,6 +499,9 @@ styler.format.thousands None String representation for t integers, and floating point and complex numbers. styler.format.escape None Whether to escape "html" or "latex" special characters in the display representation. +styler.html.mathjax True If set to False will render specific CSS classes to + table attributes that will prevent Mathjax from rendering + in Jupyter Notebook. ======================================= ============ ================================== diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index aef6128c63829..bb594b896d55e 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -75,7 +75,9 @@ Styler - :meth:`.Styler.to_latex` introduces keyword argument ``environment``, which also allows a specific "longtable" entry through a separate jinja2 template (:issue:`41866`). - :meth:`.Styler.to_html` introduces keyword arguments ``sparse_index`` and ``sparse_columns`` (:issue:`41946`) - Keyword argument ``level`` is added to :meth:`.Styler.hide_index` and :meth:`.Styler.hide_columns` for optionally controlling hidden levels in a MultiIndex (:issue:`25475`) - - Global options have been extended to configure default ``Styler`` properties including formatting and encoding options (:issue:`41395`) + - Global options have been extended to configure default ``Styler`` properties including formatting and encoding and mathjax options (:issue:`41395`) + +Formerly Styler relied on ``display.html.use_mathjax``, which has now been replaced by ``styler.html.mathjax``. There are also bug fixes and deprecations listed below. diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index a6aa285f538d3..cbe75e914981b 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -798,11 +798,17 @@ def register_converter_cb(key): The encoding used for output HTML and LaTeX files. """ +styler_mathjax = """ +: bool + If False will render special CSS classes to table attributes that indicate Mathjax + will not be used in Jupyter Notebook. +""" + with cf.config_prefix("styler"): - cf.register_option("sparse.index", True, styler_sparse_index_doc, validator=bool) + cf.register_option("sparse.index", True, styler_sparse_index_doc, validator=is_bool) cf.register_option( - "sparse.columns", True, styler_sparse_columns_doc, validator=bool + "sparse.columns", True, styler_sparse_columns_doc, validator=is_bool ) cf.register_option( @@ -847,3 +853,5 @@ def register_converter_cb(key): styler_formatter, validator=is_instance_factory([type(None), dict, callable, str]), ) + + cf.register_option("html.mathjax", True, styler_mathjax, validator=is_bool) diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index f51a1f5d9809d..370abe715185b 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -250,8 +250,7 @@ def _translate(self, sparse_index: bool, sparse_cols: bool, blank: str = "&nbsp; d.update({k: map}) table_attr = self.table_attributes - use_mathjax = get_option("display.html.use_mathjax") - if not use_mathjax: + if not get_option("styler.html.mathjax"): table_attr = table_attr or "" if 'class="' in table_attr: table_attr = table_attr.replace('class="', 'class="tex2jax_ignore ') diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index dc8be68532f0e..011730cca8136 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -402,10 +402,10 @@ def test_repr_html_ok(self): self.styler._repr_html_() def test_repr_html_mathjax(self): - # gh-19824 + # gh-19824 / 41395 assert "tex2jax_ignore" not in self.styler._repr_html_() - with pd.option_context("display.html.use_mathjax", False): + with pd.option_context("styler.html.mathjax", False): assert "tex2jax_ignore" in self.styler._repr_html_() def test_update_ctx(self):
This pandas option is added to allow the `Styler` options to be independent from the others. See #41395 - [x] add option in config - [x] add tests - [x] whats new - [x] `options.rst` will update styler user guide as a follow on when all options PRs merged. ![Screen Shot 2021-08-29 at 10 01 55](https://user-images.githubusercontent.com/24256554/131243266-a35e12be-43fa-4be8-8350-c538e32abd80.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/43283
2021-08-29T07:57:36Z
2021-09-01T17:50:00Z
2021-09-01T17:50:00Z
2021-09-01T17:57:37Z
PERF: DataFrame floordiv
diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py index ea6223765523d..3663e0682c4f4 100644 --- a/pandas/core/ops/missing.py +++ b/pandas/core/ops/missing.py @@ -74,7 +74,7 @@ def fill_zeros(result, x, y): return result -def mask_zero_div_zero(x, y, result): +def mask_zero_div_zero(x, y, result: np.ndarray) -> np.ndarray: """ Set results of 0 // 0 to np.nan, regardless of the dtypes of the numerator or the denominator. @@ -121,10 +121,12 @@ def mask_zero_div_zero(x, y, result): zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask + x_lt0 = x < 0 + x_gt0 = x > 0 nan_mask = zmask & (x == 0) with np.errstate(invalid="ignore"): - neginf_mask = (zpos_mask & (x < 0)) | (zneg_mask & (x > 0)) - posinf_mask = (zpos_mask & (x > 0)) | (zneg_mask & (x < 0)) + neginf_mask = (zpos_mask & x_lt0) | (zneg_mask & x_gt0) + posinf_mask = (zpos_mask & x_gt0) | (zneg_mask & x_lt0) if nan_mask.any() or neginf_mask.any() or posinf_mask.any(): # Fill negative/0 with -inf, positive/0 with +inf, 0/0 with NaN
``` from asv_bench.benchmarks.arithmetic import * self = MixedFrameWithSeriesAxis() self.setup("floordiv") %timeit self.time_frame_op_with_series_axis1("floordiv") 27.9 ms ± 987 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # <- master 23.7 ms ± 630 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # <- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/43281
2021-08-29T03:39:09Z
2021-08-29T09:02:00Z
2021-08-29T09:02:00Z
2021-08-29T14:05:40Z
Backport PR #43260 on branch 1.3.x (CI: Remove aiobotocore pin again)
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index 8704c65b5a83d..03f2bc84bcc01 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -30,7 +30,6 @@ dependencies: - python-dateutil - pytz - s3fs>=0.4.2 - - aiobotocore<=1.3.3 - scipy - sqlalchemy - xlrd diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 6f0a1e37dbf3d..4df55813ea21c 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -31,7 +31,6 @@ dependencies: - python-dateutil - pytz - s3fs>=0.4.2 - - aiobotocore<=1.3.3 - scipy - sqlalchemy - xlrd>=2.0 diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml index f65b794e54d58..70aa46e8a5851 100644 --- a/ci/deps/azure-windows-38.yaml +++ b/ci/deps/azure-windows-38.yaml @@ -30,7 +30,6 @@ dependencies: - python-dateutil - pytz - s3fs>=0.4.0 - - aiobotocore<=1.3.3 - scipy - xlrd<2.0 - xlsxwriter diff --git a/environment.yml b/environment.yml index 97169b99c86c3..13d022c3f0e72 100644 --- a/environment.yml +++ b/environment.yml @@ -106,7 +106,7 @@ dependencies: - pyqt>=5.9.2 # pandas.read_clipboard - pytables>=3.5.1 # pandas.read_hdf, DataFrame.to_hdf - s3fs>=0.4.0 # file IO when using 's3://...' path - - aiobotocore<=1.3.3 # Remove when s3fs is at 2021.08.0 + - aiobotocore - fsspec>=0.7.4, <2021.6.0 # for generic remote file operations - gcsfs>=0.6.0 # file IO when using 'gcs://...' path - sqlalchemy # pandas.read_sql, DataFrame.to_sql diff --git a/requirements-dev.txt b/requirements-dev.txt index 6f253b2e03d77..0341f645e595b 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -70,7 +70,7 @@ python-snappy pyqt5>=5.9.2 tables>=3.5.1 s3fs>=0.4.0 -aiobotocore<=1.3.3 +aiobotocore fsspec>=0.7.4, <2021.6.0 gcsfs>=0.6.0 sqlalchemy
Backport PR #43260: CI: Remove aiobotocore pin again
https://api.github.com/repos/pandas-dev/pandas/pulls/43279
2021-08-28T22:35:13Z
2021-08-29T07:53:04Z
2021-08-29T07:53:04Z
2021-08-29T07:53:04Z
PERF: column_arrays
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 0010624609907..bd50e5ac452e6 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -228,6 +228,11 @@ def get_values(self, dtype: DtypeObj | None = None) -> np.ndarray: # expected "ndarray") return self.values # type: ignore[return-value] + def values_for_json(self) -> np.ndarray: + # Incompatible return value type (got "Union[ndarray[Any, Any], + # ExtensionArray]", expected "ndarray[Any, Any]") + return self.values # type: ignore[return-value] + @final @cache_readonly def fill_value(self): @@ -1375,6 +1380,9 @@ def get_values(self, dtype: DtypeObj | None = None) -> np.ndarray: # TODO(EA2D): reshape not needed with 2D EAs return np.asarray(values).reshape(self.shape) + def values_for_json(self) -> np.ndarray: + return np.asarray(self.values) + def interpolate( self, method="pad", axis=0, inplace=False, limit=None, fill_value=None, **kwargs ): @@ -1805,6 +1813,11 @@ class DatetimeLikeBlock(NDArrayBackedExtensionBlock): is_numeric = False values: DatetimeArray | TimedeltaArray + def values_for_json(self) -> np.ndarray: + # special casing datetimetz to avoid conversion through + # object dtype + return self.values._ndarray + class DatetimeTZBlock(DatetimeLikeBlock): """implement a datetime64 block with a tz attribute""" diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 874065b50037f..0e0edbdbb12d1 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -973,24 +973,25 @@ def column_arrays(self) -> list[np.ndarray]: """ Used in the JSON C code to access column arrays. This optimizes compared to using `iget_values` by converting each - block.values to a np.ndarray only once up front """ - # special casing datetimetz to avoid conversion through object dtype - arrays = [ - blk.values._ndarray - if isinstance(blk, DatetimeTZBlock) - else np.asarray(blk.values) - for blk in self.blocks - ] - result = [] - for i in range(len(self.items)): - arr = arrays[self.blknos[i]] - if arr.ndim == 2: - values = arr[self.blklocs[i]] + # This is an optimized equivalent to + # result = [self.iget_values(i) for i in range(len(self.items))] + result: list[np.ndarray | None] = [None] * len(self.items) + + for blk in self.blocks: + mgr_locs = blk._mgr_locs + values = blk.values_for_json() + if values.ndim == 1: + # TODO(EA2D): special casing not needed with 2D EAs + result[mgr_locs[0]] = values + else: - values = arr - result.append(values) - return result + for i, loc in enumerate(mgr_locs): + result[loc] = values[i] + + # error: Incompatible return value type (got "List[None]", + # expected "List[ndarray[Any, Any]]") + return result # type: ignore[return-value] def iset(self, loc: int | slice | np.ndarray, value: ArrayLike): """
Shaves a couple percent off of time_to_json_wide asv Reprises #42824.
https://api.github.com/repos/pandas-dev/pandas/pulls/43278
2021-08-28T21:13:47Z
2021-09-11T14:53:40Z
2021-09-11T14:53:40Z
2021-09-11T17:02:47Z
PERF: read_stata
diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 0a608ba4194f4..1deaa634ce3ae 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -53,7 +53,6 @@ DatetimeIndex, NaT, Timestamp, - concat, isna, to_datetime, to_timedelta, @@ -1663,7 +1662,7 @@ def read( # restarting at 0 for each chunk. if index_col is None: ix = np.arange(self._lines_read - read_lines, self._lines_read) - data = data.set_index(ix) + data.index = ix # set attr instead of set_index to avoid copy if columns is not None: try: @@ -1779,19 +1778,18 @@ def _do_convert_missing(self, data: DataFrame, convert_missing: bool) -> DataFra if dtype not in (np.float32, np.float64): dtype = np.float64 replacement = Series(series, dtype=dtype) + if not replacement._values.flags["WRITEABLE"]: + # only relevant for ArrayManager; construction + # path for BlockManager ensures writeability + replacement = replacement.copy() # Note: operating on ._values is much faster than directly # TODO: can we fix that? replacement._values[missing] = np.nan replacements[colname] = replacement + if replacements: - columns = data.columns - replacement_df = DataFrame(replacements, copy=False) - replaced = concat( - [data.drop(replacement_df.columns, axis=1), replacement_df], - axis=1, - copy=False, - ) - data = replaced[columns] + for col in replacements: + data[col] = replacements[col] return data def _insert_strls(self, data: DataFrame) -> DataFrame:
``` from asv_bench.benchmarks.io.stata import * self = StataMissing() self.setup("td") %timeit self.time_read_stata("td") 113 ms ± 1.44 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # <- master 94.4 ms ± 1.72 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # <- PR ``` cc @bashtage
https://api.github.com/repos/pandas-dev/pandas/pulls/43277
2021-08-28T18:51:27Z
2021-08-30T13:27:32Z
2021-08-30T13:27:32Z
2021-08-30T14:43:15Z
PERF: indexing
diff --git a/doc/source/whatsnew/v1.3.3.rst b/doc/source/whatsnew/v1.3.3.rst index 9aac0a9ad9681..7c1a414c1f37d 100644 --- a/doc/source/whatsnew/v1.3.3.rst +++ b/doc/source/whatsnew/v1.3.3.rst @@ -21,6 +21,16 @@ Fixed regressions .. --------------------------------------------------------------------------- +.. _whatsnew_133.performance: + +Performance improvements +~~~~~~~~~~~~~~~~~~~~~~~~ +- Performance improvement for :meth:`DataFrame.__setitem__` when the key or value is not a :class:`DataFrame`, or key is not list-like (:issue:`43274`) +- +- + +.. --------------------------------------------------------------------------- + .. _whatsnew_133.bug_fixes: Bug fixes diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e02a88aafcf34..3fc83fd467bd1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3620,9 +3620,11 @@ def __setitem__(self, key, value): self._setitem_array(key, value) elif isinstance(value, DataFrame): self._set_item_frame_value(key, value) - elif is_list_like(value) and 1 < len( - self.columns.get_indexer_for([key]) - ) == len(value): + elif ( + is_list_like(value) + and not self.columns.is_unique + and 1 < len(self.columns.get_indexer_for([key])) == len(value) + ): # Column to set is duplicated self._setitem_array([key], value) else:
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Added a check as suggested in https://github.com/pandas-dev/pandas/pull/39280#issuecomment-764753400 ```python In [1]: from asv_bench.benchmarks.indexing import InsertColumns In [2]: self = InsertColumns() In [3]: self.setup() In [4]: %timeit self.time_assign_with_setitem() 27.6 ms ± 68.1 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) #master In [4]: %timeit self.time_assign_with_setitem() 8.6 ms ± 6.43 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) #PR ``` Edit: ``` before after ratio [2b3a9b16] [fa9c7140] <master> <indexing.InsertColumns.time_assign_with_setitem> - 179±4μs 163±0.6μs 0.91 indexing.NumericSeriesIndexing.time_iloc_array(<class 'pandas.core.indexes.numeric.UInt64Index'>, 'unique_monotonic_inc') - 838±50μs 759±7μs 0.90 indexing.NonNumericSeriesIndexing.time_getitem_list_like('datetime', 'nonunique_monotonic_inc') - 37.7±4μs 34.0±0.5μs 0.90 indexing.NumericSeriesIndexing.time_getitem_slice(<class 'pandas.core.indexes.numeric.UInt64Index'>, 'nonunique_monotonic_inc') - 2.91±0.09ms 2.61±0.1ms 0.90 indexing.NumericSeriesIndexing.time_loc_list_like(<class 'pandas.core.indexes.numeric.UInt64Index'>, 'unique_monotonic_inc') - 60.1±2μs 54.0±0.5μs 0.90 indexing.NumericSeriesIndexing.time_iloc_list_like(<class 'pandas.core.indexes.numeric.Int64Index'>, 'unique_monotonic_inc') - 1.56±0.03ms 1.40±0.04ms 0.90 indexing.NumericSeriesIndexing.time_loc_list_like(<class 'pandas.core.indexes.numeric.Int64Index'>, 'nonunique_monotonic_inc') - 183±20μs 164±1μs 0.89 indexing.NumericSeriesIndexing.time_iloc_array(<class 'pandas.core.indexes.numeric.Int64Index'>, 'unique_monotonic_inc') - 2.39±0.05ms 2.14±0ms 0.89 indexing.NumericSeriesIndexing.time_getitem_list_like(<class 'pandas.core.indexes.numeric.UInt64Index'>, 'nonunique_monotonic_inc') - 879±30μs 780±50μs 0.89 indexing.CategoricalIndexIndexing.time_get_indexer_list('monotonic_incr') - 184±20μs 163±1μs 0.88 indexing.NumericSeriesIndexing.time_iloc_array(<class 'pandas.core.indexes.numeric.Int64Index'>, 'nonunique_monotonic_inc') - 131±7μs 115±4μs 0.87 indexing.NumericSeriesIndexing.time_loc_scalar(<class 'pandas.core.indexes.numeric.Float64Index'>, 'nonunique_monotonic_inc') - 3.02±0.03ms 2.63±0.09ms 0.87 indexing.NumericSeriesIndexing.time_loc_list_like(<class 'pandas.core.indexes.numeric.Float64Index'>, 'nonunique_monotonic_inc') - 3.19±0.04ms 2.78±0.04ms 0.87 indexing.NumericSeriesIndexing.time_getitem_list_like(<class 'pandas.core.indexes.numeric.Float64Index'>, 'nonunique_monotonic_inc') - 11.7±0.2ms 10.2±0.2ms 0.87 indexing.NumericSeriesIndexing.time_loc_array(<class 'pandas.core.indexes.numeric.Float64Index'>, 'unique_monotonic_inc') - 1.89±0.04ms 1.65±0ms 0.87 indexing.NumericSeriesIndexing.time_getitem_list_like(<class 'pandas.core.indexes.numeric.Int64Index'>, 'unique_monotonic_inc') - 4.63±0.1ms 3.99±0.02ms 0.86 indexing.NumericSeriesIndexing.time_getitem_array(<class 'pandas.core.indexes.numeric.Int64Index'>, 'unique_monotonic_inc') - 1.82±0.04ms 1.56±0.01ms 0.86 indexing.NumericSeriesIndexing.time_getitem_list_like(<class 'pandas.core.indexes.numeric.Int64Index'>, 'nonunique_monotonic_inc') - 3.69±0.1ms 3.14±0.1ms 0.85 indexing.NumericSeriesIndexing.time_loc_list_like(<class 'pandas.core.indexes.numeric.Float64Index'>, 'unique_monotonic_inc') - 4.08±0.06ms 3.43±0.02ms 0.84 indexing.NumericSeriesIndexing.time_getitem_list_like(<class 'pandas.core.indexes.numeric.Float64Index'>, 'unique_monotonic_inc') - 150±30μs 120±3μs 0.80 indexing.NumericSeriesIndexing.time_loc_slice(<class 'pandas.core.indexes.numeric.UInt64Index'>, 'unique_monotonic_inc') - 961±30μs 762±20μs 0.79 indexing.CategoricalIndexIndexing.time_get_indexer_list('monotonic_decr') - 295±30μs 231±3μs 0.78 indexing.NumericSeriesIndexing.time_loc_slice(<class 'pandas.core.indexes.numeric.Int64Index'>, 'nonunique_monotonic_inc') - 1.11±0.3ms 825±20μs 0.74 indexing_engines.NumericEngineIndexing.time_get_loc((<class 'pandas._libs.index.UInt8Engine'>, <class 'numpy.uint8'>), 'monotonic_incr') - 741±80μs 288±9μs 0.39 indexing.AssignTimeseriesIndex.time_frame_assign_timeseries_index - 49.3±2ms 18.2±0.2ms 0.37 indexing.InsertColumns.time_assign_with_setitem - 54.3±20ms 18.5±1ms 0.34 indexing.InsertColumns.time_assign_list_like_with_setitem ```
https://api.github.com/repos/pandas-dev/pandas/pulls/43274
2021-08-28T18:07:09Z
2021-08-30T15:48:51Z
2021-08-30T15:48:51Z
2021-08-30T15:49:36Z
TYP: indexes
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 41355b9a44b85..e5f12ec53a6d4 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2498,7 +2498,7 @@ def __reduce__(self): """The expected NA value to use with this index.""" @cache_readonly - def _isnan(self) -> np.ndarray: + def _isnan(self) -> npt.NDArray[np.bool_]: """ Return if each value is NaN. """ @@ -2521,7 +2521,7 @@ def hasnans(self) -> bool: return False @final - def isna(self) -> np.ndarray: + def isna(self) -> npt.NDArray[np.bool_]: """ Detect missing values. @@ -2579,7 +2579,7 @@ def isna(self) -> np.ndarray: isnull = isna @final - def notna(self) -> np.ndarray: + def notna(self) -> npt.NDArray[np.bool_]: """ Detect existing (non-missing) values. @@ -2764,7 +2764,9 @@ def drop_duplicates(self: _IndexT, keep: str_t | bool = "first") -> _IndexT: return super().drop_duplicates(keep=keep) - def duplicated(self, keep: Literal["first", "last", False] = "first") -> np.ndarray: + def duplicated( + self, keep: Literal["first", "last", False] = "first" + ) -> npt.NDArray[np.bool_]: """ Indicate duplicate index values. @@ -5495,7 +5497,7 @@ def _get_indexer_strict(self, key, axis_name: str_t) -> tuple[Index, np.ndarray] return keyarr, indexer - def _raise_if_missing(self, key, indexer, axis_name: str_t): + def _raise_if_missing(self, key, indexer, axis_name: str_t) -> None: """ Check that indexer can be used to return a result. @@ -6119,7 +6121,9 @@ def get_slice_bound(self, label, side: str_t, kind=no_default) -> int: else: return slc - def slice_locs(self, start=None, end=None, step=None, kind=no_default): + def slice_locs( + self, start=None, end=None, step=None, kind=no_default + ) -> tuple[int, int]: """ Compute slice locations for input labels. @@ -6491,7 +6495,7 @@ def all(self, *args, **kwargs): return np.all(self.values) # type: ignore[arg-type] @final - def _maybe_disable_logical_methods(self, opname: str_t): + def _maybe_disable_logical_methods(self, opname: str_t) -> None: """ raise if this Index subclass does not support any or all. """ @@ -6606,7 +6610,7 @@ def _deprecated_arg(self, value, name: str_t, methodname: str_t) -> None: ) -def ensure_index_from_sequences(sequences, names=None): +def ensure_index_from_sequences(sequences, names=None) -> Index: """ Construct an index from sequences of data. diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 1458ff1cdaa51..b835b79b1e3e2 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -10,7 +10,10 @@ import numpy as np -from pandas._typing import ArrayLike +from pandas._typing import ( + ArrayLike, + npt, +) from pandas.compat.numpy import function as nv from pandas.util._decorators import ( cache_readonly, @@ -437,7 +440,7 @@ def astype(self, dtype, copy: bool = True) -> Index: return Index(new_values, dtype=new_values.dtype, name=self.name, copy=False) @cache_readonly - def _isnan(self) -> np.ndarray: + def _isnan(self) -> npt.NDArray[np.bool_]: # error: Incompatible return value type (got "ExtensionArray", expected # "ndarray") return self._data.isna() # type: ignore[return-value] diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 4d80480468adb..60ae71e8f888f 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -31,6 +31,7 @@ DtypeObj, Scalar, Shape, + npt, ) from pandas.compat.numpy import function as nv from pandas.errors import ( @@ -1588,7 +1589,7 @@ def _inferred_type_levels(self) -> list[str]: return [i.inferred_type for i in self.levels] @doc(Index.duplicated) - def duplicated(self, keep="first") -> np.ndarray: + def duplicated(self, keep="first") -> npt.NDArray[np.bool_]: shape = tuple(len(lev) for lev in self.levels) ids = get_group_index(self.codes, shape, sort=False, xnull=False) @@ -1842,7 +1843,7 @@ def _is_lexsorted(self) -> bool: return self._lexsort_depth == self.nlevels @property - def lexsort_depth(self): + def lexsort_depth(self) -> int: warnings.warn( "MultiIndex.is_lexsorted is deprecated as a public function, " "users should use MultiIndex.is_monotonic_increasing instead.", @@ -2152,7 +2153,7 @@ def append(self, other): except (TypeError, IndexError): return Index._with_infer(new_tuples) - def argsort(self, *args, **kwargs) -> np.ndarray: + def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]: return self._values.argsort(*args, **kwargs) @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) @@ -2371,7 +2372,7 @@ def cats(level_codes): def sortlevel( self, level=0, ascending: bool = True, sort_remaining: bool = True - ) -> tuple[MultiIndex, np.ndarray]: + ) -> tuple[MultiIndex, npt.NDArray[np.intp]]: """ Sort MultiIndex at the requested level. @@ -2392,7 +2393,7 @@ def sortlevel( ------- sorted_index : pd.MultiIndex Resulting index. - indexer : np.ndarray + indexer : np.ndarray[np.intp] Indices of output values in original index. Examples @@ -2493,7 +2494,7 @@ def _wrap_reindex_result(self, target, indexer, preserve_names: bool): target = self._maybe_preserve_names(target, preserve_names) return target - def _maybe_preserve_names(self, target: Index, preserve_names: bool): + def _maybe_preserve_names(self, target: Index, preserve_names: bool) -> Index: if ( preserve_names and target.nlevels == self.nlevels @@ -2506,7 +2507,7 @@ def _maybe_preserve_names(self, target: Index, preserve_names: bool): # -------------------------------------------------------------------- # Indexing Methods - def _check_indexing_error(self, key): + def _check_indexing_error(self, key) -> None: if not is_hashable(key) or is_iterator(key): # We allow tuples if they are hashable, whereas other Index # subclasses require scalar. @@ -2541,7 +2542,9 @@ def _get_values_for_loc(self, series: Series, loc, key): new_ser = series._constructor(new_values, index=new_index, name=series.name) return new_ser.__finalize__(series) - def _get_indexer_strict(self, key, axis_name: str) -> tuple[Index, np.ndarray]: + def _get_indexer_strict( + self, key, axis_name: str + ) -> tuple[Index, npt.NDArray[np.intp]]: keyarr = key if not isinstance(keyarr, Index): @@ -2555,7 +2558,7 @@ def _get_indexer_strict(self, key, axis_name: str) -> tuple[Index, np.ndarray]: return super()._get_indexer_strict(key, axis_name) - def _raise_if_missing(self, key, indexer, axis_name: str): + def _raise_if_missing(self, key, indexer, axis_name: str) -> None: keyarr = key if not isinstance(key, Index): keyarr = com.asarray_tuplesafe(key) @@ -2575,7 +2578,7 @@ def _raise_if_missing(self, key, indexer, axis_name: str): else: return super()._raise_if_missing(key, indexer, axis_name) - def _get_indexer_level_0(self, target) -> np.ndarray: + def _get_indexer_level_0(self, target) -> npt.NDArray[np.intp]: """ Optimized equivalent to `self.get_level_values(0).get_indexer_for(target)`. """ @@ -2640,7 +2643,9 @@ def get_slice_bound( label = (label,) return self._partial_tup_index(label, side=side) - def slice_locs(self, start=None, end=None, step=None, kind=lib.no_default): + def slice_locs( + self, start=None, end=None, step=None, kind=lib.no_default + ) -> tuple[int, int]: """ For an ordered MultiIndex, compute the slice locations for input labels. @@ -3614,7 +3619,7 @@ def _maybe_match_names(self, other): names.append(None) return names - def _wrap_intersection_result(self, other, result): + def _wrap_intersection_result(self, other, result) -> MultiIndex: _, result_names = self._convert_can_do_setop(other) if len(result) == 0: @@ -3627,7 +3632,7 @@ def _wrap_intersection_result(self, other, result): else: return MultiIndex.from_arrays(zip(*result), sortorder=0, names=result_names) - def _wrap_difference_result(self, other, result): + def _wrap_difference_result(self, other, result) -> MultiIndex: _, result_names = self._convert_can_do_setop(other) if len(result) == 0: @@ -3738,7 +3743,7 @@ def delete(self, loc) -> MultiIndex: ) @doc(Index.isin) - def isin(self, values, level=None) -> np.ndarray: + def isin(self, values, level=None) -> npt.NDArray[np.bool_]: if level is None: values = MultiIndex.from_tuples(values, names=self.names)._values return algos.isin(self._values, values)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/43273
2021-08-28T16:42:02Z
2021-08-29T09:00:53Z
2021-08-29T09:00:53Z
2021-08-29T14:05:06Z
TST: added test for ea dtypes conversion to datetimetzdtype (GH37553)
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index 7fbdc455a8dcf..732d375d136d0 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -16,6 +16,7 @@ NA, Categorical, CategoricalDtype, + DatetimeTZDtype, Index, Interval, NaT, @@ -363,6 +364,38 @@ def test_astype_nan_to_bool(self): expected = Series(True, dtype="bool") tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "dtype", + tm.ALL_INT_EA_DTYPES + tm.FLOAT_EA_DTYPES, + ) + def test_astype_ea_to_datetimetzdtype(self, dtype): + # GH37553 + result = Series([4, 0, 9], dtype=dtype).astype(DatetimeTZDtype(tz="US/Pacific")) + expected = Series( + { + 0: Timestamp("1969-12-31 16:00:00.000000004-08:00", tz="US/Pacific"), + 1: Timestamp("1969-12-31 16:00:00.000000000-08:00", tz="US/Pacific"), + 2: Timestamp("1969-12-31 16:00:00.000000009-08:00", tz="US/Pacific"), + } + ) + + if dtype in tm.FLOAT_EA_DTYPES: + expected = Series( + { + 0: Timestamp( + "1970-01-01 00:00:00.000000004-08:00", tz="US/Pacific" + ), + 1: Timestamp( + "1970-01-01 00:00:00.000000000-08:00", tz="US/Pacific" + ), + 2: Timestamp( + "1970-01-01 00:00:00.000000009-08:00", tz="US/Pacific" + ), + } + ) + + tm.assert_series_equal(result, expected) + class TestAstypeString: @pytest.mark.parametrize(
- [x] closes #37553 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Provided tests for type cast `ExtensionDtypes` -> `DatetimeTZDtype`. Tests and linter pass locally.
https://api.github.com/repos/pandas-dev/pandas/pulls/43270
2021-08-28T16:21:54Z
2021-08-31T23:32:33Z
2021-08-31T23:32:33Z
2021-08-31T23:32:37Z
BENCH: update `class SelectDtypes` to allow testing against 1.3.x
diff --git a/asv_bench/benchmarks/dtypes.py b/asv_bench/benchmarks/dtypes.py index c45d5a0814544..55f6be848aa13 100644 --- a/asv_bench/benchmarks/dtypes.py +++ b/asv_bench/benchmarks/dtypes.py @@ -50,15 +50,26 @@ def time_pandas_dtype_invalid(self, dtype): class SelectDtypes: - params = [ - tm.ALL_INT_NUMPY_DTYPES - + tm.ALL_INT_EA_DTYPES - + tm.FLOAT_NUMPY_DTYPES - + tm.COMPLEX_DTYPES - + tm.DATETIME64_DTYPES - + tm.TIMEDELTA64_DTYPES - + tm.BOOL_DTYPES - ] + try: + params = [ + tm.ALL_INT_NUMPY_DTYPES + + tm.ALL_INT_EA_DTYPES + + tm.FLOAT_NUMPY_DTYPES + + tm.COMPLEX_DTYPES + + tm.DATETIME64_DTYPES + + tm.TIMEDELTA64_DTYPES + + tm.BOOL_DTYPES + ] + except AttributeError: + params = [ + tm.ALL_INT_DTYPES + + tm.ALL_EA_INT_DTYPES + + tm.FLOAT_DTYPES + + tm.COMPLEX_DTYPES + + tm.DATETIME64_DTYPES + + tm.TIMEDELTA64_DTYPES + + tm.BOOL_DTYPES + ] param_names = ["dtype"] def setup(self, dtype):
doesn't need backport since benchmarks on master are used for comparing branches and finding performance regressions xref #43047
https://api.github.com/repos/pandas-dev/pandas/pulls/43269
2021-08-28T11:16:16Z
2021-08-31T23:29:59Z
2021-08-31T23:29:58Z
2021-09-01T10:09:36Z
PERF: to_datetime with uint
diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py index 0aa924dabd469..4cbaa184791b8 100644 --- a/asv_bench/benchmarks/inference.py +++ b/asv_bench/benchmarks/inference.py @@ -115,19 +115,27 @@ def time_maybe_convert_objects(self): class ToDatetimeFromIntsFloats: def setup(self): self.ts_sec = Series(range(1521080307, 1521685107), dtype="int64") + self.ts_sec_uint = Series(range(1521080307, 1521685107), dtype="uint64") self.ts_sec_float = self.ts_sec.astype("float64") self.ts_nanosec = 1_000_000 * self.ts_sec + self.ts_nanosec_uint = 1_000_000 * self.ts_sec_uint self.ts_nanosec_float = self.ts_nanosec.astype("float64") - # speed of int64 and float64 paths should be comparable + # speed of int64, uint64 and float64 paths should be comparable def time_nanosec_int64(self): to_datetime(self.ts_nanosec, unit="ns") + def time_nanosec_uint64(self): + to_datetime(self.ts_nanosec_uint, unit="ns") + def time_nanosec_float64(self): to_datetime(self.ts_nanosec_float, unit="ns") + def time_sec_uint64(self): + to_datetime(self.ts_sec_uint, unit="s") + def time_sec_int64(self): to_datetime(self.ts_sec, unit="s") diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index fc488504f1fdf..ad1b070c23010 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -242,7 +242,7 @@ Performance improvements - Performance improvement in :meth:`DataFrame.corr` for ``method=pearson`` on data without missing values (:issue:`40956`) - Performance improvement in some :meth:`GroupBy.apply` operations (:issue:`42992`) - Performance improvement in :func:`read_stata` (:issue:`43059`) -- +- Performance improvement in :meth:`to_datetime` with ``uint`` dtypes (:issue:`42606`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 6b1c0f851f8e7..6feb9ec768655 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -248,7 +248,7 @@ def array_with_unit_to_datetime( # if we have nulls that are not type-compat # then need to iterate - if values.dtype.kind == "i" or values.dtype.kind == "f": + if values.dtype.kind in ["i", "f", "u"]: iresult = values.astype("i8", copy=False) # fill missing values by comparing to NPY_NAT mask = iresult == NPY_NAT @@ -263,7 +263,7 @@ def array_with_unit_to_datetime( ): raise OutOfBoundsDatetime(f"cannot convert input with unit '{unit}'") - if values.dtype.kind == "i": + if values.dtype.kind in ["i", "u"]: result = (iresult * m).astype("M8[ns]") elif values.dtype.kind == "f":
- [x] closes #42606 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry ```python #PR In [3]: %time index = pd.to_datetime(np.arange(1_000_000).astype("uint64"), unit="s", utc=True) CPU times: user 20.6 ms, sys: 19.9 ms, total: 40.5 ms Wall time: 39.2 ms In [4]: %time index = pd.to_datetime(np.arange(1_000_000).astype("uint32"), unit="s", utc=True) CPU times: user 16.3 ms, sys: 6.58 ms, total: 22.8 ms Wall time: 21.2 ms #master In [3]: %time index = pd.to_datetime(np.arange(1_000_000).astype("uint64"), unit="s", utc=True) CPU times: user 12.6 s, sys: 44.3 ms, total: 12.7 s Wall time: 12.7 s In [4]: %time index = pd.to_datetime(np.arange(1_000_000).astype("uint32"), unit="s", utc=True) CPU times: user 5.88 s, sys: 21.2 ms, total: 5.9 s Wall time: 5.92 s ```
https://api.github.com/repos/pandas-dev/pandas/pulls/43268
2021-08-28T07:56:35Z
2021-08-30T13:12:40Z
2021-08-30T13:12:39Z
2021-08-30T13:48:35Z
REF: Remove Numba compat pre 0.50.1
diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py index 96907df3c48ad..03a0157a8bde4 100644 --- a/pandas/core/util/numba_.py +++ b/pandas/core/util/numba_.py @@ -9,8 +9,6 @@ from pandas.compat._optional import import_optional_dependency from pandas.errors import NumbaUtilError -from pandas.util.version import Version - GLOBAL_USE_NUMBA: bool = False NUMBA_FUNC_CACHE: dict[tuple[Callable, str], Callable] = {} @@ -87,12 +85,7 @@ def jit_user_function( """ numba = import_optional_dependency("numba") - if Version(numba.__version__) >= Version("0.49.0"): - is_jitted = numba.extending.is_jitted(func) - else: - is_jitted = isinstance(func, numba.targets.registry.CPUDispatcher) - - if is_jitted: + if numba.extending.is_jitted(func): # Don't jit a user passed jitted function numba_func = func else: diff --git a/pandas/tests/frame/test_ufunc.py b/pandas/tests/frame/test_ufunc.py index bdc4694d21963..4d858fb980860 100644 --- a/pandas/tests/frame/test_ufunc.py +++ b/pandas/tests/frame/test_ufunc.py @@ -251,7 +251,7 @@ def test_alignment_deprecation(): tm.assert_frame_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_alignment_deprecation_many_inputs(): # https://github.com/pandas-dev/pandas/issues/39184 # test that the deprecation also works with > 2 inputs -> using a numba diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index 4b915cd4c29ae..8e9df8a6da958 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -15,7 +15,7 @@ from pandas.core.util.numba_ import NUMBA_FUNC_CACHE -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_correct_function_signature(): def incorrect_function(x): return sum(x) * 2.7 @@ -31,7 +31,7 @@ def incorrect_function(x): data.groupby("key")["data"].agg(incorrect_function, engine="numba") -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_check_nopython_kwargs(): def incorrect_function(x, **kwargs): return sum(x) * 2.7 @@ -47,7 +47,7 @@ def incorrect_function(x, **kwargs): data.groupby("key")["data"].agg(incorrect_function, engine="numba", a=1) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @@ -76,7 +76,7 @@ def func_numba(values, index): tm.assert_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @@ -121,7 +121,7 @@ def func_2(values, index): tm.assert_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_use_global_config(): def func_1(values, index): return np.mean(values) - 3.4 @@ -136,7 +136,7 @@ def func_1(values, index): tm.assert_frame_equal(expected, result) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.parametrize( "agg_func", [ @@ -158,7 +158,7 @@ def test_multifunc_notimplimented(agg_func): grouped[1].agg(agg_func, engine="numba") -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_args_not_cached(): # GH 41647 def sum_last(values, index, n): @@ -175,7 +175,7 @@ def sum_last(values, index, n): tm.assert_series_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_index_data_correctly_passed(): # GH 43133 def f(values, index): diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index b2d72aec0527f..503de5ebd2330 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -12,7 +12,7 @@ from pandas.core.util.numba_ import NUMBA_FUNC_CACHE -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_correct_function_signature(): def incorrect_function(x): return x + 1 @@ -28,7 +28,7 @@ def incorrect_function(x): data.groupby("key")["data"].transform(incorrect_function, engine="numba") -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_check_nopython_kwargs(): def incorrect_function(x, **kwargs): return x + 1 @@ -44,7 +44,7 @@ def incorrect_function(x, **kwargs): data.groupby("key")["data"].transform(incorrect_function, engine="numba", a=1) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @@ -73,7 +73,7 @@ def func(values, index): tm.assert_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba @pytest.mark.parametrize("jit", [True, False]) @@ -118,7 +118,7 @@ def func_2(values, index): tm.assert_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_use_global_config(): def func_1(values, index): return values + 1 @@ -133,7 +133,7 @@ def func_1(values, index): tm.assert_frame_equal(expected, result) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.parametrize( "agg_func", [["min", "max"], "min", {"B": ["min", "max"], "C": "sum"}] ) @@ -149,7 +149,7 @@ def test_multifunc_notimplimented(agg_func): grouped[1].transform(agg_func, engine="numba") -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_args_not_cached(): # GH 41647 def sum_last(values, index, n): @@ -166,7 +166,7 @@ def sum_last(values, index, n): tm.assert_series_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_index_data_correctly_passed(): # GH 43133 def f(values, index): diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py index 30073bd55531f..fd8c11bbace6e 100644 --- a/pandas/tests/window/conftest.py +++ b/pandas/tests/window/conftest.py @@ -124,9 +124,7 @@ def ignore_na(request): return request.param -@pytest.fixture( - params=[pytest.param("numba", marks=td.skip_if_no("numba", "0.46.0")), "cython"] -) +@pytest.fixture(params=[pytest.param("numba", marks=td.skip_if_no("numba")), "cython"]) def engine(request): """engine keyword argument for rolling.apply""" return request.param @@ -134,7 +132,7 @@ def engine(request): @pytest.fixture( params=[ - pytest.param(("numba", True), marks=td.skip_if_no("numba", "0.46.0")), + pytest.param(("numba", True), marks=td.skip_if_no("numba")), ("cython", True), ("cython", False), ] diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index f507b6a465f5b..1086857f38b62 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -14,7 +14,7 @@ from pandas.core.util.numba_ import NUMBA_FUNC_CACHE -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba class TestEngine: @@ -150,7 +150,7 @@ def add(values, x): tm.assert_frame_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") class TestEWMMean: @pytest.mark.parametrize( "grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"] @@ -229,7 +229,7 @@ def test_cython_vs_numba_times(self, grouper, nogil, parallel, nopython, ignore_ tm.assert_frame_equal(result, expected) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_use_global_config(): def f(x): return np.mean(x) + 2 @@ -241,7 +241,7 @@ def f(x): tm.assert_series_equal(expected, result) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") def test_invalid_kwargs_nopython(): with pytest.raises(NumbaUtilError, match="numba does not support kwargs with"): Series(range(1)).rolling(1).apply( @@ -249,7 +249,7 @@ def test_invalid_kwargs_nopython(): ) -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.slow @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") # Filter warnings when parallel=True and the function can't be parallelized by Numba diff --git a/pandas/tests/window/test_online.py b/pandas/tests/window/test_online.py index 461c62c07326d..a21be0b8be049 100644 --- a/pandas/tests/window/test_online.py +++ b/pandas/tests/window/test_online.py @@ -10,7 +10,7 @@ import pandas._testing as tm -@td.skip_if_no("numba", "0.46.0") +@td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore:\\nThe keyword argument") class TestEWM: def test_invalid_update(self):
No longer needed since the bump https://github.com/pandas-dev/pandas/issues/43257#issuecomment-907452377
https://api.github.com/repos/pandas-dev/pandas/pulls/43266
2021-08-27T23:47:34Z
2021-08-30T07:50:59Z
2021-08-30T07:50:59Z
2021-08-30T16:53:36Z
DEPR: Passing in a string column label for DataFrame.ewm(times=...)
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2f8cb346935a9..17a5c292112b9 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -271,6 +271,7 @@ Other Deprecations - Deprecated dropping of nuisance columns in :class:`Rolling`, :class:`Expanding`, and :class:`EWM` aggregations (:issue:`42738`) - Deprecated :meth:`Index.reindex` with a non-unique index (:issue:`42568`) - Deprecated :meth:`.Styler.render` in favour of :meth:`.Styler.to_html` (:issue:`42140`) +- Deprecated passing in a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index f0bba8ae9727f..7b58af87fb1d8 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -21,6 +21,7 @@ from pandas.compat.numpy import function as nv from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import is_datetime64_ns_dtype from pandas.core.dtypes.missing import isna @@ -315,6 +316,15 @@ def __init__( if not self.adjust: raise NotImplementedError("times is not supported with adjust=False.") if isinstance(self.times, str): + warnings.warn( + ( + "Specifying times as a string column label is deprecated " + "and will be removed in a future version. Pass the column " + "into times instead." + ), + FutureWarning, + stacklevel=find_stack_level(), + ) self.times = self._selected_obj[self.times] if not is_datetime64_ns_dtype(self.times): raise ValueError("times must be datetime64[ns] dtype.") diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index e3ea53121defa..5579444f99bbb 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -107,7 +107,6 @@ def test_ewma_halflife_without_times(halflife_with_times): np.arange(10).astype("datetime64[D]").astype("datetime64[ns]"), date_range("2000", freq="D", periods=10), date_range("2000", freq="D", periods=10).tz_localize("UTC"), - "time_col", ], ) @pytest.mark.parametrize("min_periods", [0, 2]) @@ -231,3 +230,14 @@ def test_float_dtype_ewma(func, expected, float_numpy_dtype): result = getattr(e, func)() tm.assert_frame_equal(result, expected) + + +def test_times_string_col_deprecated(): + # GH 43265 + data = np.arange(10.0) + data[::2] = np.nan + df = DataFrame({"A": data, "time_col": date_range("2000", freq="D", periods=10)}) + with tm.assert_produces_warning(FutureWarning, match="Specifying times"): + result = df.ewm(halflife="1 day", min_periods=0, times="time_col").mean() + expected = df.ewm(halflife=1.0, min_periods=0).mean() + tm.assert_frame_equal(result, expected)
- [x] xref https://github.com/pandas-dev/pandas/pull/42834#discussion_r680451102 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/43265
2021-08-27T23:43:08Z
2021-09-05T01:43:20Z
2021-09-05T01:43:20Z
2021-09-05T02:48:57Z
TYP: nanops
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index db7289f7c3547..a80bd8ba76dac 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -27,11 +27,11 @@ F, Scalar, Shape, + npt, ) from pandas.compat._optional import import_optional_dependency from pandas.core.dtypes.common import ( - get_dtype, is_any_int_dtype, is_bool_dtype, is_complex, @@ -209,8 +209,8 @@ def _get_fill_value( def _maybe_get_mask( - values: np.ndarray, skipna: bool, mask: np.ndarray | None -) -> np.ndarray | None: + values: np.ndarray, skipna: bool, mask: npt.NDArray[np.bool_] | None +) -> npt.NDArray[np.bool_] | None: """ Compute a mask if and only if necessary. @@ -239,7 +239,7 @@ def _maybe_get_mask( Returns ------- - Optional[np.ndarray] + Optional[np.ndarray[bool]] """ if mask is None: if is_bool_dtype(values.dtype) or is_integer_dtype(values.dtype): @@ -257,8 +257,8 @@ def _get_values( skipna: bool, fill_value: Any = None, fill_value_typ: str | None = None, - mask: np.ndarray | None = None, -) -> tuple[np.ndarray, np.ndarray | None, np.dtype, np.dtype, Any]: + mask: npt.NDArray[np.bool_] | None = None, +) -> tuple[np.ndarray, npt.NDArray[np.bool_] | None, np.dtype, np.dtype, Any]: """ Utility to get the values view, mask, dtype, dtype_max, and fill_value. @@ -279,7 +279,7 @@ def _get_values( value to fill NaNs with fill_value_typ : str Set to '+inf' or '-inf' to handle dtype-specific infinities - mask : Optional[np.ndarray] + mask : Optional[np.ndarray[bool]] nan-mask if known Returns @@ -396,7 +396,7 @@ def new_func( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, **kwargs, ): orig_values = values @@ -454,7 +454,7 @@ def nanany( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> bool: """ Check if any elements along an axis evaluate to True. @@ -500,7 +500,7 @@ def nanall( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> bool: """ Check if all elements along an axis evaluate to True. @@ -549,7 +549,7 @@ def nansum( axis: int | None = None, skipna: bool = True, min_count: int = 0, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> float: """ Sum the elements along an axis ignoring NaNs @@ -592,7 +592,7 @@ def nansum( def _mask_datetimelike_result( result: np.ndarray | np.datetime64 | np.timedelta64, axis: int | None, - mask: np.ndarray, + mask: npt.NDArray[np.bool_], orig_values: np.ndarray, ) -> np.ndarray | np.datetime64 | np.timedelta64 | NaTType: if isinstance(result, np.ndarray): @@ -616,7 +616,7 @@ def nanmean( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> float: """ Compute the mean of the element along an axis ignoring NaNs @@ -781,10 +781,10 @@ def get_empty_reduction_result( def _get_counts_nanvar( values_shape: Shape, - mask: np.ndarray | None, + mask: npt.NDArray[np.bool_] | None, axis: int | None, ddof: int, - dtype: Dtype = float, + dtype: np.dtype = np.dtype(np.float64), ) -> tuple[int | float | np.ndarray, int | float | np.ndarray]: """ Get the count of non-null values along an axis, accounting @@ -808,7 +808,6 @@ def _get_counts_nanvar( count : int, np.nan or np.ndarray d : int, np.nan or np.ndarray """ - dtype = get_dtype(dtype) count = _get_counts(values_shape, mask, axis, dtype=dtype) d = count - dtype.type(ddof) @@ -931,7 +930,7 @@ def nanvar(values, *, axis=None, skipna=True, ddof=1, mask=None): # unless we were dealing with a float array, in which case use the same # precision as the original values array. if is_float_dtype(dtype): - result = result.astype(dtype) + result = result.astype(dtype, copy=False) return result @@ -942,7 +941,7 @@ def nansem( axis: int | None = None, skipna: bool = True, ddof: int = 1, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> float: """ Compute the standard error in the mean along given axis while ignoring NaNs @@ -993,7 +992,7 @@ def reduction( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> Dtype: values, mask, dtype, dtype_max, fill_value = _get_values( @@ -1025,7 +1024,7 @@ def nanargmax( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> int | np.ndarray: """ Parameters @@ -1071,7 +1070,7 @@ def nanargmin( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> int | np.ndarray: """ Parameters @@ -1117,7 +1116,7 @@ def nanskew( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> float: """ Compute the sample skewness. @@ -1185,7 +1184,7 @@ def nanskew( dtype = values.dtype if is_float_dtype(dtype): - result = result.astype(dtype) + result = result.astype(dtype, copy=False) if isinstance(result, np.ndarray): result = np.where(m2 == 0, 0, result) @@ -1204,7 +1203,7 @@ def nankurt( *, axis: int | None = None, skipna: bool = True, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> float: """ Compute the sample excess kurtosis @@ -1285,7 +1284,7 @@ def nankurt( dtype = values.dtype if is_float_dtype(dtype): - result = result.astype(dtype) + result = result.astype(dtype, copy=False) if isinstance(result, np.ndarray): result = np.where(denominator == 0, 0, result) @@ -1301,7 +1300,7 @@ def nanprod( axis: int | None = None, skipna: bool = True, min_count: int = 0, - mask: np.ndarray | None = None, + mask: npt.NDArray[np.bool_] | None = None, ) -> float: """ Parameters @@ -1339,7 +1338,10 @@ def nanprod( def _maybe_arg_null_out( - result: np.ndarray, axis: int | None, mask: np.ndarray | None, skipna: bool + result: np.ndarray, + axis: int | None, + mask: npt.NDArray[np.bool_] | None, + skipna: bool, ) -> np.ndarray | int: # helper function for nanargmin/nanargmax if mask is None: @@ -1367,10 +1369,10 @@ def _maybe_arg_null_out( def _get_counts( - values_shape: tuple[int, ...], - mask: np.ndarray | None, + values_shape: Shape, + mask: npt.NDArray[np.bool_] | None, axis: int | None, - dtype: Dtype = float, + dtype: np.dtype = np.dtype(np.float64), ) -> int | float | np.ndarray: """ Get the count of non-null values along an axis @@ -1390,7 +1392,6 @@ def _get_counts( ------- count : scalar or array """ - dtype = get_dtype(dtype) if axis is None: if mask is not None: n = mask.size - mask.sum() @@ -1405,20 +1406,13 @@ def _get_counts( if is_scalar(count): return dtype.type(count) - try: - return count.astype(dtype) - except AttributeError: - # error: Argument "dtype" to "array" has incompatible type - # "Union[ExtensionDtype, dtype]"; expected "Union[dtype, None, type, - # _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, - # Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, Any]]" - return np.array(count, dtype=dtype) # type: ignore[arg-type] + return count.astype(dtype, copy=False) def _maybe_null_out( result: np.ndarray | float | NaTType, axis: int | None, - mask: np.ndarray | None, + mask: npt.NDArray[np.bool_] | None, shape: tuple[int, ...], min_count: int = 1, ) -> np.ndarray | float | NaTType: @@ -1455,7 +1449,7 @@ def _maybe_null_out( def check_below_min_count( - shape: tuple[int, ...], mask: np.ndarray | None, min_count: int + shape: tuple[int, ...], mask: npt.NDArray[np.bool_] | None, min_count: int ) -> bool: """ Check for the `min_count` keyword. Returns True if below `min_count` (when @@ -1465,7 +1459,7 @@ def check_below_min_count( ---------- shape : tuple The shape of the values (`values.shape`). - mask : ndarray or None + mask : ndarray[bool] or None Boolean numpy array (typically of same shape as `shape`) or None. min_count : int Keyword passed through from sum/prod call. @@ -1634,7 +1628,11 @@ def f(x, y): def _nanpercentile_1d( - values: np.ndarray, mask: np.ndarray, q: np.ndarray, na_value: Scalar, interpolation + values: np.ndarray, + mask: npt.NDArray[np.bool_], + q: np.ndarray, + na_value: Scalar, + interpolation, ) -> Scalar | np.ndarray: """ Wrapper for np.percentile that skips missing values, specialized to @@ -1668,7 +1666,7 @@ def nanpercentile( q: np.ndarray, *, na_value, - mask: np.ndarray, + mask: npt.NDArray[np.bool_], interpolation, ): """
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/43264
2021-08-27T22:25:19Z
2021-08-30T07:50:06Z
2021-08-30T07:50:06Z
2021-08-30T14:48:26Z
BUG: rolling.corr with MultiIndex columns
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index a85b84aad9f94..5ccf3015ac257 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -408,6 +408,7 @@ Groupby/resample/rolling - Bug in :meth:`pandas.DataFrame.rolling` operation along rows (``axis=1``) incorrectly omits columns containing ``float16`` and ``float32`` (:issue:`41779`) - Bug in :meth:`Resampler.aggregate` did not allow the use of Named Aggregation (:issue:`32803`) - Bug in :meth:`Series.rolling` when the :class:`Series` ``dtype`` was ``Int64`` (:issue:`43016`) +- Bug in :meth:`DataFrame.rolling.corr` when the :class:`DataFrame` columns was a :class:`MultiIndex` (:issue:`21157`) - Bug in :meth:`DataFrame.groupby.rolling` when specifying ``on`` and calling ``__getitem__`` would subsequently return incorrect results (:issue:`43355`) Reshaping diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py index e0720c5d86df1..15144116fa924 100644 --- a/pandas/core/window/common.py +++ b/pandas/core/window/common.py @@ -83,8 +83,24 @@ def dataframe_from_int_dict(data, frame_template): # mypy needs to know columns is a MultiIndex, Index doesn't # have levels attribute arg2.columns = cast(MultiIndex, arg2.columns) - result.index = MultiIndex.from_product( - arg2.columns.levels + [result_index] + # GH 21157: Equivalent to MultiIndex.from_product( + # [result_index], <unique combinations of arg2.columns.levels>, + # ) + # A normal MultiIndex.from_product will produce too many + # combinations. + result_level = np.tile( + result_index, len(result) // len(result_index) + ) + arg2_levels = ( + np.repeat( + arg2.columns.get_level_values(i), + len(result) // len(arg2.columns), + ) + for i in range(arg2.columns.nlevels) + ) + result_names = list(arg2.columns.names) + [result_index.name] + result.index = MultiIndex.from_arrays( + [*arg2_levels, result_level], names=result_names ) # GH 34440 num_levels = len(result.index.levels) diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py index a0d24a061fc4a..f43d7ec99e312 100644 --- a/pandas/tests/window/test_pairwise.py +++ b/pandas/tests/window/test_pairwise.py @@ -222,3 +222,18 @@ def test_cov_mulittindex(self): ) tm.assert_frame_equal(result, expected) + + def test_multindex_columns_pairwise_func(self): + # GH 21157 + columns = MultiIndex.from_arrays([["M", "N"], ["P", "Q"]], names=["a", "b"]) + df = DataFrame(np.ones((5, 2)), columns=columns) + result = df.rolling(3).corr() + expected = DataFrame( + np.nan, + index=MultiIndex.from_arrays( + [np.repeat(np.arange(5), 2), ["M", "N"] * 5, ["P", "Q"] * 5], + names=[None, "a", "b"], + ), + columns=columns, + ) + tm.assert_frame_equal(result, expected)
- [x] closes #21157 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/43261
2021-08-27T19:31:50Z
2021-09-07T05:18:00Z
2021-09-07T05:18:00Z
2021-09-07T05:18:03Z
CI: Remove aiobotocore pin again
diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index 530e095895b77..a78fb30019b53 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -31,7 +31,6 @@ dependencies: - python-dateutil - pytz - s3fs>=0.4.2 - - aiobotocore<=1.3.3 - scipy - sqlalchemy - xlrd diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml index 92ff3ef7675e5..c56496bce7d6c 100644 --- a/ci/deps/azure-windows-38.yaml +++ b/ci/deps/azure-windows-38.yaml @@ -30,7 +30,6 @@ dependencies: - python-dateutil - pytz - s3fs>=0.4.0 - - aiobotocore<=1.3.3 - scipy - xlrd - xlsxwriter diff --git a/ci/deps/azure-windows-39.yaml b/ci/deps/azure-windows-39.yaml index 1e0f62e99f0c8..c4d376fd2a909 100644 --- a/ci/deps/azure-windows-39.yaml +++ b/ci/deps/azure-windows-39.yaml @@ -32,7 +32,6 @@ dependencies: - python-dateutil - pytz - s3fs>=0.4.2 - - aiobotocore<=1.3.3 - scipy - sqlalchemy - xlrd diff --git a/environment.yml b/environment.yml index 004580435655f..733bd06fbe12f 100644 --- a/environment.yml +++ b/environment.yml @@ -105,7 +105,7 @@ dependencies: - pytables>=3.6.1 # pandas.read_hdf, DataFrame.to_hdf - s3fs>=0.4.0 # file IO when using 's3://...' path - - aiobotocore<=1.3.3 # Remove when s3fs is at 2021.08.0 + - aiobotocore - fsspec>=0.7.4, <2021.6.0 # for generic remote file operations - gcsfs>=0.6.0 # file IO when using 'gcs://...' path - sqlalchemy # pandas.read_sql, DataFrame.to_sql diff --git a/requirements-dev.txt b/requirements-dev.txt index afeb9eed6c02b..9b35de4bccb48 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -69,7 +69,7 @@ pyarrow>=0.17.0 python-snappy tables>=3.6.1 s3fs>=0.4.0 -aiobotocore<=1.3.3 +aiobotocore fsspec>=0.7.4, <2021.6.0 gcsfs>=0.6.0 sqlalchemy
- [x] closes #43168 This should be fixed now.
https://api.github.com/repos/pandas-dev/pandas/pulls/43260
2021-08-27T18:41:19Z
2021-08-28T22:34:44Z
2021-08-28T22:34:44Z
2021-08-28T22:34:47Z
Backport PR #43251 on branch 1.3.x (Bug in RangeIndex.where raising AssertionError when result is not from RangeIndex)
diff --git a/doc/source/whatsnew/v1.3.3.rst b/doc/source/whatsnew/v1.3.3.rst index 3dee3aa5e7c7a..9aac0a9ad9681 100644 --- a/doc/source/whatsnew/v1.3.3.rst +++ b/doc/source/whatsnew/v1.3.3.rst @@ -17,7 +17,7 @@ Fixed regressions - Fixed regression in :class:`DataFrame` constructor failing to broadcast for defined :class:`Index` and len one list of :class:`Timestamp` (:issue:`42810`) - Performance regression in :meth:`core.window.ewm.ExponentialMovingWindow.mean` (:issue:`42333`) - Fixed regression in :meth:`.GroupBy.agg` incorrectly raising in some cases (:issue:`42390`) -- +- Fixed regression in :meth:`RangeIndex.where` and :meth:`RangeIndex.putmask` raising ``AssertionError`` when result did not represent a :class:`RangeIndex` (:issue:`43240`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e666b14b5d67c..4c5fd526523e6 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4723,8 +4723,7 @@ def putmask(self, mask, value) -> Index: values, mask.sum(), converted # type: ignore[arg-type] ) np.putmask(values, mask, converted) - - return type(self)._simple_new(values, name=self.name) + return self._shallow_copy(values) def equals(self, other: Any) -> bool: """ diff --git a/pandas/tests/indexes/ranges/test_setops.py b/pandas/tests/indexes/ranges/test_setops.py index ba938f82e9d89..210bcd300b1b0 100644 --- a/pandas/tests/indexes/ranges/test_setops.py +++ b/pandas/tests/indexes/ranges/test_setops.py @@ -354,3 +354,17 @@ def test_symmetric_difference(self): result = left.symmetric_difference(right[1:]) expected = Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]) tm.assert_index_equal(result, expected) + + def test_putmask_range_cast(self): + # GH#43240 + idx = RangeIndex(0, 5, name="test") + result = idx.putmask(np.array([True, True, False, False, False]), 10) + expected = Index([10, 10, 2, 3, 4], name="test") + tm.assert_index_equal(result, expected) + + def test_where_range_cast(self): + # GH#43240 + idx = RangeIndex(0, 5, name="test") + result = idx.where(np.array([False, False, True, True, True]), 10) + expected = Index([10, 10, 2, 3, 4], name="test") + tm.assert_index_equal(result, expected)
Backport PR #43251: Bug in RangeIndex.where raising AssertionError when result is not from RangeIndex
https://api.github.com/repos/pandas-dev/pandas/pulls/43259
2021-08-27T18:16:33Z
2021-08-28T07:46:58Z
2021-08-28T07:46:58Z
2021-08-28T07:46:58Z
TST: added tests for to_json when called on complex data (GH41174)
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index af75313b766a6..a856f031e20ba 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1782,3 +1782,41 @@ def e(self): # JSON keys should be all non-callable non-underscore attributes, see GH-42768 series = Series([_TestObject(a=1, b=2, _c=3, d=4)]) assert json.loads(series.to_json()) == {"0": {"a": 1, "b": 2, "d": 4}} + + @pytest.mark.parametrize( + "data,expected", + [ + ( + Series({0: -6 + 8j, 1: 0 + 1j, 2: 9 - 5j}), + '{"0":{"imag":8.0,"real":-6.0},' + '"1":{"imag":1.0,"real":0.0},' + '"2":{"imag":-5.0,"real":9.0}}', + ), + ( + Series({0: -9.39 + 0.66j, 1: 3.95 + 9.32j, 2: 4.03 - 0.17j}), + '{"0":{"imag":0.66,"real":-9.39},' + '"1":{"imag":9.32,"real":3.95},' + '"2":{"imag":-0.17,"real":4.03}}', + ), + ( + DataFrame([[-2 + 3j, -1 - 0j], [4 - 3j, -0 - 10j]]), + '{"0":{"0":{"imag":3.0,"real":-2.0},' + '"1":{"imag":-3.0,"real":4.0}},' + '"1":{"0":{"imag":0.0,"real":-1.0},' + '"1":{"imag":-10.0,"real":0.0}}}', + ), + ( + DataFrame( + [[-0.28 + 0.34j, -1.08 - 0.39j], [0.41 - 0.34j, -0.78 - 1.35j]] + ), + '{"0":{"0":{"imag":0.34,"real":-0.28},' + '"1":{"imag":-0.34,"real":0.41}},' + '"1":{"0":{"imag":-0.39,"real":-1.08},' + '"1":{"imag":-1.35,"real":-0.78}}}', + ), + ], + ) + def test_complex_data_tojson(self, data, expected): + # GH41174 + result = data.to_json() + assert result == expected
- [x] closes #41174 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Provided tests for `to_json` when called on complex data on both `Series` and `DataFrame`. Coefficients are both `int` and `float`. Tests and linter pass locally.
https://api.github.com/repos/pandas-dev/pandas/pulls/43258
2021-08-27T18:11:18Z
2021-08-30T07:52:26Z
2021-08-30T07:52:26Z
2021-08-30T07:52:37Z
ENH: `styler.format` options
diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst index 62a347acdaa34..41e0b754cfa81 100644 --- a/doc/source/user_guide/options.rst +++ b/doc/source/user_guide/options.rst @@ -138,7 +138,7 @@ More information can be found in the `IPython documentation import pandas as pd pd.set_option("display.max_rows", 999) - pd.set_option("precision", 5) + pd.set_option("display.precision", 5) .. _options.frequently_used: @@ -253,9 +253,9 @@ This is only a suggestion. .. ipython:: python df = pd.DataFrame(np.random.randn(5, 5)) - pd.set_option("precision", 7) + pd.set_option("display.precision", 7) df - pd.set_option("precision", 4) + pd.set_option("display.precision", 4) df ``display.chop_threshold`` sets at what level pandas rounds to zero when @@ -489,6 +489,15 @@ styler.sparse.columns True "Sparsify" MultiIndex displ in Styler output. styler.render.max_elements 262144 Maximum number of datapoints that Styler will render trimming either rows, columns or both to fit. +styler.format.formatter None Object to specify formatting functions to ``Styler.format``. +styler.format.na_rep None String representation for missing data. +styler.format.precision 6 Precision to display floating point and complex numbers. +styler.format.decimal . String representation for decimal point separator for floating + point and complex numbers. +styler.format.thousands None String representation for thousands separator for + integers, and floating point and complex numbers. +styler.format.escape None Whether to escape "html" or "latex" special + characters in the display representation. ======================================= ============ ================================== diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index be647e344f270..2b11d9f01d88d 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -75,6 +75,7 @@ Styler - :meth:`.Styler.to_latex` introduces keyword argument ``environment``, which also allows a specific "longtable" entry through a separate jinja2 template (:issue:`41866`). - :meth:`.Styler.to_html` introduces keyword arguments ``sparse_index`` and ``sparse_columns`` (:issue:`41946`) - Keyword argument ``level`` is added to :meth:`.Styler.hide_index` and :meth:`.Styler.hide_columns` for optionally controlling hidden levels in a MultiIndex (:issue:`25475`) + - Global options have been extended to configure default ``Styler`` properties including formatting options (:issue:`41395`) There are also bug fixes and deprecations listed below. diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 27b898782fbef..89f3bc76d2905 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -20,6 +20,7 @@ is_int, is_nonnegative_int, is_one_of_factory, + is_str, is_text, ) @@ -762,6 +763,36 @@ def register_converter_cb(key): trimming will occur over columns, rows or both if needed. """ +styler_precision = """ +: int + The precision for floats and complex numbers. +""" + +styler_decimal = """ +: str + The character representation for the decimal separator for floats and complex. +""" + +styler_thousands = """ +: str, optional + The character representation for thousands separator for floats, int and complex. +""" + +styler_na_rep = """ +: str, optional + The string representation for values identified as missing. +""" + +styler_escape = """ +: str, optional + Whether to escape certain characters according to the given context; html or latex. +""" + +styler_formatter = """ +: str, callable, dict, optional + A formatter object to be used as default within ``Styler.format``. +""" + with cf.config_prefix("styler"): cf.register_option("sparse.index", True, styler_sparse_index_doc, validator=bool) @@ -775,3 +806,37 @@ def register_converter_cb(key): styler_max_elements, validator=is_nonnegative_int, ) + + cf.register_option("format.decimal", ".", styler_decimal, validator=is_str) + + cf.register_option( + "format.precision", 6, styler_precision, validator=is_nonnegative_int + ) + + cf.register_option( + "format.thousands", + None, + styler_thousands, + validator=is_instance_factory([type(None), str]), + ) + + cf.register_option( + "format.na_rep", + None, + styler_na_rep, + validator=is_instance_factory([type(None), str]), + ) + + cf.register_option( + "format.escape", + None, + styler_escape, + validator=is_one_of_factory([None, "html", "latex"]), + ) + + cf.register_option( + "format.formatter", + None, + styler_formatter, + validator=is_instance_factory([type(None), dict, callable, str]), + ) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 31e10534d853a..7c3d7fe57b7b1 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -52,6 +52,7 @@ from pandas.io.formats.style_render import ( CSSProperties, CSSStyles, + ExtFormatter, StylerRenderer, Subset, Tooltips, @@ -85,8 +86,11 @@ class Styler(StylerRenderer): ---------- data : Series or DataFrame Data to be styled - either a Series or DataFrame. - precision : int - Precision to round floats to, defaults to pd.options.display.precision. + precision : int, optional + Precision to round floats to. If not given defaults to + ``pandas.options.styler.format.precision``. + + .. versionchanged:: 1.4.0 table_styles : list-like, default None List of {selector: (attr, value)} dicts; see Notes. uuid : str, default None @@ -103,7 +107,8 @@ class Styler(StylerRenderer): number and ``<num_col>`` is the column number. na_rep : str, optional Representation for missing values. - If ``na_rep`` is None, no special formatting is applied. + If ``na_rep`` is None, no special formatting is applied, and falls back to + ``pandas.options.styler.format.na_rep``. .. versionadded:: 1.0.0 @@ -113,13 +118,15 @@ class Styler(StylerRenderer): .. versionadded:: 1.2.0 - decimal : str, default "." - Character used as decimal separator for floats, complex and integers + decimal : str, optional + Character used as decimal separator for floats, complex and integers. If not + given uses ``pandas.options.styler.format.decimal``. .. versionadded:: 1.3.0 thousands : str, optional, default None - Character used as thousands separator for floats, complex and integers + Character used as thousands separator for floats, complex and integers. If not + given uses ``pandas.options.styler.format.thousands``. .. versionadded:: 1.3.0 @@ -128,9 +135,14 @@ class Styler(StylerRenderer): in cell display string with HTML-safe sequences. Use 'latex' to replace the characters ``&``, ``%``, ``$``, ``#``, ``_``, ``{``, ``}``, ``~``, ``^``, and ``\`` in the cell display string with - LaTeX-safe sequences. + LaTeX-safe sequences. If not given uses ``pandas.options.styler.format.escape`` .. versionadded:: 1.3.0 + formatter : str, callable, dict, optional + Object to define how values are displayed. See ``Styler.format``. If not given + uses ``pandas.options.styler.format.formatter``. + + .. versionadded:: 1.4.0 Attributes ---------- @@ -184,9 +196,10 @@ def __init__( cell_ids: bool = True, na_rep: str | None = None, uuid_len: int = 5, - decimal: str = ".", + decimal: str | None = None, thousands: str | None = None, escape: str | None = None, + formatter: ExtFormatter | None = None, ): super().__init__( data=data, @@ -196,13 +209,21 @@ def __init__( table_attributes=table_attributes, caption=caption, cell_ids=cell_ids, + precision=precision, ) # validate ordered args + thousands = thousands or get_option("styler.format.thousands") + decimal = decimal or get_option("styler.format.decimal") + na_rep = na_rep or get_option("styler.format.na_rep") + escape = escape or get_option("styler.format.escape") + formatter = formatter or get_option("styler.format.formatter") + # precision is handled by superclass as default for performance + self.precision = precision # can be removed on set_precision depr cycle self.na_rep = na_rep # can be removed on set_na_rep depr cycle self.format( - formatter=None, + formatter=formatter, precision=precision, na_rep=na_rep, escape=escape, diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 4f1e98225aafe..69ab134a38e29 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -77,6 +77,7 @@ def __init__( table_attributes: str | None = None, caption: str | tuple | None = None, cell_ids: bool = True, + precision: int | None = None, ): # validate ordered args @@ -107,10 +108,10 @@ def __init__( self.cell_context: DefaultDict[tuple[int, int], str] = defaultdict(str) self._todo: list[tuple[Callable, tuple, dict]] = [] self.tooltips: Tooltips | None = None - def_precision = get_option("display.precision") + precision = precision or get_option("styler.format.precision") self._display_funcs: DefaultDict[ # maps (row, col) -> formatting function tuple[int, int], Callable[[Any], str] - ] = defaultdict(lambda: partial(_default_formatter, precision=def_precision)) + ] = defaultdict(lambda: partial(_default_formatter, precision=precision)) def _render_html(self, sparse_index: bool, sparse_columns: bool, **kwargs) -> str: """ @@ -686,6 +687,16 @@ def format( When using a ``formatter`` string the dtypes must be compatible, otherwise a `ValueError` will be raised. + When instantiating a Styler, default formatting can be applied be setting the + ``pandas.options``: + + - ``styler.format.formatter``: default None. + - ``styler.format.na_rep``: default None. + - ``styler.format.precision``: default 6. + - ``styler.format.decimal``: default ".". + - ``styler.format.thousands``: default None. + - ``styler.format.escape``: default None. + Examples -------- Using ``na_rep`` and ``precision`` with the default ``formatter`` @@ -954,11 +965,9 @@ def _default_formatter(x: Any, precision: int, thousands: bool = False) -> Any: Matches input type, or string if input is float or complex or int with sep. """ if isinstance(x, (float, complex)): - if thousands: - return f"{x:,.{precision}f}" - return f"{x:.{precision}f}" - elif isinstance(x, int) and thousands: - return f"{x:,.0f}" + return f"{x:,.{precision}f}" if thousands else f"{x:.{precision}f}" + elif isinstance(x, int): + return f"{x:,.0f}" if thousands else f"{x:.0f}" return x @@ -1022,7 +1031,7 @@ def _maybe_wrap_formatter( elif callable(formatter): func_0 = formatter elif formatter is None: - precision = get_option("display.precision") if precision is None else precision + precision = precision or get_option("styler.format.precision") func_0 = partial( _default_formatter, precision=precision, thousands=(thousands is not None) ) diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py index 299643028c141..58f18a6959efa 100644 --- a/pandas/tests/io/formats/style/test_format.py +++ b/pandas/tests/io/formats/style/test_format.py @@ -6,6 +6,7 @@ IndexSlice, NaT, Timestamp, + option_context, ) pytest.importorskip("jinja2") @@ -256,3 +257,44 @@ def test_str_escape_error(): _str_escape("text", []) _str_escape(2.00, "bad_escape") # OK since dtype is float + + +def test_format_options(): + df = DataFrame({"int": [2000, 1], "float": [1.009, None], "str": ["&<", "&~"]}) + ctx = df.style._translate(True, True) + + # test option: na_rep + assert ctx["body"][1][2]["display_value"] == "nan" + with option_context("styler.format.na_rep", "MISSING"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][1][2]["display_value"] == "MISSING" + + # test option: decimal and precision + assert ctx["body"][0][2]["display_value"] == "1.009000" + with option_context("styler.format.decimal", "_"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][2]["display_value"] == "1_009000" + with option_context("styler.format.precision", 2): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][2]["display_value"] == "1.01" + + # test option: thousands + assert ctx["body"][0][1]["display_value"] == "2000" + with option_context("styler.format.thousands", "_"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][1]["display_value"] == "2_000" + + # test option: escape + assert ctx["body"][0][3]["display_value"] == "&<" + assert ctx["body"][1][3]["display_value"] == "&~" + with option_context("styler.format.escape", "html"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][3]["display_value"] == "&amp;&lt;" + with option_context("styler.format.escape", "latex"): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][1][3]["display_value"] == "\\&\\textasciitilde " + + # test option: formatter + with option_context("styler.format.formatter", {"int": "{:,.2f}"}): + ctx_with_op = df.style._translate(True, True) + assert ctx_with_op["body"][0][1]["display_value"] == "2,000.00" diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 5022a1eaa2c6e..afa50cf1cf963 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -1128,9 +1128,9 @@ def test_hide_columns_index_mult_levels(self): assert ctx["body"][0][0]["is_visible"] # data assert ctx["body"][1][2]["is_visible"] - assert ctx["body"][1][2]["display_value"] == 3 + assert ctx["body"][1][2]["display_value"] == "3" assert ctx["body"][1][3]["is_visible"] - assert ctx["body"][1][3]["display_value"] == 4 + assert ctx["body"][1][3]["display_value"] == "4" # hide top column level, which hides both columns ctx = df.style.hide_columns("b")._translate(True, True) @@ -1146,7 +1146,7 @@ def test_hide_columns_index_mult_levels(self): assert not ctx["head"][1][2]["is_visible"] # 0 assert not ctx["body"][1][2]["is_visible"] # 3 assert ctx["body"][1][3]["is_visible"] - assert ctx["body"][1][3]["display_value"] == 4 + assert ctx["body"][1][3]["display_value"] == "4" # hide second column and index ctx = df.style.hide_columns([("b", 1)]).hide_index()._translate(True, True) @@ -1157,7 +1157,7 @@ def test_hide_columns_index_mult_levels(self): assert not ctx["head"][1][2]["is_visible"] # 1 assert not ctx["body"][1][3]["is_visible"] # 4 assert ctx["body"][1][2]["is_visible"] - assert ctx["body"][1][2]["display_value"] == 3 + assert ctx["body"][1][2]["display_value"] == "3" # hide top row level, which hides both rows ctx = df.style.hide_index("a")._translate(True, True)
- [x] adds to #41395 - [x] add options - [x] add tests - [x] update `Styler.format` docstring - [x] update `options.rst` - [x] update `Styler` init docstring - [x] whatsnew update user guide **will be a follow-on when all options are merged** ![Screen Shot 2021-08-28 at 13 26 44](https://user-images.githubusercontent.com/24256554/131216430-ef0a76bc-7ae7-4576-aa05-c684b13db67a.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/43256
2021-08-27T17:27:56Z
2021-08-31T20:03:48Z
2021-08-31T20:03:48Z
2021-08-31T20:56:45Z
WEB: Updated list of active maintainers #43254
diff --git a/web/pandas/config.yml b/web/pandas/config.yml index 9da7d3bbe8ab6..82eb023f185c8 100644 --- a/web/pandas/config.yml +++ b/web/pandas/config.yml @@ -87,6 +87,9 @@ maintainers: - MarcoGorelli - rhshadrach - phofl + - attack68 + - fangchenli + - twoertwein emeritus: - Wouter Overmeire - Skipper Seabold
Added *attack68, fangchenli, twoertwein, tswast* to the list of active maintainers. - [X] closes #43254 - [X] tests added / passed - [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/43255
2021-08-27T16:56:15Z
2021-08-27T18:40:02Z
2021-08-27T18:40:02Z
2021-08-27T18:40:03Z
BUG: fix is_named_tuple for objects that are not subclass of tuple #40682
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2f8cb346935a9..b7c4d8827ade0 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -375,6 +375,7 @@ I/O - Bug in :func:`read_csv` with multi-header input and arguments referencing column names as tuples (:issue:`42446`) - Bug in :func:`read_fwf`, where difference in lengths of ``colspecs`` and ``names`` was not raising ``ValueError`` (:issue:`40830`) - Bug in :func:`Series.to_json` and :func:`DataFrame.to_json` where some attributes were skipped when serialising plain Python objects to JSON (:issue:`42768`, :issue:`33043`) +- Column headers are dropped when constructing a :class:`DataFrame` from a sqlalchemy's ``Row`` object (:issue:`40682`) - Period diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index 1360b66e77dc0..ae961e53d8b79 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -315,7 +315,7 @@ def is_named_tuple(obj) -> bool: >>> is_named_tuple((1, 2)) False """ - return isinstance(obj, tuple) and hasattr(obj, "_fields") + return isinstance(obj, abc.Sequence) and hasattr(obj, "_fields") def is_hashable(obj) -> bool: diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 7f73b4f12c2fb..eb3097618e158 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -2189,6 +2189,44 @@ def test_bigint_warning(self): with tm.assert_produces_warning(None): sql.read_sql_table("test_bigintwarning", self.conn) + def test_row_object_is_named_tuple(self): + # GH 40682 + # Test for the is_named_tuple() function + # Placed here due to its usage of sqlalchemy + + from sqlalchemy import ( + Column, + Integer, + String, + ) + from sqlalchemy.orm import sessionmaker + + if _gt14(): + from sqlalchemy.orm import declarative_base + else: + from sqlalchemy.ext.declarative import declarative_base + + BaseModel = declarative_base() + + class Test(BaseModel): + __tablename__ = "test_frame" + id = Column(Integer, primary_key=True) + foo = Column(String(50)) + + BaseModel.metadata.create_all(self.conn) + Session = sessionmaker(bind=self.conn) + session = Session() + + df = DataFrame({"id": [0, 1], "foo": ["hello", "world"]}) + df.to_sql("test_frame", con=self.conn, index=False, if_exists="replace") + + session.commit() + foo = session.query(Test.id, Test.foo) + df = DataFrame(foo) + session.close() + + assert list(df.columns) == ["id", "foo"] + class _TestMySQLAlchemy: """
- [x] closes #40682 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/43253
2021-08-27T16:44:41Z
2021-09-04T14:33:27Z
2021-09-04T14:33:26Z
2022-11-18T02:20:50Z
Bug in RangeIndex.where raising AssertionError when result is not from RangeIndex
diff --git a/doc/source/whatsnew/v1.3.3.rst b/doc/source/whatsnew/v1.3.3.rst index 3dee3aa5e7c7a..9aac0a9ad9681 100644 --- a/doc/source/whatsnew/v1.3.3.rst +++ b/doc/source/whatsnew/v1.3.3.rst @@ -17,7 +17,7 @@ Fixed regressions - Fixed regression in :class:`DataFrame` constructor failing to broadcast for defined :class:`Index` and len one list of :class:`Timestamp` (:issue:`42810`) - Performance regression in :meth:`core.window.ewm.ExponentialMovingWindow.mean` (:issue:`42333`) - Fixed regression in :meth:`.GroupBy.agg` incorrectly raising in some cases (:issue:`42390`) -- +- Fixed regression in :meth:`RangeIndex.where` and :meth:`RangeIndex.putmask` raising ``AssertionError`` when result did not represent a :class:`RangeIndex` (:issue:`43240`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2615bfffb3cd9..41355b9a44b85 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4890,8 +4890,7 @@ def putmask(self, mask, value) -> Index: values, mask.sum(), converted # type: ignore[arg-type] ) np.putmask(values, mask, converted) - - return type(self)._simple_new(values, name=self.name) + return self._shallow_copy(values) def equals(self, other: Any) -> bool: """ diff --git a/pandas/tests/indexes/ranges/test_setops.py b/pandas/tests/indexes/ranges/test_setops.py index ba938f82e9d89..210bcd300b1b0 100644 --- a/pandas/tests/indexes/ranges/test_setops.py +++ b/pandas/tests/indexes/ranges/test_setops.py @@ -354,3 +354,17 @@ def test_symmetric_difference(self): result = left.symmetric_difference(right[1:]) expected = Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]) tm.assert_index_equal(result, expected) + + def test_putmask_range_cast(self): + # GH#43240 + idx = RangeIndex(0, 5, name="test") + result = idx.putmask(np.array([True, True, False, False, False]), 10) + expected = Index([10, 10, 2, 3, 4], name="test") + tm.assert_index_equal(result, expected) + + def test_where_range_cast(self): + # GH#43240 + idx = RangeIndex(0, 5, name="test") + result = idx.where(np.array([False, False, True, True, True]), 10) + expected = Index([10, 10, 2, 3, 4], name="test") + tm.assert_index_equal(result, expected)
- [x] closes #43240 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry cc @jbrockmendel 2 options here: - calling ``_shallow_copy`` which handles the cast to Int64Index in theses cases - implementing a similar logic in ``_simple_new`` passing the call through to Int64Index or Float64Index depending on the dtype But not sure if this would be counterintuitive for ``_simple_new``.
https://api.github.com/repos/pandas-dev/pandas/pulls/43251
2021-08-27T14:31:54Z
2021-08-27T18:16:25Z
2021-08-27T18:16:24Z
2021-08-27T18:17:33Z
Backport PR #43172 on branch 1.3.x (BUG: Pass index data correctly in groupby.transform/agg w/ engine=numba)
diff --git a/doc/source/whatsnew/v1.3.3.rst b/doc/source/whatsnew/v1.3.3.rst index 1340188c3d609..3dee3aa5e7c7a 100644 --- a/doc/source/whatsnew/v1.3.3.rst +++ b/doc/source/whatsnew/v1.3.3.rst @@ -25,7 +25,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -- +- Bug in :meth:`.DataFrameGroupBy.agg` and :meth:`.DataFrameGroupBy.transform` with ``engine="numba"`` where ``index`` data was not being correctly passed into ``func`` (:issue:`43133`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 0080791a51a4b..5a70db517ad12 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1143,9 +1143,15 @@ def _numba_prep(self, func, data): sorted_ids = algorithms.take_nd(ids, sorted_index, allow_fill=False) sorted_data = data.take(sorted_index, axis=self.axis).to_numpy() + sorted_index_data = data.index.take(sorted_index).to_numpy() starts, ends = lib.generate_slices(sorted_ids, ngroups) - return starts, ends, sorted_index, sorted_data + return ( + starts, + ends, + sorted_index_data, + sorted_data, + ) @final def _transform_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs): diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index ba2d6eeb287c0..4b915cd4c29ae 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -173,3 +173,17 @@ def sum_last(values, index, n): result = grouped_x.agg(sum_last, 2, engine="numba") expected = Series([2.0] * 2, name="x", index=Index([0, 1], name="id")) tm.assert_series_equal(result, expected) + + +@td.skip_if_no("numba", "0.46.0") +def test_index_data_correctly_passed(): + # GH 43133 + def f(values, index): + return np.mean(index) + + df = DataFrame({"group": ["A", "A", "B"], "v": [4, 5, 6]}, index=[-1, -2, -3]) + result = df.groupby("group").aggregate(f, engine="numba") + expected = DataFrame( + [-1.5, -3.0], columns=["v"], index=Index(["A", "B"], name="group") + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index 8019071be72f3..b2d72aec0527f 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -164,3 +164,15 @@ def sum_last(values, index, n): result = grouped_x.transform(sum_last, 2, engine="numba") expected = Series([2.0] * 4, name="x") tm.assert_series_equal(result, expected) + + +@td.skip_if_no("numba", "0.46.0") +def test_index_data_correctly_passed(): + # GH 43133 + def f(values, index): + return index - 1 + + df = DataFrame({"group": ["A", "A", "B"], "v": [4, 5, 6]}, index=[-1, -2, -3]) + result = df.groupby("group").transform(f, engine="numba") + expected = DataFrame([-4.0, -3.0, -2.0], columns=["v"], index=[-1, -2, -3]) + tm.assert_frame_equal(result, expected)
Backport PR #43172: BUG: Pass index data correctly in groupby.transform/agg w/ engine=numba
https://api.github.com/repos/pandas-dev/pandas/pulls/43250
2021-08-27T13:52:52Z
2021-08-27T18:12:42Z
2021-08-27T18:12:42Z
2021-08-27T18:12:42Z
ENH: consistency of input args for boundaries in DataFrame.between_time() #40245
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 69ad20269319f..f19b0fe10fe6e 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -108,6 +108,7 @@ Other enhancements - Methods that relied on hashmap based algos such as :meth:`DataFrameGroupBy.value_counts`, :meth:`DataFrameGroupBy.count` and :func:`factorize` ignored imaginary component for complex numbers (:issue:`17927`) - Add :meth:`Series.str.removeprefix` and :meth:`Series.str.removesuffix` introduced in Python 3.9 to remove pre-/suffixes from string-type :class:`Series` (:issue:`36944`) + .. --------------------------------------------------------------------------- .. _whatsnew_140.notable_bug_fixes: @@ -278,6 +279,7 @@ Other Deprecations - Deprecated :meth:`Index.reindex` with a non-unique index (:issue:`42568`) - Deprecated :meth:`.Styler.render` in favour of :meth:`.Styler.to_html` (:issue:`42140`) - Deprecated passing in a string column label into ``times`` in :meth:`DataFrame.ewm` (:issue:`43265`) +- Deprecated the 'include_start' and 'include_end' arguments in :meth:`DataFrame.between_time`; in a future version passing 'include_start' or 'include_end' will raise (:issue:`40245`) - Deprecated the ``squeeze`` argument to :meth:`read_csv`, :meth:`read_table`, and :meth:`read_excel`. Users should squeeze the DataFrame afterwards with ``.squeeze("columns")`` instead. (:issue:`43242`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index b8485864704dd..67eb457ab93b1 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7606,8 +7606,9 @@ def between_time( self: FrameOrSeries, start_time, end_time, - include_start: bool_t = True, - include_end: bool_t = True, + include_start: bool_t | lib.NoDefault = lib.no_default, + include_end: bool_t | lib.NoDefault = lib.no_default, + inclusive: str | None = None, axis=None, ) -> FrameOrSeries: """ @@ -7624,8 +7625,20 @@ def between_time( End time as a time filter limit. include_start : bool, default True Whether the start time needs to be included in the result. + + .. deprecated:: 1.4.0 + Arguments `include_start` and `include_end` have been deprecated + to standardize boundary inputs. Use `inclusive` instead, to set + each bound as closed or open. include_end : bool, default True Whether the end time needs to be included in the result. + + .. deprecated:: 1.4.0 + Arguments `include_start` and `include_end` have been deprecated + to standardize boundary inputs. Use `inclusive` instead, to set + each bound as closed or open. + inclusive : {"both", "neither", "left", "right"}, default "both" + Include boundaries; whether to set each bound as closed or open. axis : {0 or 'index', 1 or 'columns'}, default 0 Determine range time on index or columns value. @@ -7679,8 +7692,46 @@ def between_time( if not isinstance(index, DatetimeIndex): raise TypeError("Index must be DatetimeIndex") + if (include_start != lib.no_default or include_end != lib.no_default) and ( + inclusive is not None + ): + raise ValueError( + "Deprecated arguments `include_start` and `include_end` " + "cannot be passed if `inclusive` has been given." + ) + # If any of the deprecated arguments ('include_start', 'include_end') + # have been passed + elif (include_start != lib.no_default) or (include_end != lib.no_default): + warnings.warn( + "`include_start` and `include_end` are deprecated in " + "favour of `inclusive`.", + FutureWarning, + stacklevel=2, + ) + left = True if isinstance(include_start, lib.NoDefault) else include_start + right = True if isinstance(include_end, lib.NoDefault) else include_end + + inc_dict = { + (True, True): "both", + (True, False): "left", + (False, True): "right", + (False, False): "neither", + } + inclusive = inc_dict[(left, right)] + else: # On arg removal inclusive can default to "both" + if inclusive is None: + inclusive = "both" + elif inclusive not in ["both", "neither", "left", "right"]: + raise ValueError( + f"Inclusive has to be either string of 'both', " + f"'left', 'right', or 'neither'. Got {inclusive}." + ) + indexer = index.indexer_between_time( - start_time, end_time, include_start=include_start, include_end=include_end + start_time, + end_time, + include_start=inclusive in ["both", "left"], + include_end=inclusive in ["both", "right"], ) return self._take_with_is_copy(indexer, axis=axis) diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py index 7d485ee62c7d2..92f81ff3a00fa 100644 --- a/pandas/tests/frame/conftest.py +++ b/pandas/tests/frame/conftest.py @@ -1,5 +1,3 @@ -from itertools import product - import numpy as np import pytest @@ -11,8 +9,8 @@ import pandas._testing as tm -@pytest.fixture(params=product([True, False], [True, False])) -def close_open_fixture(request): +@pytest.fixture(params=["both", "neither", "left", "right"]) +def inclusive_endpoints_fixture(request): return request.param diff --git a/pandas/tests/frame/methods/test_between_time.py b/pandas/tests/frame/methods/test_between_time.py index 0daa267767269..ae1aaaaf75d9b 100644 --- a/pandas/tests/frame/methods/test_between_time.py +++ b/pandas/tests/frame/methods/test_between_time.py @@ -69,7 +69,7 @@ def test_between_time_types(self, frame_or_series): with pytest.raises(ValueError, match=msg): obj.between_time(datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) - def test_between_time(self, close_open_fixture, frame_or_series): + def test_between_time(self, inclusive_endpoints_fixture, frame_or_series): rng = date_range("1/1/2000", "1/5/2000", freq="5min") ts = DataFrame(np.random.randn(len(rng), 2), index=rng) if frame_or_series is not DataFrame: @@ -77,24 +77,25 @@ def test_between_time(self, close_open_fixture, frame_or_series): stime = time(0, 0) etime = time(1, 0) - inc_start, inc_end = close_open_fixture + inclusive = inclusive_endpoints_fixture - filtered = ts.between_time(stime, etime, inc_start, inc_end) + filtered = ts.between_time(stime, etime, inclusive=inclusive) exp_len = 13 * 4 + 1 - if not inc_start: + + if inclusive in ["right", "neither"]: exp_len -= 5 - if not inc_end: + if inclusive in ["left", "neither"]: exp_len -= 4 assert len(filtered) == exp_len for rs in filtered.index: t = rs.time() - if inc_start: + if inclusive in ["left", "both"]: assert t >= stime else: assert t > stime - if inc_end: + if inclusive in ["right", "both"]: assert t <= etime else: assert t < etime @@ -111,22 +112,22 @@ def test_between_time(self, close_open_fixture, frame_or_series): stime = time(22, 0) etime = time(9, 0) - filtered = ts.between_time(stime, etime, inc_start, inc_end) + filtered = ts.between_time(stime, etime, inclusive=inclusive) exp_len = (12 * 11 + 1) * 4 + 1 - if not inc_start: + if inclusive in ["right", "neither"]: exp_len -= 4 - if not inc_end: + if inclusive in ["left", "neither"]: exp_len -= 4 assert len(filtered) == exp_len for rs in filtered.index: t = rs.time() - if inc_start: + if inclusive in ["left", "both"]: assert (t >= stime) or (t <= etime) else: assert (t > stime) or (t <= etime) - if inc_end: + if inclusive in ["right", "both"]: assert (t <= etime) or (t >= stime) else: assert (t < etime) or (t >= stime) @@ -207,3 +208,91 @@ def test_between_time_datetimeindex(self): tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result, expected2) assert len(result) == 12 + + @pytest.mark.parametrize("include_start", [True, False]) + @pytest.mark.parametrize("include_end", [True, False]) + def test_between_time_warn(self, include_start, include_end, frame_or_series): + # GH40245 + rng = date_range("1/1/2000", "1/5/2000", freq="5min") + ts = DataFrame(np.random.randn(len(rng), 2), index=rng) + if frame_or_series is not DataFrame: + ts = ts[0] + + stime = time(0, 0) + etime = time(1, 0) + + match = ( + "`include_start` and `include_end` " + "are deprecated in favour of `inclusive`." + ) + with tm.assert_produces_warning(FutureWarning, match=match): + _ = ts.between_time(stime, etime, include_start, include_end) + + def test_between_time_incorr_arg_inclusive(self): + # GH40245 + rng = date_range("1/1/2000", "1/5/2000", freq="5min") + ts = DataFrame(np.random.randn(len(rng), 2), index=rng) + + stime = time(0, 0) + etime = time(1, 0) + inclusive = "bad_string" + msg = ( + "Inclusive has to be either string of 'both', 'left', 'right', " + "or 'neither'. Got bad_string." + ) + with pytest.raises(ValueError, match=msg): + ts.between_time(stime, etime, inclusive=inclusive) + + @pytest.mark.parametrize( + "include_start, include_end", [(True, None), (True, True), (None, True)] + ) + def test_between_time_incompatiable_args_given(self, include_start, include_end): + # GH40245 + rng = date_range("1/1/2000", "1/5/2000", freq="5min") + ts = DataFrame(np.random.randn(len(rng), 2), index=rng) + + stime = time(0, 0) + etime = time(1, 0) + msg = ( + "Deprecated arguments `include_start` and `include_end` cannot be " + "passed if `inclusive` has been given." + ) + with pytest.raises(ValueError, match=msg): + ts.between_time(stime, etime, include_start, include_end, inclusive="left") + + def test_between_time_same_functionality_old_and_new_args(self): + # GH40245 + rng = date_range("1/1/2000", "1/5/2000", freq="5min") + ts = DataFrame(np.random.randn(len(rng), 2), index=rng) + stime = time(0, 0) + etime = time(1, 0) + match = ( + "`include_start` and `include_end` " + "are deprecated in favour of `inclusive`." + ) + + result = ts.between_time(stime, etime) + expected = ts.between_time(stime, etime, inclusive="both") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match=match): + result = ts.between_time(stime, etime, include_start=False) + expected = ts.between_time(stime, etime, inclusive="right") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match=match): + result = ts.between_time(stime, etime, include_end=False) + expected = ts.between_time(stime, etime, inclusive="left") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match=match): + result = ts.between_time( + stime, etime, include_start=False, include_end=False + ) + expected = ts.between_time(stime, etime, inclusive="neither") + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match=match): + result = ts.between_time(stime, etime, include_start=True, include_end=True) + expected = ts.between_time(stime, etime, inclusive="both") + tm.assert_frame_equal(result, expected)
- [ ] xref #40245 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/43248
2021-08-27T10:17:39Z
2021-09-10T17:17:38Z
2021-09-10T17:17:38Z
2021-09-27T11:39:31Z
DOC PR09 Add "." on to_hdf format parameter
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 4927f479ba905..11c63aba43aac 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2645,7 +2645,7 @@ def to_hdf( which may perform worse but allow more flexible operations like searching / selecting subsets of the data. - If None, pd.get_option('io.hdf.default_format') is checked, - followed by fallback to "fixed" + followed by fallback to "fixed". errors : str, default 'strict' Specifies how encoding and decoding errors are to be handled. See the errors argument for :func:`open` for a full list
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry From #28602: ``` pandas.Series.to_hdf: Parameter "format" description should finish with "." pandas.DataFrame.to_hdf: Parameter "format" description should finish with "." ```
https://api.github.com/repos/pandas-dev/pandas/pulls/43246
2021-08-27T08:03:16Z
2021-08-27T08:09:21Z
2021-08-27T08:09:21Z
2021-08-27T08:45:44Z
PERF: DataFrame._reduce
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e02a88aafcf34..6688150400aaa 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9824,26 +9824,28 @@ def _reduce( assert filter_type is None or filter_type == "bool", filter_type out_dtype = "bool" if filter_type == "bool" else None - own_dtypes = [arr.dtype for arr in self._iter_column_arrays()] + if numeric_only is None and name in ["mean", "median"]: + own_dtypes = [arr.dtype for arr in self._mgr.arrays] - dtype_is_dt = np.array( - [is_datetime64_any_dtype(dtype) for dtype in own_dtypes], - dtype=bool, - ) - if numeric_only is None and name in ["mean", "median"] and dtype_is_dt.any(): - warnings.warn( - "DataFrame.mean and DataFrame.median with numeric_only=None " - "will include datetime64 and datetime64tz columns in a " - "future version.", - FutureWarning, - stacklevel=5, + dtype_is_dt = np.array( + [is_datetime64_any_dtype(dtype) for dtype in own_dtypes], + dtype=bool, ) - # Non-copy equivalent to - # cols = self.columns[~dtype_is_dt] - # self = self[cols] - predicate = lambda x: not is_datetime64_any_dtype(x.dtype) - mgr = self._mgr._get_data_subset(predicate) - self = type(self)(mgr) + if dtype_is_dt.any(): + warnings.warn( + "DataFrame.mean and DataFrame.median with numeric_only=None " + "will include datetime64 and datetime64tz columns in a " + "future version.", + FutureWarning, + stacklevel=5, + ) + # Non-copy equivalent to + # dt64_cols = self.dtypes.apply(is_datetime64_any_dtype) + # cols = self.columns[~dt64_cols] + # self = self[cols] + predicate = lambda x: not is_datetime64_any_dtype(x.dtype) + mgr = self._mgr._get_data_subset(predicate) + self = type(self)(mgr) # TODO: Make other agg func handle axis=None properly GH#21597 axis = self._get_axis_number(axis)
``` from asv_bench.benchmarks.groupby import * self = GroupByMethods() self.setup("int", "skew", "direct", 2) %timeit self.time_dtype_as_group("int", "skew", "direct", 2) 434 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <- master 367 ms ± 8.51 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/43243
2021-08-27T02:53:03Z
2021-08-30T15:14:33Z
2021-08-30T15:14:33Z
2021-08-30T15:16:32Z
DOC: Update minimum pip version
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index e42ef334c60a4..20ae37c85a9d9 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -132,6 +132,9 @@ Installing from PyPI pandas can be installed via pip from `PyPI <https://pypi.org/project/pandas>`__. +.. note:: + You must have ``pip>=19.3`` to install from PyPI. + :: pip install pandas
- [ ] closes #42745 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/43241
2021-08-27T00:17:37Z
2021-08-27T13:51:09Z
2021-08-27T13:51:09Z
2021-08-27T15:28:49Z
ENH: Add Storage Options kwarg to read_table
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 205a49e7786a7..663b0a30aa48f 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -92,7 +92,7 @@ Other enhancements - :meth:`Series.sample`, :meth:`DataFrame.sample`, and :meth:`.GroupBy.sample` now accept a ``np.random.Generator`` as input to ``random_state``. A generator will be more performant, especially with ``replace=False`` (:issue:`38100`) - :meth:`Series.ewm`, :meth:`DataFrame.ewm`, now support a ``method`` argument with a ``'table'`` option that performs the windowing operation over an entire :class:`DataFrame`. See :ref:`Window Overview <window.overview>` for performance and functional benefits (:issue:`42273`) - :meth:`.GroupBy.cummin` and :meth:`.GroupBy.cummax` now support the argument ``skipna`` (:issue:`34047`) -- +- :meth:`read_table` now supports the argument ``storage_options`` (:issue:`39167`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index c639a4a9d494e..f1461e3b604a5 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -646,6 +646,7 @@ def read_table( escapechar=None, comment=None, encoding=None, + encoding_errors: str | None = "strict", dialect=None, # Error Handling error_bad_lines=None, @@ -653,12 +654,12 @@ def read_table( # TODO (2.0): set on_bad_lines to "error". # See _refine_defaults_read comment for why we do this. on_bad_lines=None, - encoding_errors: str | None = "strict", # Internal delim_whitespace=False, low_memory=_c_parser_defaults["low_memory"], memory_map=False, float_precision=None, + storage_options: StorageOptions = None, ): # locals() should never be modified kwds = locals().copy() diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py index eccfab3a31241..2e495b2bcec18 100644 --- a/pandas/tests/io/test_fsspec.py +++ b/pandas/tests/io/test_fsspec.py @@ -13,6 +13,7 @@ read_parquet, read_pickle, read_stata, + read_table, ) import pandas._testing as tm from pandas.util import _test_decorators as td @@ -122,6 +123,17 @@ def test_csv_options(fsspectest): assert fsspectest.test[0] == "csv_read" +def test_read_table_options(fsspectest): + # GH #39167 + df = DataFrame({"a": [0]}) + df.to_csv( + "testmem://test/test.csv", storage_options={"test": "csv_write"}, index=False + ) + assert fsspectest.test[0] == "csv_write" + read_table("testmem://test/test.csv", storage_options={"test": "csv_read"}) + assert fsspectest.test[0] == "csv_read" + + @pytest.mark.parametrize("extension", ["xlsx", "xls"]) def test_excel_options(fsspectest, extension): if extension == "xls":
- [x] closes #39167 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Follow up from https://github.com/pandas-dev/pandas/pull/35381 - looks like this was missed Not sure if this is an enhancements or a bug given the docs already mention this arg is supported. https://pandas.pydata.org/docs/reference/api/pandas.read_table.html
https://api.github.com/repos/pandas-dev/pandas/pulls/43239
2021-08-26T22:29:29Z
2021-08-31T13:13:23Z
2021-08-31T13:13:22Z
2021-08-31T13:13:23Z