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
REF: use cached inferred_type when calling lib.infer_dtype(index)
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index a312fdc6cda22..5256bdc988995 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1173,15 +1173,15 @@ cdef class Seen: or self.nat_) -cdef object _try_infer_map(object v): +cdef object _try_infer_map(object dtype): """ If its in our map, just return the dtype. """ cdef: object val str attr - for attr in ['name', 'kind', 'base']: - val = getattr(v.dtype, attr) + for attr in ["name", "kind", "base"]: + val = getattr(dtype, attr) if val in _TYPE_MAP: return _TYPE_MAP[val] return None @@ -1294,44 +1294,49 @@ def infer_dtype(value: object, skipna: bool = True) -> str: if util.is_array(value): values = value - elif hasattr(value, 'dtype'): + elif hasattr(value, "inferred_type") and skipna is False: + # Index, use the cached attribute if possible, populate the cache otherwise + return value.inferred_type + elif hasattr(value, "dtype"): # this will handle ndarray-like # e.g. categoricals - try: - values = getattr(value, '_values', getattr(value, 'values', value)) - except TypeError: - # This gets hit if we have an EA, since cython expects `values` - # to be an ndarray - value = _try_infer_map(value) + dtype = value.dtype + if not isinstance(dtype, np.dtype): + value = _try_infer_map(value.dtype) if value is not None: return value - # its ndarray like but we can't handle + # its ndarray-like but we can't handle raise ValueError(f"cannot infer type for {type(value)}") + # Unwrap Series/Index + values = np.asarray(value) + else: if not isinstance(value, list): value = list(value) + from pandas.core.dtypes.cast import ( construct_1d_object_array_from_listlike) values = construct_1d_object_array_from_listlike(value) # make contiguous - values = values.ravel() + # for f-contiguous array 1000 x 1000, passing order="K" gives 5000x speedup + values = values.ravel(order="K") - val = _try_infer_map(values) + val = _try_infer_map(values.dtype) if val is not None: return val if values.dtype != np.object_: - values = values.astype('O') + values = values.astype("O") if skipna: values = values[~isnaobj(values)] n = len(values) if n == 0: - return 'empty' + return "empty" # try to use a valid value for i in range(n): diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 69e9b77633b56..4bc5599297066 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1944,7 +1944,7 @@ def inferred_type(self) -> str_t: """ Return a string of the type inferred from the values. """ - return lib.infer_dtype(self, skipna=False) + return lib.infer_dtype(self._values, skipna=False) @cache_readonly def is_all_dates(self) -> bool:
Among other things, this will let us avoid a couple of ugly calls in Series ``` if isinstance(key, Index): key_type = key.inferred_type else: key_type = lib.infer_dtype(key, skipna=False) ``` Cleanup of nearby EA-handling code
https://api.github.com/repos/pandas-dev/pandas/pulls/33537
2020-04-14T01:30:47Z
2020-04-25T22:22:08Z
2020-04-25T22:22:08Z
2020-04-25T22:27:38Z
CI: pin cython==0.29.16 in npdev build
diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 29ebfe2639e32..17c3d318ce54d 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -14,7 +14,8 @@ dependencies: - pytz - pip - pip: - - cython>=0.29.16 + - cython==0.29.16 + # GH#33507 cython 3.0a1 is causing TypeErrors 2020-04-13 - "git+git://github.com/dateutil/dateutil.git" - "-f https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com" - "--pre"
xref #33507
https://api.github.com/repos/pandas-dev/pandas/pulls/33534
2020-04-13T22:07:32Z
2020-04-13T22:41:36Z
2020-04-13T22:41:36Z
2020-04-13T22:42:28Z
CLN: Change isocalendar to be a method
diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst index a09a5576ca378..6ba58310000cb 100644 --- a/doc/source/user_guide/timeseries.rst +++ b/doc/source/user_guide/timeseries.rst @@ -772,7 +772,6 @@ There are several time/date properties that one can access from ``Timestamp`` or week,"The week ordinal of the year" dayofweek,"The number of the day of the week with Monday=0, Sunday=6" weekday,"The number of the day of the week with Monday=0, Sunday=6" - isocalendar,"The ISO 8601 year, week and day of the date" quarter,"Quarter of the date: Jan-Mar = 1, Apr-Jun = 2, etc." days_in_month,"The number of days in the month of the datetime" is_month_start,"Logical indicating if first day of month (defined by frequency)" @@ -794,7 +793,7 @@ You may obtain the year, week and day components of the ISO year from the ISO 86 .. ipython:: python idx = pd.date_range(start='2019-12-29', freq='D', periods=4) - idx.to_series().dt.isocalendar + idx.to_series().dt.isocalendar() .. _timeseries.offsets: diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 2f4e961ff433f..d0e3e5c96dc3a 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -88,7 +88,7 @@ Other enhancements - :class:`Series.str` now has a `fullmatch` method that matches a regular expression against the entire string in each row of the series, similar to `re.fullmatch` (:issue:`32806`). - :meth:`DataFrame.sample` will now also allow array-like and BitGenerator objects to be passed to ``random_state`` as seeds (:issue:`32503`) - :meth:`MultiIndex.union` will now raise `RuntimeWarning` if the object inside are unsortable, pass `sort=False` to suppress this warning (:issue:`33015`) -- :class:`Series.dt` and :class:`DatatimeIndex` now have an `isocalendar` accessor that returns a :class:`DataFrame` with year, week, and day calculated according to the ISO 8601 calendar (:issue:`33206`). +- :class:`Series.dt` and :class:`DatatimeIndex` now have an `isocalendar` method that returns a :class:`DataFrame` with year, week, and day calculated according to the ISO 8601 calendar (:issue:`33206`). - The :meth:`DataFrame.to_feather` method now supports additional keyword arguments (e.g. to set the compression) that are added in pyarrow 0.17 (:issue:`33422`). diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 2ccc0ff2fa31d..f5cc0817e8bd7 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -183,7 +183,7 @@ class DatetimeArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps, dtl.DatelikeOps "microsecond", "nanosecond", ] - _other_ops = ["date", "time", "timetz", "isocalendar"] + _other_ops = ["date", "time", "timetz"] _datetimelike_ops = _field_ops + _object_ops + _bool_ops + _other_ops _datetimelike_methods = [ "to_period", @@ -1242,7 +1242,6 @@ def date(self): return tslib.ints_to_pydatetime(timestamps, box="date") - @property def isocalendar(self): """ Returns a DataFrame with the year, week, and day calculated according to @@ -1263,13 +1262,13 @@ def isocalendar(self): Examples -------- >>> idx = pd.date_range(start='2019-12-29', freq='D', periods=4) - >>> idx.isocalendar + >>> idx.isocalendar() year week day 0 2019 52 7 1 2020 1 1 2 2020 1 2 3 2020 1 3 - >>> idx.isocalendar.week + >>> idx.isocalendar().week 0 52 1 1 2 1 diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index d44fed9e097e7..e56de83d4dae4 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -219,7 +219,6 @@ def to_pydatetime(self) -> np.ndarray: def freq(self): return self._get_values().inferred_freq - @property def isocalendar(self): """ Returns a DataFrame with the year, week, and day calculated according to @@ -240,16 +239,16 @@ def isocalendar(self): Examples -------- >>> ser = pd.to_datetime(pd.Series(["2010-01-01", pd.NaT])) - >>> ser.dt.isocalendar + >>> ser.dt.isocalendar() year week day 0 2009 53 5 1 <NA> <NA> <NA> - >>> ser.dt.isocalendar.week + >>> ser.dt.isocalendar().week 0 53 1 <NA> Name: week, dtype: UInt32 """ - return self._get_values().isocalendar.set_index(self._parent.index) + return self._get_values().isocalendar().set_index(self._parent.index) @delegate_names( diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index 515e75b82371a..e903e850ec36c 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -49,6 +49,7 @@ def test_dt_namespace_accessor(self): "ceil", "day_name", "month_name", + "isocalendar", ] ok_for_td = TimedeltaIndex._datetimelike_ops ok_for_td_methods = [ @@ -678,7 +679,7 @@ def test_setitem_with_different_tz(self): ], ) def test_isocalendar(self, input_series, expected_output): - result = pd.to_datetime(pd.Series(input_series)).dt.isocalendar + result = pd.to_datetime(pd.Series(input_series)).dt.isocalendar() expected_frame = pd.DataFrame( expected_output, columns=["year", "week", "day"], dtype="UInt32" )
For consistency with `Timestamp.isocalendar`, `Series.dt.isocalendar` and `DatetimeIndex.isocalendar` should rather be methods and not attributes. Followup of #33220, see the discussions following the merge of that PR
https://api.github.com/repos/pandas-dev/pandas/pulls/33533
2020-04-13T19:58:13Z
2020-04-14T16:22:53Z
2020-04-14T16:22:53Z
2020-05-27T08:23:27Z
CLN: General cleanup in `_libs/lib.pyx`
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 6147d6d9c1658..bbb4d562b8971 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1,9 +1,6 @@ from collections import abc from decimal import Decimal -from fractions import Fraction -from numbers import Number -import sys import warnings import cython
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33532
2020-04-13T18:43:09Z
2020-04-14T00:07:12Z
2020-04-14T00:07:11Z
2021-05-03T12:28:31Z
REF: matching-dtype case first in concat_compat
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 301c9bb7b3f5c..0255c6507313a 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -105,7 +105,15 @@ def is_nonempty(x) -> bool: _contains_datetime = any(typ.startswith("datetime") for typ in typs) _contains_period = any(typ.startswith("period") for typ in typs) - if "category" in typs: + all_empty = not len(non_empties) + single_dtype = len({x.dtype for x in to_concat}) == 1 + any_ea = any(is_extension_array_dtype(x.dtype) for x in to_concat) + + if any_ea and single_dtype and axis == 0: + cls = type(to_concat[0]) + return cls._concat_same_type(to_concat) + + elif "category" in typs: # this must be prior to concat_datetime, # to support Categorical + datetime-like return concat_categorical(to_concat, axis=axis) @@ -117,18 +125,11 @@ def is_nonempty(x) -> bool: elif "sparse" in typs: return _concat_sparse(to_concat, axis=axis, typs=typs) - all_empty = not len(non_empties) - single_dtype = len({x.dtype for x in to_concat}) == 1 - any_ea = any(is_extension_array_dtype(x.dtype) for x in to_concat) - - if any_ea and axis == 1: + elif any_ea and axis == 1: to_concat = [np.atleast_2d(x.astype("object")) for x in to_concat] + return np.concatenate(to_concat, axis=axis) - elif any_ea and single_dtype and axis == 0: - cls = type(to_concat[0]) - return cls._concat_same_type(to_concat) - - if all_empty: + elif all_empty: # we have all empties, but may need to coerce the result dtype to # object if we have non-numeric type operands (numpy would otherwise # cast this to float) @@ -292,7 +293,7 @@ def union_categoricals( [b, c, a, b] Categories (3, object): [b, c, a] """ - from pandas import Index, Categorical + from pandas import Categorical from pandas.core.arrays.categorical import recode_for_categories if len(to_union) == 0: @@ -300,7 +301,7 @@ def union_categoricals( def _maybe_unwrap(x): if isinstance(x, (ABCCategoricalIndex, ABCSeries)): - return x.values + return x._values elif isinstance(x, Categorical): return x else: @@ -343,7 +344,7 @@ def _maybe_unwrap(x): elif ignore_order or all(not c.ordered for c in to_union): # different categories - union and recode cats = first.categories.append([c.categories for c in to_union[1:]]) - categories = Index(cats.unique()) + categories = cats.unique() if sort_categories: categories = categories.sort_values()
Moving towards clarifying the EA._concat_same_type behavior with unique vs non-unique dtypes
https://api.github.com/repos/pandas-dev/pandas/pulls/33530
2020-04-13T17:16:03Z
2020-04-17T02:41:56Z
2020-04-17T02:41:56Z
2020-04-17T02:55:53Z
CLN: .values->._values in hashing
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index d9c8611c94cdb..ebfba5a1e1ff6 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -90,13 +90,13 @@ def hash_pandas_object( return Series(hash_tuples(obj, encoding, hash_key), dtype="uint64", copy=False) elif isinstance(obj, ABCIndexClass): - h = hash_array(obj.values, encoding, hash_key, categorize).astype( + h = hash_array(obj._values, encoding, hash_key, categorize).astype( "uint64", copy=False ) h = Series(h, index=obj, dtype="uint64", copy=False) elif isinstance(obj, ABCSeries): - h = hash_array(obj.values, encoding, hash_key, categorize).astype( + h = hash_array(obj._values, encoding, hash_key, categorize).astype( "uint64", copy=False ) if index: @@ -107,7 +107,7 @@ def hash_pandas_object( encoding=encoding, hash_key=hash_key, categorize=categorize, - ).values + )._values for _ in [None] ) arrays = itertools.chain([h], index_iter) @@ -116,7 +116,7 @@ def hash_pandas_object( h = Series(h, index=obj.index, dtype="uint64", copy=False) elif isinstance(obj, ABCDataFrame): - hashes = (hash_array(series.values) for _, series in obj.items()) + hashes = (hash_array(series._values) for _, series in obj.items()) num_items = len(obj.columns) if index: index_hash_generator = ( @@ -126,7 +126,7 @@ def hash_pandas_object( encoding=encoding, hash_key=hash_key, categorize=categorize, - ).values # noqa + )._values for _ in [None] ) num_items += 1 @@ -185,28 +185,6 @@ def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key): return h -def hash_tuple(val, encoding: str = "utf8", hash_key: str = _default_hash_key): - """ - Hash a single tuple efficiently - - Parameters - ---------- - val : single tuple - encoding : str, default 'utf8' - hash_key : str, default _default_hash_key - - Returns - ------- - hash - - """ - hashes = (_hash_scalar(v, encoding=encoding, hash_key=hash_key) for v in val) - - h = _combine_hash_arrays(hashes, len(val))[0] - - return h - - def _hash_categorical(c, encoding: str, hash_key: str): """ Hash a Categorical by hashing its categories, and then mapping the codes @@ -223,7 +201,7 @@ def _hash_categorical(c, encoding: str, hash_key: str): ndarray of hashed values array, same size as len(c) """ # Convert ExtensionArrays to ndarrays - values = np.asarray(c.categories.values) + values = np.asarray(c.categories._values) hashed = hash_array(values, encoding, hash_key, categorize=False) # we have uint64, as we don't directly support missing values diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index 6411b9ab654f1..ff29df39e1871 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -1,12 +1,10 @@ -import datetime - import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series import pandas._testing as tm -from pandas.core.util.hashing import _hash_scalar, hash_tuple, hash_tuples +from pandas.core.util.hashing import hash_tuples from pandas.util import hash_array, hash_pandas_object @@ -111,46 +109,6 @@ def test_hash_tuples(): assert result == expected[0] -@pytest.mark.parametrize( - "tup", - [(1, "one"), (1, np.nan), (1.0, pd.NaT, "A"), ("A", pd.Timestamp("2012-01-01"))], -) -def test_hash_tuple(tup): - # Test equivalence between - # hash_tuples and hash_tuple. - result = hash_tuple(tup) - expected = hash_tuples([tup])[0] - - assert result == expected - - -@pytest.mark.parametrize( - "val", - [ - 1, - 1.4, - "A", - b"A", - pd.Timestamp("2012-01-01"), - pd.Timestamp("2012-01-01", tz="Europe/Brussels"), - datetime.datetime(2012, 1, 1), - pd.Timestamp("2012-01-01", tz="EST").to_pydatetime(), - pd.Timedelta("1 days"), - datetime.timedelta(1), - pd.Period("2012-01-01", freq="D"), - pd.Interval(0, 1), - np.nan, - pd.NaT, - None, - ], -) -def test_hash_scalar(val): - result = _hash_scalar(val) - expected = hash_array(np.array([val], dtype=object), categorize=True) - - assert result[0] == expected[0] - - @pytest.mark.parametrize("val", [5, "foo", pd.Timestamp("20130101")]) def test_hash_tuples_err(val): msg = "must be convertible to a list-of-tuples"
This sits on top of #33511 (at first thought it could be orthogonal, but this breaks a couple of hash_scalar tests if we dont rip those out first)
https://api.github.com/repos/pandas-dev/pandas/pulls/33529
2020-04-13T16:59:51Z
2020-04-15T01:28:13Z
2020-04-15T01:28:13Z
2020-04-15T01:35:22Z
REF: simplify concat_datetime
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 30a34282889f8..ece92acae6461 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -723,7 +723,7 @@ def take(self, indices, allow_fill=False, fill_value=None): return type(self)(new_values, dtype=self.dtype) @classmethod - def _concat_same_type(cls, to_concat): + def _concat_same_type(cls, to_concat, axis: int = 0): # do not pass tz to set because tzlocal cannot be hashed dtypes = {str(x.dtype) for x in to_concat} @@ -733,14 +733,15 @@ def _concat_same_type(cls, to_concat): obj = to_concat[0] dtype = obj.dtype - values = np.concatenate([x.asi8 for x in to_concat]) + i8values = [x.asi8 for x in to_concat] + values = np.concatenate(i8values, axis=axis) - if is_period_dtype(to_concat[0].dtype): + new_freq = None + if is_period_dtype(dtype): new_freq = obj.freq - else: + elif axis == 0: # GH 3232: If the concat result is evenly spaced, we can retain the # original frequency - new_freq = None to_concat = [x for x in to_concat if len(x)] if obj.freq is not None and all(x.freq == obj.freq for x in to_concat): diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 301c9bb7b3f5c..367cf25fe763b 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -4,11 +4,7 @@ import numpy as np -from pandas._libs import tslib, tslibs - from pandas.core.dtypes.common import ( - DT64NS_DTYPE, - TD64NS_DTYPE, is_bool_dtype, is_categorical_dtype, is_datetime64_dtype, @@ -19,13 +15,7 @@ is_sparse, is_timedelta64_dtype, ) -from pandas.core.dtypes.generic import ( - ABCCategoricalIndex, - ABCDatetimeArray, - ABCIndexClass, - ABCRangeIndex, - ABCSeries, -) +from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCRangeIndex, ABCSeries def get_dtype_kinds(l): @@ -390,70 +380,39 @@ def concat_datetime(to_concat, axis=0, typs=None): if typs is None: typs = get_dtype_kinds(to_concat) - # multiple types, need to coerce to object - if len(typs) != 1: - return _concatenate_2d( - [_convert_datetimelike_to_object(x) for x in to_concat], axis=axis - ) - - # must be single dtype - if any(typ.startswith("datetime") for typ in typs): - - if "datetime" in typs: - to_concat = [x.astype(np.int64, copy=False) for x in to_concat] - return _concatenate_2d(to_concat, axis=axis).view(DT64NS_DTYPE) - else: - # when to_concat has different tz, len(typs) > 1. - # thus no need to care - return _concat_datetimetz(to_concat) - - elif "timedelta" in typs: - return _concatenate_2d([x.view(np.int64) for x in to_concat], axis=axis).view( - TD64NS_DTYPE - ) - - elif any(typ.startswith("period") for typ in typs): - assert len(typs) == 1 - cls = to_concat[0] - new_values = cls._concat_same_type(to_concat) - return new_values - + to_concat = [_wrap_datetimelike(x) for x in to_concat] + single_dtype = len({x.dtype for x in to_concat}) == 1 -def _convert_datetimelike_to_object(x): - # coerce datetimelike array to object dtype + # multiple types, need to coerce to object + if not single_dtype: + # wrap_datetimelike ensures that astype(object) wraps in Timestamp/Timedelta + return _concatenate_2d([x.astype(object) for x in to_concat], axis=axis) - # if dtype is of datetimetz or timezone - if x.dtype.kind == DT64NS_DTYPE.kind: - if getattr(x, "tz", None) is not None: - x = np.asarray(x.astype(object)) - else: - shape = x.shape - x = tslib.ints_to_pydatetime(x.view(np.int64).ravel(), box="timestamp") - x = x.reshape(shape) + if axis == 1: + # TODO(EA2D): kludge not necessary with 2D EAs + to_concat = [x.reshape(1, -1) if x.ndim == 1 else x for x in to_concat] - elif x.dtype == TD64NS_DTYPE: - shape = x.shape - x = tslibs.ints_to_pytimedelta(x.view(np.int64).ravel(), box=True) - x = x.reshape(shape) + result = type(to_concat[0])._concat_same_type(to_concat, axis=axis) - return x + if result.ndim == 2 and is_extension_array_dtype(result.dtype): + # TODO(EA2D): kludge not necessary with 2D EAs + assert result.shape[0] == 1 + result = result[0] + return result -def _concat_datetimetz(to_concat, name=None): +def _wrap_datetimelike(arr): """ - concat DatetimeIndex with the same tz - all inputs must be DatetimeIndex - it is used in DatetimeIndex.append also + Wrap datetime64 and timedelta64 ndarrays in DatetimeArray/TimedeltaArray. + + DTA/TDA handle .astype(object) correctly. """ - # Right now, internals will pass a List[DatetimeArray] here - # for reductions like quantile. I would like to disentangle - # all this before we get here. - sample = to_concat[0] - - if isinstance(sample, ABCIndexClass): - return sample._concat_same_dtype(to_concat, name=name) - elif isinstance(sample, ABCDatetimeArray): - return sample._concat_same_type(to_concat) + from pandas.core.construction import array as pd_array, extract_array + + arr = extract_array(arr, extract_numpy=True) + if isinstance(arr, np.ndarray) and arr.dtype.kind in ["m", "M"]: + arr = pd_array(arr) + return arr def _concat_sparse(to_concat, axis=0, typs=None): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 25333b3a08dce..c15680a47d216 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -778,8 +778,8 @@ def _fast_union(self, other, sort=None): left, right = self, other left_start = left[0] loc = right.searchsorted(left_start, side="left") - right_chunk = right.values[:loc] - dates = concat_compat((left.values, right_chunk)) + right_chunk = right._values[:loc] + dates = concat_compat([left._values, right_chunk]) result = self._shallow_copy(dates) result._set_freq("infer") # TODO: can we infer that it has self.freq? @@ -793,8 +793,8 @@ def _fast_union(self, other, sort=None): # concatenate if left_end < right_end: loc = right.searchsorted(left_end, side="right") - right_chunk = right.values[loc:] - dates = concat_compat((left.values, right_chunk)) + right_chunk = right._values[loc:] + dates = concat_compat([left._values, right_chunk]) result = self._shallow_copy(dates) result._set_freq("infer") # TODO: can we infer that it has self.freq?
By wrapping dt64/td64 ndarrays in DTA/TDA, we can get rid of a bunch of .astype(object) logic
https://api.github.com/repos/pandas-dev/pandas/pulls/33526
2020-04-13T14:27:46Z
2020-04-15T01:32:20Z
2020-04-15T01:32:20Z
2020-04-15T01:36:43Z
TST: Add Categorical Series test
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 635b1a1cd1326..235aa8e4aa922 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -1098,6 +1098,14 @@ def test_min_max_ordered(self, values, categories, function): expected = categories[0] if function == "min" else categories[2] assert result == expected + @pytest.mark.parametrize("function", ["min", "max"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_min_max_ordered_with_nan_only(self, function, skipna): + # https://github.com/pandas-dev/pandas/issues/33450 + cat = Series(Categorical([np.nan], categories=[1, 2], ordered=True)) + result = getattr(cat, function)(skipna=skipna) + assert result is np.nan + @pytest.mark.parametrize("function", ["min", "max"]) @pytest.mark.parametrize("skipna", [True, False]) def test_min_max_skipna(self, function, skipna):
Follow up to https://github.com/pandas-dev/pandas/pull/33513 cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/33525
2020-04-13T14:20:13Z
2020-04-21T14:49:08Z
2020-04-21T14:49:08Z
2020-04-21T18:32:12Z
CLN: redundant code in IntegerArray._reduce
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 37620edfd9a95..5605b3fbc5dfa 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -571,10 +571,6 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): if np.isnan(result): return libmissing.NA - # if we have a boolean op, don't coerce - if name in ["any", "all"]: - pass - return result def _maybe_mask_result(self, result, mask, other, op_name: str):
https://api.github.com/repos/pandas-dev/pandas/pulls/33523
2020-04-13T13:03:07Z
2020-04-13T14:55:20Z
2020-04-13T14:55:20Z
2020-04-13T15:08:39Z
BUG: Fixed concat with reindex and extension types
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 567b6853bd633..0476c34db3773 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1073,6 +1073,7 @@ ExtensionArray ^^^^^^^^^^^^^^ - Fixed bug where :meth:`Series.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`) +- Fixed bug in :func:`concat` when concatenating DataFrames with non-overlaping columns resulting in object-dtype columns rather than preserving the extension dtype (:issue:`27692`, :issue:`33027`) - Fixed bug where :meth:`StringArray.isna` would return ``False`` for NA values when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`33655`) - Fixed bug in :class:`Series` construction with EA dtype and index but no data or scalar data fails (:issue:`26469`) - Fixed bug that caused :meth:`Series.__repr__()` to crash for extension types whose elements are multidimensional arrays (:issue:`33770`). diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index fd8c5f5e27c02..2cc7461986c8f 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -29,7 +29,7 @@ def concatenate_block_managers( - mgrs_indexers, axes, concat_axis: int, copy: bool + mgrs_indexers, axes, concat_axis: int, copy: bool, ) -> BlockManager: """ Concatenate block managers into one. @@ -76,7 +76,7 @@ def concatenate_block_managers( b = make_block(values, placement=placement, ndim=blk.ndim) else: b = make_block( - _concatenate_join_units(join_units, concat_axis, copy=copy), + _concatenate_join_units(join_units, concat_axis, copy=copy,), placement=placement, ) blocks.append(b) @@ -260,6 +260,16 @@ def get_reindexed_values(self, empty_dtype, upcasted_na): pass elif getattr(self.block, "is_extension", False): pass + elif is_extension_array_dtype(empty_dtype): + missing_arr = empty_dtype.construct_array_type()._from_sequence( + [], dtype=empty_dtype + ) + ncols, nrows = self.shape + assert ncols == 1, ncols + empty_arr = -1 * np.ones((nrows,), dtype=np.intp) + return missing_arr.take( + empty_arr, allow_fill=True, fill_value=fill_value + ) else: missing_arr = np.empty(self.shape, dtype=empty_dtype) missing_arr.fill(fill_value) @@ -329,7 +339,7 @@ def _concatenate_join_units(join_units, concat_axis, copy): # 2D to put it a non-EA Block concat_values = np.atleast_2d(concat_values) else: - concat_values = concat_compat(to_concat, axis=concat_axis) + concat_values = concat_compat(to_concat, axis=concat_axis,) return concat_values @@ -374,6 +384,10 @@ def _get_empty_dtype_and_na(join_units): upcast_cls = "category" elif is_datetime64tz_dtype(dtype): upcast_cls = "datetimetz" + + elif is_extension_array_dtype(dtype): + upcast_cls = "extension" + elif issubclass(dtype.type, np.bool_): upcast_cls = "bool" elif issubclass(dtype.type, np.object_): @@ -384,8 +398,6 @@ def _get_empty_dtype_and_na(join_units): upcast_cls = "timedelta" elif is_sparse(dtype): upcast_cls = dtype.subtype.name - elif is_extension_array_dtype(dtype): - upcast_cls = "object" elif is_float_dtype(dtype) or is_numeric_dtype(dtype): upcast_cls = dtype.name else: @@ -401,10 +413,15 @@ def _get_empty_dtype_and_na(join_units): if not upcast_classes: upcast_classes = null_upcast_classes - # TODO: de-duplicate with maybe_promote? # create the result - if "object" in upcast_classes: + if "extension" in upcast_classes: + if len(upcast_classes) == 1: + cls = upcast_classes["extension"][0] + return cls, cls.na_value + else: + return np.dtype("object"), np.nan + elif "object" in upcast_classes: return np.dtype(np.object_), np.nan elif "bool" in upcast_classes: if has_none_blocks: diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index db7e9265ac21d..3a7ad61694224 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -497,7 +497,7 @@ def get_result(self): mgrs_indexers.append((obj._mgr, indexers)) new_data = concatenate_block_managers( - mgrs_indexers, self.new_axes, concat_axis=self.bm_axis, copy=self.copy + mgrs_indexers, self.new_axes, concat_axis=self.bm_axis, copy=self.copy, ) if not self.copy: new_data._consolidate_inplace() diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index cd932e842e00c..3774e018a8e51 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -107,6 +107,19 @@ def test_concat_extension_arrays_copy_false(self, data, na_value): result = pd.concat([df1, df2], axis=1, copy=False) self.assert_frame_equal(result, expected) + def test_concat_with_reindex(self, data): + # GH-33027 + a = pd.DataFrame({"a": data[:5]}) + b = pd.DataFrame({"b": data[:5]}) + result = pd.concat([a, b], ignore_index=True) + expected = pd.DataFrame( + { + "a": data.take(list(range(5)) + ([-1] * 5), allow_fill=True), + "b": data.take(([-1] * 5) + list(range(5)), allow_fill=True), + } + ) + self.assert_frame_equal(result, expected) + def test_align(self, data, na_value): a = data[:3] b = data[2:5] diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index d1211e477fe3e..f7b572a70073a 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -93,7 +93,8 @@ class TestConstructors(base.BaseConstructorsTests): class TestReshaping(base.BaseReshapingTests): - pass + def test_concat_with_reindex(self, data): + pytest.xfail(reason="Deliberately upcast to object?") class TestGetitem(base.BaseGetitemTests):
Closes https://github.com/pandas-dev/pandas/issues/27692 Closes https://github.com/pandas-dev/pandas/issues/33027 I have a larger cleanup planned, but this fixes the linked issues for now.
https://api.github.com/repos/pandas-dev/pandas/pulls/33522
2020-04-13T11:35:47Z
2020-07-01T01:43:27Z
2020-07-01T01:43:26Z
2020-07-02T08:12:21Z
TYP: disallow decorator preserves function signature
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f8cb99e2b2e75..06b6d4242e622 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8522,6 +8522,12 @@ def idxmin(self, axis=0, skipna=True) -> Series: """ axis = self._get_axis_number(axis) indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna) + + # indices will always be np.ndarray since axis is not None and + # values is a 2d array for DataFrame + # error: Item "int" of "Union[int, Any]" has no attribute "__iter__" + assert isinstance(indices, np.ndarray) # for mypy + index = self._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return Series(result, index=self._get_agg_axis(axis)) @@ -8589,6 +8595,12 @@ def idxmax(self, axis=0, skipna=True) -> Series: """ axis = self._get_axis_number(axis) indices = nanops.nanargmax(self.values, axis=axis, skipna=skipna) + + # indices will always be np.ndarray since axis is not None and + # values is a 2d array for DataFrame + # error: Item "int" of "Union[int, Any]" has no attribute "__iter__" + assert isinstance(indices, np.ndarray) # for mypy + index = self._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return Series(result, index=self._get_agg_axis(axis)) diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 32b05872ded3f..d74a6ba605666 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -1,14 +1,14 @@ import functools import itertools import operator -from typing import Any, Optional, Tuple, Union +from typing import Any, Optional, Tuple, Union, cast import numpy as np from pandas._config import get_option from pandas._libs import NaT, Timedelta, Timestamp, iNaT, lib -from pandas._typing import ArrayLike, Dtype, Scalar +from pandas._typing import ArrayLike, Dtype, F, Scalar from pandas.compat._optional import import_optional_dependency from pandas.core.dtypes.cast import _int64_max, maybe_upcast_putmask @@ -57,7 +57,7 @@ def __init__(self, *dtypes): def check(self, obj) -> bool: return hasattr(obj, "dtype") and issubclass(obj.dtype.type, self.dtypes) - def __call__(self, f): + def __call__(self, f: F) -> F: @functools.wraps(f) def _f(*args, **kwargs): obj_iter = itertools.chain(args, kwargs.values()) @@ -78,7 +78,7 @@ def _f(*args, **kwargs): raise TypeError(e) from e raise - return _f + return cast(F, _f) class bottleneck_switch: @@ -878,7 +878,7 @@ def nanargmax( axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, -) -> int: +) -> Union[int, np.ndarray]: """ Parameters ---------- @@ -890,15 +890,25 @@ def nanargmax( Returns ------- - result : int - The index of max value in specified axis or -1 in the NA case + result : int or ndarray[int] + The index/indices of max value in specified axis or -1 in the NA case Examples -------- >>> import pandas.core.nanops as nanops - >>> s = pd.Series([1, 2, 3, np.nan, 4]) - >>> nanops.nanargmax(s) + >>> arr = np.array([1, 2, 3, np.nan, 4]) + >>> nanops.nanargmax(arr) 4 + + >>> arr = np.array(range(12), dtype=np.float64).reshape(4, 3) + >>> arr[2:, 2] = np.nan + >>> arr + array([[ 0., 1., 2.], + [ 3., 4., 5.], + [ 6., 7., nan], + [ 9., 10., nan]]) + >>> nanops.nanargmax(arr, axis=1) + array([2, 2, 1, 1], dtype=int64) """ values, mask, dtype, _, _ = _get_values( values, True, fill_value_typ="-inf", mask=mask @@ -914,7 +924,7 @@ def nanargmin( axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, -) -> int: +) -> Union[int, np.ndarray]: """ Parameters ---------- @@ -926,15 +936,25 @@ def nanargmin( Returns ------- - result : int - The index of min value in specified axis or -1 in the NA case + result : int or ndarray[int] + The index/indices of min value in specified axis or -1 in the NA case Examples -------- >>> import pandas.core.nanops as nanops - >>> s = pd.Series([1, 2, 3, np.nan, 4]) - >>> nanops.nanargmin(s) + >>> arr = np.array([1, 2, 3, np.nan, 4]) + >>> nanops.nanargmin(arr) 0 + + >>> arr = np.array(range(12), dtype=np.float64).reshape(4, 3) + >>> arr[2:, 0] = np.nan + >>> arr + array([[ 0., 1., 2.], + [ 3., 4., 5.], + [nan, 7., 8.], + [nan, 10., 11.]]) + >>> nanops.nanargmin(arr, axis=1) + array([0, 0, 1, 1], dtype=int64) """ values, mask, dtype, _, _ = _get_values( values, True, fill_value_typ="+inf", mask=mask
xref #33455
https://api.github.com/repos/pandas-dev/pandas/pulls/33521
2020-04-13T11:19:21Z
2020-05-02T16:30:23Z
2020-05-02T16:30:23Z
2020-05-02T18:00:27Z
TYP: remove assert mask is not None for mypy
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 9494248a423a8..b9ff0a5959c01 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -300,11 +300,8 @@ def _get_values( dtype, fill_value=fill_value, fill_value_typ=fill_value_typ ) - copy = (mask is not None) and (fill_value is not None) - - if skipna and copy: + if skipna and (mask is not None) and (fill_value is not None): values = values.copy() - assert mask is not None # for mypy if dtype_ok and mask.any(): np.putmask(values, mask, fill_value)
https://api.github.com/repos/pandas-dev/pandas/pulls/33520
2020-04-13T11:16:19Z
2020-04-14T17:28:46Z
2020-04-14T17:28:46Z
2020-04-14T19:31:22Z
BUG: Fix Categorical.min / max bug
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5fe7d12188860..2f4e961ff433f 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -397,6 +397,7 @@ Categorical - Bug where :class:`Categorical` comparison operator ``__ne__`` would incorrectly evaluate to ``False`` when either element was missing (:issue:`32276`) - :meth:`Categorical.fillna` now accepts :class:`Categorical` ``other`` argument (:issue:`32420`) - Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`) +- Bug where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`) Datetimelike ^^^^^^^^^^^^ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c9b8db28e0cf6..b3fb3459891e0 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2143,7 +2143,7 @@ def min(self, skipna=True): good = self._codes != -1 if not good.all(): - if skipna: + if skipna and good.any(): pointer = self._codes[good].min() else: return np.nan @@ -2178,7 +2178,7 @@ def max(self, skipna=True): good = self._codes != -1 if not good.all(): - if skipna: + if skipna and good.any(): pointer = self._codes[good].max() else: return np.nan diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index c470f677b5386..67b491165b8cc 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -88,6 +88,14 @@ def test_min_max_with_nan(self, skipna): assert _min == 2 assert _max == 1 + @pytest.mark.parametrize("function", ["min", "max"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_min_max_only_nan(self, function, skipna): + # https://github.com/pandas-dev/pandas/issues/33450 + cat = Categorical([np.nan], categories=[1, 2], ordered=True) + result = getattr(cat, function)(skipna=skipna) + assert result is np.nan + @pytest.mark.parametrize("method", ["min", "max"]) def test_deprecate_numeric_only_min_max(self, method): # GH 25303
- [ ] closes #33450 - [ ] 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/33513
2020-04-13T03:40:56Z
2020-04-13T08:16:59Z
2020-04-13T08:16:59Z
2020-05-05T09:07:23Z
TST/CLN: Clean categorical min / max tests
diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index 67b491165b8cc..83ecebafbea07 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -53,40 +53,28 @@ def test_min_max_ordered(self): @pytest.mark.parametrize("aggregation", ["min", "max"]) def test_min_max_ordered_empty(self, categories, expected, aggregation): # GH 30227 - cat = Categorical([], categories=list("ABC"), ordered=True) + cat = Categorical([], categories=categories, ordered=True) agg_func = getattr(cat, aggregation) result = agg_func() assert result is expected + @pytest.mark.parametrize( + "values, categories", + [(["a", "b", "c", np.nan], list("cba")), ([1, 2, 3, np.nan], [3, 2, 1])], + ) @pytest.mark.parametrize("skipna", [True, False]) - def test_min_max_with_nan(self, skipna): + @pytest.mark.parametrize("function", ["min", "max"]) + def test_min_max_with_nan(self, values, categories, function, skipna): # GH 25303 - cat = Categorical( - [np.nan, "b", "c", np.nan], categories=["d", "c", "b", "a"], ordered=True - ) - _min = cat.min(skipna=skipna) - _max = cat.max(skipna=skipna) - - if skipna is False: - assert np.isnan(_min) - assert np.isnan(_max) - else: - assert _min == "c" - assert _max == "b" - - cat = Categorical( - [np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True - ) - _min = cat.min(skipna=skipna) - _max = cat.max(skipna=skipna) + cat = Categorical(values, categories=categories, ordered=True) + result = getattr(cat, function)(skipna=skipna) if skipna is False: - assert np.isnan(_min) - assert np.isnan(_max) + assert result is np.nan else: - assert _min == 2 - assert _max == 1 + expected = categories[0] if function == "min" else categories[2] + assert result == expected @pytest.mark.parametrize("function", ["min", "max"]) @pytest.mark.parametrize("skipna", [True, False]) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index fa62d5d8c4983..635b1a1cd1326 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -1072,67 +1072,45 @@ class TestCategoricalSeriesReductions: # were moved from a series-specific test file, _not_ that these tests are # intended long-term to be series-specific - def test_min_max(self): + @pytest.mark.parametrize("function", ["min", "max"]) + def test_min_max_unordered_raises(self, function): # unordered cats have no min/max cat = Series(Categorical(["a", "b", "c", "d"], ordered=False)) - with pytest.raises(TypeError): - cat.min() - with pytest.raises(TypeError): - cat.max() - - cat = Series(Categorical(["a", "b", "c", "d"], ordered=True)) - _min = cat.min() - _max = cat.max() - assert _min == "a" - assert _max == "d" - - cat = Series( - Categorical( - ["a", "b", "c", "d"], categories=["d", "c", "b", "a"], ordered=True - ) - ) - _min = cat.min() - _max = cat.max() - assert _min == "d" - assert _max == "a" - - cat = Series( - Categorical( - [np.nan, "b", "c", np.nan], - categories=["d", "c", "b", "a"], - ordered=True, - ) - ) - _min = cat.min() - _max = cat.max() - assert _min == "c" - assert _max == "b" + msg = f"Categorical is not ordered for operation {function}" + with pytest.raises(TypeError, match=msg): + getattr(cat, function)() - cat = Series( - Categorical( - [np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True - ) - ) - _min = cat.min() - _max = cat.max() - assert _min == 2 - assert _max == 1 + @pytest.mark.parametrize( + "values, categories", + [ + (list("abc"), list("abc")), + (list("abc"), list("cba")), + (list("abc") + [np.nan], list("cba")), + ([1, 2, 3], [3, 2, 1]), + ([1, 2, 3, np.nan], [3, 2, 1]), + ], + ) + @pytest.mark.parametrize("function", ["min", "max"]) + def test_min_max_ordered(self, values, categories, function): + # GH 25303 + cat = Series(Categorical(values, categories=categories, ordered=True)) + result = getattr(cat, function)(skipna=True) + expected = categories[0] if function == "min" else categories[2] + assert result == expected + @pytest.mark.parametrize("function", ["min", "max"]) @pytest.mark.parametrize("skipna", [True, False]) - def test_min_max_skipna(self, skipna): - # GH 25303 + def test_min_max_skipna(self, function, skipna): cat = Series( Categorical(["a", "b", np.nan, "a"], categories=["b", "a"], ordered=True) ) - _min = cat.min(skipna=skipna) - _max = cat.max(skipna=skipna) + result = getattr(cat, function)(skipna=skipna) if skipna is True: - assert _min == "b" - assert _max == "a" + expected = "b" if function == "min" else "a" + assert result == expected else: - assert np.isnan(_min) - assert np.isnan(_max) + assert result is np.nan class TestSeriesMode:
Fixes one small error in a test, and otherwise tries to remove some code duplication
https://api.github.com/repos/pandas-dev/pandas/pulls/33512
2020-04-13T03:21:12Z
2020-04-14T17:26:28Z
2020-04-14T17:26:28Z
2020-04-14T17:58:58Z
CLN: remove unused util.hashing functions
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index d9c8611c94cdb..3406753a3b5ba 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -6,10 +6,8 @@ import numpy as np -from pandas._libs import Timestamp import pandas._libs.hashing as hashing -from pandas.core.dtypes.cast import infer_dtype_from_scalar from pandas.core.dtypes.common import ( is_categorical_dtype, is_extension_array_dtype, @@ -21,7 +19,6 @@ ABCMultiIndex, ABCSeries, ) -from pandas.core.dtypes.missing import isna # 16 byte long hashing key _default_hash_key = "0123456789123456" @@ -185,28 +182,6 @@ def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key): return h -def hash_tuple(val, encoding: str = "utf8", hash_key: str = _default_hash_key): - """ - Hash a single tuple efficiently - - Parameters - ---------- - val : single tuple - encoding : str, default 'utf8' - hash_key : str, default _default_hash_key - - Returns - ------- - hash - - """ - hashes = (_hash_scalar(v, encoding=encoding, hash_key=hash_key) for v in val) - - h = _combine_hash_arrays(hashes, len(val))[0] - - return h - - def _hash_categorical(c, encoding: str, hash_key: str): """ Hash a Categorical by hashing its categories, and then mapping the codes @@ -321,37 +296,3 @@ def hash_array( vals *= np.uint64(0x94D049BB133111EB) vals ^= vals >> 31 return vals - - -def _hash_scalar( - val, encoding: str = "utf8", hash_key: str = _default_hash_key -) -> np.ndarray: - """ - Hash scalar value. - - Parameters - ---------- - val : scalar - encoding : str, default "utf8" - hash_key : str, default _default_hash_key - - Returns - ------- - 1d uint64 numpy array of hash value, of length 1 - """ - if isna(val): - # this is to be consistent with the _hash_categorical implementation - return np.array([np.iinfo(np.uint64).max], dtype="u8") - - if getattr(val, "tzinfo", None) is not None: - # for tz-aware datetimes, we need the underlying naive UTC value and - # not the tz aware object or pd extension type (as - # infer_dtype_from_scalar would do) - if not isinstance(val, Timestamp): - val = Timestamp(val) - val = val.tz_convert(None) - - dtype, val = infer_dtype_from_scalar(val) - vals = np.array([val], dtype=dtype) - - return hash_array(vals, hash_key=hash_key, encoding=encoding, categorize=False) diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index 6411b9ab654f1..ff29df39e1871 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -1,12 +1,10 @@ -import datetime - import numpy as np import pytest import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series import pandas._testing as tm -from pandas.core.util.hashing import _hash_scalar, hash_tuple, hash_tuples +from pandas.core.util.hashing import hash_tuples from pandas.util import hash_array, hash_pandas_object @@ -111,46 +109,6 @@ def test_hash_tuples(): assert result == expected[0] -@pytest.mark.parametrize( - "tup", - [(1, "one"), (1, np.nan), (1.0, pd.NaT, "A"), ("A", pd.Timestamp("2012-01-01"))], -) -def test_hash_tuple(tup): - # Test equivalence between - # hash_tuples and hash_tuple. - result = hash_tuple(tup) - expected = hash_tuples([tup])[0] - - assert result == expected - - -@pytest.mark.parametrize( - "val", - [ - 1, - 1.4, - "A", - b"A", - pd.Timestamp("2012-01-01"), - pd.Timestamp("2012-01-01", tz="Europe/Brussels"), - datetime.datetime(2012, 1, 1), - pd.Timestamp("2012-01-01", tz="EST").to_pydatetime(), - pd.Timedelta("1 days"), - datetime.timedelta(1), - pd.Period("2012-01-01", freq="D"), - pd.Interval(0, 1), - np.nan, - pd.NaT, - None, - ], -) -def test_hash_scalar(val): - result = _hash_scalar(val) - expected = hash_array(np.array([val], dtype=object), categorize=True) - - assert result[0] == expected[0] - - @pytest.mark.parametrize("val", [5, "foo", pd.Timestamp("20130101")]) def test_hash_tuples_err(val): msg = "must be convertible to a list-of-tuples"
The only place where _any_ of util.hashing is used internally is in `CategoricalDtype.__hash__`. It's pretty ugly dependency-tree wise. This just prunes a couple of entirely unused functions.
https://api.github.com/repos/pandas-dev/pandas/pulls/33511
2020-04-13T03:06:31Z
2020-04-15T01:29:42Z
2020-04-15T01:29:41Z
2020-04-15T01:35:56Z
ENH: clearer error message if read_hdf loads upsupported HDF file (GH9539)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 0682e179a7640..8c745d01aba71 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -576,6 +576,8 @@ I/O - Bug in :meth:`read_excel` did not correctly handle multiple embedded spaces in OpenDocument text cells. (:issue:`32207`) - Bug in :meth:`read_json` was raising ``TypeError`` when reading a list of booleans into a Series. (:issue:`31464`) - Bug in :func:`pandas.io.json.json_normalize` where location specified by `record_path` doesn't point to an array. (:issue:`26284`) +- :func:`pandas.read_hdf` has a more explicit error message when loading an + unsupported HDF file (:issue:`9539`) Plotting ^^^^^^^^ diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 3dd87ae6ed758..425118694fa02 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -387,7 +387,10 @@ def read_hdf( if key is None: groups = store.groups() if len(groups) == 0: - raise ValueError("No dataset in HDF5 file.") + raise ValueError( + "Dataset(s) incompatible with Pandas data types, " + "not table, or no datasets found in HDF5 file." + ) candidate_only_group = groups[0] # For the HDF file to have only one dataset, all other groups diff --git a/pandas/tests/io/data/legacy_hdf/incompatible_dataset.h5 b/pandas/tests/io/data/legacy_hdf/incompatible_dataset.h5 new file mode 100644 index 0000000000000..50fbee0f5018b Binary files /dev/null and b/pandas/tests/io/data/legacy_hdf/incompatible_dataset.h5 differ diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 536f4aa760b9c..6b6ae8e5f0ca2 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -4776,3 +4776,14 @@ def test_to_hdf_multiindex_extension_dtype(self, idx, setup_path): with ensure_clean_path(setup_path) as path: with pytest.raises(NotImplementedError, match="Saving a MultiIndex"): df.to_hdf(path, "df") + + def test_unsuppored_hdf_file_error(self, datapath): + # GH 9539 + data_path = datapath("io", "data", "legacy_hdf/incompatible_dataset.h5") + message = ( + r"Dataset\(s\) incompatible with Pandas data types, " + "not table, or no datasets found in HDF5 file." + ) + + with pytest.raises(ValueError, match=message): + pd.read_hdf(data_path)
- [x] closes #9539 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry The error message changed since the original bug report but still could be made more clear.
https://api.github.com/repos/pandas-dev/pandas/pulls/33509
2020-04-13T00:37:04Z
2020-04-17T18:08:36Z
2020-04-17T18:08:36Z
2020-04-20T04:18:38Z
Added two tests for issue #29697
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 29d3bf302545e..a92e628960456 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -2024,6 +2024,36 @@ def test_merge_suffix(col1, col2, kwargs, expected_cols): tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize( + "how,expected", + [ + ( + "right", + DataFrame( + {"A": [100, 200, 300], "B1": [60, 70, np.nan], "B2": [600, 700, 800]} + ), + ), + ( + "outer", + DataFrame( + { + "A": [100, 200, 1, 300], + "B1": [60, 70, 80, np.nan], + "B2": [600, 700, np.nan, 800], + } + ), + ), + ], +) +def test_merge_duplicate_suffix(how, expected): + left_df = DataFrame({"A": [100, 200, 1], "B": [60, 70, 80]}) + right_df = DataFrame({"A": [100, 200, 300], "B": [600, 700, 800]}) + result = merge(left_df, right_df, on="A", how=how, suffixes=("_x", "_x")) + expected.columns = ["A", "B_x", "B_x"] + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( "col1, col2, suffixes", [
I added two basic tests for `merge` as requested in #29697, one for `how="outer"` and one for `how="right"`. I'm not sure if the way I'm creating duplicate columns for the `expected` dataframe is the recommended way but I could not find anything on this. Please let me know if there's a better way to do this. - [x] closes #29697 - [x] 2 tests added / 2 passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/33508
2020-04-13T00:28:11Z
2020-04-26T20:24:18Z
2020-04-26T20:24:17Z
2020-04-26T20:24:21Z
Removed xfail for issue #31883
diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 39049006edb7c..563a82395c7f3 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -408,10 +408,6 @@ def test_get_loc_nan(self, level, nulls_fixture): key = ["b", "d"] levels[level] = np.array([0, nulls_fixture], dtype=type(nulls_fixture)) key[level] = nulls_fixture - - if nulls_fixture is pd.NA: - pytest.xfail("MultiIndex from pd.NA in np.array broken; see GH 31883") - idx = MultiIndex.from_product(levels) assert idx.get_loc(tuple(key)) == 3
I removed the xfail in lines 412-414 as discussed in https://github.com/pandas-dev/pandas/issues/31883. - [x] closes #31883 - [x] 0 tests added / 0 passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/33506
2020-04-12T23:05:53Z
2020-04-14T15:00:53Z
2020-04-14T15:00:51Z
2020-04-14T15:01:00Z
CI: Setup 3.9 Travis Build
diff --git a/.travis.yml b/.travis.yml index 2c8533d02ddc1..98826a2d9e115 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,6 +27,11 @@ matrix: fast_finish: true include: + # In allowed failures + - dist: bionic + python: 3.9-dev + env: + - JOB="3.9-dev" PATTERN="(not slow and not network and not clipboard)" - env: - JOB="3.8" ENV_FILE="ci/deps/travis-38.yaml" PATTERN="(not slow and not network and not clipboard)" @@ -53,6 +58,11 @@ matrix: services: - mysql - postgresql + allow_failures: + - dist: bionic + python: 3.9-dev + env: + - JOB="3.9-dev" PATTERN="(not slow and not network)" before_install: - echo "before_install" @@ -83,7 +93,7 @@ install: script: - echo "script start" - echo "$JOB" - - source activate pandas-dev + - if [ "$JOB" != "3.9-dev" ]; then source activate pandas-dev; fi - ci/run_tests.sh after_script: diff --git a/ci/build39.sh b/ci/build39.sh new file mode 100755 index 0000000000000..f85e1c7def206 --- /dev/null +++ b/ci/build39.sh @@ -0,0 +1,21 @@ +#!/bin/bash -e +# Special build for python3.9 until numpy puts its own wheels up + +sudo apt-get install build-essential gcc xvfb +pip install --no-deps -U pip wheel setuptools +pip install python-dateutil pytz pytest pytest-xdist hypothesis +pip install cython --pre # https://github.com/cython/cython/issues/3395 + +git clone https://github.com/numpy/numpy +cd numpy +python setup.py build_ext --inplace +python setup.py install +cd .. +rm -rf numpy + +python setup.py build_ext -inplace +python -m pip install --no-build-isolation -e . + +python -c "import sys; print(sys.version_info)" +python -c "import pandas as pd" +python -c "import hypothesis" diff --git a/ci/setup_env.sh b/ci/setup_env.sh index 16bbd7693da37..76f47b7ed3634 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -1,5 +1,10 @@ #!/bin/bash -e +if [ "$JOB" == "3.9-dev" ]; then + /bin/bash ci/build39.sh + exit 0 +fi + # edit the locale file if needed if [[ "$(uname)" == "Linux" && -n "$LC_ALL" ]]; then echo "Adding locale to the first line of pandas/__init__.py" diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 6570e0782a69a..f7bb73b916ce0 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -16,6 +16,7 @@ PY37 = sys.version_info >= (3, 7) PY38 = sys.version_info >= (3, 8) +PY39 = sys.version_info >= (3, 9) PYPY = platform.python_implementation() == "PyPy" diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index 2d86ce275de7c..2114962cfc0bd 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -8,7 +8,7 @@ import pytest import pandas as pd -from pandas import NaT, Timedelta, Timestamp, _is_numpy_dev, offsets +from pandas import NaT, Timedelta, Timestamp, _is_numpy_dev, compat, offsets import pandas._testing as tm from pandas.core import ops @@ -422,7 +422,8 @@ def test_td_div_numeric_scalar(self): pytest.param( np.float64("NaN"), marks=pytest.mark.xfail( - _is_numpy_dev, + # Works on numpy dev only in python 3.9 + _is_numpy_dev and not compat.PY39, raises=RuntimeWarning, reason="https://github.com/pandas-dev/pandas/issues/31992", ),
- [x] closes https://github.com/pandas-dev/pandas/issues/33395 - In a very similar fashion to @jbrockmendel work for 3.8 - might be useful to have start a 3.9 build so we can start eliminating the issues @TomAugspurger mentioned in https://github.com/pandas-dev/pandas/issues/33395. This is using currently using `Python 3.9.0a5+` Currently failing with ``` ImportError while loading conftest '/home/travis/build/pandas-dev/pandas/pandas/conftest.py'. pandas/conftest.py:1123: in <module> ("period", [pd.Period(2013), pd.NaT, pd.Period(2018)]), pandas/_libs/tslibs/period.pyx:2470: in pandas._libs.tslibs.period.Period.__new__ freq = Resolution.get_freq(reso) pandas/_libs/tslibs/resolution.pyx:240: in pandas._libs.tslibs.resolution.Resolution.get_freq return cls._reso_freq_map[resostr] E AttributeError: type object 'type' has no attribute '_reso_freq_map' The command "ci/run_tests.sh" exited with 4. cache.2 store build cache ```
https://api.github.com/repos/pandas-dev/pandas/pulls/33505
2020-04-12T22:57:21Z
2020-05-09T23:26:57Z
2020-05-09T23:26:57Z
2020-05-10T01:01:13Z
ENH: Make Series.update() use objects coercible to Series
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 845f7773c263c..430c0913ee6ad 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -98,6 +98,8 @@ Other enhancements This can be used to set a custom compression level, e.g., ``df.to_csv(path, compression={'method': 'gzip', 'compresslevel': 1}`` (:issue:`33196`) +- :meth:`Series.update` now accepts objects that can be coerced to a :class:`Series`, + such as ``dict`` and ``list``, mirroring the behavior of :meth:`DataFrame.update` (:issue:`33215`) - :meth:`~pandas.core.groupby.GroupBy.transform` and :meth:`~pandas.core.groupby.GroupBy.aggregate` has gained ``engine`` and ``engine_kwargs`` arguments that supports executing functions with ``Numba`` (:issue:`32854`, :issue:`33388`) - :meth:`~pandas.core.resample.Resampler.interpolate` now supports SciPy interpolation method :class:`scipy.interpolate.CubicSpline` as method ``cubicspline`` (:issue:`33670`) - diff --git a/pandas/core/series.py b/pandas/core/series.py index 0de9da4c7f070..7c08fd0e67a8a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2786,7 +2786,7 @@ def update(self, other) -> None: Parameters ---------- - other : Series + other : Series, or object coercible into Series Examples -------- @@ -2824,7 +2824,30 @@ def update(self, other) -> None: 1 2 2 6 dtype: int64 + + ``other`` can also be a non-Series object type + that is coercible into a Series + + >>> s = pd.Series([1, 2, 3]) + >>> s.update([4, np.nan, 6]) + >>> s + 0 4 + 1 2 + 2 6 + dtype: int64 + + >>> s = pd.Series([1, 2, 3]) + >>> s.update({1: 9}) + >>> s + 0 1 + 1 9 + 2 3 + dtype: int64 """ + + if not isinstance(other, Series): + other = Series(other) + other = other.reindex_like(self) mask = notna(other) diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py index b7f5f33294792..98959599569a9 100644 --- a/pandas/tests/series/methods/test_update.py +++ b/pandas/tests/series/methods/test_update.py @@ -56,3 +56,21 @@ def test_update_dtypes(self, other, dtype, expected): ser.update(other) tm.assert_series_equal(ser, expected) + + @pytest.mark.parametrize( + "series, other, expected", + [ + # update by key + ( + Series({"a": 1, "b": 2, "c": 3, "d": 4}), + {"b": 5, "c": np.nan}, + Series({"a": 1, "b": 5, "c": 3, "d": 4}), + ), + # update by position + (Series([1, 2, 3, 4]), [np.nan, 5, 1], Series([1, 5, 1, 4])), + ], + ) + def test_update_from_non_series(self, series, other, expected): + # GH 33215 + series.update(other) + tm.assert_series_equal(series, expected)
- [x] closes #33215 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Allows `Series.update()` to accept objects that can be coerced into a `Series`, like a `dict`. This mirrors the existing behavior of `DataFrame.update()`.
https://api.github.com/repos/pandas-dev/pandas/pulls/33502
2020-04-12T19:48:56Z
2020-04-26T19:49:37Z
2020-04-26T19:49:37Z
2020-04-27T04:32:35Z
CLN: use _values_for_argsort in fewer places
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 62a3808d36ba2..9db9805e09b50 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -616,7 +616,7 @@ def factorize( values = _ensure_arraylike(values) original = values - if is_extension_array_dtype(values): + if is_extension_array_dtype(values.dtype): values = extract_array(values) codes, uniques = values.factorize(na_sentinel=na_sentinel) dtype = original.dtype diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index b3fb3459891e0..af07dee3b6838 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -370,7 +370,7 @@ def __init__( # we're inferring from values dtype = CategoricalDtype(categories, dtype.ordered) - elif is_categorical_dtype(values): + elif is_categorical_dtype(values.dtype): old_codes = ( values._values.codes if isinstance(values, ABCSeries) else values.codes ) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 530aaee24c7fb..97c1ea962ed0c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3597,12 +3597,8 @@ def _join_non_unique(self, other, how="left", return_indexers=False): # We only get here if dtypes match assert self.dtype == other.dtype - if is_extension_array_dtype(self.dtype): - lvalues = self._data._values_for_argsort() - rvalues = other._data._values_for_argsort() - else: - lvalues = self._values - rvalues = other._values + lvalues = self._get_engine_target() + rvalues = other._get_engine_target() left_idx, right_idx = _get_join_indexers( [lvalues], [rvalues], how=how, sort=True @@ -3774,12 +3770,8 @@ def _join_monotonic(self, other, how="left", return_indexers=False): else: return ret_index - if is_extension_array_dtype(self.dtype): - sv = self._data._values_for_argsort() - ov = other._data._values_for_argsort() - else: - sv = self._values - ov = other._values + sv = self._get_engine_target() + ov = other._get_engine_target() if self.is_unique and other.is_unique: # We can perform much better than the general case diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index c752990531b34..6e965ecea7cd8 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -232,6 +232,9 @@ def __array__(self, dtype=None) -> np.ndarray: return np.asarray(self._data, dtype=dtype) def _get_engine_target(self) -> np.ndarray: + # NB: _values_for_argsort happens to match the desired engine targets + # for all of our existing EA-backed indexes, but in general + # cannot be relied upon to exist. return self._data._values_for_argsort() @doc(Index.dropna)
https://api.github.com/repos/pandas-dev/pandas/pulls/33501
2020-04-12T19:22:19Z
2020-04-17T18:06:20Z
2020-04-17T18:06:20Z
2020-04-17T18:10:38Z
BUG: Fix a bug in 'timedelta_range' that produced an extra point on a edge case (fix #30353)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 95cb4ccbbb796..79f78471922bc 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -574,6 +574,9 @@ Timedelta - Timedeltas now understand ``µs`` as identifier for microsecond (:issue:`32899`) - :class:`Timedelta` string representation now includes nanoseconds, when nanoseconds are non-zero (:issue:`9309`) - Bug in comparing a :class:`Timedelta`` object against a ``np.ndarray`` with ``timedelta64`` dtype incorrectly viewing all entries as unequal (:issue:`33441`) +- Bug in :func:`timedelta_range` that produced an extra point on a edge case (:issue:`30353`, :issue:`33498`) +- Bug in :meth:`DataFrame.resample` that produced an extra point on a edge case (:issue:`30353`, :issue:`13022`, :issue:`33498`) +- Bug in :meth:`DataFrame.resample` that ignored the ``loffset`` argument when dealing with timedelta (:issue:`7687`, :issue:`33498`) Timezones ^^^^^^^^^ diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py index 471bfa736d4b9..3b090ca458d88 100644 --- a/pandas/core/arrays/_ranges.py +++ b/pandas/core/arrays/_ranges.py @@ -3,84 +3,71 @@ (and possibly TimedeltaArray/PeriodArray) """ -from typing import Tuple +from typing import Union import numpy as np -from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp +from pandas._libs.tslibs import OutOfBoundsDatetime, Timedelta, Timestamp -from pandas.tseries.offsets import DateOffset, Tick, generate_range +from pandas.tseries.offsets import DateOffset def generate_regular_range( - start: Timestamp, end: Timestamp, periods: int, freq: DateOffset -) -> Tuple[np.ndarray, str]: + start: Union[Timestamp, Timedelta], + end: Union[Timestamp, Timedelta], + periods: int, + freq: DateOffset, +): """ - Generate a range of dates with the spans between dates described by - the given `freq` DateOffset. + Generate a range of dates or timestamps with the spans between dates + described by the given `freq` DateOffset. Parameters ---------- - start : Timestamp or None - first point of produced date range - end : Timestamp or None - last point of produced date range + start : Timedelta, Timestamp or None + First point of produced date range. + end : Timedelta, Timestamp or None + Last point of produced date range. periods : int - number of periods in produced date range - freq : DateOffset - describes space between dates in produced date range + Number of periods in produced date range. + freq : Tick + Describes space between dates in produced date range. Returns ------- - ndarray[np.int64] representing nanosecond unix timestamps + ndarray[np.int64] Representing nanoseconds. """ - if isinstance(freq, Tick): - stride = freq.nanos - if periods is None: - b = Timestamp(start).value - # cannot just use e = Timestamp(end) + 1 because arange breaks when - # stride is too large, see GH10887 - e = b + (Timestamp(end).value - b) // stride * stride + stride // 2 + 1 - # end.tz == start.tz by this point due to _generate implementation - tz = start.tz - elif start is not None: - b = Timestamp(start).value - e = _generate_range_overflow_safe(b, periods, stride, side="start") - tz = start.tz - elif end is not None: - e = Timestamp(end).value + stride - b = _generate_range_overflow_safe(e, periods, stride, side="end") - tz = end.tz - else: - raise ValueError( - "at least 'start' or 'end' should be specified " - "if a 'period' is given." - ) - - with np.errstate(over="raise"): - # If the range is sufficiently large, np.arange may overflow - # and incorrectly return an empty array if not caught. - try: - values = np.arange(b, e, stride, dtype=np.int64) - except FloatingPointError: - xdr = [b] - while xdr[-1] != e: - xdr.append(xdr[-1] + stride) - values = np.array(xdr[:-1], dtype=np.int64) - + start = start.value if start is not None else None + end = end.value if end is not None else None + stride = freq.nanos + + if periods is None: + b = start + # cannot just use e = Timestamp(end) + 1 because arange breaks when + # stride is too large, see GH10887 + e = b + (end - b) // stride * stride + stride // 2 + 1 + elif start is not None: + b = start + e = _generate_range_overflow_safe(b, periods, stride, side="start") + elif end is not None: + e = end + stride + b = _generate_range_overflow_safe(e, periods, stride, side="end") else: - tz = None - # start and end should have the same timezone by this point - if start is not None: - tz = start.tz - elif end is not None: - tz = end.tz - - xdr = generate_range(start=start, end=end, periods=periods, offset=freq) - - values = np.array([x.value for x in xdr], dtype=np.int64) + raise ValueError( + "at least 'start' or 'end' should be specified if a 'period' is given." + ) - return values, tz + with np.errstate(over="raise"): + # If the range is sufficiently large, np.arange may overflow + # and incorrectly return an empty array if not caught. + try: + values = np.arange(b, e, stride, dtype=np.int64) + except FloatingPointError: + xdr = [b] + while xdr[-1] != e: + xdr.append(xdr[-1] + stride) + values = np.array(xdr[:-1], dtype=np.int64) + return values def _generate_range_overflow_safe( diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 8a1cacfe304ca..3134ffab2ea5a 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -48,7 +48,7 @@ import pandas.core.common as com from pandas.tseries.frequencies import get_period_alias, to_offset -from pandas.tseries.offsets import Day, Tick +from pandas.tseries.offsets import Day, Tick, generate_range _midnight = time(0, 0) @@ -370,33 +370,22 @@ def _generate_range( if end is not None: end = Timestamp(end) - if start is None and end is None: - if closed is not None: - raise ValueError( - "Closed has to be None if not both of start and end are defined" - ) if start is NaT or end is NaT: raise ValueError("Neither `start` nor `end` can be NaT") left_closed, right_closed = dtl.validate_endpoints(closed) - start, end, _normalized = _maybe_normalize_endpoints(start, end, normalize) - tz = _infer_tz_from_endpoints(start, end, tz) if tz is not None: # Localize the start and end arguments + start_tz = None if start is None else start.tz + end_tz = None if end is None else end.tz start = _maybe_localize_point( - start, - getattr(start, "tz", None), - start, - freq, - tz, - ambiguous, - nonexistent, + start, start_tz, start, freq, tz, ambiguous, nonexistent ) end = _maybe_localize_point( - end, getattr(end, "tz", None), end, freq, tz, ambiguous, nonexistent + end, end_tz, end, freq, tz, ambiguous, nonexistent ) if freq is not None: # We break Day arithmetic (fixed 24 hour) here and opt for @@ -408,7 +397,13 @@ def _generate_range( if end is not None: end = end.tz_localize(None) - values, _tz = generate_regular_range(start, end, periods, freq) + if isinstance(freq, Tick): + values = generate_regular_range(start, end, periods, freq) + else: + xdr = generate_range(start=start, end=end, periods=periods, offset=freq) + values = np.array([x.value for x in xdr], dtype=np.int64) + + _tz = start.tz if start is not None else end.tz index = cls._simple_new(values, freq=freq, dtype=tz_to_dtype(_tz)) if tz is not None and index.tz is None: diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index a62f94b1a3665..8cd4b874d10ee 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -33,6 +33,7 @@ from pandas.core import nanops from pandas.core.algorithms import checked_add_with_arr from pandas.core.arrays import datetimelike as dtl +from pandas.core.arrays._ranges import generate_regular_range import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.ops.common import unpack_zerodim_and_defer @@ -255,16 +256,10 @@ def _generate_range(cls, start, end, periods, freq, closed=None): if end is not None: end = Timedelta(end) - if start is None and end is None: - if closed is not None: - raise ValueError( - "Closed has to be None if not both of start and end are defined" - ) - left_closed, right_closed = dtl.validate_endpoints(closed) if freq is not None: - index = _generate_regular_range(start, end, periods, freq) + index = generate_regular_range(start, end, periods, freq) else: index = np.linspace(start.value, end.value, periods).astype("i8") if len(index) >= 2: @@ -1048,24 +1043,3 @@ def _validate_td64_dtype(dtype): raise ValueError(f"dtype {dtype} cannot be converted to timedelta64[ns]") return dtype - - -def _generate_regular_range(start, end, periods, offset): - stride = offset.nanos - if periods is None: - b = Timedelta(start).value - e = Timedelta(end).value - e += stride - e % stride - elif start is not None: - b = Timedelta(start).value - e = b + periods * stride - elif end is not None: - e = Timedelta(end).value + stride - b = e - periods * stride - else: - raise ValueError( - "at least 'start' or 'end' should be specified if a 'period' is given." - ) - - data = np.arange(b, e, stride, dtype=np.int64) - return data diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 06751d9c35fab..6d79ae070c103 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1499,9 +1499,12 @@ def _get_time_delta_bins(self, ax): end_stamps = labels + self.freq bins = ax.searchsorted(end_stamps, side="left") - # Addresses GH #10530 if self.base > 0: + # GH #10530 labels += type(self.freq)(self.base) + if self.loffset: + # GH #33498 + labels += self.loffset return binner, bins, labels diff --git a/pandas/tests/indexes/timedeltas/test_timedelta_range.py b/pandas/tests/indexes/timedeltas/test_timedelta_range.py index c07a6471c732f..7d78fbf9ff190 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta_range.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta_range.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from pandas import timedelta_range, to_timedelta +from pandas import Timedelta, timedelta_range, to_timedelta import pandas._testing as tm from pandas.tseries.offsets import Day, Second @@ -61,3 +61,21 @@ def test_errors(self): # too many params with pytest.raises(ValueError, match=msg): timedelta_range(start="0 days", end="5 days", periods=10, freq="H") + + @pytest.mark.parametrize( + "start, end, freq, expected_periods", + [ + ("1D", "10D", "2D", (10 - 1) // 2 + 1), + ("2D", "30D", "3D", (30 - 2) // 3 + 1), + ("2s", "50s", "5s", (50 - 2) // 5 + 1), + # tests that worked before GH 33498: + ("4D", "16D", "3D", (16 - 4) // 3 + 1), + ("8D", "16D", "40s", (16 * 3600 * 24 - 8 * 3600 * 24) // 40 + 1), + ], + ) + def test_timedelta_range_freq_divide_end(self, start, end, freq, expected_periods): + # GH 33498 only the cases where `(end % freq) == 0` used to fail + res = timedelta_range(start=start, end=end, freq=freq) + assert Timedelta(start) == res[0] + assert Timedelta(end) >= res[-1] + assert len(res) == expected_periods diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py index 6384c5f19c898..d0559923fec51 100644 --- a/pandas/tests/resample/test_base.py +++ b/pandas/tests/resample/test_base.py @@ -10,7 +10,7 @@ from pandas.core.groupby.grouper import Grouper 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.indexes.timedeltas import timedelta_range from pandas.core.resample import _asfreq_compat # a fixture value can be overridden by the test parameter value. Note that the @@ -182,7 +182,6 @@ def test_resample_size_empty_dataframe(freq, empty_frame_dti): @pytest.mark.parametrize("index", tm.all_timeseries_index_generator(0)) @pytest.mark.parametrize("dtype", [np.float, np.int, np.object, "datetime64[ns]"]) def test_resample_empty_dtypes(index, dtype, resample_method): - # Empty series were sometimes causing a segfault (for the functions # with Cython bounds-checking disabled) or an IndexError. We just run # them to ensure they no longer do. (GH #10228) @@ -215,13 +214,7 @@ def test_resample_loffset_arg_type(frame, create_index, arg): if isinstance(arg, list): expected.columns = pd.MultiIndex.from_tuples([("value", "mean")]) - # GH 13022, 7687 - TODO: fix resample w/ TimedeltaIndex - if isinstance(expected.index, TimedeltaIndex): - msg = "DataFrame are different" - with pytest.raises(AssertionError, match=msg): - tm.assert_frame_equal(result_agg, expected) - else: - tm.assert_frame_equal(result_agg, expected) + tm.assert_frame_equal(result_agg, expected) @all_ts diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py index 9fc355a45b656..1b4a625f078c9 100644 --- a/pandas/tests/resample/test_timedelta.py +++ b/pandas/tests/resample/test_timedelta.py @@ -1,6 +1,7 @@ from datetime import timedelta import numpy as np +import pytest import pandas as pd from pandas import DataFrame, Series @@ -114,10 +115,10 @@ def test_resample_timedelta_values(): # check that timedelta dtype is preserved when NaT values are # introduced by the resampling - times = timedelta_range("1 day", "4 day", freq="4D") + times = timedelta_range("1 day", "6 day", freq="4D") df = DataFrame({"time": times}, index=times) - times2 = timedelta_range("1 day", "4 day", freq="2D") + times2 = timedelta_range("1 day", "6 day", freq="2D") exp = Series(times2, index=times2, name="time") exp.iloc[1] = pd.NaT @@ -125,3 +126,28 @@ def test_resample_timedelta_values(): tm.assert_series_equal(res, exp) res = df["time"].resample("2D").first() tm.assert_series_equal(res, exp) + + +@pytest.mark.parametrize( + "start, end, freq, resample_freq", + [ + ("8H", "21h59min50s", "10S", "3H"), # GH 30353 example + ("3H", "22H", "1H", "5H"), + ("527D", "5006D", "3D", "10D"), + ("1D", "10D", "1D", "2D"), # GH 13022 example + # tests that worked before GH 33498: + ("8H", "21h59min50s", "10S", "2H"), + ("0H", "21h59min50s", "10S", "3H"), + ("10D", "85D", "D", "2D"), + ], +) +def test_resample_timedelta_edge_case(start, end, freq, resample_freq): + # GH 33498 + # check that the timedelta bins does not contains an extra bin + idx = pd.timedelta_range(start=start, end=end, freq=freq) + s = pd.Series(np.arange(len(idx)), index=idx) + result = s.resample(resample_freq).min() + expected_index = pd.timedelta_range(freq=resample_freq, start=start, end=end) + tm.assert_index_equal(result.index, expected_index) + assert result.index.freq == expected_index.freq + assert not np.isnan(result[-1])
The issue from #30353 came actually from `timedelta_range`. ```python import pandas as pd def mock_timedelta_range(start=None, end=None, periods=None, freq=None, name=None, closed=None): epoch = pd.Timestamp(0) if start is not None: start = epoch + pd.Timedelta(start) if end is not None: end = epoch + pd.Timedelta(end) res = pd.date_range(start=start, end=end, periods=periods, freq=freq, name=name, closed=closed) res -= epoch res.freq = freq return res print(mock_timedelta_range("1day", "10day", freq="2D")) print(pd.timedelta_range("1day", "10day", freq="2D")) ``` The outputs from `mock_timedelta_range` and from `pd.timedelta_range` are supposed to equivalent, but are not on pandas v1.0.0: Outputs without this PR: ``` TimedeltaIndex(['1 days', '3 days', '5 days', '7 days', '9 days'], dtype='timedelta64[ns]', freq='2D') TimedeltaIndex(['1 days', '3 days', '5 days', '7 days', '9 days', '11 days'], dtype='timedelta64[ns]', freq='2D') ``` Outputs with this PR: ``` TimedeltaIndex(['1 days', '3 days', '5 days', '7 days', '9 days'], dtype='timedelta64[ns]', freq='2D') TimedeltaIndex(['1 days', '3 days', '5 days', '7 days', '9 days'], dtype='timedelta64[ns]', freq='2D') ``` ---- It also solve an issue (that fail on master) related to this comment: https://github.com/pandas-dev/pandas/issues/13022#issuecomment-238382933 ```python import pandas as pd rng = pd.timedelta_range(start='1d', periods=10, freq='d') df = pd.Series(range(10), index=rng) df.resample('2D').count() ``` Outputs with this PR: ``` 1 days 2 3 days 2 5 days 2 7 days 2 9 days 2 Freq: 2D, dtype: int64 ``` ---- On the firsts commits I just fixed the issue in `_generate_regular_range`, then I decided to do a refactor and to use the same code that generate ranges in `core/arrays/_ranges.py` for `date_range` and `timedelta_range`. Linked with #10887. ---- - [X] closes #30353 closes #13022 closes #7687 (for loffset when resampling Timedelta) - [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/33498
2020-04-12T16:44:54Z
2020-05-09T19:23:30Z
2020-05-09T19:23:29Z
2020-05-09T20:41:27Z
CLN: assorted cleanups, annotations, de-privatizing
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 306636278bcbe..4c7d03d51e909 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -157,8 +157,8 @@ cdef _wrap_timedelta_result(result): """ if PyDelta_Check(result): # convert Timedelta back to a Tick - from pandas.tseries.offsets import _delta_to_tick - return _delta_to_tick(result) + from pandas.tseries.offsets import delta_to_tick + return delta_to_tick(result) return result diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 99d9d69d66ec2..2d9522b00627c 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -39,7 +39,7 @@ import pandas.core.common as com from pandas.tseries import frequencies -from pandas.tseries.offsets import DateOffset, Tick, _delta_to_tick +from pandas.tseries.offsets import DateOffset, Tick, delta_to_tick def _field_accessor(name: str, alias: int, docstring=None): @@ -487,7 +487,7 @@ def _time_shift(self, periods, freq=None): def _box_func(self): return lambda x: Period._from_ordinal(ordinal=x, freq=self.freq) - def asfreq(self, freq=None, how="E") -> "PeriodArray": + def asfreq(self, freq=None, how: str = "E") -> "PeriodArray": """ Convert the Period Array/Index to the specified frequency `freq`. @@ -759,7 +759,7 @@ def raise_on_incompatible(left, right): elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)): other_freq = right.freqstr else: - other_freq = _delta_to_tick(Timedelta(right)).freqstr + other_freq = delta_to_tick(Timedelta(right)).freqstr msg = DIFFERENT_FREQ.format( cls=type(left).__name__, own_freq=left.freqstr, other_freq=other_freq diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index d44fed9e097e7..e2477932e29e4 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -429,7 +429,6 @@ def __new__(cls, data: "Series"): # we need to choose which parent (datetime or timedelta) is # appropriate. Since we're checking the dtypes anyway, we'll just # do all the validation here. - from pandas import Series if not isinstance(data, ABCSeries): raise TypeError( @@ -438,7 +437,7 @@ def __new__(cls, data: "Series"): orig = data if is_categorical_dtype(data) else None if orig is not None: - data = Series( + data = data._constructor( orig.array, name=orig.name, copy=False, diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 1f565828ec7a5..eb01053aacad9 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -6,9 +6,8 @@ from pandas._libs import index as libindex from pandas._libs.lib import no_default -from pandas._libs.tslibs import frequencies as libfrequencies, resolution +from pandas._libs.tslibs import Period, frequencies as libfrequencies, resolution from pandas._libs.tslibs.parsing import parse_time_string -from pandas._libs.tslibs.period import Period from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender, cache_readonly, doc diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 765b948f13e96..083586645196d 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -29,16 +29,7 @@ @inherit_names( - [ - "_box_values", - "__neg__", - "__pos__", - "__abs__", - "total_seconds", - "round", - "floor", - "ceil", - ] + ["__neg__", "__pos__", "__abs__", "total_seconds", "round", "floor", "ceil"] + TimedeltaArray._field_ops, TimedeltaArray, wrap=True, diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 185b0f4da2627..1ffc6d6b60967 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -218,7 +218,7 @@ def get_block_values_for_json(self) -> np.ndarray: """ This is used in the JSON C code. """ - # TODO(2DEA): reshape will be unnecessary with 2D EAs + # TODO(EA2D): reshape will be unnecessary with 2D EAs return np.asarray(self.values).reshape(self.shape) @property @@ -353,6 +353,7 @@ def apply(self, func, **kwargs) -> List["Block"]: def _split_op_result(self, result) -> List["Block"]: # See also: split_and_operate if is_extension_array_dtype(result) and result.ndim > 1: + # TODO(EA2D): unnecessary with 2D EAs # if we get a 2D ExtensionArray, we need to split it into 1D pieces nbs = [] for i, loc in enumerate(self.mgr_locs): @@ -1560,7 +1561,7 @@ def __init__(self, values, placement, ndim=None): super().__init__(values, placement, ndim=ndim) if self.ndim == 2 and len(self.mgr_locs) != 1: - # TODO(2DEA): check unnecessary with 2D EAs + # TODO(EA2D): check unnecessary with 2D EAs raise AssertionError("block.size != values.size") @property @@ -2307,7 +2308,7 @@ def equals(self, other) -> bool: def quantile(self, qs, interpolation="linear", axis=0): naive = self.values.view("M8[ns]") - # kludge for 2D block with 1D values + # TODO(EA2D): kludge for 2D block with 1D values naive = naive.reshape(self.shape) blk = self.make_block(naive) @@ -2432,7 +2433,7 @@ def f(mask, val, idx): copy=copy, ) if isinstance(values, np.ndarray): - # TODO: allow EA once reshape is supported + # TODO(EA2D): allow EA once reshape is supported values = values.reshape(shape) return values diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 720e6799a3bf3..1cdfa07827d84 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -4,7 +4,7 @@ import numpy as np -from pandas._libs import internals as libinternals, tslibs +from pandas._libs import NaT, internals as libinternals from pandas.util._decorators import cache_readonly from pandas.core.dtypes.cast import maybe_promote @@ -395,7 +395,7 @@ def _get_empty_dtype_and_na(join_units): # GH-25014. We use NaT instead of iNaT, since this eventually # ends up in DatetimeArray.take, which does not allow iNaT. dtype = upcast_classes["datetimetz"] - return dtype[0], tslibs.NaT + return dtype[0], NaT elif "datetime" in upcast_classes: return np.dtype("M8[ns]"), np.datetime64("NaT", "ns") elif "timedelta" in upcast_classes: diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 1e93597d92a5d..bfef4f63e2e8a 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -323,7 +323,7 @@ def _gotitem(self, key, ndim: int, subset=None): Parameters ---------- key : string / list of selections - ndim : 1,2 + ndim : {1, 2} requested ndim of result subset : object, default None subset to act on diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index beb16c9549cc4..2c363ee82e5c1 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -313,7 +313,9 @@ def test_subtraction_ops(self): tm.assert_index_equal(result, expected, check_names=False) result = dti - td - expected = DatetimeIndex(["20121231", "20130101", "20130102"], name="bar") + expected = DatetimeIndex( + ["20121231", "20130101", "20130102"], freq="D", name="bar" + ) tm.assert_index_equal(result, expected, check_names=False) result = dt - tdi @@ -401,7 +403,9 @@ def _check(result, expected): _check(result, expected) result = dti_tz - td - expected = DatetimeIndex(["20121231", "20130101", "20130102"], tz="US/Eastern") + expected = DatetimeIndex( + ["20121231", "20130101", "20130102"], tz="US/Eastern", freq="D" + ) tm.assert_index_equal(result, expected) def test_dti_tdi_numeric_ops(self): diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index 1c54e2b988219..330c682216f53 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -186,11 +186,7 @@ def check_replace(to_rep, val, expected): check_replace(tr, v, e) # test an object with dates + floats + integers + strings - dr = ( - pd.date_range("1/1/2001", "1/10/2001", freq="D") - .to_series() - .reset_index(drop=True) - ) + dr = pd.Series(pd.date_range("1/1/2001", "1/10/2001", freq="D")) result = dr.astype(object).replace([dr[0], dr[1], dr[2]], [1.0, 2, "a"]) expected = pd.Series([1.0, 2, "a"] + dr[3:].tolist(), dtype=object) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py index 297e5c3178379..89f5f362e51f3 100644 --- a/pandas/tests/tseries/offsets/test_ticks.py +++ b/pandas/tests/tseries/offsets/test_ticks.py @@ -33,11 +33,11 @@ def test_apply_ticks(): def test_delta_to_tick(): delta = timedelta(3) - tick = offsets._delta_to_tick(delta) + tick = offsets.delta_to_tick(delta) assert tick == offsets.Day(3) td = Timedelta(nanoseconds=5) - tick = offsets._delta_to_tick(td) + tick = offsets.delta_to_tick(td) assert tick == Nano(5) diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index bc20d784c8dee..8ba10f56f163c 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -2548,7 +2548,7 @@ def __add__(self, other): if type(self) == type(other): return type(self)(self.n + other.n) else: - return _delta_to_tick(self.delta + other.delta) + return delta_to_tick(self.delta + other.delta) elif isinstance(other, Period): return other + self try: @@ -2635,7 +2635,7 @@ def is_anchored(self) -> bool: return False -def _delta_to_tick(delta: timedelta) -> Tick: +def delta_to_tick(delta: timedelta) -> Tick: if delta.microseconds == 0 and getattr(delta, "nanoseconds", 0) == 0: # nanoseconds only for pd.Timedelta if delta.seconds == 0:
https://api.github.com/repos/pandas-dev/pandas/pulls/33497
2020-04-12T16:33:55Z
2020-04-17T02:47:40Z
2020-04-17T02:47:40Z
2020-04-17T02:53:56Z
CLN: remove ensure_categorical
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index b2301ab0190c7..cf00535385c24 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -111,27 +111,6 @@ def ensure_str(value: Union[bytes, Any]) -> str: return value -def ensure_categorical(arr): - """ - Ensure that an array-like object is a Categorical (if not already). - - Parameters - ---------- - arr : array-like - The array that we want to convert into a Categorical. - - Returns - ------- - cat_arr : The original array cast as a Categorical. If it already - is a Categorical, we return as is. - """ - if not is_categorical_dtype(arr.dtype): - from pandas import Categorical - - arr = Categorical(arr) - return arr - - def ensure_int_or_float(arr: ArrayLike, copy: bool = False) -> np.array: """ Ensure that an dtype array of some integer dtype diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 9bd098d1d49a3..235b3113a2ae7 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -11,7 +11,6 @@ from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import ( - ensure_categorical, is_categorical_dtype, is_datetime64_dtype, is_list_like, @@ -418,7 +417,7 @@ def indices(self): if isinstance(self.grouper, ops.BaseGrouper): return self.grouper.indices - values = ensure_categorical(self.grouper) + values = Categorical(self.grouper) return values._reverse_indexer() @property diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 530aaee24c7fb..a91757fc45c9d 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -24,7 +24,6 @@ validate_numeric_casting, ) from pandas.core.dtypes.common import ( - ensure_categorical, ensure_int64, ensure_object, ensure_platform_int, @@ -68,7 +67,7 @@ from pandas.core import ops from pandas.core.accessor import CachedAccessor import pandas.core.algorithms as algos -from pandas.core.arrays import ExtensionArray +from pandas.core.arrays import Categorical, ExtensionArray from pandas.core.arrays.datetimes import tz_to_dtype, validate_tz_from_dtype from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com @@ -4727,8 +4726,8 @@ def groupby(self, values) -> PrettyDict[Hashable, np.ndarray]: # TODO: if we are a MultiIndex, we can do better # that converting to tuples if isinstance(values, ABCMultiIndex): - values = values.values - values = ensure_categorical(values) + values = values._values + values = Categorical(values) result = values._reverse_indexer() # map to the label diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 82d6b1df19393..3d58df258e8e9 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -21,7 +21,6 @@ from pandas.core.dtypes import inference from pandas.core.dtypes.common import ( - ensure_categorical, ensure_int32, is_bool, is_datetime64_any_dtype, @@ -1502,13 +1501,3 @@ def test_ensure_int32(): values = np.arange(10, dtype=np.int64) result = ensure_int32(values) assert result.dtype == np.int32 - - -def test_ensure_categorical(): - values = np.arange(10, dtype=np.int32) - result = ensure_categorical(values) - assert result.dtype == "category" - - values = Categorical(values) - result = ensure_categorical(values) - tm.assert_categorical_equal(result, values)
only used in two places, its a misnomer because it really only ensures categorical dtype, and it complicates the dependency structure
https://api.github.com/repos/pandas-dev/pandas/pulls/33495
2020-04-12T15:56:39Z
2020-04-17T02:48:49Z
2020-04-17T02:48:49Z
2020-04-17T02:55:17Z
BUG: groupby.hist legend should use group keys
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 567b6853bd633..22b83425b58c2 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -292,6 +292,7 @@ Other enhancements - :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` now accept an ``errors`` argument (:issue:`22610`) - :meth:`groupby.transform` now allows ``func`` to be ``pad``, ``backfill`` and ``cumcount`` (:issue:`31269`). - :meth:`~pandas.io.json.read_json` now accepts `nrows` parameter. (:issue:`33916`). +- :meth:`DataFrame.hist`, :meth:`Series.hist`, :meth:`core.groupby.DataFrameGroupBy.hist`, and :meth:`core.groupby.SeriesGroupBy.hist` have gained the ``legend`` argument. Set to True to show a legend in the histogram. (:issue:`6279`) - :func:`concat` and :meth:`~DataFrame.append` now preserve extension dtypes, for example combining a nullable integer column with a numpy integer column will no longer result in object dtype but preserve the integer dtype (:issue:`33607`, :issue:`34339`). diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 32cd89383dde9..4f5b7b2d7a888 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -1,7 +1,9 @@ import importlib +from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union from pandas._config import get_option +from pandas._typing import Label from pandas.util._decorators import Appender, Substitution from pandas.core.dtypes.common import is_integer, is_list_like @@ -9,19 +11,23 @@ from pandas.core.base import PandasObject +if TYPE_CHECKING: + from pandas import DataFrame + def hist_series( self, by=None, ax=None, - grid=True, - xlabelsize=None, - xrot=None, - ylabelsize=None, - yrot=None, - figsize=None, - bins=10, - backend=None, + grid: bool = True, + xlabelsize: Optional[int] = None, + xrot: Optional[float] = None, + ylabelsize: Optional[int] = None, + yrot: Optional[float] = None, + figsize: Optional[Tuple[int, int]] = None, + bins: Union[int, Sequence[int]] = 10, + backend: Optional[str] = None, + legend: bool = False, **kwargs, ): """ @@ -58,6 +64,11 @@ def hist_series( .. versionadded:: 1.0.0 + legend : bool, default False + Whether to show the legend. + + ..versionadded:: 1.1.0 + **kwargs To be passed to the actual plotting function. @@ -82,26 +93,28 @@ def hist_series( yrot=yrot, figsize=figsize, bins=bins, + legend=legend, **kwargs, ) def hist_frame( - data, - column=None, + data: "DataFrame", + column: Union[Label, Sequence[Label]] = None, by=None, - grid=True, - xlabelsize=None, - xrot=None, - ylabelsize=None, - yrot=None, + grid: bool = True, + xlabelsize: Optional[int] = None, + xrot: Optional[float] = None, + ylabelsize: Optional[int] = None, + yrot: Optional[float] = None, ax=None, - sharex=False, - sharey=False, - figsize=None, - layout=None, - bins=10, - backend=None, + sharex: bool = False, + sharey: bool = False, + figsize: Optional[Tuple[int, int]] = None, + layout: Optional[Tuple[int, int]] = None, + bins: Union[int, Sequence[int]] = 10, + backend: Optional[str] = None, + legend: bool = False, **kwargs, ): """ @@ -154,6 +167,7 @@ def hist_frame( bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. + backend : str, default None Backend to use instead of the backend specified in the option ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to @@ -162,6 +176,11 @@ def hist_frame( .. versionadded:: 1.0.0 + legend : bool, default False + Whether to show the legend. + + ..versionadded:: 1.1.0 + **kwargs All other plotting keyword arguments to be passed to :meth:`matplotlib.pyplot.hist`. @@ -203,6 +222,7 @@ def hist_frame( sharey=sharey, figsize=figsize, layout=layout, + legend=legend, bins=bins, **kwargs, ) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index b0ce43dc2eb36..ee41479b3c7c9 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -225,6 +225,7 @@ def _grouped_hist( xrot=None, ylabelsize=None, yrot=None, + legend=False, **kwargs, ): """ @@ -243,15 +244,26 @@ def _grouped_hist( sharey : bool, default False rot : int, default 90 grid : bool, default True + legend: : bool, default False kwargs : dict, keyword arguments passed to matplotlib.Axes.hist Returns ------- collection of Matplotlib Axes """ + if legend: + assert "label" not in kwargs + if data.ndim == 1: + kwargs["label"] = data.name + elif column is None: + kwargs["label"] = data.columns + else: + kwargs["label"] = column def plot_group(group, ax): ax.hist(group.dropna().values, bins=bins, **kwargs) + if legend: + ax.legend() if xrot is None: xrot = rot @@ -290,10 +302,14 @@ def hist_series( yrot=None, figsize=None, bins=10, + legend: bool = False, **kwds, ): import matplotlib.pyplot as plt + if legend and "label" in kwds: + raise ValueError("Cannot use both legend and label") + if by is None: if kwds.get("layout", None) is not None: raise ValueError("The 'layout' keyword is not supported when 'by' is None") @@ -308,8 +324,11 @@ def hist_series( elif ax.get_figure() != fig: raise AssertionError("passed axis not bound to passed figure") values = self.dropna().values - + if legend: + kwds["label"] = self.name ax.hist(values, bins=bins, **kwds) + if legend: + ax.legend() ax.grid(grid) axes = np.array([ax]) @@ -334,6 +353,7 @@ def hist_series( xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, + legend=legend, **kwds, ) @@ -358,8 +378,11 @@ def hist_frame( figsize=None, layout=None, bins=10, + legend: bool = False, **kwds, ): + if legend and "label" in kwds: + raise ValueError("Cannot use both legend and label") if by is not None: axes = _grouped_hist( data, @@ -376,6 +399,7 @@ def hist_frame( xrot=xrot, ylabelsize=ylabelsize, yrot=yrot, + legend=legend, **kwds, ) return axes @@ -401,11 +425,17 @@ def hist_frame( ) _axes = _flatten(axes) + can_set_label = "label" not in kwds + for i, col in enumerate(data.columns): ax = _axes[i] + if legend and can_set_label: + kwds["label"] = col ax.hist(data[col].dropna().values, bins=bins, **kwds) ax.set_title(col) ax.grid(grid) + if legend: + ax.legend() _set_ticks_props( axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py index 238639bd3732d..4ac23c2cffa15 100644 --- a/pandas/tests/plotting/test_groupby.py +++ b/pandas/tests/plotting/test_groupby.py @@ -2,10 +2,11 @@ import numpy as np +import pytest import pandas.util._test_decorators as td -from pandas import DataFrame, Series +from pandas import DataFrame, Index, Series import pandas._testing as tm from pandas.tests.plotting.common import TestPlotBase @@ -65,3 +66,49 @@ def test_plot_kwargs(self): res = df.groupby("z").plot.scatter(x="x", y="y") assert len(res["a"].collections) == 1 + + @pytest.mark.parametrize("column, expected_axes_num", [(None, 2), ("b", 1)]) + def test_groupby_hist_frame_with_legend(self, column, expected_axes_num): + # GH 6279 - DataFrameGroupBy histogram can have a legend + expected_layout = (1, expected_axes_num) + expected_labels = column or [["a"], ["b"]] + + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"]) + g = df.groupby("c") + + for axes in g.hist(legend=True, column=column): + self._check_axes_shape( + axes, axes_num=expected_axes_num, layout=expected_layout + ) + for ax, expected_label in zip(axes[0], expected_labels): + self._check_legend_labels(ax, expected_label) + + @pytest.mark.parametrize("column", [None, "b"]) + def test_groupby_hist_frame_with_legend_raises(self, column): + # GH 6279 - DataFrameGroupBy histogram with legend and label raises + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"]) + g = df.groupby("c") + + with pytest.raises(ValueError, match="Cannot use both legend and label"): + g.hist(legend=True, column=column, label="d") + + def test_groupby_hist_series_with_legend(self): + # GH 6279 - SeriesGroupBy histogram can have a legend + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"]) + g = df.groupby("c") + + for ax in g["a"].hist(legend=True): + self._check_axes_shape(ax, axes_num=1, layout=(1, 1)) + self._check_legend_labels(ax, ["1", "2"]) + + def test_groupby_hist_series_with_legend_raises(self): + # GH 6279 - SeriesGroupBy histogram with legend and label raises + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"]) + g = df.groupby("c") + + with pytest.raises(ValueError, match="Cannot use both legend and label"): + g.hist(legend=True, label="d") diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index 0d3425d001229..b6a6c326c3df3 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -6,7 +6,7 @@ import pandas.util._test_decorators as td -from pandas import DataFrame, Series +from pandas import DataFrame, Index, Series import pandas._testing as tm from pandas.tests.plotting.common import TestPlotBase, _check_plot_works @@ -129,6 +129,29 @@ def test_plot_fails_when_ax_differs_from_figure(self): with pytest.raises(AssertionError): self.ts.hist(ax=ax1, figure=fig2) + @pytest.mark.parametrize( + "by, expected_axes_num, expected_layout", [(None, 1, (1, 1)), ("b", 2, (1, 2))] + ) + def test_hist_with_legend(self, by, expected_axes_num, expected_layout): + # GH 6279 - Series histogram can have a legend + index = 15 * ["1"] + 15 * ["2"] + s = Series(np.random.randn(30), index=index, name="a") + s.index.name = "b" + + axes = _check_plot_works(s.hist, legend=True, by=by) + self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) + self._check_legend_labels(axes, "a") + + @pytest.mark.parametrize("by", [None, "b"]) + def test_hist_with_legend_raises(self, by): + # GH 6279 - Series histogram with legend and label raises + index = 15 * ["1"] + 15 * ["2"] + s = Series(np.random.randn(30), index=index, name="a") + s.index.name = "b" + + with pytest.raises(ValueError, match="Cannot use both legend and label"): + s.hist(legend=True, by=by, label="c") + @td.skip_if_no_mpl class TestDataFramePlots(TestPlotBase): @@ -293,6 +316,36 @@ def test_hist_column_order_unchanged(self, column, expected): assert result == expected + @pytest.mark.parametrize("by", [None, "c"]) + @pytest.mark.parametrize("column", [None, "b"]) + def test_hist_with_legend(self, by, column): + # GH 6279 - DataFrame histogram can have a legend + expected_axes_num = 1 if by is None and column is not None else 2 + expected_layout = (1, expected_axes_num) + expected_labels = column or ["a", "b"] + if by is not None: + expected_labels = [expected_labels] * 2 + + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"]) + + axes = _check_plot_works(df.hist, legend=True, by=by, column=column) + self._check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) + if by is None and column is None: + axes = axes[0] + for expected_label, ax in zip(expected_labels, axes): + self._check_legend_labels(ax, expected_label) + + @pytest.mark.parametrize("by", [None, "c"]) + @pytest.mark.parametrize("column", [None, "b"]) + def test_hist_with_legend_raises(self, by, column): + # GH 6279 - DataFrame histogram with legend and label raises + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame(np.random.randn(30, 2), index=index, columns=["a", "b"]) + + with pytest.raises(ValueError, match="Cannot use both legend and label"): + df.hist(legend=True, by=by, column=column, label="d") + @td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase):
- [x] closes #6279 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry cc @TomAugspurger Added argument "legend" to histogram backend. This adds the ability to display a legend even when not using a groupby. ```` df = pd.DataFrame(np.random.randn(30, 2), columns=['A', 'B']) df['C'] = 15 * ['a'] + 15 * ['b'] df = df.set_index('C') df.groupby('C')['A'].hist(legend=True) ```` produces ![image](https://user-images.githubusercontent.com/45562402/79070334-25911500-7ca3-11ea-8303-d44ded966137.png) I went off the tests that already existed in test_hist_method and test_groupby, but perhaps more stringent tests should be added. I've been manually checking with the following code: ```` import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame(np.random.randn(30, 2), columns=['A', 'B']) df['C'] = 15 * ['a'] + 15 * ['b'] df = df.set_index('C') df.groupby('C')['A'].hist(legend=False) plt.show() df.groupby('C')['A'].hist(legend=True) plt.show() df.A.hist(by='C', legend=False) plt.show() df.A.hist(by='C', legend=True) plt.show() plt.show() df.hist(by='C', legend=False) plt.show() df.hist(by='C', legend=True) plt.show() df.hist(by='C', column='B', legend=False) plt.show() df.hist(by='C', column='B', legend=True) plt.show() df.groupby('C')['A'].hist(label='D', legend=False) plt.show() df.groupby('C')['A'].hist(label='D', legend=True) plt.show() df.A.hist(by='C', label='D', legend=False) plt.show() df.A.hist(by='C', label='D', legend=True) plt.show() df.hist(by='C', label='D', legend=False) plt.show() df.hist(by='C', label='D', legend=True) plt.show() df.hist(by='C', column='B', label='D', legend=False) plt.show() df.hist(by='C', column='B', label='D', legend=True) plt.show() ````
https://api.github.com/repos/pandas-dev/pandas/pulls/33493
2020-04-12T13:55:43Z
2020-06-22T15:30:56Z
2020-06-22T15:30:55Z
2020-07-11T16:02:04Z
REF: de-duplicate code in libperiod
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index dd745f840d0ab..c4a7df0017619 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -806,24 +806,22 @@ cdef int64_t get_period_ordinal(npy_datetimestruct *dts, int freq) nogil: return unix_date_to_week(unix_date, freq - FR_WK) -cdef void get_date_info(int64_t ordinal, int freq, - npy_datetimestruct *dts) nogil: +cdef void get_date_info(int64_t ordinal, int freq, npy_datetimestruct *dts) nogil: cdef: - int64_t unix_date - double abstime + int64_t unix_date, nanos + npy_datetimestruct dts2 unix_date = get_unix_date(ordinal, freq) - abstime = get_abs_time(freq, unix_date, ordinal) - - while abstime < 0: - abstime += 86400 - unix_date -= 1 + nanos = get_time_nanos(freq, unix_date, ordinal) - while abstime >= 86400: - abstime -= 86400 - unix_date += 1 + pandas_datetime_to_datetimestruct(unix_date, NPY_FR_D, dts) - date_info_from_days_and_time(dts, unix_date, abstime) + dt64_to_dtstruct(nanos, &dts2) + dts.hour = dts2.hour + dts.min = dts2.min + dts.sec = dts2.sec + dts.us = dts2.us + dts.ps = dts2.ps cdef int64_t get_unix_date(int64_t period_ordinal, int freq) nogil: @@ -855,74 +853,50 @@ cdef int64_t get_unix_date(int64_t period_ordinal, int freq) nogil: @cython.cdivision -cdef void date_info_from_days_and_time(npy_datetimestruct *dts, - int64_t unix_date, - double abstime) nogil: +cdef int64_t get_time_nanos(int freq, int64_t unix_date, int64_t ordinal) nogil: """ - Set the instance's value using the given date and time. + Find the number of nanoseconds after midnight on the given unix_date + that the ordinal represents in the given frequency. Parameters ---------- - dts : npy_datetimestruct* + freq : int unix_date : int64_t - days elapsed since datetime(1970, 1, 1) - abstime : double - seconds elapsed since beginning of day described by unix_date + ordinal : int64_t - Notes - ----- - Updates dts inplace + Returns + ------- + int64_t """ cdef: - int inttime - int hour, minute - double second, subsecond_fraction - - # Bounds check - # The calling function is responsible for ensuring that - # abstime >= 0.0 and abstime <= 86400 - - # Calculate the date - pandas_datetime_to_datetimestruct(unix_date, NPY_FR_D, dts) + int64_t sub, factor - # Calculate the time - inttime = <int>abstime - hour = inttime / 3600 - minute = (inttime % 3600) / 60 - second = abstime - <double>(hour * 3600 + minute * 60) + freq = get_freq_group(freq) - dts.hour = hour - dts.min = minute - dts.sec = <int>second - - subsecond_fraction = second - dts.sec - dts.us = int((subsecond_fraction) * 1e6) - dts.ps = int(((subsecond_fraction) * 1e6 - dts.us) * 1e6) + if freq <= FR_DAY: + return 0 + elif freq == FR_NS: + factor = 1 -@cython.cdivision -cdef double get_abs_time(int freq, int64_t unix_date, int64_t ordinal) nogil: - cdef: - int freq_index, day_index, base_index - int64_t per_day, start_ord - double unit, result + elif freq == FR_US: + factor = 10**3 - if freq <= FR_DAY: - return 0 + elif freq == FR_MS: + factor = 10**6 - freq_index = freq // 1000 - day_index = FR_DAY // 1000 - base_index = FR_SEC // 1000 + elif freq == FR_SEC: + factor = 10 **9 - per_day = get_daytime_conversion_factor(day_index, freq_index) - unit = get_daytime_conversion_factor(freq_index, base_index) + elif freq == FR_MIN: + factor = 10**9 * 60 - if base_index < freq_index: - unit = 1 / unit + else: + # We must have freq == FR_HR + factor = 10**9 * 3600 - start_ord = unix_date * per_day - result = <double>(unit * (ordinal - start_ord)) - return result + sub = ordinal - unix_date * 24 * 3600 * 10**9 / factor + return sub * factor cdef int get_yq(int64_t ordinal, int freq, int *quarter, int *year): @@ -1176,11 +1150,7 @@ cdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) except? -1: if ordinal == NPY_NAT: return NPY_NAT - if freq == 11000: - # Microsecond, avoid get_date_info to prevent floating point errors - pandas_datetime_to_datetimestruct(ordinal, NPY_FR_us, &dts) - else: - get_date_info(ordinal, freq, &dts) + get_date_info(ordinal, freq, &dts) check_dts_bounds(&dts) return dtstruct_to_dt64(&dts)
discussed a few months ago, this gets rid of `date_info_from_days_and_time` and instead re-uses `pandas_datetime_to_datetimestruct`
https://api.github.com/repos/pandas-dev/pandas/pulls/33491
2020-04-12T04:16:46Z
2020-04-15T19:20:55Z
2020-04-15T19:20:55Z
2020-04-15T19:38:19Z
API: dont infer freq in DTA/TDA arithmetic ops
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 30a34282889f8..0b50f18e0e290 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1176,10 +1176,7 @@ def _add_timedeltalike_scalar(self, other): # adding a scalar preserves freq new_freq = self.freq - if new_freq is not None: - # fastpath that doesnt require inference - return type(self)(new_values, dtype=self.dtype, freq=new_freq) - return type(self)(new_values, dtype=self.dtype)._with_freq("infer") + return type(self)(new_values, dtype=self.dtype, freq=new_freq) def _add_timedelta_arraylike(self, other): """ @@ -1209,7 +1206,7 @@ def _add_timedelta_arraylike(self, other): mask = (self._isnan) | (other._isnan) new_values[mask] = iNaT - return type(self)(new_values, dtype=self.dtype)._with_freq("infer") + return type(self)(new_values, dtype=self.dtype) def _add_nat(self): """ diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 2ccc0ff2fa31d..1b897d04b4d35 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -698,7 +698,7 @@ def _add_offset(self, offset): # GH#30336 _from_sequence won't be able to infer self.tz return type(self)._from_sequence(result).tz_localize(self.tz) - return type(self)._from_sequence(result)._with_freq("infer") + return type(self)._from_sequence(result) def _sub_datetimelike_scalar(self, other): # subtract a datetime from myself, yielding a ndarray[timedelta64[ns]] diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 25333b3a08dce..d15bec764275e 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -625,6 +625,11 @@ def _set_freq(self, freq): # GH#29843 self._data._with_freq(freq) + def _with_freq(self, freq): + index = self.copy(deep=False) + index._set_freq(freq) + return index + def _shallow_copy(self, values=None, name: Label = lib.no_default): name = self.name if name is lib.no_default else name cache = self._cache.copy() if values is None else {} diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 765b948f13e96..7fafebd0a64f3 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -57,7 +57,6 @@ "std", "median", "_format_native_types", - "freq", ], TimedeltaArray, ) diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 56c5647d865d3..a8e9ad9ff7cc9 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -865,7 +865,7 @@ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): tdi = pd.TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) tdarr = tdi.values - expected = pd.date_range("2015-12-31", periods=3, tz=tz) + expected = pd.date_range("2015-12-31", "2016-01-02", periods=3, tz=tz) dtarr = tm.box_expected(dti, box_with_array) expected = tm.box_expected(expected, box_with_array) @@ -875,7 +875,7 @@ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): result = tdarr + dtarr tm.assert_equal(result, expected) - expected = pd.date_range("2016-01-02", periods=3, tz=tz) + expected = pd.date_range("2016-01-02", "2016-01-04", periods=3, tz=tz) expected = tm.box_expected(expected, box_with_array) result = dtarr - tdarr @@ -1385,13 +1385,13 @@ def test_dt64arr_add_sub_DateOffset(self, box_with_array): s = tm.box_expected(s, box_with_array) result = s + pd.DateOffset(years=1) result2 = pd.DateOffset(years=1) + s - exp = date_range("2001-01-01", "2001-01-31", name="a") + exp = date_range("2001-01-01", "2001-01-31", name="a")._with_freq(None) exp = tm.box_expected(exp, box_with_array) tm.assert_equal(result, exp) tm.assert_equal(result2, exp) result = s - pd.DateOffset(years=1) - exp = date_range("1999-01-01", "1999-01-31", name="a") + exp = date_range("1999-01-01", "1999-01-31", name="a")._with_freq(None) exp = tm.box_expected(exp, box_with_array) tm.assert_equal(result, exp) @@ -1553,7 +1553,7 @@ def test_dti_add_sub_nonzero_mth_offset( mth = getattr(date, op) result = mth(offset) - expected = pd.DatetimeIndex(exp, tz=tz, freq=exp_freq) + expected = pd.DatetimeIndex(exp, tz=tz) expected = tm.box_expected(expected, box_with_array, False) tm.assert_equal(result, expected) @@ -2344,29 +2344,29 @@ def test_ufunc_coercions(self): assert result.freq == "2D" exp = date_range("2010-12-31", periods=3, freq="2D", name="x") + for result in [idx - delta, np.subtract(idx, delta)]: assert isinstance(result, DatetimeIndex) tm.assert_index_equal(result, exp) assert result.freq == "2D" + # When adding/subtracting an ndarray (which has no .freq), the result + # does not infer freq + idx = idx._with_freq(None) delta = np.array( [np.timedelta64(1, "D"), np.timedelta64(2, "D"), np.timedelta64(3, "D")] ) - exp = DatetimeIndex( - ["2011-01-02", "2011-01-05", "2011-01-08"], freq="3D", name="x" - ) + exp = DatetimeIndex(["2011-01-02", "2011-01-05", "2011-01-08"], name="x") + for result in [idx + delta, np.add(idx, delta)]: - assert isinstance(result, DatetimeIndex) tm.assert_index_equal(result, exp) - assert result.freq == "3D" + assert result.freq == exp.freq - exp = DatetimeIndex( - ["2010-12-31", "2011-01-01", "2011-01-02"], freq="D", name="x" - ) + exp = DatetimeIndex(["2010-12-31", "2011-01-01", "2011-01-02"], name="x") for result in [idx - delta, np.subtract(idx, delta)]: assert isinstance(result, DatetimeIndex) tm.assert_index_equal(result, exp) - assert result.freq == "D" + assert result.freq == exp.freq @pytest.mark.parametrize( "names", [("foo", None, None), ("baz", "bar", None), ("bar", "bar", "bar")] diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index beb16c9549cc4..e2b1a4499e197 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -487,6 +487,7 @@ def test_timedelta(self, freq): shifted = index + timedelta(1) back = shifted + timedelta(-1) + back = back._with_freq("infer") tm.assert_index_equal(index, back) if freq == "D": diff --git a/pandas/tests/indexes/timedeltas/test_shift.py b/pandas/tests/indexes/timedeltas/test_shift.py index c02aa71d97aac..1282bd510ec17 100644 --- a/pandas/tests/indexes/timedeltas/test_shift.py +++ b/pandas/tests/indexes/timedeltas/test_shift.py @@ -38,7 +38,8 @@ def test_tdi_shift_minutes(self): def test_tdi_shift_int(self): # GH#8083 - trange = pd.to_timedelta(range(5), unit="d") + pd.offsets.Hour(1) + tdi = pd.to_timedelta(range(5), unit="d") + trange = tdi._with_freq("infer") + pd.offsets.Hour(1) result = trange.shift(1) expected = TimedeltaIndex( [ @@ -54,7 +55,8 @@ def test_tdi_shift_int(self): def test_tdi_shift_nonstandard_freq(self): # GH#8083 - trange = pd.to_timedelta(range(5), unit="d") + pd.offsets.Hour(1) + tdi = pd.to_timedelta(range(5), unit="d") + trange = tdi._with_freq("infer") + pd.offsets.Hour(1) result = trange.shift(3, freq="2D 1s") expected = TimedeltaIndex( [ diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 129bdef870a14..f724badd51da8 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -30,7 +30,9 @@ def indices(self): return tm.makeTimedeltaIndex(10) def create_index(self) -> TimedeltaIndex: - return pd.to_timedelta(range(5), unit="d") + pd.offsets.Hour(1) + index = pd.to_timedelta(range(5), unit="d")._with_freq("infer") + assert index.freq == "D" + return index + pd.offsets.Hour(1) def test_numeric_compat(self): # Dummy method to override super's version; this test is now done
- [x] closes #23216 freq inference is pure overhead for the Series/DataFrame op because freq gets discarded.
https://api.github.com/repos/pandas-dev/pandas/pulls/33487
2020-04-11T21:20:39Z
2020-04-17T21:42:53Z
2020-04-17T21:42:53Z
2020-04-17T22:03:53Z
REF: remove Block.concat_same_type
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 185b0f4da2627..ebdc331a673ab 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -48,7 +48,6 @@ is_timedelta64_dtype, pandas_dtype, ) -from pandas.core.dtypes.concat import concat_categorical, concat_datetime from pandas.core.dtypes.dtypes import ExtensionDtype from pandas.core.dtypes.generic import ( ABCDataFrame, @@ -110,7 +109,6 @@ class Block(PandasObject): _can_consolidate = True _verify_integrity = True _validate_ndim = True - _concatenator = staticmethod(np.concatenate) def __init__(self, values, placement, ndim=None): self.ndim = self._check_ndim(values, ndim) @@ -309,16 +307,6 @@ def shape(self): def dtype(self): return self.values.dtype - def concat_same_type(self, to_concat): - """ - Concatenate list of single blocks of the same type. - """ - values = self._concatenator( - [blk.values for blk in to_concat], axis=self.ndim - 1 - ) - placement = self.mgr_locs if self.ndim == 2 else slice(len(values)) - return self.make_block_same_class(values, placement=placement) - def iget(self, i): return self.values[i] @@ -1770,14 +1758,6 @@ def _slice(self, slicer): return self.values[slicer] - def concat_same_type(self, to_concat): - """ - Concatenate list of single blocks of the same type. - """ - values = self._holder._concat_same_type([blk.values for blk in to_concat]) - placement = self.mgr_locs if self.ndim == 2 else slice(len(values)) - return self.make_block_same_class(values, placement=placement) - def fillna(self, value, limit=None, inplace=False, downcast=None): values = self.values if inplace else self.values.copy() values = values.fillna(value=value, limit=limit) @@ -2258,20 +2238,6 @@ def diff(self, n: int, axis: int = 0) -> List["Block"]: new_values = new_values.astype("timedelta64[ns]") return [TimeDeltaBlock(new_values, placement=self.mgr_locs.indexer)] - def concat_same_type(self, to_concat): - # need to handle concat([tz1, tz2]) here, since DatetimeArray - # only handles cases where all the tzs are the same. - # Instead of placing the condition here, it could also go into the - # is_uniform_join_units check, but I'm not sure what is better. - if len({x.dtype for x in to_concat}) > 1: - values = concat_datetime([x.values for x in to_concat]) - - values = values.astype(object, copy=False) - placement = self.mgr_locs if self.ndim == 2 else slice(len(values)) - - return self.make_block(values, placement=placement) - return super().concat_same_type(to_concat) - def fillna(self, value, limit=None, inplace=False, downcast=None): # We support filling a DatetimeTZ with a `value` whose timezone # is different by coercing to object. @@ -2642,7 +2608,6 @@ class CategoricalBlock(ExtensionBlock): is_categorical = True _verify_integrity = True _can_hold_na = True - _concatenator = staticmethod(concat_categorical) should_store = Block.should_store @@ -2656,26 +2621,6 @@ def __init__(self, values, placement, ndim=None): def _holder(self): return Categorical - def concat_same_type(self, to_concat): - """ - Concatenate list of single blocks of the same type. - - Note that this CategoricalBlock._concat_same_type *may* not - return a CategoricalBlock. When the categories in `to_concat` - differ, this will return an object ndarray. - - If / when we decide we don't like that behavior: - - 1. Change Categorical._concat_same_type to use union_categoricals - 2. Delete this method. - """ - values = self._concatenator( - [blk.values for blk in to_concat], axis=self.ndim - 1 - ) - placement = self.mgr_locs if self.ndim == 2 else slice(len(values)) - # not using self.make_block_same_class as values can be object dtype - return self.make_block(values, placement=placement) - def replace( self, to_replace, diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 720e6799a3bf3..37e081aeba3f6 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -1,6 +1,7 @@ # TODO: Needs a better name; too many modules are already called "concat" from collections import defaultdict import copy +from typing import List import numpy as np @@ -61,8 +62,18 @@ def concatenate_block_managers( values = values.view() b = b.make_block_same_class(values, placement=placement) elif _is_uniform_join_units(join_units): - b = join_units[0].block.concat_same_type([ju.block for ju in join_units]) - b.mgr_locs = placement + blk = join_units[0].block + vals = [ju.block.values for ju in join_units] + + if not blk.is_extension or blk.is_datetimetz or blk.is_categorical: + # datetimetz and categorical can have the same type but multiple + # dtypes, concatting does not necessarily preserve dtype + values = concat_compat(vals, axis=blk.ndim - 1) + else: + # TODO(EA2D): special-casing not needed with 2D EAs + values = concat_compat(vals) + + b = make_block(values, placement=placement, ndim=blk.ndim) else: b = make_block( _concatenate_join_units(join_units, concat_axis, copy=copy), @@ -419,13 +430,15 @@ def _get_empty_dtype_and_na(join_units): raise AssertionError(msg) -def _is_uniform_join_units(join_units) -> bool: +def _is_uniform_join_units(join_units: List[JoinUnit]) -> bool: """ Check if the join units consist of blocks of uniform type that can be concatenated using Block.concat_same_type instead of the generic _concatenate_join_units (which uses `concat_compat`). """ + # TODO: require dtype match in addition to same type? e.g. DatetimeTZBlock + # cannot necessarily join return ( # all blocks need to have the same type all(type(ju.block) is type(join_units[0].block) for ju in join_units) diff --git a/pandas/tests/extension/test_external_block.py b/pandas/tests/extension/test_external_block.py index 9925fd51561ae..1843126898f3d 100644 --- a/pandas/tests/extension/test_external_block.py +++ b/pandas/tests/extension/test_external_block.py @@ -32,12 +32,6 @@ def df(): return pd.DataFrame(block_manager) -def test_concat_dataframe(df): - # GH17728 - res = pd.concat([df, df]) - assert isinstance(res._mgr.blocks[1], CustomBlock) - - def test_concat_axis1(df): # GH17954 df2 = pd.DataFrame({"c": [0.1, 0.2, 0.3]})
All the relevant logic lives in concat_compat already.
https://api.github.com/repos/pandas-dev/pandas/pulls/33486
2020-04-11T20:56:32Z
2020-04-15T19:22:47Z
2020-04-15T19:22:46Z
2020-04-15T19:34:21Z
TST: Don't use deprecated version of read_html
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 3d73e983402a7..2c93dbb5b6b83 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -321,7 +321,7 @@ def test_invalid_table_attrs(self): url = self.banklist_data with pytest.raises(ValueError, match="No tables found"): self.read_html( - url, "First Federal Bank of Florida", attrs={"id": "tasdfable"} + url, match="First Federal Bank of Florida", attrs={"id": "tasdfable"} ) def _bank_data(self, *args, **kwargs): @@ -573,7 +573,9 @@ def try_remove_ws(x): except AttributeError: return x - df = self.read_html(self.banklist_data, "Metcalf", attrs={"id": "table"})[0] + df = self.read_html(self.banklist_data, match="Metcalf", attrs={"id": "table"})[ + 0 + ] ground_truth = read_csv( datapath("io", "data", "csv", "banklist.csv"), converters={"Updated Date": Timestamp, "Closing Date": Timestamp}, @@ -883,7 +885,7 @@ def test_wikipedia_states_table(self, datapath): def test_wikipedia_states_multiindex(self, datapath): data = datapath("io", "data", "html", "wikipedia_states.html") - result = self.read_html(data, "Arizona", index_col=0)[0] + result = self.read_html(data, match="Arizona", index_col=0)[0] assert result.shape == (60, 11) assert "Unnamed" in result.columns[-1][1] assert result.columns.nlevels == 2
Usage of function read_html is marked as deprecated when used with positional arguments. In case when we do not explicitly check the warning message with assert_produces_warning we should use non-deprecated version. This will resolve #33397 To identify candidates to change I modified decorator to raise an `Exception` ```diff --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -294,6 +294,7 @@ def deprecate_nonkeyword_arguments( "Starting with Pandas version {version} all arguments of {funcname}" "{except_args} will be keyword-only" ).format(version=version, funcname=func.__name__, except_args=arguments) + raise Exception("keyword argument test") warnings.warn(msg, FutureWarning, stacklevel=stacklevel) return func(*args, **kwargs) ``` Related test build https://dev.azure.com/piotrnielacny/piotrnielacny/_build/results?buildId=2&view=ms.vss-test-web.build-test-results-tab - [x] closes #33397 - [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/33482
2020-04-11T14:33:30Z
2020-04-12T21:48:32Z
2020-04-12T21:48:32Z
2020-04-12T21:48:37Z
BUG: Add unordered option to pandas.cut (#33141)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 597a0c5386cf0..8650eb24f615d 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -139,6 +139,7 @@ Other enhancements - The :meth:`DataFrame.to_feather` method now supports additional keyword arguments (e.g. to set the compression) that are added in pyarrow 0.17 (:issue:`33422`). +- The :func:`cut` will now accept parameter ``ordered`` with default ``ordered=True``. If ``ordered=False`` and no labels are provided, an error will be raised (:issue:`33141`) - :meth:`DataFrame.to_csv`, :meth:`DataFrame.to_pickle`, and :meth:`DataFrame.to_json` now support passing a dict of compression arguments when using the ``gzip`` and ``bz2`` protocols. @@ -720,6 +721,7 @@ Reshaping - Bug in :meth:`concat` where when passing a non-dict mapping as ``objs`` would raise a ``TypeError`` (:issue:`32863`) - :meth:`DataFrame.agg` now provides more descriptive ``SpecificationError`` message when attempting to aggregating non-existant column (:issue:`32755`) - Bug in :meth:`DataFrame.unstack` when MultiIndexed columns and MultiIndexed rows were used (:issue:`32624`, :issue:`24729` and :issue:`28306`) +- Bug in :func:`cut` raised an error when non-unique labels (:issue:`33141`) Sparse diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 66c2f5c9b927f..345239eeb2372 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -38,6 +38,7 @@ def cut( precision: int = 3, include_lowest: bool = False, duplicates: str = "raise", + ordered: bool = True, ): """ Bin values into discrete intervals. @@ -73,7 +74,7 @@ def cut( the resulting bins. If False, returns only integer indicators of the bins. This affects the type of the output container (see below). This argument is ignored when `bins` is an IntervalIndex. If True, - raises an error. + raises an error. When `ordered=False`, labels must be provided. retbins : bool, default False Whether to return the bins or not. Useful when bins is provided as a scalar. @@ -85,6 +86,13 @@ def cut( If bin edges are not unique, raise ValueError or drop non-uniques. .. versionadded:: 0.23.0 + ordered : bool, default True + Whether the labels are ordered or not. Applies to returned types + Categorical and Series (with Categorical dtype). If True, + the resulting categorical will be ordered. If False, the resulting + categorical will be unordered (labels must be provided). + + .. versionadded:: 1.1.0 Returns ------- @@ -145,6 +153,14 @@ def cut( [bad, good, medium, medium, good, bad] Categories (3, object): [bad < medium < good] + ``ordered=False`` will result in unordered categories when labels are passed. + This parameter can be used to allow non-unique labels: + + >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, + ... labels=["B", "A", "B"], ordered=False) + [B, B, A, A, B, B] + Categories (2, object): [A, B] + ``labels=False`` implies you just want the bins back. >>> pd.cut([0, 1, 1, 2], bins=4, labels=False) @@ -265,6 +281,7 @@ def cut( include_lowest=include_lowest, dtype=dtype, duplicates=duplicates, + ordered=ordered, ) return _postprocess_for_cut(fac, bins, retbins, dtype, original) @@ -362,7 +379,10 @@ def _bins_to_cuts( include_lowest: bool = False, dtype=None, duplicates: str = "raise", + ordered: bool = True, ): + if not ordered and not labels: + raise ValueError("'labels' must be provided if 'ordered = False'") if duplicates not in ["raise", "drop"]: raise ValueError( @@ -405,16 +425,22 @@ def _bins_to_cuts( labels = _format_labels( bins, precision, right=right, include_lowest=include_lowest, dtype=dtype ) - + elif ordered and len(set(labels)) != len(labels): + raise ValueError( + "labels must be unique if ordered=True; pass ordered=False for duplicate labels" # noqa + ) else: if len(labels) != len(bins) - 1: raise ValueError( "Bin labels must be one fewer than the number of bin edges" ) - if not is_categorical_dtype(labels): - labels = Categorical(labels, categories=labels, ordered=True) - + labels = Categorical( + labels, + categories=labels if len(set(labels)) == len(labels) else None, + ordered=ordered, + ) + # TODO: handle mismach between categorical label order and pandas.cut order. np.putmask(ids, na_mask, 0) result = algos.take_nd(labels, ids - 1) diff --git a/pandas/tests/reshape/test_cut.py b/pandas/tests/reshape/test_cut.py index 830e786fd1c6d..60c80a8abdba6 100644 --- a/pandas/tests/reshape/test_cut.py +++ b/pandas/tests/reshape/test_cut.py @@ -625,3 +625,42 @@ def test_cut_nullable_integer(bins, right, include_lowest): ) expected = cut(a, bins, right=right, include_lowest=include_lowest) tm.assert_categorical_equal(result, expected) + + +@pytest.mark.parametrize( + "data, bins, labels, expected_codes, expected_labels", + [ + ([15, 17, 19], [14, 16, 18, 20], ["A", "B", "A"], [0, 1, 0], ["A", "B"]), + ([1, 3, 5], [0, 2, 4, 6, 8], [2, 0, 1, 2], [2, 0, 1], [0, 1, 2]), + ], +) +def test_cut_non_unique_labels(data, bins, labels, expected_codes, expected_labels): + # GH 33141 + result = cut(data, bins=bins, labels=labels, ordered=False) + expected = Categorical.from_codes( + expected_codes, categories=expected_labels, ordered=False + ) + tm.assert_categorical_equal(result, expected) + + +@pytest.mark.parametrize( + "data, bins, labels, expected_codes, expected_labels", + [ + ([15, 17, 19], [14, 16, 18, 20], ["C", "B", "A"], [0, 1, 2], ["C", "B", "A"]), + ([1, 3, 5], [0, 2, 4, 6, 8], [3, 0, 1, 2], [0, 1, 2], [3, 0, 1, 2]), + ], +) +def test_cut_unordered_labels(data, bins, labels, expected_codes, expected_labels): + # GH 33141 + result = cut(data, bins=bins, labels=labels, ordered=False) + expected = Categorical.from_codes( + expected_codes, categories=expected_labels, ordered=False + ) + tm.assert_categorical_equal(result, expected) + + +def test_cut_unordered_with_missing_labels_raises_error(): + # GH 33141 + msg = "'labels' must be provided if 'ordered = False'" + with pytest.raises(ValueError, match=msg): + cut([0.5, 3], bins=[0, 1, 2], ordered=False)
Added tests and error message when there are no labels and `ordered=False`. Issue: Pandas cut raises error if labels are non-unique (Closes #33141) - [x] closes #33141 - [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/33480
2020-04-11T14:07:04Z
2020-05-01T00:31:48Z
2020-05-01T00:31:47Z
2020-05-01T00:31:53Z
Send None parameter to pandas-gbq to set no progress bar
diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml index 3fc19f1bca084..2c8403acf6971 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-36-locale.yaml @@ -27,7 +27,7 @@ dependencies: - numexpr - numpy - openpyxl - - pandas-gbq=0.8.0 + - pandas-gbq=0.12.0 - psycopg2=2.6.2 - pymysql=0.7.11 - pytables diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index ba99aaa9f430c..da1161c8f68b4 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -274,7 +274,7 @@ lxml 3.8.0 HTML parser for read_html (see :ref matplotlib 2.2.2 Visualization numba 0.46.0 Alternative execution engine for rolling operations openpyxl 2.5.7 Reading / writing for xlsx files -pandas-gbq 0.8.0 Google Big Query access +pandas-gbq 0.12.0 Google Big Query access psycopg2 PostgreSQL engine for sqlalchemy pyarrow 0.12.0 Parquet, ORC (requires 0.13.0), and feather reading / writing pymysql 0.7.11 MySQL engine for sqlalchemy diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 86d3e50493bd1..17623b943bf87 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -289,6 +289,7 @@ Other enhancements - Make :class:`pandas.core.window.Rolling` and :class:`pandas.core.window.Expanding` iterable(:issue:`11704`) - Make ``option_context`` a :class:`contextlib.ContextDecorator`, which allows it to be used as a decorator over an entire function (:issue:`34253`). - :meth:`groupby.transform` now allows ``func`` to be ``pad``, ``backfill`` and ``cumcount`` (:issue:`31269`). +- :meth `~pandas.io.gbq.read_gbq` now allows to disable progress bar (:issue:`33360`). .. --------------------------------------------------------------------------- @@ -355,6 +356,8 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+---------+ | xlwt | 1.2.0 | | +-----------------+-----------------+---------+ +| pandas-gbq | 1.2.0 | X | ++-----------------+-----------------+---------+ See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more. diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index c5fd294699c45..0a5e0f5050040 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -15,7 +15,7 @@ "numexpr": "2.6.2", "odfpy": "1.3.0", "openpyxl": "2.5.7", - "pandas_gbq": "0.8.0", + "pandas_gbq": "0.12.0", "pyarrow": "0.13.0", "pytables": "3.4.3", "pytest": "5.0.1", diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py index 405bf27cac02d..9b46f970afc66 100644 --- a/pandas/io/gbq.py +++ b/pandas/io/gbq.py @@ -162,14 +162,13 @@ def read_gbq( """ pandas_gbq = _try_import() - kwargs: Dict[str, Union[str, bool]] = {} + kwargs: Dict[str, Union[str, bool, None]] = {} # START: new kwargs. Don't populate unless explicitly set. if use_bqstorage_api is not None: kwargs["use_bqstorage_api"] = use_bqstorage_api - if progress_bar_type is not None: - kwargs["progress_bar_type"] = progress_bar_type + kwargs["progress_bar_type"] = progress_bar_type # END: new kwargs return pandas_gbq.read_gbq( diff --git a/pandas/tests/io/test_gbq.py b/pandas/tests/io/test_gbq.py index 7a5eba5264421..e9cefe3056130 100644 --- a/pandas/tests/io/test_gbq.py +++ b/pandas/tests/io/test_gbq.py @@ -142,11 +142,7 @@ def mock_read_gbq(sql, **kwargs): monkeypatch.setattr("pandas_gbq.read_gbq", mock_read_gbq) pd.read_gbq("SELECT 1", progress_bar_type=progress_bar) - - if progress_bar: - assert "progress_bar_type" in captured_kwargs - else: - assert "progress_bar_type" not in captured_kwargs + assert "progress_bar_type" in captured_kwargs @pytest.mark.single
- [x] closes #33360 - [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/33477
2020-04-11T11:12:16Z
2020-06-04T17:41:35Z
2020-06-04T17:41:34Z
2020-06-04T18:10:02Z
REF: unstack
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d8875b38ed738..185b0f4da2627 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1384,15 +1384,13 @@ def equals(self, other) -> bool: return False return array_equivalent(self.values, other.values) - def _unstack(self, unstacker, new_columns, fill_value, value_columns): + def _unstack(self, unstacker, fill_value, new_placement): """ Return a list of unstacked blocks of self Parameters ---------- unstacker : reshape._Unstacker - new_columns : Index - All columns of the unstacked BlockManager. fill_value : int Only used in ExtensionBlock._unstack @@ -1403,17 +1401,17 @@ def _unstack(self, unstacker, new_columns, fill_value, value_columns): mask : array_like of bool The mask of columns of `blocks` we should keep. """ - new_items = unstacker.get_new_columns(value_columns) - new_placement = new_columns.get_indexer(new_items) new_values, mask = unstacker.get_new_values( self.values.T, fill_value=fill_value ) mask = mask.any(0) + # TODO: in all tests we have mask.all(); can we rely on that? + new_values = new_values.T[mask] new_placement = new_placement[mask] - blocks = [make_block(new_values, placement=new_placement)] + blocks = [self.make_block_same_class(new_values, placement=new_placement)] return blocks, mask def quantile(self, qs, interpolation="linear", axis: int = 0): @@ -1878,7 +1876,7 @@ def where( return [self.make_block_same_class(result, placement=self.mgr_locs)] - def _unstack(self, unstacker, new_columns, fill_value, value_columns): + def _unstack(self, unstacker, fill_value, new_placement): # ExtensionArray-safe unstack. # We override ObjectBlock._unstack, which unstacks directly on the # values of the array. For EA-backed blocks, this would require @@ -1888,10 +1886,9 @@ def _unstack(self, unstacker, new_columns, fill_value, value_columns): n_rows = self.shape[-1] dummy_arr = np.arange(n_rows) - new_items = unstacker.get_new_columns(value_columns) - new_placement = new_columns.get_indexer(new_items) new_values, mask = unstacker.get_new_values(dummy_arr, fill_value=-1) mask = mask.any(0) + # TODO: in all tests we have mask.all(); can we rely on that? blocks = [ self.make_block_same_class( diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index f3b4ebad9cec1..0f105b0a7ee75 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1461,8 +1461,11 @@ def unstack(self, unstacker, fill_value) -> "BlockManager": for blk in self.blocks: blk_cols = self.items[blk.mgr_locs.indexer] + new_items = unstacker.get_new_columns(blk_cols) + new_placement = new_columns.get_indexer(new_items) + blocks, mask = blk._unstack( - unstacker, new_columns, fill_value, value_columns=blk_cols, + unstacker, fill_value, new_placement=new_placement ) new_blocks.extend(blocks) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index b883c5b1568a0..882e3e0a649cc 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -142,7 +142,7 @@ def sorted_labels(self): indexer, to_sort = self._indexer_and_to_sort return [l.take(indexer) for l in to_sort] - def _make_sorted_values(self, values): + def _make_sorted_values(self, values: np.ndarray) -> np.ndarray: indexer, _ = self._indexer_and_to_sort sorted_values = algos.take_nd(values, indexer, axis=0) @@ -205,6 +205,9 @@ def get_new_values(self, values, fill_value=None): # we can simply reshape if we don't have a mask if mask_all and len(values): + # TODO: Under what circumstances can we rely on sorted_values + # matching values? When that holds, we can slice instead + # of take (in particular for EAs) new_values = ( sorted_values.reshape(length, width, stride) .swapaxes(1, 2)
cc @jreback this moves a small amount of the unstack logic up the call stack, which is worthwhile, but the big wins available are if you can help me figure out the questions in inline comments.
https://api.github.com/repos/pandas-dev/pandas/pulls/33474
2020-04-11T03:00:36Z
2020-04-12T20:33:38Z
2020-04-12T20:33:38Z
2020-12-02T17:58:46Z
BUG: Series.__setitem__[listlike_of_integers] with IntervalIndex
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 67dba3fab23e1..bccfce4f7e077 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -525,6 +525,7 @@ Indexing - Bug in `Series.__getitem__` with an integer key and a :class:`MultiIndex` with leading integer level failing to raise ``KeyError`` if the key is not present in the first level (:issue:`33355`) - Bug in :meth:`DataFrame.iloc` when slicing a single column-:class:`DataFrame`` with ``ExtensionDtype`` (e.g. ``df.iloc[:, :1]``) returning an invalid result (:issue:`32957`) - Bug in :meth:`DatetimeIndex.insert` and :meth:`TimedeltaIndex.insert` causing index ``freq`` to be lost when setting an element into an empty :class:`Series` (:issue:33573`) +- Bug in :meth:`Series.__setitem__` with an :class:`IntervalIndex` and a list-like key of integers (:issue:`33473`) Missing ^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 530aaee24c7fb..3c67cfc5dfd12 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4604,9 +4604,9 @@ def _check_indexing_error(self, key): def _should_fallback_to_positional(self) -> bool: """ - If an integer key is not found, should we fall back to positional indexing? + Should an integer key be treated as positional? """ - if len(self) > 0 and (self.holds_integer() or self.is_boolean()): + if self.holds_integer() or self.is_boolean(): return False return True diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 18e995ce4efd7..6ae16db2e82db 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -514,7 +514,7 @@ def is_overlapping(self) -> bool: # GH 23309 return self._engine.is_overlapping - def _should_fallback_to_positional(self): + def _should_fallback_to_positional(self) -> bool: # integer lookups in Series.__getitem__ are unambiguously # positional in this case return self.dtype.subtype.kind in ["m", "M"] diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 42e0d228dab09..d411867af2ef8 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2342,10 +2342,8 @@ def _check_indexing_error(self, key): def _should_fallback_to_positional(self) -> bool: """ - If an integer key is not found, should we fall back to positional indexing? + Should integer key(s) be treated as positional? """ - if not self.nlevels: - return False # GH#33355 return self.levels[0]._should_fallback_to_positional() diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index e2be58a56018d..06040166d0f9e 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -376,7 +376,7 @@ def astype(self, dtype, copy=True): # Indexing Methods @doc(Index._should_fallback_to_positional) - def _should_fallback_to_positional(self): + def _should_fallback_to_positional(self) -> bool: return False @doc(Index._convert_slice_indexer) diff --git a/pandas/core/series.py b/pandas/core/series.py index 3f5927828e541..9182e378fbaeb 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -79,7 +79,6 @@ from pandas.core.indexes.api import ( Float64Index, Index, - IntervalIndex, InvalidIndexError, MultiIndex, ensure_index, @@ -945,9 +944,7 @@ def _get_with(self, key): if key_type == "integer": # We need to decide whether to treat this as a positional indexer # (i.e. self.iloc) or label-based (i.e. self.loc) - if self.index.is_integer() or self.index.is_floating(): - return self.loc[key] - elif isinstance(self.index, IntervalIndex): + if not self.index._should_fallback_to_positional(): return self.loc[key] else: return self.iloc[key] @@ -1070,7 +1067,7 @@ def _set_with(self, key, value): # Note: key_type == "boolean" should not occur because that # should be caught by the is_bool_indexer check in __setitem__ if key_type == "integer": - if self.index.inferred_type == "integer": + if not self.index._should_fallback_to_positional(): self._set_labels(key, value) else: self._set_values(key, value) diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index a49bd6d59d01b..2922f3c741320 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -90,6 +90,18 @@ def test_getitem_intlist_intindex_periodvalues(self): tm.assert_series_equal(result, exp) assert result.dtype == "Period[D]" + @pytest.mark.parametrize("box", [list, np.array, pd.Index]) + def test_getitem_intlist_intervalindex_non_int(self, box): + # GH#33404 fall back to positional since ints are unambiguous + dti = date_range("2000-01-03", periods=3) + ii = pd.IntervalIndex.from_breaks(dti) + ser = Series(range(len(ii)), index=ii) + + expected = ser.iloc[:1] + key = box([0]) + result = ser[key] + tm.assert_series_equal(result, expected) + def test_getitem_generator(string_series): gen = (x > 0 for x in string_series) diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 900374824eb25..c2b5117d395f9 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -159,9 +159,9 @@ def test_getitem_out_of_bounds(datetime_series): datetime_series[len(datetime_series)] # GH #917 - msg = r"index -\d+ is out of bounds for axis 0 with size \d+" + # With a RangeIndex, an int key gives a KeyError s = Series([], dtype=object) - with pytest.raises(IndexError, match=msg): + with pytest.raises(KeyError, match="-1"): s[-1]
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33473
2020-04-11T01:54:00Z
2020-04-17T18:09:59Z
2020-04-17T18:09:59Z
2020-04-17T19:44:12Z
REF: Simplify __getitem__ by doing positional-int check first
diff --git a/pandas/core/series.py b/pandas/core/series.py index a73ef08b606e3..3f5927828e541 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -881,32 +881,35 @@ def __getitem__(self, key): if isinstance(key, (list, tuple)): key = unpack_1tuple(key) - if key_is_scalar or isinstance(self.index, MultiIndex): + if is_integer(key) and self.index._should_fallback_to_positional(): + return self._values[key] + + elif key_is_scalar: + return self._get_value(key) + + if ( + isinstance(key, tuple) + and is_hashable(key) + and isinstance(self.index, MultiIndex) + ): # Otherwise index.get_value will raise InvalidIndexError try: - result = self.index.get_value(self, key) + result = self._get_value(key) return result - except InvalidIndexError: - if not isinstance(self.index, MultiIndex): - raise - except (KeyError, ValueError): - if isinstance(key, tuple) and isinstance(self.index, MultiIndex): - # kludge - pass - else: - raise + except KeyError: + # We still have the corner case where this tuple is a key + # in the first level of our MultiIndex + return self._get_values_tuple(key) - if not key_is_scalar: - # avoid expensive checks if we know we have a scalar - if is_iterator(key): - key = list(key) + if is_iterator(key): + key = list(key) - if com.is_bool_indexer(key): - key = check_bool_indexer(self.index, key) - key = np.asarray(key, dtype=bool) - return self._get_values(key) + if com.is_bool_indexer(key): + key = check_bool_indexer(self.index, key) + key = np.asarray(key, dtype=bool) + return self._get_values(key) return self._get_with(key)
This gets rid of the last non-test usage of `Index.get_value`, so that can be deprecated, xref #19728 This focuses only on `__getitem__`; `__setitem__` is tougher for a few reasons, including #33469.
https://api.github.com/repos/pandas-dev/pandas/pulls/33471
2020-04-10T23:22:34Z
2020-04-12T20:29:57Z
2020-04-12T20:29:57Z
2020-04-12T20:31:02Z
DOC: timezone conversion example added to pandas.Series.astype doc #33399
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index eb6554bf2260c..f5ebd6bc08bfb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5538,6 +5538,24 @@ def astype( 0 10 1 2 dtype: int64 + + Create a series of dates: + + >>> ser_date = pd.Series(pd.date_range('20200101', periods=3)) + >>> ser_date + 0 2020-01-01 + 1 2020-01-02 + 2 2020-01-03 + dtype: datetime64[ns] + + Datetimes are localized to UTC first before + converting to the specified timezone: + + >>> ser_date.astype('datetime64[ns, US/Eastern]') + 0 2019-12-31 19:00:00-05:00 + 1 2020-01-01 19:00:00-05:00 + 2 2020-01-02 19:00:00-05:00 + dtype: datetime64[ns, US/Eastern] """ if is_dict_like(dtype): if self.ndim == 1: # i.e. Series
…3399 - [x] closes #33399 Have added an example in the documentation page of pandas.Series.astype for datetime type with timezone.
https://api.github.com/repos/pandas-dev/pandas/pulls/33470
2020-04-10T23:00:35Z
2020-04-12T21:47:12Z
2020-04-12T21:47:12Z
2020-04-13T01:58:00Z
Groupby test_apply_mutate
diff --git a/pandas/tests/groupby/test_apply_mutate.py b/pandas/tests/groupby/test_apply_mutate.py new file mode 100644 index 0000000000000..529f76bf692ce --- /dev/null +++ b/pandas/tests/groupby/test_apply_mutate.py @@ -0,0 +1,70 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +def test_mutate_groups(): + + # GH3380 + + df = pd.DataFrame( + { + "cat1": ["a"] * 8 + ["b"] * 6, + "cat2": ["c"] * 2 + + ["d"] * 2 + + ["e"] * 2 + + ["f"] * 2 + + ["c"] * 2 + + ["d"] * 2 + + ["e"] * 2, + "cat3": [f"g{x}" for x in range(1, 15)], + "val": np.random.randint(100, size=14), + } + ) + + def f_copy(x): + x = x.copy() + x["rank"] = x.val.rank(method="min") + return x.groupby("cat2")["rank"].min() + + def f_no_copy(x): + x["rank"] = x.val.rank(method="min") + return x.groupby("cat2")["rank"].min() + + grpby_copy = df.groupby("cat1").apply(f_copy) + grpby_no_copy = df.groupby("cat1").apply(f_no_copy) + tm.assert_series_equal(grpby_copy, grpby_no_copy) + + +def test_no_mutate_but_looks_like(): + + # GH 8467 + # first show's mutation indicator + # second does not, but should yield the same results + df = pd.DataFrame({"key": [1, 1, 1, 2, 2, 2, 3, 3, 3], "value": range(9)}) + + result1 = df.groupby("key", group_keys=True).apply(lambda x: x[:].key) + result2 = df.groupby("key", group_keys=True).apply(lambda x: x.key) + tm.assert_series_equal(result1, result2) + + +def test_apply_function_with_indexing(): + # GH: 33058 + df = pd.DataFrame( + {"col1": ["A", "A", "A", "B", "B", "B"], "col2": [1, 2, 3, 4, 5, 6]} + ) + + def fn(x): + x.col2[x.index[-1]] = 0 + return x.col2 + + result = df.groupby(["col1"], as_index=False).apply(fn) + expected = pd.Series( + [1, 2, 0, 4, 5, 0], + index=pd.MultiIndex.from_tuples( + [(0, 0), (0, 1), (0, 2), (1, 3), (1, 4), (1, 5)] + ), + name="col2", + ) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index b8d8f56512a69..c88d16e34eab8 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -921,51 +921,6 @@ def test_groupby_complex(): tm.assert_series_equal(result, expected) -def test_mutate_groups(): - - # GH3380 - - df = DataFrame( - { - "cat1": ["a"] * 8 + ["b"] * 6, - "cat2": ["c"] * 2 - + ["d"] * 2 - + ["e"] * 2 - + ["f"] * 2 - + ["c"] * 2 - + ["d"] * 2 - + ["e"] * 2, - "cat3": [f"g{x}" for x in range(1, 15)], - "val": np.random.randint(100, size=14), - } - ) - - def f_copy(x): - x = x.copy() - x["rank"] = x.val.rank(method="min") - return x.groupby("cat2")["rank"].min() - - def f_no_copy(x): - x["rank"] = x.val.rank(method="min") - return x.groupby("cat2")["rank"].min() - - grpby_copy = df.groupby("cat1").apply(f_copy) - grpby_no_copy = df.groupby("cat1").apply(f_no_copy) - tm.assert_series_equal(grpby_copy, grpby_no_copy) - - -def test_no_mutate_but_looks_like(): - - # GH 8467 - # first show's mutation indicator - # second does not, but should yield the same results - df = DataFrame({"key": [1, 1, 1, 2, 2, 2, 3, 3, 3], "value": range(9)}) - - result1 = df.groupby("key", group_keys=True).apply(lambda x: x[:].key) - result2 = df.groupby("key", group_keys=True).apply(lambda x: x.key) - tm.assert_series_equal(result1, result2) - - def test_groupby_series_indexed_differently(): s1 = Series( [5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7],
@jreback comment in https://github.com/pandas-dev/pandas/pull/33072#pullrequestreview-391657128
https://api.github.com/repos/pandas-dev/pandas/pulls/33468
2020-04-10T21:03:01Z
2020-04-10T22:24:01Z
2020-04-10T22:24:00Z
2023-04-12T20:17:00Z
API: more permissive conversion to StringDtype
diff --git a/doc/source/user_guide/text.rst b/doc/source/user_guide/text.rst index bea0f42f6849c..3408b98b3179d 100644 --- a/doc/source/user_guide/text.rst +++ b/doc/source/user_guide/text.rst @@ -63,6 +63,29 @@ Or ``astype`` after the ``Series`` or ``DataFrame`` is created s s.astype("string") + +.. versionchanged:: 1.1.0 + +You can also use :class:`StringDtype`/``"string"`` as the dtype on non-string data and +it will be converted to ``string`` dtype: + +.. ipython:: python + + s = pd.Series(['a', 2, np.nan], dtype="string") + s + type(s[1]) + +or convert from existing pandas data: + +.. ipython:: python + + s1 = pd.Series([1, 2, np.nan], dtype="Int64") + s1 + s2 = s1.astype("string") + s2 + type(s2[0]) + + .. _text.differences: Behavior differences diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 20e2cce1a3dfa..64fdf5b2244cb 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -13,6 +13,24 @@ including other versions of pandas. Enhancements ~~~~~~~~~~~~ +.. _whatsnew_110.astype_string: + +All dtypes can now be converted to ``StringDtype`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Previously, declaring or converting to :class:`StringDtype` was in general only possible if the data was already only ``str`` or nan-like (:issue:`31204`). +:class:`StringDtype` now works in all situations where ``astype(str)`` or ``dtype=str`` work: + +For example, the below now works: + +.. ipython:: python + + ser = pd.Series([1, "abc", np.nan], dtype="string") + ser + ser[0] + pd.Series([1, 2, np.nan], dtype="Int64").astype("string") + + .. _whatsnew_110.period_index_partial_string_slicing: Nonmonotonic PeriodIndex Partial String Slicing diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index fb9e2f6732018..b5e917bafca7e 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -20,7 +20,7 @@ from pandas.util._validators import validate_fillna_kwargs from pandas.core.dtypes.cast import maybe_cast_to_extension_array -from pandas.core.dtypes.common import is_array_like, is_list_like +from pandas.core.dtypes.common import is_array_like, is_list_like, pandas_dtype from pandas.core.dtypes.dtypes import ExtensionDtype from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries from pandas.core.dtypes.missing import isna @@ -178,7 +178,7 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): ---------- scalars : Sequence Each element will be an instance of the scalar type for this - array, ``cls.dtype.type``. + array, ``cls.dtype.type`` or be converted into this type in this method. dtype : dtype, optional Construct for this particular dtype. This should be a Dtype compatible with the ExtensionArray. @@ -451,6 +451,12 @@ def astype(self, dtype, copy=True): array : ndarray NumPy ndarray with 'dtype' for its dtype. """ + from pandas.core.arrays.string_ import StringDtype + + dtype = pandas_dtype(dtype) + if isinstance(dtype, StringDtype): # allow conversion to StringArrays + return dtype.construct_array_type()._from_sequence(self, copy=False) + return np.array(self, dtype=dtype, copy=copy) def isna(self) -> ArrayLike: diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 3c1602344c314..cf3cde155a3bb 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -27,6 +27,7 @@ is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_dtype_equal, + is_extension_array_dtype, is_float_dtype, is_integer_dtype, is_list_like, @@ -619,7 +620,11 @@ def astype(self, dtype, copy=True): if is_object_dtype(dtype): return self._box_values(self.asi8.ravel()).reshape(self.shape) elif is_string_dtype(dtype) and not is_categorical_dtype(dtype): - return self._format_native_types() + if is_extension_array_dtype(dtype): + arr_cls = dtype.construct_array_type() + return arr_cls._from_sequence(self, dtype=dtype) + else: + return self._format_native_types() elif is_integer_dtype(dtype): # we deliberately ignore int32 vs. int64 here. # See https://github.com/pandas-dev/pandas/issues/24381 for more. diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 59954f548fd33..d4137f9666946 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -1,5 +1,5 @@ import numbers -from typing import TYPE_CHECKING, List, Optional, Tuple, Type, Union +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Type, Union import warnings import numpy as np @@ -442,17 +442,20 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: if incompatible type with an IntegerDtype, equivalent of same_kind casting """ - from pandas.core.arrays.boolean import BooleanArray, BooleanDtype + from pandas.core.arrays.boolean import BooleanDtype + from pandas.core.arrays.string_ import StringDtype 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) + return dtype.construct_array_type()(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) + return dtype.construct_array_type()(result, mask=self._mask, copy=False) + elif isinstance(dtype, StringDtype): + return dtype.construct_array_type()._from_sequence(self, copy=False) # coerce if is_float_dtype(dtype): @@ -722,7 +725,7 @@ class UInt64Dtype(_IntegerDtype): __doc__ = _dtype_docstring.format(dtype="uint64") -_dtypes = { +_dtypes: Dict[str, _IntegerDtype] = { "int8": Int8Dtype(), "int16": Int16Dtype(), "int32": Int32Dtype(), diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index c5366884fbdfe..c861d25afd13f 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -680,8 +680,11 @@ def astype(self, dtype, copy=True): array : ExtensionArray or ndarray ExtensionArray or NumPy ndarray with 'dtype' for its dtype. """ + from pandas.core.arrays.string_ import StringDtype + if dtype is not None: dtype = pandas_dtype(dtype) + if is_interval_dtype(dtype): if dtype == self.dtype: return self.copy() if copy else self @@ -698,6 +701,9 @@ def astype(self, dtype, copy=True): return self._shallow_copy(new_left, new_right) elif is_categorical_dtype(dtype): return Categorical(np.asarray(self)) + elif isinstance(dtype, StringDtype): + return dtype.construct_array_type()._from_sequence(self, copy=False) + # TODO: This try/except will be repeated. try: return np.asarray(self).astype(dtype, copy=copy) diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index a9090570e64a9..8d17ed412f6b4 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -13,6 +13,7 @@ from pandas.core.dtypes.cast import astype_nansafe from pandas.core.dtypes.common import ( is_bool_dtype, + is_extension_array_dtype, is_object_dtype, is_scalar, is_string_dtype, @@ -322,6 +323,9 @@ def update_dtype(self, dtype): dtype = pandas_dtype(dtype) if not isinstance(dtype, cls): + if is_extension_array_dtype(dtype): + raise TypeError("sparse arrays of extension dtypes not supported") + fill_value = astype_nansafe(np.array(self.fill_value), dtype).item() dtype = cls(dtype, fill_value=fill_value) diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 537b1cf3dd439..ac501a8afbe09 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -152,15 +152,21 @@ class StringArray(PandasArray): ['This is', 'some text', <NA>, 'data.'] Length: 4, dtype: string - Unlike ``object`` dtype arrays, ``StringArray`` doesn't allow non-string - values. + Unlike arrays instantiated with ``dtype="object"``, ``StringArray`` + will convert the values to strings. + >>> pd.array(['1', 1], dtype="object") + <PandasArray> + ['1', 1] + Length: 2, dtype: object >>> pd.array(['1', 1], dtype="string") - Traceback (most recent call last): - ... - ValueError: StringArray requires an object-dtype ndarray of strings. + <StringArray> + ['1', '1'] + Length: 2, dtype: string + + However, instantiating StringArrays directly with non-strings will raise an error. - For comparison methods, this returns a :class:`pandas.BooleanArray` + For comparison methods, `StringArray` returns a :class:`pandas.BooleanArray`: >>> pd.array(["a", None, "c"], dtype="string") == "a" <BooleanArray> @@ -203,10 +209,15 @@ def _from_sequence(cls, scalars, dtype=None, copy=False): # TODO: it would be nice to do this in _validate / lib.is_string_array # We are already doing a scan over the values there. na_values = isna(result) - if na_values.any(): - if result is scalars: - # force a copy now, if we haven't already - result = result.copy() + has_nans = na_values.any() + if has_nans and result is scalars: + # force a copy now, if we haven't already + result = result.copy() + + # convert to str, then to object to avoid dtype like '<U3', then insert na_value + result = np.asarray(result, dtype=str) + result = np.asarray(result, dtype="object") + if has_nans: result[na_values] = StringDtype.na_value return cls(result) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 424eb9d673df5..2a47a03b8d387 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -337,9 +337,16 @@ def maybe_cast_to_extension_array(cls: Type["ExtensionArray"], obj, dtype=None): ------- ExtensionArray or obj """ + from pandas.core.arrays.string_ import StringArray + assert isinstance(cls, type), f"must pass a type: {cls}" assertion_msg = f"must pass a subclass of ExtensionArray: {cls}" assert issubclass(cls, ABCExtensionArray), assertion_msg + + # Everything can be be converted to StringArrays, but we may not want to convert + if issubclass(cls, StringArray) and lib.infer_dtype(obj) != "string": + return obj + try: result = cls._from_sequence(obj, dtype=dtype) except Exception: diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index f33f960e8e341..567a62a8b33a5 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -33,7 +33,13 @@ def test_tolist(self, data): def test_astype_str(self, data): result = pd.Series(data[:5]).astype(str) - expected = pd.Series(data[:5].astype(str)) + expected = pd.Series([str(x) for x in data[:5]], dtype=str) + self.assert_series_equal(result, expected) + + def test_astype_string(self, data): + # GH-33465 + result = pd.Series(data[:5]).astype("string") + expected = pd.Series([str(x) for x in data[:5]], dtype="string") self.assert_series_equal(result, expected) def test_to_numpy(self, data): diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 85d8ad6ec6e38..4d5be75ff8200 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -7,6 +7,7 @@ import numpy as np from pandas.core.dtypes.base import ExtensionDtype +from pandas.core.dtypes.common import pandas_dtype import pandas as pd from pandas.api.extensions import no_default, register_extension_dtype @@ -130,9 +131,11 @@ def copy(self): return type(self)(self._data.copy()) def astype(self, dtype, copy=True): + dtype = pandas_dtype(dtype) if isinstance(dtype, type(self.dtype)): return type(self)(self._data, context=dtype.context) - return np.asarray(self, dtype=dtype) + + return super().astype(dtype, copy=copy) def __setitem__(self, key, value): if pd.api.types.is_list_like(value): diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 94f971938b690..3132b39a7d6d6 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -21,6 +21,8 @@ import numpy as np +from pandas.core.dtypes.common import pandas_dtype + import pandas as pd from pandas.api.extensions import ExtensionArray, ExtensionDtype @@ -160,12 +162,18 @@ def astype(self, dtype, copy=True): # NumPy has issues when all the dicts are the same length. # np.array([UserDict(...), UserDict(...)]) fails, # but np.array([{...}, {...}]) works, so cast. + from pandas.core.arrays.string_ import StringDtype + dtype = pandas_dtype(dtype) # needed to add this check for the Series constructor if isinstance(dtype, type(self.dtype)) and dtype == self.dtype: if copy: return self.copy() return self + elif isinstance(dtype, StringDtype): + value = self.astype(str) # numpy doesn'y like nested dicts + return dtype.construct_array_type()._from_sequence(value, copy=False) + return np.array([dict(x) for x in self], dtype=dtype, copy=copy) def unique(self): diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 1e21249988df6..78000c0252375 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -139,6 +139,12 @@ def test_astype_str(self, data): # ValueError: setting an array element with a sequence super().test_astype_str(data) + @skip_nested + def test_astype_string(self, data): + # GH-33465 + # ValueError: setting an array element with a sequence + super().test_astype_string(data) + class TestConstructors(BaseNumPyTests, base.BaseConstructorsTests): @pytest.mark.skip(reason="We don't register our dtype") diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index e59b3f0600867..332a7f5a4e124 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -343,6 +343,16 @@ def test_astype_object_frame(self, all_data): # comp = result.dtypes.equals(df.dtypes) # assert not comp.any() + def test_astype_str(self, data): + result = pd.Series(data[:5]).astype(str) + expected_dtype = pd.SparseDtype(str, str(data.fill_value)) + expected = pd.Series([str(x) for x in data[:5]], dtype=expected_dtype) + self.assert_series_equal(result, expected) + + @pytest.mark.xfail(raises=TypeError, reason="no sparse StringDtype") + def test_astype_string(self, data): + super().test_astype_string(data) + class TestArithmeticOps(BaseSparseTests, base.BaseArithmeticOpsTests): series_scalar_exc = None
- [x] closes #31204 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This is a proposal to make using ``StringDtype`` more permissive and be usable inplace of ``dtype=str``. ATM converting to StringDtype will only accept arrays that are ``str`` already, meaning you will often have to use ``astype(str).astype("string")`` to be sure not to get errors, which can be tedious. For example these fail in master and work in this PR: ```python >>> pd.Series([1,2, np.nan], dtype="string") 0 1 1 2 2 <NA> dtype: string >>> pd.array([1,2, np.nan], dtype="string") <StringArray> ['1', '2', <NA>] Length: 3, dtype: string >>> pd.Series([1,2, np.nan]).astype("string") 0 1.0 1 2.0 2 <NA> dtype: string >>> pd.Series([1,2, np.nan], dtype="Int64").astype("string") 0 1 1 2 2 <NA> dtype: string ``` etc. now work. Previously the above all gave errors. ## The proposed solution: ``ExtensionArray._from_sequence`` is in master explicitly stated to expect a sequence of scalars of the *correct* type. This makes it not usable for type conversion. I've therefore added a new ``ExtensionArray._from_sequence_of_any_type`` that accepts scalars of any type and may change the scalars to the correct type before passing them on to ``_from_sequence``. Currently it just routes everything through to ``ExtensionArray._from_sequence``, except in ``StringArray._from_sequence_of_any_type``, where it massages the input scalars into strings before passing them on. Obviously tests and doc updates are still missing, but I would appreciate feedback if this solution looks ok and I'll add tests and doc updates if this is ok.
https://api.github.com/repos/pandas-dev/pandas/pulls/33465
2020-04-10T19:50:25Z
2020-05-26T22:20:21Z
2020-05-26T22:20:20Z
2020-05-27T05:56:38Z
CLN: Nitpicks
diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx index e74b5919a4590..aed5e1d612088 100644 --- a/pandas/_libs/reshape.pyx +++ b/pandas/_libs/reshape.pyx @@ -36,7 +36,7 @@ ctypedef fused reshape_t: @cython.wraparound(False) @cython.boundscheck(False) -def unstack(reshape_t[:, :] values, uint8_t[:] mask, +def unstack(reshape_t[:, :] values, const uint8_t[:] mask, Py_ssize_t stride, Py_ssize_t length, Py_ssize_t width, reshape_t[:, :] new_values, uint8_t[:, :] new_mask): """ diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 22a44d65a947a..b74399ed86fbd 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -827,7 +827,7 @@ def _getitem_nested_tuple(self, tup: Tuple): # this is iterative obj = self.obj axis = 0 - for i, key in enumerate(tup): + for key in tup: if com.is_null_slice(key): axis += 1 @@ -1420,7 +1420,7 @@ def _is_scalar_access(self, key: Tuple) -> bool: if len(key) != self.ndim: return False - for i, k in enumerate(key): + for k in key: if not is_integer(k): return False @@ -2234,8 +2234,7 @@ def is_nested_tuple(tup, labels) -> bool: if not isinstance(tup, tuple): return False - for i, k in enumerate(tup): - + for k in tup: if is_list_like(k) or isinstance(k, slice): return isinstance(labels, ABCMultiIndex) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b8f45523106b3..385a417343ad4 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -48,8 +48,6 @@ make_block, ) -from pandas.io.formats.printing import pprint_thing - # TODO: flexible with index=None and/or items=None T = TypeVar("T", bound="BlockManager") @@ -325,7 +323,7 @@ def __repr__(self) -> str: output += f"\nAxis {i}: {ax}" for block in self.blocks: - output += f"\n{pprint_thing(block)}" + output += f"\n{block}" return output def _verify_integrity(self) -> None:
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33464
2020-04-10T19:33:41Z
2020-04-11T18:41:33Z
2020-04-11T18:41:33Z
2020-04-11T18:54:14Z
BUG: None converted to NaN after groupby first and last
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 718de09a0c3e4..f789b74e1b795 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -546,6 +546,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`) - Bug in :meth:`DataFrame.resample` where an ``AmbiguousTimeError`` would be raised when the resulting timezone aware :class:`DatetimeIndex` had a DST transition at midnight (:issue:`25758`) - Bug in :meth:`DataFrame.groupby` where a ``ValueError`` would be raised when grouping by a categorical column with read-only categories and ``sort=False`` (:issue:`33410`) +- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`) Reshaping ^^^^^^^^^ diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index e7ac3b8442c6d..53e66c4b8723d 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -893,7 +893,9 @@ def group_last(rank_t[:, :] out, for j in range(K): val = values[i, j] - if not checknull(val): + # None should not be treated like other NA-like + # so that it won't be converted to nan + if not checknull(val) or val is None: # NB: use _treat_as_na here once # conditional-nogil is available. nobs[lab, j] += 1 @@ -986,7 +988,9 @@ def group_nth(rank_t[:, :] out, for j in range(K): val = values[i, j] - if not checknull(val): + # None should not be treated like other NA-like + # so that it won't be converted to nan + if not checknull(val) or val is None: # NB: use _treat_as_na here once # conditional-nogil is available. nobs[lab, j] += 1 diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index e1bc058508bee..947907caf5cbc 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -94,6 +94,17 @@ def test_nth_with_na_object(index, nulls_fixture): tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize("method", ["first", "last"]) +def test_first_last_with_None(method): + # https://github.com/pandas-dev/pandas/issues/32800 + # None should be preserved as object dtype + df = pd.DataFrame.from_dict({"id": ["a"], "value": [None]}) + groups = df.groupby("id", as_index=False) + result = getattr(groups, method)() + + tm.assert_frame_equal(result, df) + + def test_first_last_nth_dtypes(df_mixed_floats): df = df_mixed_floats.copy()
- [x] closes #32800 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This PR solves #32800. In #32124 `not checknull()` was introduced to `groupfirst()` and `grouplast()`. `None` is not caught in this conditional and it's being converted to `nan` because of that. I'm a newbie and not sure whether I should add whatsnew entry or not. Should I?
https://api.github.com/repos/pandas-dev/pandas/pulls/33462
2020-04-10T17:48:02Z
2020-04-17T02:53:39Z
2020-04-17T02:53:39Z
2020-05-26T09:36:35Z
CI: fix lint issue
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 75c935cdf2e60..80573f32b936e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -8,7 +8,7 @@ from pandas._libs import NaT, algos as libalgos, lib, writers import pandas._libs.internals as libinternals -from pandas._libs.tslibs import Timedelta, conversion +from pandas._libs.tslibs import conversion from pandas._libs.tslibs.timezones import tz_compare from pandas._typing import ArrayLike from pandas.util._validators import validate_bool_kwarg
https://github.com/pandas-dev/pandas/runs/577244968 Linting .py code ##[error]./pandas/core/internals/blocks.py:11:1:F401:'pandas._libs.tslibs.Timedelta' imported but unused Linting .py code DONE
https://api.github.com/repos/pandas-dev/pandas/pulls/33461
2020-04-10T17:45:51Z
2020-04-10T19:16:14Z
2020-04-10T19:16:14Z
2020-04-11T08:36:45Z
TST: concat(..., copy=False) with datetime tz-aware data raises ValueError: cannot create a DatetimeTZBlock without a tz
diff --git a/pandas/tests/dtypes/test_concat.py b/pandas/tests/dtypes/test_concat.py index 1fbbd3356ae13..5a9ad732792ea 100644 --- a/pandas/tests/dtypes/test_concat.py +++ b/pandas/tests/dtypes/test_concat.py @@ -88,3 +88,14 @@ def test_concat_mismatched_categoricals_with_empty(): result = _concat.concat_compat([ser1._values, ser2._values]) expected = pd.concat([ser1, ser2])._values tm.assert_categorical_equal(result, expected) + + +@pytest.mark.parametrize("copy", [True, False]) +def test_concat_single_dataframe_tz_aware(copy): + # https://github.com/pandas-dev/pandas/issues/25257 + df = pd.DataFrame( + {"timestamp": [pd.Timestamp("2020-04-08 09:00:00.709949+0000", tz="UTC")]} + ) + expected = df.copy() + result = pd.concat([df], copy=copy) + tm.assert_frame_equal(result, expected)
…n version 0.24.1 but passes on current version - [x] closes #25257 - [x] tests added / passed
https://api.github.com/repos/pandas-dev/pandas/pulls/33458
2020-04-10T15:30:26Z
2020-07-13T12:55:12Z
2020-07-13T12:55:12Z
2020-07-13T12:55:29Z
TYP: F used in decorators to _typing
diff --git a/pandas/_config/config.py b/pandas/_config/config.py index df706bf25097e..8955a06187109 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -51,20 +51,11 @@ from collections import namedtuple from contextlib import contextmanager import re -from typing import ( - Any, - Callable, - Dict, - Iterable, - List, - Optional, - Tuple, - Type, - TypeVar, - cast, -) +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, cast import warnings +from pandas._typing import F + DeprecatedOption = namedtuple("DeprecatedOption", "key msg rkey removal_ver") RegisteredOption = namedtuple("RegisteredOption", "key defval doc validator cb") @@ -704,9 +695,6 @@ def pp(name: str, ks: Iterable[str]) -> List[str]: # # helpers -FuncType = Callable[..., Any] -F = TypeVar("F", bound=FuncType) - @contextmanager def config_prefix(prefix): diff --git a/pandas/_typing.py b/pandas/_typing.py index e1b6a5e2e6876..850f10bd7f811 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -75,3 +75,7 @@ # to maintain type information across generic functions and parametrization T = TypeVar("T") +# used in decorators to preserve the signature of the function it decorates +# see https://mypy.readthedocs.io/en/stable/generics.html#declaring-decorators +FuncType = Callable[..., Any] +F = TypeVar("F", bound=FuncType) diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 3547a33ea357b..6570e0782a69a 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -12,6 +12,8 @@ import sys import warnings +from pandas._typing import F + PY37 = sys.version_info >= (3, 7) PY38 = sys.version_info >= (3, 8) PYPY = platform.python_implementation() == "PyPy" @@ -25,7 +27,7 @@ # found at https://bitbucket.org/gutworth/six -def set_function_name(f, name, cls): +def set_function_name(f: F, name: str, cls) -> F: """ Bind the name/qualname attributes of the function. """ diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index 71d02db10c7ba..17815c437249b 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -1,24 +1,11 @@ from functools import wraps import inspect from textwrap import dedent -from typing import ( - Any, - Callable, - List, - Mapping, - Optional, - Tuple, - Type, - TypeVar, - Union, - cast, -) +from typing import Any, Callable, List, Mapping, Optional, Tuple, Type, Union, cast import warnings from pandas._libs.properties import cache_readonly # noqa - -FuncType = Callable[..., Any] -F = TypeVar("F", bound=FuncType) +from pandas._typing import F def deprecate( @@ -29,7 +16,7 @@ def deprecate( klass: Optional[Type[Warning]] = None, stacklevel: int = 2, msg: Optional[str] = None, -) -> Callable[..., Any]: +) -> Callable[[F], F]: """ Return a new function that emits a deprecation warning on use. @@ -100,7 +87,7 @@ def deprecate_kwarg( new_arg_name: Optional[str], mapping: Optional[Union[Mapping[Any, Any], Callable[[Any], Any]]] = None, stacklevel: int = 2, -) -> Callable[..., Any]: +) -> Callable[[F], F]: """ Decorator to deprecate a keyword argument of a function.
xref #27404
https://api.github.com/repos/pandas-dev/pandas/pulls/33456
2020-04-10T14:14:39Z
2020-04-10T17:02:33Z
2020-04-10T17:02:33Z
2020-04-10T17:10:57Z
Bump cython asv
diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json index 7886b63e9983e..7c10a2d17775a 100644 --- a/asv_bench/asv.conf.json +++ b/asv_bench/asv.conf.json @@ -39,7 +39,7 @@ // followed by the pip installed packages). "matrix": { "numpy": [], - "Cython": [], + "Cython": ["0.29.16"], "matplotlib": [], "sqlalchemy": [], "scipy": [],
We were pulling in an older version, possibly from defaults. I think we should plan a major update of all these (notably python 3.6 -> 3.8) but that'll require some care to not invalidate the results at pandas.pydata.org/speed/pandas.
https://api.github.com/repos/pandas-dev/pandas/pulls/33454
2020-04-10T13:07:26Z
2020-04-10T13:53:34Z
2020-04-10T13:53:34Z
2020-04-10T13:53:37Z
CLN/TYP: redundant casts and unused ignores
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index df58593bc930c..54e49eaf60021 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3838,7 +3838,7 @@ def values(self) -> np.ndarray: return self._data.view(np.ndarray) @cache_readonly - @doc(IndexOpsMixin.array) # type: ignore + @doc(IndexOpsMixin.array) def array(self) -> ExtensionArray: array = self._data if isinstance(array, np.ndarray): diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py index 6e68c1cf5e27e..69e9b111a6c20 100644 --- a/pandas/io/json/_normalize.py +++ b/pandas/io/json/_normalize.py @@ -231,7 +231,7 @@ def _pull_field( js: Dict[str, Any], spec: Union[List, str] ) -> Union[Scalar, Iterable]: """Internal function to pull field""" - result = js # type: ignore + result = js if isinstance(spec, list): for field in spec: result = result[field] @@ -251,7 +251,7 @@ def _pull_records(js: Dict[str, Any], spec: Union[List, str]) -> Iterable: # null, otherwise return an empty list if not isinstance(result, Iterable): if pd.isnull(result): - result = [] # type: ignore + result = [] else: raise TypeError( f"{js} has non iterable value {result} for path {spec}. " diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index a22251b29da54..3dd87ae6ed758 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1916,9 +1916,7 @@ def is_indexed(self) -> bool: if not hasattr(self.table, "cols"): # e.g. if infer hasn't been called yet, self.table will be None. return False - # GH#29692 mypy doesn't recognize self.table as having a "cols" attribute - # 'error: "None" has no attribute "cols"' - return getattr(self.table.cols, self.cname).is_indexed # type: ignore + return getattr(self.table.cols, self.cname).is_indexed def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): """ diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 8f3aa60b7a9cc..b9b43685415d1 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -356,10 +356,9 @@ def parse_dates_safe(dates, delta=False, year=False, days=False): time_delta = dates - stata_epoch d["delta"] = time_delta._values.astype(np.int64) // 1000 # microseconds if days or year: - # ignore since mypy reports that DatetimeIndex has no year/month date_index = DatetimeIndex(dates) - d["year"] = date_index.year # type: ignore - d["month"] = date_index.month # type: ignore + d["year"] = date_index.year + d["month"] = date_index.month if days: days_in_ns = dates.astype(np.int64) - to_datetime( d["year"], format="%Y" diff --git a/setup.cfg b/setup.cfg index fda4ba4065e2f..6c42b27c7b015 100644 --- a/setup.cfg +++ b/setup.cfg @@ -126,6 +126,8 @@ ignore_missing_imports=True no_implicit_optional=True check_untyped_defs=True strict_equality=True +warn_redundant_casts = True +warn_unused_ignores = True [mypy-pandas.tests.*] check_untyped_defs=False
https://api.github.com/repos/pandas-dev/pandas/pulls/33453
2020-04-10T12:26:20Z
2020-04-10T15:38:42Z
2020-04-10T15:38:42Z
2020-04-10T15:50:55Z
Whitelist std and var for use with custom rolling windows
diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst index af2f02a09428b..d7d025981f2f4 100644 --- a/doc/source/user_guide/computation.rst +++ b/doc/source/user_guide/computation.rst @@ -312,8 +312,8 @@ We provide a number of common statistical functions: :meth:`~Rolling.median`, Arithmetic median of values :meth:`~Rolling.min`, Minimum :meth:`~Rolling.max`, Maximum - :meth:`~Rolling.std`, Bessel-corrected sample standard deviation - :meth:`~Rolling.var`, Unbiased variance + :meth:`~Rolling.std`, Sample standard deviation + :meth:`~Rolling.var`, Sample variance :meth:`~Rolling.skew`, Sample skewness (3rd moment) :meth:`~Rolling.kurt`, Sample kurtosis (4th moment) :meth:`~Rolling.quantile`, Sample quantile (value at %) @@ -321,6 +321,26 @@ We provide a number of common statistical functions: :meth:`~Rolling.cov`, Unbiased covariance (binary) :meth:`~Rolling.corr`, Correlation (binary) +.. _computation.window_variance.caveats: + +.. note:: + + Please note that :meth:`~Rolling.std` and :meth:`~Rolling.var` use the sample + variance formula by default, i.e. the sum of squared differences is divided by + ``window_size - 1`` and not by ``window_size`` during averaging. In statistics, + we use sample when the dataset is drawn from a larger population that we + don't have access to. Using it implies that the data in our window is a + random sample from the population, and we are interested not in the variance + inside the specific window but in the variance of some general window that + our windows represent. In this situation, using the sample variance formula + results in an unbiased estimator and so is preferred. + + Usually, we are instead interested in the variance of each window as we slide + it over the data, and in this case we should specify ``ddof=0`` when calling + these methods to use population variance instead of sample variance. Using + sample variance under the circumstances would result in a biased estimator + of the variable we are trying to determine. + .. _stats.rolling_apply: Rolling apply @@ -848,8 +868,8 @@ Method summary :meth:`~Expanding.median`, Arithmetic median of values :meth:`~Expanding.min`, Minimum :meth:`~Expanding.max`, Maximum - :meth:`~Expanding.std`, Unbiased standard deviation - :meth:`~Expanding.var`, Unbiased variance + :meth:`~Expanding.std`, Sample standard deviation + :meth:`~Expanding.var`, Sample variance :meth:`~Expanding.skew`, Unbiased skewness (3rd moment) :meth:`~Expanding.kurt`, Unbiased kurtosis (4th moment) :meth:`~Expanding.quantile`, Sample quantile (value at %) @@ -857,6 +877,13 @@ Method summary :meth:`~Expanding.cov`, Unbiased covariance (binary) :meth:`~Expanding.corr`, Correlation (binary) +.. note:: + + Using sample variance formulas for :meth:`~Expanding.std` and + :meth:`~Expanding.var` comes with the same caveats as using them with rolling + windows. See :ref:`this section <computation.window_variance.caveats>` for more + information. + .. currentmodule:: pandas Aside from not having a ``window`` parameter, these functions have the same diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 2f4e961ff433f..00b52c0650920 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -129,7 +129,7 @@ Other API changes - 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`) -- Using a :func:`pandas.api.indexers.BaseIndexer` with ``std``, ``var``, ``count``, ``skew``, ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`) +- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``skew``, ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`) - Using a :func:`pandas.api.indexers.BaseIndexer` with ``min``, ``max`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`) - Added a :func:`pandas.api.indexers.FixedForwardWindowIndexer` class to support forward-looking windows during ``rolling`` operations. - diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py index 05f19de19f9f7..40f17126fa163 100644 --- a/pandas/core/window/common.py +++ b/pandas/core/window/common.py @@ -327,7 +327,17 @@ def func(arg, window, min_periods=None): def validate_baseindexer_support(func_name: Optional[str]) -> None: # GH 32865: These functions work correctly with a BaseIndexer subclass - BASEINDEXER_WHITELIST = {"min", "max", "mean", "sum", "median", "kurt", "quantile"} + BASEINDEXER_WHITELIST = { + "min", + "max", + "mean", + "sum", + "median", + "std", + "var", + "kurt", + "quantile", + } if isinstance(func_name, str) and func_name not in BASEINDEXER_WHITELIST: raise NotImplementedError( f"{func_name} is not supported with using a BaseIndexer " diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py index bb93c70b8a597..43489e310bb93 100644 --- a/pandas/tests/window/test_base_indexer.py +++ b/pandas/tests/window/test_base_indexer.py @@ -82,7 +82,7 @@ def get_window_bounds(self, num_values, min_periods, center, closed): df.rolling(indexer, win_type="boxcar") -@pytest.mark.parametrize("func", ["std", "var", "count", "skew", "cov", "corr"]) +@pytest.mark.parametrize("func", ["count", "skew", "cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer): @@ -97,13 +97,52 @@ def get_window_bounds(self, num_values, min_periods, center, closed): @pytest.mark.parametrize("constructor", [Series, DataFrame]) @pytest.mark.parametrize( - "func,alt_func,expected", + "func,np_func,expected,np_kwargs", [ - ("min", np.min, [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, np.nan]), - ("max", np.max, [2.0, 3.0, 4.0, 100.0, 100.0, 100.0, 8.0, 9.0, 9.0, np.nan]), + ("min", np.min, [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 6.0, 7.0, 8.0, np.nan], {},), + ( + "max", + np.max, + [2.0, 3.0, 4.0, 100.0, 100.0, 100.0, 8.0, 9.0, 9.0, np.nan], + {}, + ), + ( + "std", + np.std, + [ + 1.0, + 1.0, + 1.0, + 55.71654452, + 54.85739087, + 53.9845657, + 1.0, + 1.0, + 0.70710678, + np.nan, + ], + {"ddof": 1}, + ), + ( + "var", + np.var, + [ + 1.0, + 1.0, + 1.0, + 3104.333333, + 3009.333333, + 2914.333333, + 1.0, + 1.0, + 0.500000, + np.nan, + ], + {"ddof": 1}, + ), ], ) -def test_rolling_forward_window(constructor, func, alt_func, expected): +def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs): # GH 32865 values = np.arange(10) values[5] = 100.0 @@ -124,5 +163,5 @@ def test_rolling_forward_window(constructor, func, alt_func, expected): result = getattr(rolling, func)() expected = constructor(expected) tm.assert_equal(result, expected) - expected2 = constructor(rolling.apply(lambda x: alt_func(x))) + expected2 = constructor(rolling.apply(lambda x: np_func(x, **np_kwargs))) tm.assert_equal(result, expected2)
- [X] xref #32865 - [X] 0 tests added / 0 passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry ### The problem While researching what funcitons are broken for #32865 , I added `std` and `var` to the list since their output didn't match numpy output. I have since discovered that this is because we default to the sample variance formula for all window calculations. After closer examination, the algorithm itself turned out to be very robust against custom indexers. It is even resilient against non-monothonic window starts and ends. There is nothing to do there, so we should revert blacklisting `std` and `var`. I don't think tests are necessary, since we aren't changing anything. ### Food for thought Some background information to make our decision here more informed: The reason I first believed these functions to be broken is because using the sample variance formula for sliding windows makes no sense to me from a statistical viewpoint. We use sample variance when the dataset is a sample drawn from a larger population. **A window is not a sample**. When we calculate sliding window variance, we aren't interested in getting the correct variance for some underlying general window, we are interested in computing it correctly for each window, and thus each window is the population. However, as we discussed with @mroeschke: 1) Usually users are interested in calculating variance for large windows, and the difference between formulas for variance is proportional to `1 / (window_size - 1) - 1 / window_size` 2) We use sample variance as a default everywhere else in pandas. 3) The user can specify `rolling.var(ddof=0)` to set degrees of freedom to zero and get population variance, if they know what they want and are aware that pandas uses sample variance by default. So the default doesn't make much sense, but it is consistent with the rest of our software, and the harm is negligible for most use cases. The harm in changing the default would be that people who know the package well might expect the sample variance default. Apologies for the long read. It's a part of my job to find mistakes in data science models, so I'm sensitive to stuff like this.
https://api.github.com/repos/pandas-dev/pandas/pulls/33448
2020-04-10T07:21:48Z
2020-04-17T02:54:51Z
2020-04-17T02:54:51Z
2020-04-17T06:27:03Z
BUG: Fix ValueError when grouping by read-only category (#33410)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5c39377899a20..38f850422d7ae 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -517,6 +517,7 @@ Groupby/resample/rolling - Bug in :meth:`SeriesGroupBy.first`, :meth:`SeriesGroupBy.last`, :meth:`SeriesGroupBy.min`, and :meth:`SeriesGroupBy.max` returning floats when applied to nullable Booleans (:issue:`33071`) - Bug in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`) - Bug in :meth:`DataFrame.resample` where an ``AmbiguousTimeError`` would be raised when the resulting timezone aware :class:`DatetimeIndex` had a DST transition at midnight (:issue:`25758`) +- Bug in :meth:`DataFrame.groupby` where a ``ValueError`` would be raised when grouping by a categorical column with read-only categories and ``sort=False`` (:issue:`33410`) Reshaping ^^^^^^^^^ diff --git a/pandas/_libs/hashtable_func_helper.pxi.in b/pandas/_libs/hashtable_func_helper.pxi.in index f8f3858b803a5..6e5509a5570e8 100644 --- a/pandas/_libs/hashtable_func_helper.pxi.in +++ b/pandas/_libs/hashtable_func_helper.pxi.in @@ -206,7 +206,7 @@ def duplicated_{{dtype}}({{c_type}}[:] values, object keep='first'): {{if dtype == 'object'}} def ismember_{{dtype}}(ndarray[{{c_type}}] arr, ndarray[{{c_type}}] values): {{else}} -def ismember_{{dtype}}({{c_type}}[:] arr, {{c_type}}[:] values): +def ismember_{{dtype}}(const {{c_type}}[:] arr, {{c_type}}[:] values): {{endif}} """ Return boolean of values in arr on an diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index e570ea201cc3a..da8327f64e26f 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1380,3 +1380,15 @@ def test_groupby_agg_non_numeric(): result = df.groupby([1, 2, 1]).nunique() tm.assert_frame_equal(result, expected) + + +def test_read_only_category_no_sort(): + # GH33410 + cats = np.array([1, 2]) + cats.flags.writeable = False + df = DataFrame( + {"a": [1, 3, 5, 7], "b": Categorical([1, 1, 2, 2], categories=Index(cats))} + ) + expected = DataFrame(data={"a": [2, 6]}, index=CategoricalIndex([1, 2], name="b")) + result = df.groupby("b", sort=False).mean() + tm.assert_frame_equal(result, expected)
- [x] closes #33410 - [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/33446
2020-04-10T02:12:31Z
2020-04-10T16:57:10Z
2020-04-10T16:57:09Z
2020-04-10T17:10:43Z
REF: remove replace_list kludge
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 75c935cdf2e60..80573f32b936e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -8,7 +8,7 @@ from pandas._libs import NaT, algos as libalgos, lib, writers import pandas._libs.internals as libinternals -from pandas._libs.tslibs import Timedelta, conversion +from pandas._libs.tslibs import conversion from pandas._libs.tslibs.timezones import tz_compare from pandas._typing import ArrayLike from pandas.util._validators import validate_bool_kwarg diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b8f45523106b3..fcde8d12d1609 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -7,14 +7,13 @@ import numpy as np -from pandas._libs import Timedelta, Timestamp, internals as libinternals, lib +from pandas._libs import internals as libinternals, lib from pandas._typing import ArrayLike, DtypeObj, Label, Scalar from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import ( find_common_type, infer_dtype_from_scalar, - maybe_convert_objects, maybe_promote, ) from pandas.core.dtypes.common import ( @@ -33,6 +32,7 @@ import pandas.core.algorithms as algos from pandas.core.arrays.sparse import SparseDtype from pandas.core.base import PandasObject +import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.api import Index, ensure_index @@ -626,11 +626,8 @@ def comp(s, regex=False): """ if isna(s): return isna(values) - if isinstance(s, (Timedelta, Timestamp)) and getattr(s, "tz", None) is None: - return _compare_or_regex_search( - maybe_convert_objects(values), s.asm8, regex - ) + s = com.maybe_box_datetimelike(s) return _compare_or_regex_search(values, s, regex) masks = [comp(s, regex) for s in src_list] @@ -643,11 +640,10 @@ def comp(s, regex=False): # replace ALWAYS will return a list rb = [blk if inplace else blk.copy()] for i, (s, d) in enumerate(zip(src_list, dest_list)): - # TODO: assert/validate that `d` is always a scalar? new_rb: List[Block] = [] for b in rb: m = masks[i][b.mgr_locs.indexer] - convert = i == src_len + convert = i == src_len # only convert once at the end result = b._replace_coerce( mask=m, to_replace=s, diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index 685457aff6341..1c54e2b988219 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -108,6 +108,16 @@ def test_replace_gh5319(self): expected = pd.Series([pd.Timestamp.min, ts], dtype=object) tm.assert_series_equal(expected, result) + def test_replace_timedelta_td64(self): + tdi = pd.timedelta_range(0, periods=5) + ser = pd.Series(tdi) + + # Using a single dict argument means we go through replace_list + result = ser.replace({ser[1]: ser[3]}) + + expected = pd.Series([ser[0], ser[3], ser[2], ser[3], ser[4]]) + tm.assert_series_equal(result, expected) + def test_replace_with_single_list(self): ser = pd.Series([0, 1, 2, 3, 4]) result = ser.replace([1, 2, 3])
This sits on top of #33441
https://api.github.com/repos/pandas-dev/pandas/pulls/33445
2020-04-10T01:43:16Z
2020-04-10T20:55:01Z
2020-04-10T20:55:01Z
2020-04-10T20:57:33Z
DOC: Fix heading capitalization in doc/source/whatsnew - part4 (#32550)
diff --git a/doc/source/whatsnew/v0.14.0.rst b/doc/source/whatsnew/v0.14.0.rst index 0041f6f03afef..847a42b3a7643 100644 --- a/doc/source/whatsnew/v0.14.0.rst +++ b/doc/source/whatsnew/v0.14.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0140: -v0.14.0 (May 31 , 2014) ------------------------ +Version 0.14.0 (May 31 , 2014) +------------------------------ {{ header }} @@ -321,7 +321,7 @@ Text parsing API changes .. _whatsnew_0140.groupby: -Groupby API changes +GroupBy API changes ~~~~~~~~~~~~~~~~~~~ More consistent behavior for some groupby methods: @@ -473,8 +473,8 @@ Some other enhancements to the sql functions include: .. _whatsnew_0140.slicers: -Multiindexing using slicers -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Multi-indexing using slicers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In 0.14.0 we added a new way to slice MultiIndexed objects. You can slice a MultiIndex by providing multiple indexers. diff --git a/doc/source/whatsnew/v0.14.1.rst b/doc/source/whatsnew/v0.14.1.rst index 26018c5745a11..3dfc4272681df 100644 --- a/doc/source/whatsnew/v0.14.1.rst +++ b/doc/source/whatsnew/v0.14.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0141: -v0.14.1 (July 11, 2014) ------------------------ +Version 0.14.1 (July 11, 2014) +------------------------------ {{ header }} diff --git a/doc/source/whatsnew/v0.15.0.rst b/doc/source/whatsnew/v0.15.0.rst index fc190908bdc07..b80ed7446f805 100644 --- a/doc/source/whatsnew/v0.15.0.rst +++ b/doc/source/whatsnew/v0.15.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0150: -v0.15.0 (October 18, 2014) --------------------------- +Version 0.15.0 (October 18, 2014) +--------------------------------- {{ header }} @@ -105,7 +105,7 @@ For full docs, see the :ref:`categorical introduction <categorical>` and the .. _whatsnew_0150.timedeltaindex: -TimedeltaIndex/Scalar +TimedeltaIndex/scalar ^^^^^^^^^^^^^^^^^^^^^ We introduce a new scalar type ``Timedelta``, which is a subclass of ``datetime.timedelta``, and behaves in a similar manner, @@ -247,8 +247,8 @@ Additionally :meth:`~pandas.DataFrame.memory_usage` is an available method for a .. _whatsnew_0150.dt: -.dt accessor -^^^^^^^^^^^^ +Series.dt accessor +^^^^^^^^^^^^^^^^^^ ``Series`` has gained an accessor to succinctly return datetime like properties for the *values* of the Series, if its a datetime/period like Series. (:issue:`7207`) This will return a Series, indexed like the existing Series. See the :ref:`docs <basics.dt_accessors>` @@ -600,7 +600,7 @@ Rolling/expanding moments improvements .. _whatsnew_0150.sql: -Improvements in the SQL io module +Improvements in the SQL IO module ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Added support for a ``chunksize`` parameter to ``to_sql`` function. This allows DataFrame to be written in chunks and avoid packet-size overflow errors (:issue:`8062`). diff --git a/doc/source/whatsnew/v0.15.1.rst b/doc/source/whatsnew/v0.15.1.rst index 2e036267b5804..f9c17058dc3ee 100644 --- a/doc/source/whatsnew/v0.15.1.rst +++ b/doc/source/whatsnew/v0.15.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0151: -v0.15.1 (November 9, 2014) --------------------------- +Version 0.15.1 (November 9, 2014) +--------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.15.2.rst b/doc/source/whatsnew/v0.15.2.rst index 292351c709940..a4eabb97471de 100644 --- a/doc/source/whatsnew/v0.15.2.rst +++ b/doc/source/whatsnew/v0.15.2.rst @@ -1,7 +1,7 @@ .. _whatsnew_0152: -v0.15.2 (December 12, 2014) ---------------------------- +Version 0.15.2 (December 12, 2014) +---------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.16.0.rst b/doc/source/whatsnew/v0.16.0.rst index 855d0b8695bb1..4ad533e68e275 100644 --- a/doc/source/whatsnew/v0.16.0.rst +++ b/doc/source/whatsnew/v0.16.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0160: -v0.16.0 (March 22, 2015) ------------------------- +Version 0.16.0 (March 22, 2015) +------------------------------- {{ header }} @@ -218,7 +218,7 @@ Backwards incompatible API changes .. _whatsnew_0160.api_breaking.timedelta: -Changes in Timedelta +Changes in timedelta ^^^^^^^^^^^^^^^^^^^^ In v0.15.0 a new scalar type ``Timedelta`` was introduced, that is a diff --git a/doc/source/whatsnew/v0.16.1.rst b/doc/source/whatsnew/v0.16.1.rst index 502c1287efdbe..8dcac4c1044be 100644 --- a/doc/source/whatsnew/v0.16.1.rst +++ b/doc/source/whatsnew/v0.16.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0161: -v0.16.1 (May 11, 2015) ----------------------- +Version 0.16.1 (May 11, 2015) +----------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.16.2.rst b/doc/source/whatsnew/v0.16.2.rst index 543f9c6bbf300..a3c34db09f555 100644 --- a/doc/source/whatsnew/v0.16.2.rst +++ b/doc/source/whatsnew/v0.16.2.rst @@ -1,7 +1,7 @@ .. _whatsnew_0162: -v0.16.2 (June 12, 2015) ------------------------ +Version 0.16.2 (June 12, 2015) +------------------------------ {{ header }} diff --git a/doc/source/whatsnew/v0.17.0.rst b/doc/source/whatsnew/v0.17.0.rst index 67abad659dc8d..11c252192be6b 100644 --- a/doc/source/whatsnew/v0.17.0.rst +++ b/doc/source/whatsnew/v0.17.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0170: -v0.17.0 (October 9, 2015) -------------------------- +Version 0.17.0 (October 9, 2015) +-------------------------------- {{ header }} @@ -181,8 +181,8 @@ Each method signature only includes relevant arguments. Currently, these are lim Additional methods for ``dt`` accessor ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -strftime -"""""""" +Series.dt.strftime +"""""""""""""""""" We are now supporting a ``Series.dt.strftime`` method for datetime-likes to generate a formatted string (:issue:`10110`). Examples: @@ -202,8 +202,8 @@ We are now supporting a ``Series.dt.strftime`` method for datetime-likes to gene The string format is as the python standard library and details can be found `here <https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>`_ -total_seconds -""""""""""""" +Series.dt.total_seconds +""""""""""""""""""""""" ``pd.Series`` of type ``timedelta64`` has new method ``.dt.total_seconds()`` returning the duration of the timedelta in seconds (:issue:`10817`) diff --git a/doc/source/whatsnew/v0.17.1.rst b/doc/source/whatsnew/v0.17.1.rst index 55080240f2a55..5d15a01aee5a0 100644 --- a/doc/source/whatsnew/v0.17.1.rst +++ b/doc/source/whatsnew/v0.17.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0171: -v0.17.1 (November 21, 2015) ---------------------------- +Version 0.17.1 (November 21, 2015) +---------------------------------- {{ header }} diff --git a/scripts/validate_rst_title_capitalization.py b/scripts/validate_rst_title_capitalization.py index 907db4ab4c7ce..9cf4922fa2662 100755 --- a/scripts/validate_rst_title_capitalization.py +++ b/scripts/validate_rst_title_capitalization.py @@ -58,6 +58,7 @@ "DatetimeIndex", "IntervalIndex", "CategoricalIndex", + "Categorical", "GroupBy", "SPSS", "ORC", @@ -112,6 +113,14 @@ "November", "December", "Float64Index", + "TZ", + "GIL", + "strftime", + "XPORT", + "Unicode", + "East", + "Asian", + "None", } CAP_EXCEPTIONS_DICT = {word.lower(): word for word in CAPITALIZATION_EXCEPTIONS}
Add exceptions to the list in 'scripts/validate_rst_title_capitalization.py' - [ ] Modify files in doc/source/whatsnew: v0.14.0.rst, v0.14.1.rst, v0.15.0.rst, v0.15.1.rst, v0.15.2.rst, v0.16.0.rst, v0.16.1.rst, v0.16.2.rst, v0.17.0.rst, v0.17.1.rst - [ ] Modify files in scripts: validate_rst_title_capitalization.py
https://api.github.com/repos/pandas-dev/pandas/pulls/33444
2020-04-09T22:21:38Z
2020-04-17T02:55:35Z
2020-04-17T02:55:35Z
2020-04-17T02:55:52Z
ENH: Add prod to masked_reductions
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 718de09a0c3e4..b31041886cf15 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -377,7 +377,7 @@ Performance improvements sparse values from ``scipy.sparse`` matrices using the :meth:`DataFrame.sparse.from_spmatrix` constructor (:issue:`32821`, :issue:`32825`, :issue:`32826`, :issue:`32856`, :issue:`32858`). -- Performance improvement in reductions (sum, min, max) for nullable (integer and boolean) dtypes (:issue:`30982`, :issue:`33261`). +- Performance improvement in reductions (sum, prod, min, max) for nullable (integer and boolean) dtypes (:issue:`30982`, :issue:`33261`, :issue:`33442`). .. --------------------------------------------------------------------------- diff --git a/pandas/core/array_algos/masked_reductions.py b/pandas/core/array_algos/masked_reductions.py index b3723340cefd6..1b9ed014f27b7 100644 --- a/pandas/core/array_algos/masked_reductions.py +++ b/pandas/core/array_algos/masked_reductions.py @@ -3,6 +3,8 @@ for missing values. """ +from typing import Callable + import numpy as np from pandas._libs import missing as libmissing @@ -11,14 +13,19 @@ from pandas.core.nanops import check_below_min_count -def sum( - values: np.ndarray, mask: np.ndarray, skipna: bool = True, min_count: int = 0, +def _sumprod( + func: Callable, + values: np.ndarray, + mask: np.ndarray, + skipna: bool = True, + min_count: int = 0, ): """ - Sum for 1D masked array. + Sum or product for 1D masked array. Parameters ---------- + func : np.sum or np.prod values : np.ndarray Numpy array with the values (can be of any dtype that support the operation). @@ -31,23 +38,33 @@ def sum( ``min_count`` non-NA values are present the result will be NA. """ if not skipna: - if mask.any(): + if mask.any() or check_below_min_count(values.shape, None, min_count): return libmissing.NA else: - if check_below_min_count(values.shape, None, min_count): - return libmissing.NA - return np.sum(values) + return func(values) else: if check_below_min_count(values.shape, mask, min_count): return libmissing.NA if _np_version_under1p17: - return np.sum(values[~mask]) + return func(values[~mask]) else: - return np.sum(values, where=~mask) + return func(values, where=~mask) + + +def sum(values: np.ndarray, mask: np.ndarray, skipna: bool = True, min_count: int = 0): + return _sumprod( + np.sum, values=values, mask=mask, skipna=skipna, min_count=min_count + ) -def _minmax(func, values: np.ndarray, mask: np.ndarray, skipna: bool = True): +def prod(values: np.ndarray, mask: np.ndarray, skipna: bool = True, min_count: int = 0): + return _sumprod( + np.prod, values=values, mask=mask, skipna=skipna, min_count=min_count + ) + + +def _minmax(func: Callable, values: np.ndarray, mask: np.ndarray, skipna: bool = True): """ Reduction for 1D masked array. @@ -63,18 +80,15 @@ def _minmax(func, values: np.ndarray, mask: np.ndarray, skipna: bool = True): Whether to skip NA. """ if not skipna: - if mask.any(): + if mask.any() or not values.size: + # min/max with empty array raise in numpy, pandas returns NA return libmissing.NA else: - if values.size: - return func(values) - else: - # min/max with empty array raise in numpy, pandas returns NA - return libmissing.NA + return func(values) else: subset = values[~mask] if subset.size: - return func(values[~mask]) + return func(subset) else: # min/max with empty array raise in numpy, pandas returns NA return libmissing.NA diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 40c838cbbd1df..685a9ec48228f 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -24,7 +24,7 @@ ) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries -from pandas.core.dtypes.missing import isna, notna +from pandas.core.dtypes.missing import isna from pandas.core import nanops, ops from pandas.core.array_algos import masked_reductions @@ -686,7 +686,7 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): data = self._data mask = self._mask - if name in {"sum", "min", "max"}: + if name in {"sum", "prod", "min", "max"}: op = getattr(masked_reductions, name) return op(data, mask, skipna=skipna, **kwargs) @@ -700,12 +700,6 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): if np.isnan(result): return libmissing.NA - # if we have numeric op that would result in an int, coerce to int if possible - if name == "prod" and notna(result): - int_result = np.int64(result) - if int_result == result: - result = int_result - return result def _maybe_mask_result(self, result, mask, other, op_name: str): diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 5d6f49852e696..37620edfd9a95 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -28,7 +28,6 @@ from pandas.core import nanops, ops from pandas.core.array_algos import masked_reductions -import pandas.core.common as com from pandas.core.indexers import check_array_indexer from pandas.core.ops import invalid_comparison from pandas.core.ops.common import unpack_zerodim_and_defer @@ -557,7 +556,7 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): data = self._data mask = self._mask - if name in {"sum", "min", "max"}: + if name in {"sum", "prod", "min", "max"}: op = getattr(masked_reductions, name) return op(data, mask, skipna=skipna, **kwargs) @@ -576,12 +575,6 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): if name in ["any", "all"]: pass - # if we have a preservable numeric op, - # provide coercion back to an integer type if possible - elif name == "prod": - # GH#31409 more performant than casting-then-checking - result = com.cast_scalar_indexer(result) - return result def _maybe_mask_result(self, result, mask, other, op_name: str): diff --git a/pandas/tests/arrays/boolean/test_reduction.py b/pandas/tests/arrays/boolean/test_reduction.py index 5dd5620162a8a..a5c18a25f8e16 100644 --- a/pandas/tests/arrays/boolean/test_reduction.py +++ b/pandas/tests/arrays/boolean/test_reduction.py @@ -52,7 +52,7 @@ def test_reductions_return_types(dropna, data, all_numeric_reductions): if op == "sum": assert isinstance(getattr(s, op)(), np.int_) elif op == "prod": - assert isinstance(getattr(s, op)(), np.int64) + assert isinstance(getattr(s, op)(), np.int_) elif op in ("min", "max"): assert isinstance(getattr(s, op)(), np.bool_) else: diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py index 515013e95c717..a02501e2dcbf2 100644 --- a/pandas/tests/arrays/integer/test_dtypes.py +++ b/pandas/tests/arrays/integer/test_dtypes.py @@ -34,7 +34,7 @@ def test_preserve_dtypes(op): # op result = getattr(df.C, op)() - if op in {"sum", "min", "max"}: + if op in {"sum", "prod", "min", "max"}: assert isinstance(result, np.int64) else: assert isinstance(result, int) diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index f55ec75b47dfa..725533765ca2c 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -238,9 +238,10 @@ def check_reduce(self, s, op_name, skipna): # overwrite to ensure pd.NA is tested instead of np.nan # https://github.com/pandas-dev/pandas/issues/30958 result = getattr(s, op_name)(skipna=skipna) - expected = getattr(s.astype("float64"), op_name)(skipna=skipna) - if np.isnan(expected): + if not skipna and s.isna().any(): expected = pd.NA + else: + expected = getattr(s.dropna().astype("int64"), op_name)(skipna=skipna) tm.assert_almost_equal(result, expected)
Adding prod to /core/array_algos/masked_reductions.py and using them for IntegerArray and BooleanArray. This also seems to offer a decent speedup over nanops like the other reductions: ```python # Branch [ins] In [3]: %timeit arr.prod() # arr = pd.Series([None, 0, 1, 2] * 10_000, dtype="Int64") 102 µs ± 379 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) [ins] In [5]: %timeit arr.prod() # arr = pd.Series([0, 0, 1, 2] * 10_000, dtype="Int64") 82.6 µs ± 752 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # Master [ins] In [4]: %timeit arr.prod() # arr = pd.Series([None, 0, 1, 2] * 10_000, dtype="Int64") 291 µs ± 6.23 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) [ins] In [6]: %timeit arr.prod() # arr = pd.Series([0, 0, 1, 2] * 10_000, dtype="Int64") 78.6 µs ± 2.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/33442
2020-04-09T20:14:40Z
2020-04-12T22:59:02Z
2020-04-12T22:59:02Z
2020-04-12T23:21:57Z
BUG: Timedelta == ndarray[td64]
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5c39377899a20..1161ac2d19049 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -395,6 +395,7 @@ Timedelta - Bug in dividing ``np.nan`` or ``None`` by :class:`Timedelta`` incorrectly returning ``NaT`` (:issue:`31869`) - Timedeltas now understand ``µs`` as identifier for microsecond (:issue:`32899`) - :class:`Timedelta` string representation now includes nanoseconds, when nanoseconds are non-zero (:issue:`9309`) +- Bug in comparing a :class:`Timedelta`` object against a ``np.ndarray`` with ``timedelta64`` dtype incorrectly viewing all entries as unequal (:issue:`33441`) Timezones ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 3af2279e2440f..c5092c8630f06 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -778,36 +778,32 @@ cdef class _Timedelta(timedelta): if isinstance(other, _Timedelta): ots = other - elif PyDelta_Check(other) or isinstance(other, Tick): + elif (is_timedelta64_object(other) or PyDelta_Check(other) + or isinstance(other, Tick)): ots = Timedelta(other) - else: - ndim = getattr(other, "ndim", -1) + # TODO: watch out for overflows - if ndim != -1: - if ndim == 0: - if is_timedelta64_object(other): - other = Timedelta(other) - else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - # only allow ==, != ops - raise TypeError(f'Cannot compare type ' - f'{type(self).__name__} with ' - f'type {type(other).__name__}') - if util.is_array(other): - return PyObject_RichCompare(np.array([self]), other, op) - return PyObject_RichCompare(other, self, reverse_ops[op]) - else: - if other is NaT: - return PyObject_RichCompare(other, self, reverse_ops[op]) - elif op == Py_EQ: - return False - elif op == Py_NE: - return True - raise TypeError(f'Cannot compare type {type(self).__name__} with ' - f'type {type(other).__name__}') + elif other is NaT: + return op == Py_NE + + elif util.is_array(other): + # TODO: watch out for zero-dim + if other.dtype.kind == "m": + return PyObject_RichCompare(self.asm8, other, op) + elif other.dtype.kind == "O": + # operate element-wise + return np.array( + [PyObject_RichCompare(self, x, op) for x in other], + dtype=bool, + ) + if op == Py_EQ: + return np.zeros(other.shape, dtype=bool) + elif op == Py_NE: + return np.ones(other.shape, dtype=bool) + return NotImplemented # let other raise TypeError + + else: + return NotImplemented return cmp_scalar(self.value, ots.value, op) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index bfb16b48d832c..a4f2daac65211 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -880,6 +880,7 @@ def to_dict(self, copy: bool = True): for b in self.blocks: bd.setdefault(str(b.dtype), []).append(b) + # TODO(EA2D): the combine will be unnecessary with 2D EAs return {dtype: self._combine(blocks, copy=copy) for dtype, blocks in bd.items()} def fast_xs(self, loc: int) -> ArrayLike: diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 9a6ae76658949..56c5647d865d3 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -734,7 +734,7 @@ def test_dti_cmp_object_dtype(self): result = dti == other expected = np.array([True] * 5 + [False] * 5) tm.assert_numpy_array_equal(result, expected) - msg = "Cannot compare type" + msg = ">=' not supported between instances of 'Timestamp' and 'Timedelta'" with pytest.raises(TypeError, match=msg): dti >= other diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index 12572648fca9e..7baeb8f5673bc 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -904,6 +904,25 @@ def test_compare_timedelta_ndarray(self): expected = np.array([False, False]) tm.assert_numpy_array_equal(result, expected) + def test_compare_td64_ndarray(self): + # GG#33441 + arr = np.arange(5).astype("timedelta64[ns]") + td = pd.Timedelta(arr[1]) + + expected = np.array([False, True, False, False, False], dtype=bool) + + result = td == arr + tm.assert_numpy_array_equal(result, expected) + + result = arr == td + tm.assert_numpy_array_equal(result, expected) + + result = td != arr + tm.assert_numpy_array_equal(result, ~expected) + + result = arr != td + tm.assert_numpy_array_equal(result, ~expected) + @pytest.mark.skip(reason="GH#20829 is reverted until after 0.24.0") def test_compare_custom_object(self): """ @@ -943,7 +962,7 @@ def __gt__(self, other): def test_compare_unknown_type(self, val): # GH#20829 t = Timedelta("1s") - msg = "Cannot compare type Timedelta with type (int|str)" + msg = "not supported between instances of 'Timedelta' and '(int|str)'" with pytest.raises(TypeError, match=msg): t >= val with pytest.raises(TypeError, match=msg): @@ -984,7 +1003,7 @@ def test_ops_error_str(): with pytest.raises(TypeError, match=msg): left + right - msg = "Cannot compare type" + msg = "not supported between instances of" with pytest.raises(TypeError, match=msg): left > right
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry xref #33346 Between the two of these, we should be able to get rid of this kludge: https://github.com/pandas-dev/pandas/blob/master/pandas/core/internals/managers.py#L629 IIRC there were some test_coercion xfails related to that kludge, will be worth revisiting.
https://api.github.com/repos/pandas-dev/pandas/pulls/33441
2020-04-09T19:49:45Z
2020-04-10T15:58:10Z
2020-04-10T15:58:10Z
2020-04-10T18:06:09Z
BUG: `weights` is not working for multiple columns in df.plot.hist
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 584e21e87390d..c5be188f5c9b7 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -504,7 +504,7 @@ Plotting ^^^^^^^^ - :func:`.plot` for line/bar now accepts color by dictonary (:issue:`8193`). -- +- Bug in :meth:`DataFrame.plot.hist` where weights are not working for multiple columns (:issue:`33173`) - Bug in :meth:`DataFrame.boxplot` and :meth:`DataFrame.plot.boxplot` lost color attributes of ``medianprops``, ``whiskerprops``, ``capprops`` and ``medianprops`` (:issue:`30346`) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index d54fc73b495ba..3a0cdc90dfd5c 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -28,10 +28,7 @@ def _args_adjust(self): values = values[~isna(values)] _, self.bins = np.histogram( - values, - bins=self.bins, - range=self.kwds.get("range", None), - weights=self.kwds.get("weights", None), + values, bins=self.bins, range=self.kwds.get("range", None) ) if is_list_like(self.bottom): @@ -77,6 +74,14 @@ def _make_plot(self): kwds["style"] = style kwds = self._make_plot_keywords(kwds, y) + + # We allow weights to be a multi-dimensional array, e.g. a (10, 2) array, + # and each sub-array (10,) will be called in each iteration. If users only + # provide 1D array, we assume the same weights is used for all iterations + weights = kwds.get("weights", None) + if weights is not None and np.ndim(weights) != 1: + kwds["weights"] = weights[:, i] + artists = self._plot(ax, y, column_num=i, stacking_id=stacking_id, **kwds) self._add_legend_handle(artists[0], label, index=i) diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 4a9efe9554c6e..197fb69a746bf 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1682,6 +1682,25 @@ def test_hist_df(self): axes = df.plot.hist(rot=50, fontsize=8, orientation="horizontal") self._check_ticks_props(axes, xrot=0, yrot=50, ylabelsize=8) + @pytest.mark.parametrize( + "weights", [0.1 * np.ones(shape=(100,)), 0.1 * np.ones(shape=(100, 2))] + ) + def test_hist_weights(self, weights): + # GH 33173 + np.random.seed(0) + df = pd.DataFrame(dict(zip(["A", "B"], np.random.randn(2, 100,)))) + + ax1 = _check_plot_works(df.plot, kind="hist", weights=weights) + ax2 = _check_plot_works(df.plot, kind="hist") + + patch_height_with_weights = [patch.get_height() for patch in ax1.patches] + + # original heights with no weights, and we manually multiply with example + # weights, so after multiplication, they should be almost same + expected_patch_height = [0.1 * patch.get_height() for patch in ax2.patches] + + tm.assert_almost_equal(patch_height_with_weights, expected_patch_height) + def _check_box_coord( self, patches,
- [x] closes #33173 - [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/33440
2020-04-09T19:41:52Z
2020-04-10T16:59:56Z
2020-04-10T16:59:56Z
2020-04-10T17:00:00Z
BUG: Fix bug when concatenating Index of strings
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5c39377899a20..13b0d6ee66eb8 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -421,7 +421,7 @@ Strings ^^^^^^^ - Bug in the :meth:`~Series.astype` method when converting "string" dtype data to nullable integer dtype (:issue:`32450`). -- +- Bug in :meth:`Series.str.cat` returning ``NaN`` output when other had :class:`Index` type (:issue:`33425`) Interval diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 52d9a81489db4..76b851d8ac923 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2297,7 +2297,7 @@ def _get_series_list(self, others): if isinstance(others, ABCSeries): return [others] elif isinstance(others, ABCIndexClass): - return [Series(others._values, index=others)] + return [Series(others._values, index=idx)] elif isinstance(others, ABCDataFrame): return [others[x] for x in others] elif isinstance(others, np.ndarray) and others.ndim == 2: diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 6289c2efea7f1..6260d13524da3 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -3624,3 +3624,12 @@ def test_string_array_extract(): result = result.astype(object) tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("klass", [tuple, list, np.array, pd.Series, pd.Index]) +def test_cat_different_classes(klass): + # https://github.com/pandas-dev/pandas/issues/33425 + s = pd.Series(["a", "b", "c"]) + result = s.str.cat(klass(["x", "y", "z"])) + expected = pd.Series(["ax", "by", "cz"]) + tm.assert_series_equal(result, expected)
- [ ] closes #33425 - [ ] 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/33436
2020-04-09T18:07:20Z
2020-04-10T17:47:26Z
2020-04-10T17:47:25Z
2020-04-10T18:10:06Z
Temporary fix for Py38 build issues on macOS
diff --git a/setup.py b/setup.py index 089baae123d2a..338686bddd146 100755 --- a/setup.py +++ b/setup.py @@ -454,6 +454,9 @@ def run(self): ): os.environ["MACOSX_DEPLOYMENT_TARGET"] = "10.9" + if sys.version_info[:2] == (3, 8): # GH 33239 + extra_compile_args.append("-Wno-error=deprecated-declarations") + # enable coverage by building cython files by setting the environment variable # "PANDAS_CYTHON_COVERAGE" (with a Truthy value) or by running build_ext # with `--with-cython-coverage`enabled
ref #33239 works around issues confirmed by @jbrockmendel and @TomAugspurger Ideally could fix upstream, but may not be worth the effort given the level of nuance
https://api.github.com/repos/pandas-dev/pandas/pulls/33431
2020-04-09T16:52:58Z
2020-04-09T18:26:58Z
2020-04-09T18:26:58Z
2023-04-12T20:17:37Z
DOC: Fix heading capitalization in doc/source/whatsnew - part3 (#32550)
diff --git a/doc/source/whatsnew/v0.10.0.rst b/doc/source/whatsnew/v0.10.0.rst index 2e0442364b2f3..443250592a4a7 100644 --- a/doc/source/whatsnew/v0.10.0.rst +++ b/doc/source/whatsnew/v0.10.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0100: -v0.10.0 (December 17, 2012) ---------------------------- +Version 0.10.0 (December 17, 2012) +---------------------------------- {{ header }} @@ -490,7 +490,7 @@ Updated PyTables support however, query terms using the prior (undocumented) methodology are unsupported. You must read in the entire file and write it out using the new format to take advantage of the updates. -N dimensional Panels (experimental) +N dimensional panels (experimental) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Adding experimental support for Panel4D and factory functions to create n-dimensional named panels. diff --git a/doc/source/whatsnew/v0.10.1.rst b/doc/source/whatsnew/v0.10.1.rst index c4251f70d85b6..1e9eafd2700e9 100644 --- a/doc/source/whatsnew/v0.10.1.rst +++ b/doc/source/whatsnew/v0.10.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0101: -v0.10.1 (January 22, 2013) ---------------------------- +Version 0.10.1 (January 22, 2013) +--------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.11.0.rst b/doc/source/whatsnew/v0.11.0.rst index 148ee349b049c..6c13a125a4e54 100644 --- a/doc/source/whatsnew/v0.11.0.rst +++ b/doc/source/whatsnew/v0.11.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0110: -v0.11.0 (April 22, 2013) ------------------------- +Version 0.11.0 (April 22, 2013) +------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.12.0.rst b/doc/source/whatsnew/v0.12.0.rst index 823e177f3e05e..9e864f63c43e0 100644 --- a/doc/source/whatsnew/v0.12.0.rst +++ b/doc/source/whatsnew/v0.12.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0120: -v0.12.0 (July 24, 2013) ------------------------- +Version 0.12.0 (July 24, 2013) +------------------------------ {{ header }} @@ -177,8 +177,8 @@ API changes ``__repr__``). Plus string safety throughout. Now employed in many places throughout the pandas library. (:issue:`4090`, :issue:`4092`) -I/O enhancements -~~~~~~~~~~~~~~~~ +IO enhancements +~~~~~~~~~~~~~~~ - ``pd.read_html()`` can now parse HTML strings, files or urls and return DataFrames, courtesy of @cpcloud. (:issue:`3477`, :issue:`3605`, :issue:`3606`, :issue:`3616`). diff --git a/doc/source/whatsnew/v0.13.0.rst b/doc/source/whatsnew/v0.13.0.rst index de5e1986744fe..5a904d6c85c61 100644 --- a/doc/source/whatsnew/v0.13.0.rst +++ b/doc/source/whatsnew/v0.13.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0130: -v0.13.0 (January 3, 2014) ---------------------------- +Version 0.13.0 (January 3, 2014) +-------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.13.1.rst b/doc/source/whatsnew/v0.13.1.rst index 4f9ab761334e7..6fe010be8fb2d 100644 --- a/doc/source/whatsnew/v0.13.1.rst +++ b/doc/source/whatsnew/v0.13.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0131: -v0.13.1 (February 3, 2014) --------------------------- +Version 0.13.1 (February 3, 2014) +--------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.8.0.rst b/doc/source/whatsnew/v0.8.0.rst index 072d1bae2a2b9..2a49315cc3b12 100644 --- a/doc/source/whatsnew/v0.8.0.rst +++ b/doc/source/whatsnew/v0.8.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_080: -v0.8.0 (June 29, 2012) ------------------------- +Version 0.8.0 (June 29, 2012) +----------------------------- {{ header }} @@ -42,7 +42,7 @@ Bug fixes to the 0.7.x series for legacy NumPy < 1.6 users will be provided as they arise. There will be no more further development in 0.7.x beyond bug fixes. -Time series changes and improvements +Time Series changes and improvements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. note:: diff --git a/doc/source/whatsnew/v0.8.1.rst b/doc/source/whatsnew/v0.8.1.rst index 1e6b9746c85a5..a00a57a0a1cdb 100644 --- a/doc/source/whatsnew/v0.8.1.rst +++ b/doc/source/whatsnew/v0.8.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0801: -v0.8.1 (July 22, 2012) ----------------------- +Version 0.8.1 (July 22, 2012) +----------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.9.0.rst b/doc/source/whatsnew/v0.9.0.rst index 3d9ff3c7a89fd..565b965c116db 100644 --- a/doc/source/whatsnew/v0.9.0.rst +++ b/doc/source/whatsnew/v0.9.0.rst @@ -3,8 +3,8 @@ {{ header }} -v0.9.0 (October 7, 2012) ------------------------- +Version 0.9.0 (October 7, 2012) +------------------------------- This is a major release from 0.8.1 and includes several new features and enhancements along with a large number of bug fixes. New features include diff --git a/doc/source/whatsnew/v0.9.1.rst b/doc/source/whatsnew/v0.9.1.rst index b8932ae2ae522..3b2924d175cdf 100644 --- a/doc/source/whatsnew/v0.9.1.rst +++ b/doc/source/whatsnew/v0.9.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0901: -v0.9.1 (November 14, 2012) --------------------------- +Version 0.9.1 (November 14, 2012) +--------------------------------- {{ header }} diff --git a/scripts/validate_rst_title_capitalization.py b/scripts/validate_rst_title_capitalization.py index 3d19e37ac7a1d..edc9730db58e5 100755 --- a/scripts/validate_rst_title_capitalization.py +++ b/scripts/validate_rst_title_capitalization.py @@ -99,6 +99,7 @@ "BusinessHour", "BusinessDay", "DateOffset", + "Float64Index", } CAP_EXCEPTIONS_DICT = {word.lower(): word for word in CAPITALIZATION_EXCEPTIONS}
- [ ] Modify files v0.8.0.rst, v0.8.1.rst, v0.9.0.rst, v0.9.1.rst, v010.0.rst, v0.10.1.rst, v0.11.0.rst, v0.12.0.rst, v0.13.0.rst, v0.13.1.rst
https://api.github.com/repos/pandas-dev/pandas/pulls/33429
2020-04-09T16:29:36Z
2020-04-10T17:48:06Z
2020-04-10T17:48:06Z
2020-04-10T17:48:10Z
CLN: avoid accessing private functions
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 6cb597ba75852..7447d593a7ff0 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -1206,7 +1206,7 @@ def _maybe_convert(arr): return _maybe_convert(res) - op_name = ops._get_op_name(op, True) + op_name = f"__{op.__name__}__" return set_function_name(_binop, op_name, cls) @classmethod diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index df58593bc930c..d9a93ac7ba289 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3286,7 +3286,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None): preserve_names = not hasattr(target, "name") # GH7774: preserve dtype/tz if target is empty and not an Index. - target = _ensure_has_len(target) # target may be an iterator + target = ensure_has_len(target) # target may be an iterator if not isinstance(target, Index) and len(target) == 0: if isinstance(self, ABCRangeIndex): @@ -5573,7 +5573,7 @@ def ensure_index(index_like, copy: bool = False): return Index(index_like) -def _ensure_has_len(seq): +def ensure_has_len(seq): """ If seq is an iterator, put its values into a list. """ diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7aa1456846612..9126a7a3309d2 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2288,7 +2288,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None): # GH7774: preserve dtype/tz if target is empty and not an Index. # target may be an iterator - target = ibase._ensure_has_len(target) + target = ibase.ensure_has_len(target) if len(target) == 0 and not isinstance(target, Index): idx = self.levels[level] attrs = idx._get_attributes_dict() diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index d6ba9d763366b..c14c4a311d66c 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -10,7 +10,7 @@ from pandas._libs import lib from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op # noqa:F401 -from pandas._typing import ArrayLike, Level +from pandas._typing import Level from pandas.util._decorators import Appender from pandas.core.dtypes.common import is_list_like @@ -224,7 +224,7 @@ def _get_opstr(op): }[op] -def _get_op_name(op, special): +def _get_op_name(op, special: bool) -> str: """ Find the name to attach to this method according to conventions for special and non-special methods. @@ -385,42 +385,6 @@ def _align_method_SERIES(left, right, align_asobject=False): return left, right -def _construct_result( - left: ABCSeries, result: ArrayLike, index: ABCIndexClass, name, -): - """ - Construct an appropriately-labelled Series from the result of an op. - - Parameters - ---------- - left : Series - result : ndarray or ExtensionArray - index : Index - name : object - - Returns - ------- - Series - In the case of __divmod__ or __rdivmod__, a 2-tuple of Series. - """ - if isinstance(result, tuple): - # produced by divmod or rdivmod - return ( - _construct_result(left, result[0], index=index, name=name), - _construct_result(left, result[1], index=index, name=name), - ) - - # We do not pass dtype to ensure that the Series constructor - # does inference in the case where `result` has object-dtype. - out = left._constructor(result, index=index) - out = out.__finalize__(left) - - # Set the result's name after __finalize__ is called because __finalize__ - # would set it back to self.name - out.name = name - return out - - def _arith_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid @@ -439,7 +403,7 @@ def wrapper(left, right): rvalues = extract_array(right, extract_numpy=True) result = arithmetic_op(lvalues, rvalues, op, str_rep) - return _construct_result(left, result, index=left.index, name=res_name) + return left._construct_result(result, name=res_name) wrapper.__name__ = op_name return wrapper @@ -466,7 +430,7 @@ def wrapper(self, other): res_values = comparison_op(lvalues, rvalues, op, str_rep) - return _construct_result(self, res_values, index=self.index, name=res_name) + return self._construct_result(res_values, name=res_name) wrapper.__name__ = op_name return wrapper @@ -488,7 +452,7 @@ def wrapper(self, other): rvalues = extract_array(other, extract_numpy=True) res_values = logical_op(lvalues, rvalues, op) - return _construct_result(self, res_values, index=self.index, name=res_name) + return self._construct_result(res_values, name=res_name) wrapper.__name__ = op_name return wrapper diff --git a/pandas/core/series.py b/pandas/core/series.py index 2f4ca61a402dc..78368ee9f6851 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -14,6 +14,7 @@ Optional, Tuple, Type, + Union, ) import warnings @@ -22,7 +23,7 @@ from pandas._config import get_option from pandas._libs import lib, properties, reshape, tslibs -from pandas._typing import Axis, DtypeObj, Label +from pandas._typing import ArrayLike, Axis, DtypeObj, Label from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, Substitution, doc from pandas.util._validators import validate_bool_kwarg, validate_percentile @@ -2623,12 +2624,10 @@ def _binop(self, other, func, level=None, fill_value=None): if not isinstance(other, Series): raise AssertionError("Other operand must be Series") - new_index = self.index this = self if not self.index.equals(other.index): this, other = self.align(other, level=level, join="outer", copy=False) - new_index = this.index this_vals, other_vals = ops.fill_binop(this.values, other.values, fill_value) @@ -2636,9 +2635,46 @@ def _binop(self, other, func, level=None, fill_value=None): result = func(this_vals, other_vals) name = ops.get_op_result_name(self, other) - ret = ops._construct_result(self, result, new_index, name) + ret = this._construct_result(result, name) return ret + def _construct_result( + self, result: Union[ArrayLike, Tuple[ArrayLike, ArrayLike]], name: Label + ) -> Union["Series", Tuple["Series", "Series"]]: + """ + Construct an appropriately-labelled Series from the result of an op. + + Parameters + ---------- + result : ndarray or ExtensionArray + name : Label + + Returns + ------- + Series + In the case of __divmod__ or __rdivmod__, a 2-tuple of Series. + """ + if isinstance(result, tuple): + # produced by divmod or rdivmod + + res1 = self._construct_result(result[0], name=name) + res2 = self._construct_result(result[1], name=name) + + # GH#33427 assertions to keep mypy happy + assert isinstance(res1, Series) + assert isinstance(res2, Series) + return (res1, res2) + + # We do not pass dtype to ensure that the Series constructor + # does inference in the case where `result` has object-dtype. + out = self._constructor(result, index=self.index) + out = out.__finalize__(self) + + # Set the result's name after __finalize__ is called because __finalize__ + # would set it back to self.name + out.name = name + return out + def combine(self, other, func, fill_value=None) -> "Series": """ Combine the Series with a Series or scalar according to `func`.
xref #33394 @simonjayhawkins thoughts on how to handle the mypy complaint?
https://api.github.com/repos/pandas-dev/pandas/pulls/33427
2020-04-09T16:13:57Z
2020-04-10T16:08:54Z
2020-04-10T16:08:54Z
2020-04-10T18:02:12Z
CLN: remove unnecessary branches in Series.__setitem__
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 6e41ff189592c..a47303ddc93cf 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -194,7 +194,7 @@ cdef class IntervalMixin: f"expected {repr(self.closed)}.") -cdef _interval_like(other): +cdef bint _interval_like(other): return (hasattr(other, 'left') and hasattr(other, 'right') and hasattr(other, 'closed')) diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 6a9ecfe709847..b2301ab0190c7 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -1059,23 +1059,6 @@ def is_datetime_or_timedelta_dtype(arr_or_dtype) -> bool: return _is_dtype_type(arr_or_dtype, classes(np.datetime64, np.timedelta64)) -def _is_unorderable_exception(e: TypeError) -> bool: - """ - Check if the exception raised is an unorderable exception. - - Parameters - ---------- - e : Exception or sub-class - The exception object to check. - - Returns - ------- - bool - Whether or not the exception raised is an unorderable exception. - """ - return "'>' not supported between instances of" in str(e) - - # This exists to silence numpy deprecation warnings, see GH#29553 def is_numeric_v_string_like(a, b): """ diff --git a/pandas/core/series.py b/pandas/core/series.py index c9684d0985173..9e8bdc099063c 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -33,7 +33,6 @@ validate_numeric_casting, ) from pandas.core.dtypes.common import ( - _is_unorderable_exception, ensure_platform_int, is_bool, is_categorical_dtype, @@ -1005,26 +1004,24 @@ def __setitem__(self, key, value): except (KeyError, ValueError): values = self._values if is_integer(key) and not self.index.inferred_type == "integer": + # positional setter values[key] = value else: + # GH#12862 adding an new key to the Series self.loc[key] = value except TypeError as e: if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): raise ValueError("Can only tuple-index with a MultiIndex") from e - # python 3 type errors should be raised - if _is_unorderable_exception(e): - raise IndexError(key) from e - if com.is_bool_indexer(key): key = check_bool_indexer(self.index, key) key = np.asarray(key, dtype=bool) try: self._where(~key, value, inplace=True) - return except InvalidIndexError: self._set_values(key.astype(np.bool_), value) + return else: self._set_with(key, value) @@ -1044,20 +1041,8 @@ def _set_with(self, key, value): indexer = self.index._convert_slice_indexer(key, kind="getitem") return self._set_values(indexer, value) - elif is_scalar(key) and not is_integer(key) and key not in self.index: - # GH#12862 adding an new key to the Series - # Note: have to exclude integers because that is ambiguously - # position-based - self.loc[key] = value - return - else: - if isinstance(key, tuple): - try: - # TODO: no test cases that get here - self._set_values(key, value) - except Exception: - pass + assert not isinstance(key, tuple) if is_scalar(key): key = [key] @@ -1074,7 +1059,7 @@ def _set_with(self, key, value): if self.index.inferred_type == "integer": self._set_labels(key, value) else: - return self._set_values(key, value) + self._set_values(key, value) else: self._set_labels(key, value)
Eventually I'd like to get the structure of `__setitem__` to parallel the structure of `__getitem__`. Some big improvements to both will be available following #33404.
https://api.github.com/repos/pandas-dev/pandas/pulls/33424
2020-04-09T15:04:59Z
2020-04-09T18:28:32Z
2020-04-09T18:28:32Z
2021-11-20T23:23:12Z
Unpin Python 37 in environment.yml
diff --git a/environment.yml b/environment.yml index 935f8e97d4bf6..c874c5a8f68da 100644 --- a/environment.yml +++ b/environment.yml @@ -4,7 +4,7 @@ channels: dependencies: # required - numpy>=1.15 - - python=3.7 + - python=3 - python-dateutil>=2.6.1 - pytz
I believe this was supposed to be temporary, so quick follow up to #29431 @TomAugspurger
https://api.github.com/repos/pandas-dev/pandas/pulls/33423
2020-04-09T14:48:36Z
2020-04-09T15:38:05Z
2020-04-09T15:38:05Z
2023-04-12T20:17:03Z
ENH: update feather IO for pyarrow 0.17 / Feather V2
diff --git a/doc/source/conf.py b/doc/source/conf.py index d24483abd28e1..d2404b757ca11 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -416,6 +416,7 @@ "python": ("https://docs.python.org/3/", None), "scipy": ("https://docs.scipy.org/doc/scipy/reference/", None), "statsmodels": ("https://www.statsmodels.org/devel/", None), + "pyarrow": ("https://arrow.apache.org/docs/", None), } # extlinks alias diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index d721e00a0a0b6..f2152c43ceaba 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -4583,17 +4583,15 @@ frames efficient, and to make sharing data across data analysis languages easy. Feather is designed to faithfully serialize and de-serialize DataFrames, supporting all of the pandas dtypes, including extension dtypes such as categorical and datetime with tz. -Several caveats. +Several caveats: -* This is a newer library, and the format, though stable, is not guaranteed to be backward compatible - to the earlier versions. * The format will NOT write an ``Index``, or ``MultiIndex`` for the ``DataFrame`` and will raise an error if a non-default one is provided. You can ``.reset_index()`` to store the index or ``.reset_index(drop=True)`` to ignore it. * Duplicate column names and non-string columns names are not supported -* Non supported types include ``Period`` and actual Python object types. These will raise a helpful error message - on an attempt at serialization. +* Actual Python objects in object dtype columns are not supported. These will + raise a helpful error message on an attempt at serialization. See the `Full Documentation <https://github.com/wesm/feather>`__. diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 8a7db87b75d7b..0ba845aa06489 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -88,7 +88,9 @@ Other enhancements - :class:`Series.str` now has a `fullmatch` method that matches a regular expression against the entire string in each row of the series, similar to `re.fullmatch` (:issue:`32806`). - :meth:`DataFrame.sample` will now also allow array-like and BitGenerator objects to be passed to ``random_state`` as seeds (:issue:`32503`) - :meth:`MultiIndex.union` will now raise `RuntimeWarning` if the object inside are unsortable, pass `sort=False` to suppress this warning (:issue:`33015`) -- +- The :meth:`DataFrame.to_feather` method now supports additional keyword + arguments (e.g. to set the compression) that are added in pyarrow 0.17 + (:issue:`33422`). .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index aedbba755227d..6f0f8f881933b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2058,18 +2058,24 @@ def to_stata( writer.write_file() @deprecate_kwarg(old_arg_name="fname", new_arg_name="path") - def to_feather(self, path) -> None: + def to_feather(self, path, **kwargs) -> None: """ - Write out the binary feather-format for DataFrames. + Write a DataFrame to the binary Feather format. Parameters ---------- path : str String file path. + **kwargs : + Additional keywords passed to :func:`pyarrow.feather.write_feather`. + Starting with pyarrow 0.17, this includes the `compression`, + `compression_level`, `chunksize` and `version` keywords. + + .. versionadded:: 1.1.0 """ from pandas.io.feather_format import to_feather - to_feather(self, path) + to_feather(self, path, **kwargs) @Appender( """ diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index 5d4925620e75f..cd7045e7f2d2e 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -7,15 +7,18 @@ from pandas.io.common import stringify_path -def to_feather(df: DataFrame, path): +def to_feather(df: DataFrame, path, **kwargs): """ - Write a DataFrame to the feather-format + Write a DataFrame to the binary Feather format. Parameters ---------- df : DataFrame path : string file path, or file-like object + **kwargs : + Additional keywords passed to `pyarrow.feather.write_feather`. + .. versionadded:: 1.1.0 """ import_optional_dependency("pyarrow") from pyarrow import feather @@ -58,7 +61,7 @@ def to_feather(df: DataFrame, path): if df.columns.inferred_type not in valid_types: raise ValueError("feather must have string column names") - feather.write_feather(df, path) + feather.write_feather(df, path, **kwargs) def read_feather(path, columns=None, use_threads: bool = True): diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 0038df78dd866..0755501ee6285 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -4,6 +4,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd import pandas._testing as tm @@ -27,15 +29,15 @@ def check_error_on_write(self, df, exc): with tm.ensure_clean() as path: to_feather(df, path) - def check_round_trip(self, df, expected=None, **kwargs): + def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs): if expected is None: expected = df with tm.ensure_clean() as path: - to_feather(df, path) + to_feather(df, path, **write_kwargs) - result = read_feather(path, **kwargs) + result = read_feather(path, **read_kwargs) tm.assert_frame_equal(result, expected) def test_error(self): @@ -71,6 +73,10 @@ def test_basic(self): "dtns": pd.date_range("20130101", periods=3, freq="ns"), } ) + if pyarrow_version >= LooseVersion("0.16.1.dev"): + df["periods"] = pd.period_range("2013", freq="M", periods=3) + df["timedeltas"] = pd.timedelta_range("1 day", periods=3) + df["intervals"] = pd.interval_range(0, 3, 3) assert df.dttz.dtype.tz.zone == "US/Eastern" self.check_round_trip(df) @@ -102,8 +108,8 @@ def test_read_columns(self): def test_unsupported_other(self): - # period - df = pd.DataFrame({"a": pd.period_range("2013", freq="M", periods=3)}) + # mixed python objects + df = pd.DataFrame({"a": ["a", 1, 2.0]}) # Some versions raise ValueError, others raise ArrowInvalid. self.check_error_on_write(df, Exception) @@ -148,3 +154,8 @@ def test_path_localpath(self): df = tm.makeDataFrame().reset_index() result = tm.round_trip_localpath(df.to_feather, pd.read_feather) tm.assert_frame_equal(df, result) + + @td.skip_if_no("pyarrow", min_version="0.16.1.dev") + def test_passthrough_keywords(self): + df = tm.makeDataFrame().reset_index() + self.check_round_trip(df, write_kwargs=dict(version=1))
Upcoming pyarrow 0.17 release will include an upgraded feather format. This PRs updates pandas for that, more specifically ensures the new keywords can be passed through (the basics should keep working out of the box, since the public API did not change), and small update to the tests
https://api.github.com/repos/pandas-dev/pandas/pulls/33422
2020-04-09T14:19:31Z
2020-04-10T08:37:48Z
2020-04-10T08:37:48Z
2020-06-21T17:26:14Z
lreshape and wide_to_long documentation (Closes #33417)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1587dd8798ec3..a4408d1f5d23d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6609,6 +6609,8 @@ def groupby( duplicate values for one index/column pair. DataFrame.unstack : Pivot based on the index values instead of a column. + wide_to_long : Wide panel to long format. Less flexible but more + user-friendly than melt. Notes ----- @@ -6763,6 +6765,10 @@ def pivot(self, index=None, columns=None, values=None) -> "DataFrame": -------- DataFrame.pivot : Pivot without aggregation that can handle non-numeric data. + DataFrame.melt: Unpivot a DataFrame from wide to long format, + optionally leaving identifiers set. + wide_to_long : Wide panel to long format. Less flexible but more + user-friendly than melt. Examples -------- diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 1ba6854a79265..8724f7674f0c8 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -144,14 +144,43 @@ def melt( @deprecate_kwarg(old_arg_name="label", new_arg_name=None) def lreshape(data: "DataFrame", groups, dropna: bool = True, label=None) -> "DataFrame": """ - Reshape long-format data to wide. Generalized inverse of DataFrame.pivot + Reshape wide-format data to long. Generalized inverse of DataFrame.pivot. + + Accepts a dictionary, ``groups``, in which each key is a new column name + and each value is a list of old column names that will be "melted" under + the new column name as part of the reshape. Parameters ---------- data : DataFrame + The wide-format DataFrame. groups : dict - {new_name : list_of_columns} - dropna : boolean, default True + {new_name : list_of_columns}. + dropna : bool, default True + Do not include columns whose entries are all NaN. + label : None + Not used. + + .. deprecated:: 1.0.0 + + Returns + ------- + DataFrame + Reshaped DataFrame. + + See Also + -------- + melt : Unpivot a DataFrame from wide to long format, optionally leaving + identifiers set. + pivot : Create a spreadsheet-style pivot table as a DataFrame. + DataFrame.pivot : Pivot without aggregation that can handle + non-numeric data. + DataFrame.pivot_table : Generalization of pivot that can handle + duplicate values for one index/column pair. + DataFrame.unstack : Pivot based on the index values instead of a + column. + wide_to_long : Wide panel to long format. Less flexible but more + user-friendly than melt. Examples -------- @@ -169,10 +198,6 @@ def lreshape(data: "DataFrame", groups, dropna: bool = True, label=None) -> "Dat 1 Yankees 2007 573 2 Red Sox 2008 545 3 Yankees 2008 526 - - Returns - ------- - reshaped : DataFrame """ if isinstance(groups, dict): keys = list(groups.keys()) @@ -262,6 +287,18 @@ def wide_to_long( A DataFrame that contains each stub name as a variable, with new index (i, j). + See Also + -------- + melt : Unpivot a DataFrame from wide to long format, optionally leaving + identifiers set. + pivot : Create a spreadsheet-style pivot table as a DataFrame. + DataFrame.pivot : Pivot without aggregation that can handle + non-numeric data. + DataFrame.pivot_table : Generalization of pivot that can handle + duplicate values for one index/column pair. + DataFrame.unstack : Pivot based on the index values instead of a + column. + Notes ----- All extra variables are left untouched. This simply uses
- [ ] closes #33417 - [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/33418
2020-04-09T06:39:07Z
2020-08-19T13:05:41Z
2020-08-19T13:05:41Z
2020-08-19T13:05:48Z
DOC: Fix EX01 in DataFrame.duplicated
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d2da52ba7bdd0..e14325759e509 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4740,6 +4740,73 @@ def duplicated( Returns ------- Series + Boolean series for each duplicated rows. + + See Also + -------- + Index.duplicated : Equivalent method on index. + Series.duplicated : Equivalent method on Series. + Series.drop_duplicates : Remove duplicate values from Series. + DataFrame.drop_duplicates : Remove duplicate values from DataFrame. + + Examples + -------- + Consider dataset containing ramen rating. + + >>> df = pd.DataFrame({ + ... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'], + ... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'], + ... 'rating': [4, 4, 3.5, 15, 5] + ... }) + >>> df + brand style rating + 0 Yum Yum cup 4.0 + 1 Yum Yum cup 4.0 + 2 Indomie cup 3.5 + 3 Indomie pack 15.0 + 4 Indomie pack 5.0 + + By default, for each set of duplicated values, the first occurrence + is set on False and all others on True. + + >>> df.duplicated() + 0 False + 1 True + 2 False + 3 False + 4 False + dtype: bool + + By using 'last', the last occurrence of each set of duplicated values + is set on False and all others on True. + + >>> df.duplicated(keep='last') + 0 True + 1 False + 2 False + 3 False + 4 False + dtype: bool + + By setting ``keep`` on False, all duplicates are True. + + >>> df.duplicated(keep=False) + 0 True + 1 True + 2 False + 3 False + 4 False + dtype: bool + + To find duplicates on specific column(s), use ``subset``. + + >>> df.duplicated(subset=['brand']) + 0 False + 1 True + 2 False + 3 True + 4 True + dtype: bool """ from pandas.core.sorting import get_group_index from pandas._libs.hashtable import duplicated_int64, _SIZE_HINT_LIMIT
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Related to #27977. ``` ################################################################################ ################################## Validation ################################## ################################################################################
https://api.github.com/repos/pandas-dev/pandas/pulls/33416
2020-04-09T03:24:13Z
2020-04-09T17:53:33Z
2020-04-09T17:53:33Z
2020-04-09T17:53:40Z
use https link for Anaconda
diff --git a/doc/source/getting_started/index.rst b/doc/source/getting_started/index.rst index 9ac8c58e1d8f2..3f15c91f83c6a 100644 --- a/doc/source/getting_started/index.rst +++ b/doc/source/getting_started/index.rst @@ -21,7 +21,7 @@ Installation <div class="card-body"> <p class="card-text"> -pandas is part of the `Anaconda <http://docs.continuum.io/anaconda/>`__ distribution and can be +pandas is part of the `Anaconda <https://docs.continuum.io/anaconda/>`__ distribution and can be installed with Anaconda or Miniconda: .. raw:: html
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33413
2020-04-09T01:35:50Z
2020-04-09T02:22:07Z
2020-04-09T02:22:07Z
2020-04-09T02:22:12Z
REF: collect DataFrame.__setitem__ tests
diff --git a/pandas/tests/frame/indexing/test_categorical.py b/pandas/tests/frame/indexing/test_categorical.py index 0ae2f81108be9..d94dc8d2ffe00 100644 --- a/pandas/tests/frame/indexing/test_categorical.py +++ b/pandas/tests/frame/indexing/test_categorical.py @@ -391,11 +391,3 @@ def test_loc_indexing_preserves_index_category_dtype(self): result = df.loc[["a"]].index.levels[0] tm.assert_index_equal(result, expected) - - def test_wrong_length_cat_dtype_raises(self): - # GH29523 - cat = pd.Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) - df = pd.DataFrame({"bar": range(10)}) - err = "Length of values does not match length of index" - with pytest.raises(ValueError, match=err): - df["foo"] = cat diff --git a/pandas/tests/frame/indexing/test_datetime.py b/pandas/tests/frame/indexing/test_datetime.py index c1a7cb9f45a3a..1937a4c380dc9 100644 --- a/pandas/tests/frame/indexing/test_datetime.py +++ b/pandas/tests/frame/indexing/test_datetime.py @@ -44,12 +44,3 @@ def test_set_reset(self): df = result.set_index("foo") tm.assert_index_equal(df.index, idx) - - def test_scalar_assignment(self): - # issue #19843 - df = pd.DataFrame(index=(0, 1, 2)) - df["now"] = pd.Timestamp("20130101", tz="UTC") - expected = pd.DataFrame( - {"now": pd.Timestamp("20130101", tz="UTC")}, index=[0, 1, 2] - ) - tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index c3b9a7bf05c7b..ed3c4689c92d9 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1921,22 +1921,6 @@ def test_getitem_sparse_column(self): result = df.loc[:, "A"] tm.assert_series_equal(result, expected) - def test_setitem_with_sparse_value(self): - # GH8131 - df = pd.DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) - sp_array = SparseArray([0, 0, 1]) - df["new_column"] = sp_array - tm.assert_series_equal( - df["new_column"], pd.Series(sp_array, name="new_column"), check_names=False - ) - - def test_setitem_with_unaligned_sparse_value(self): - df = pd.DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) - sp_series = pd.Series(SparseArray([0, 0, 1]), index=[2, 1, 0]) - df["new_column"] = sp_series - exp = pd.Series(SparseArray([1, 0, 0]), name="new_column") - tm.assert_series_equal(df["new_column"], exp) - def test_setitem_with_unaligned_tz_aware_datetime_column(self): # GH 12981 # Assignment of unaligned offset-aware datetime series. diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index c12643f413490..d53665539309c 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -1,13 +1,12 @@ import numpy as np import pytest -from pandas import DataFrame, Index, Series +from pandas import Categorical, DataFrame, Index, Series, Timestamp, date_range import pandas._testing as tm +from pandas.core.arrays import SparseArray -# Column add, remove, delete. - -class TestDataFrameMutateColumns: +class TestDataFrameSetItem: def test_setitem_error_msmgs(self): # GH 7432 @@ -84,3 +83,46 @@ def test_setitem_empty_columns(self): df["X"] = ["x", "y", "z"] exp = DataFrame(data={"X": ["x", "y", "z"]}, index=["A", "B", "C"]) tm.assert_frame_equal(df, exp) + + def test_setitem_dt64_index_empty_columns(self): + rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s") + df = DataFrame(index=np.arange(len(rng))) + + df["A"] = rng + assert df["A"].dtype == np.dtype("M8[ns]") + + def test_setitem_timestamp_empty_columns(self): + # GH#19843 + df = DataFrame(index=range(3)) + df["now"] = Timestamp("20130101", tz="UTC") + + expected = DataFrame( + [[Timestamp("20130101", tz="UTC")]] * 3, index=[0, 1, 2], columns=["now"], + ) + tm.assert_frame_equal(df, expected) + + def test_setitem_wrong_length_categorical_dtype_raises(self): + # GH#29523 + cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"]) + df = DataFrame(range(10), columns=["bar"]) + + msg = "Length of values does not match length of index" + with pytest.raises(ValueError, match=msg): + df["foo"] = cat + + def test_setitem_with_sparse_value(self): + # GH#8131 + df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) + sp_array = SparseArray([0, 0, 1]) + df["new_column"] = sp_array + + expected = Series(sp_array, name="new_column") + tm.assert_series_equal(df["new_column"], expected) + + def test_setitem_with_unaligned_sparse_value(self): + df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) + sp_series = Series(SparseArray([0, 0, 1]), index=[2, 1, 0]) + + df["new_column"] = sp_series + expected = Series(SparseArray([1, 0, 0]), name="new_column") + tm.assert_series_equal(df["new_column"], expected) diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index dea921a92ae37..63361789b8e50 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -13,13 +13,6 @@ def test_frame_ctor_datetime64_column(self): df = DataFrame({"A": np.random.randn(len(rng)), "B": dates}) assert np.issubdtype(df["B"].dtype, np.dtype("M8[ns]")) - def test_frame_append_datetime64_column(self): - rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s") - df = DataFrame(index=np.arange(len(rng))) - - df["A"] = rng - assert np.issubdtype(df["A"].dtype, np.dtype("M8[ns]")) - def test_frame_append_datetime64_col_other_units(self): n = 100 diff --git a/pandas/tests/indexing/multiindex/test_insert.py b/pandas/tests/indexing/multiindex/test_insert.py index 835e61da2fb3e..42922c3deeee4 100644 --- a/pandas/tests/indexing/multiindex/test_insert.py +++ b/pandas/tests/indexing/multiindex/test_insert.py @@ -5,7 +5,7 @@ class TestMultiIndexInsertion: - def test_mixed_depth_insert(self): + def test_setitem_mixed_depth(self): arrays = [ ["a", "top", "top", "routine1", "routine1", "routine2"], ["", "OD", "OD", "result1", "result2", "result1"],
https://api.github.com/repos/pandas-dev/pandas/pulls/33408
2020-04-08T21:44:12Z
2020-04-08T23:22:32Z
2020-04-08T23:22:31Z
2020-04-08T23:23:50Z
REF: call pandas_dtype up-front in Index.__new__
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1c5cdd1617cbd..530aaee24c7fb 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -48,6 +48,7 @@ is_signed_integer_dtype, is_timedelta64_dtype, is_unsigned_integer_dtype, + pandas_dtype, ) from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.generic import ( @@ -68,6 +69,7 @@ from pandas.core.accessor import CachedAccessor import pandas.core.algorithms as algos from pandas.core.arrays import ExtensionArray +from pandas.core.arrays.datetimes import tz_to_dtype, validate_tz_from_dtype from pandas.core.base import IndexOpsMixin, PandasObject import pandas.core.common as com from pandas.core.indexers import deprecate_ndim_indexing @@ -292,10 +294,19 @@ def __new__( name = maybe_extract_name(name, data, cls) + if dtype is not None: + dtype = pandas_dtype(dtype) + if "tz" in kwargs: + tz = kwargs.pop("tz") + validate_tz_from_dtype(dtype, tz) + dtype = tz_to_dtype(tz) + if isinstance(data, ABCPandasArray): # ensure users don't accidentally put a PandasArray in an index. data = data.to_numpy() + data_dtype = getattr(data, "dtype", None) + # range if isinstance(data, RangeIndex): return RangeIndex(start=data, copy=copy, dtype=dtype, name=name) @@ -303,43 +314,39 @@ def __new__( return RangeIndex.from_range(data, dtype=dtype, name=name) # categorical - elif is_categorical_dtype(data) or is_categorical_dtype(dtype): + elif is_categorical_dtype(data_dtype) or is_categorical_dtype(dtype): # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 from pandas.core.indexes.category import CategoricalIndex return _maybe_asobject(dtype, CategoricalIndex, data, copy, name, **kwargs) # interval - elif is_interval_dtype(data) or is_interval_dtype(dtype): + elif is_interval_dtype(data_dtype) or is_interval_dtype(dtype): # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 from pandas.core.indexes.interval import IntervalIndex return _maybe_asobject(dtype, IntervalIndex, data, copy, name, **kwargs) - elif ( - is_datetime64_any_dtype(data) - or is_datetime64_any_dtype(dtype) - or "tz" in kwargs - ): + elif is_datetime64_any_dtype(data_dtype) or is_datetime64_any_dtype(dtype): # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 from pandas import DatetimeIndex return _maybe_asobject(dtype, DatetimeIndex, data, copy, name, **kwargs) - elif is_timedelta64_dtype(data) or is_timedelta64_dtype(dtype): + elif is_timedelta64_dtype(data_dtype) or is_timedelta64_dtype(dtype): # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 from pandas import TimedeltaIndex return _maybe_asobject(dtype, TimedeltaIndex, data, copy, name, **kwargs) - elif is_period_dtype(data) or is_period_dtype(dtype): + elif is_period_dtype(data_dtype) or is_period_dtype(dtype): # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 from pandas import PeriodIndex return _maybe_asobject(dtype, PeriodIndex, data, copy, name, **kwargs) # extension dtype - elif is_extension_array_dtype(data) or is_extension_array_dtype(dtype): + elif is_extension_array_dtype(data_dtype) or is_extension_array_dtype(dtype): if not (dtype is None or is_object_dtype(dtype)): # coerce to the provided dtype ea_cls = dtype.construct_array_type() diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 75c935cdf2e60..80573f32b936e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -8,7 +8,7 @@ from pandas._libs import NaT, algos as libalgos, lib, writers import pandas._libs.internals as libinternals -from pandas._libs.tslibs import Timedelta, conversion +from pandas._libs.tslibs import conversion from pandas._libs.tslibs.timezones import tz_compare from pandas._typing import ArrayLike from pandas.util._validators import validate_bool_kwarg diff --git a/pandas/tests/indexes/ranges/test_constructors.py b/pandas/tests/indexes/ranges/test_constructors.py index 426341a53a5d1..b7f673428ae38 100644 --- a/pandas/tests/indexes/ranges/test_constructors.py +++ b/pandas/tests/indexes/ranges/test_constructors.py @@ -43,7 +43,7 @@ def test_constructor_invalid_args(self): r"kind, 0 was passed" ) with pytest.raises(TypeError, match=msg): - Index(0, 1000) + Index(0) @pytest.mark.parametrize( "args",
This leaves us in position to drop in dtype-only is_foo_dtype checks
https://api.github.com/repos/pandas-dev/pandas/pulls/33407
2020-04-08T20:59:44Z
2020-04-10T20:52:11Z
2020-04-10T20:52:11Z
2020-04-10T20:58:58Z
BUG: to_period() freq was not infered
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 718de09a0c3e4..f3b301a29b8c3 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -409,6 +409,8 @@ Datetimelike - Bug in :meth:`DatetimeIndex.searchsorted` not accepting a ``list`` or :class:`Series` as its argument (:issue:`32762`) - Bug where :meth:`PeriodIndex` raised when passed a :class:`Series` of strings (:issue:`26109`) - Bug in :class:`Timestamp` arithmetic when adding or subtracting a ``np.ndarray`` with ``timedelta64`` dtype (:issue:`33296`) +- Bug in :meth:`DatetimeIndex.to_period` not infering the frequency when called with no arguments (:issue:`33358`) + Timedelta ^^^^^^^^^ diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index b9f9edcebad5b..77001f274e8e8 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -18,6 +18,7 @@ timezones, tzconversion, ) +import pandas._libs.tslibs.frequencies as libfrequencies from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import ( @@ -1097,7 +1098,14 @@ def to_period(self, freq=None): "You must pass a freq argument as current index has none." ) - freq = get_period_alias(freq) + res = get_period_alias(freq) + + # https://github.com/pandas-dev/pandas/issues/33358 + if res is None: + base, stride = libfrequencies._base_and_stride(freq) + res = f"{stride}{base}" + + freq = res return PeriodArray._from_datetime64(self._data, freq, tz=self.tz) diff --git a/pandas/tests/indexes/datetimes/test_to_period.py b/pandas/tests/indexes/datetimes/test_to_period.py index 7b75e676a2c12..d82fc1ef6743b 100644 --- a/pandas/tests/indexes/datetimes/test_to_period.py +++ b/pandas/tests/indexes/datetimes/test_to_period.py @@ -1,3 +1,5 @@ +import warnings + import dateutil.tz from dateutil.tz import tzlocal import pytest @@ -75,6 +77,28 @@ def test_to_period_monthish(self): with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): date_range("01-Jan-2012", periods=8, freq="EOM") + def test_to_period_infer(self): + # https://github.com/pandas-dev/pandas/issues/33358 + rng = date_range( + start="2019-12-22 06:40:00+00:00", + end="2019-12-22 08:45:00+00:00", + freq="5min", + ) + + with tm.assert_produces_warning(None): + # Using simple filter because we are not checking for the warning here + warnings.simplefilter("ignore", UserWarning) + + pi1 = rng.to_period("5min") + + with tm.assert_produces_warning(None): + # Using simple filter because we are not checking for the warning here + warnings.simplefilter("ignore", UserWarning) + + pi2 = rng.to_period() + + tm.assert_index_equal(pi1, pi2) + def test_period_dt64_round_trip(self): dti = date_range("1/1/2000", "1/7/2002", freq="B") pi = dti.to_period()
- [x] closes #33358 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry --- When running ```pytest -q --cache-clear pandas/tests/ -k "period"``` some tests in ```pandas/tests/indexing/``` are failing, but when running ```pytest -q --cache-clear pandas/tests/indexing/``` __all__ the tests are passing (on my local machine), so I figured and debug from here, thoughts?
https://api.github.com/repos/pandas-dev/pandas/pulls/33406
2020-04-08T19:56:23Z
2020-04-12T23:00:01Z
2020-04-12T23:00:01Z
2020-06-10T15:15:38Z
CLN: follow-ups to #33340
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index d69b417f6e056..d3d8bead88d08 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -106,13 +106,8 @@ cdef class BlockPlacement: else: return self._as_array - def isin(self, arr): - from pandas.core.indexes.api import Int64Index - - return Int64Index(self.as_array, copy=False).isin(arr) - @property - def as_array(self): + def as_array(self) -> np.ndarray: cdef: Py_ssize_t start, stop, end, _ @@ -146,10 +141,10 @@ cdef class BlockPlacement: return BlockPlacement(val) - def delete(self, loc): + def delete(self, loc) -> "BlockPlacement": return BlockPlacement(np.delete(self.as_array, loc, axis=0)) - def append(self, others): + def append(self, others) -> "BlockPlacement": if not len(others): return self @@ -190,12 +185,10 @@ cdef class BlockPlacement: val = newarr return BlockPlacement(val) - def add(self, other): + def add(self, other) -> "BlockPlacement": + # We can get here with int or ndarray return self.iadd(other) - def sub(self, other): - return self.add(-other) - cdef slice _ensure_has_slice(self): if not self._has_slice: self._as_slice = indexer_as_slice(self._as_array) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f8ecc2509ad10..2df352a8d72a2 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5305,10 +5305,10 @@ def _check_inplace_setting(self, value) -> bool_t: return True def _get_numeric_data(self): - return self._constructor(self._mgr.get_numeric_data()).__finalize__(self,) + return self._constructor(self._mgr.get_numeric_data()).__finalize__(self) def _get_bool_data(self): - return self._constructor(self._mgr.get_bool_data()).__finalize__(self,) + return self._constructor(self._mgr.get_bool_data()).__finalize__(self) # ---------------------------------------------------------------------- # Internal Interface Methods @@ -6542,21 +6542,16 @@ def replace( if not self.size: return self - new_data = self._mgr if is_dict_like(to_replace): if is_dict_like(value): # {'A' : NA} -> {'A' : 0} - res = self if inplace else self.copy() - for c, src in to_replace.items(): - if c in value and c in self: - # object conversion is handled in - # series.replace which is called recursively - res[c] = res[c].replace( - to_replace=src, - value=value[c], - inplace=False, - regex=regex, - ) - return None if inplace else res + # Note: Checking below for `in foo.keys()` instead of + # `in foo`is needed for when we have a Series and not dict + mapping = { + col: (to_replace[col], value[col]) + for col in to_replace.keys() + if col in value.keys() and col in self + } + return self._replace_columnwise(mapping, inplace, regex) # {'A': NA} -> 0 elif not is_list_like(value): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index f241410b25a82..bfb16b48d832c 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -110,8 +110,6 @@ class BlockManager(PandasObject): __slots__ = [ "axes", "blocks", - "_ndim", - "_shape", "_known_consolidated", "_is_consolidated", "_blknos", @@ -759,9 +757,7 @@ def get_slice(self, slobj: slice, axis: int = 0) -> "BlockManager": if axis == 0: new_blocks = self._slice_take_blocks_ax0(slobj) elif axis == 1: - _slicer = [slice(None)] * (axis + 1) - _slicer[axis] = slobj - slicer = tuple(_slicer) + slicer = (slice(None), slobj) new_blocks = [blk.getitem_block(slicer) for blk in self.blocks] else: raise IndexError("Requested axis not found in manager") @@ -1103,7 +1099,6 @@ def value_getitem(placement): if len(val_locs) == len(blk.mgr_locs): removed_blknos.append(blkno) else: - self._blklocs[blk.mgr_locs.indexer] = -1 blk.delete(blk_locs) self._blklocs[blk.mgr_locs.indexer] = np.arange(len(blk)) @@ -1115,9 +1110,7 @@ def value_getitem(placement): new_blknos = np.empty(self.nblocks, dtype=np.int64) new_blknos.fill(-1) new_blknos[~is_deleted] = np.arange(self.nblocks - len(removed_blknos)) - self._blknos = algos.take_1d( - new_blknos, self._blknos, axis=0, allow_fill=False - ) + self._blknos = new_blknos[self._blknos] self.blocks = tuple( blk for i, blk in enumerate(self.blocks) if i not in set(removed_blknos) ) @@ -1128,8 +1121,9 @@ def value_getitem(placement): new_blocks: List[Block] = [] if value_is_extension_type: - # This code (ab-)uses the fact that sparse blocks contain only + # This code (ab-)uses the fact that EA blocks contain only # one item. + # TODO(EA2D): special casing unnecessary with 2D EAs new_blocks.extend( make_block( values=value, @@ -1162,7 +1156,7 @@ def value_getitem(placement): # Newly created block's dtype may already be present. self._known_consolidated = False - def insert(self, loc: int, item, value, allow_duplicates: bool = False): + def insert(self, loc: int, item: Label, value, allow_duplicates: bool = False): """ Insert item at selected position. @@ -1185,7 +1179,7 @@ def insert(self, loc: int, item, value, allow_duplicates: bool = False): # insert to the axis; this could possibly raise a TypeError new_axis = self.items.insert(loc, item) - if value.ndim == self.ndim - 1 and not is_extension_array_dtype(value): + if value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype): value = _safe_reshape(value, (1,) + value.shape) block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1)) @@ -1959,14 +1953,14 @@ def _compare_or_regex_search(a, b, regex=False): return result -def _fast_count_smallints(arr): +def _fast_count_smallints(arr: np.ndarray) -> np.ndarray: """Faster version of set(arr) for sequences of small numbers.""" counts = np.bincount(arr.astype(np.int_)) nz = counts.nonzero()[0] return np.c_[nz, counts[nz]] -def _preprocess_slice_or_indexer(slice_or_indexer, length, allow_fill): +def _preprocess_slice_or_indexer(slice_or_indexer, length: int, allow_fill: bool): if isinstance(slice_or_indexer, slice): return ( "slice",
https://api.github.com/repos/pandas-dev/pandas/pulls/33405
2020-04-08T19:49:03Z
2020-04-08T20:41:07Z
2020-04-08T20:41:07Z
2020-04-08T20:49:52Z
BUG: Series.__getitem__ with MultiIndex and leading integer level
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5c39377899a20..0e68c3799efa7 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -447,6 +447,7 @@ Indexing - Bug in :meth:`DataFrame.lookup` incorrectly raising an ``AttributeError`` when ``frame.index`` or ``frame.columns`` is not unique; this will now raise a ``ValueError`` with a helpful error message (:issue:`33041`) - Bug in :meth:`DataFrame.iloc.__setitem__` creating a new array instead of overwriting ``Categorical`` values in-place (:issue:`32831`) - Bug in :meth:`DataFrame.copy` _item_cache not invalidated after copy causes post-copy value updates to not be reflected (:issue:`31784`) +- Bug in `Series.__getitem__` with an integer key and a :class:`MultiIndex` with leading integer level failing to raise ``KeyError`` if the key is not present in the first level (:issue:`33355`) Missing ^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index df58593bc930c..73038bb44e236 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4568,10 +4568,7 @@ def get_value(self, series: "Series", key): ------- scalar or Series """ - if not is_scalar(key): - # if key is not a scalar, directly raise an error (the code below - # would convert to numpy arrays and raise later any way) - GH29926 - raise InvalidIndexError(key) + self._check_indexing_error(key) try: # GH 20882, 21257 @@ -4592,6 +4589,12 @@ def get_value(self, series: "Series", key): return self._get_values_for_loc(series, loc, key) + def _check_indexing_error(self, key): + if not is_scalar(key): + # if key is not a scalar, directly raise an error (the code below + # would convert to numpy arrays and raise later any way) - GH29926 + raise InvalidIndexError(key) + def _should_fallback_to_positional(self) -> bool: """ If an integer key is not found, should we fall back to positional indexing? diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7aa1456846612..6e36029441f1b 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2333,23 +2333,21 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None): # -------------------------------------------------------------------- # Indexing Methods - def get_value(self, series, key): - # Label-based + def _check_indexing_error(self, key): if not is_hashable(key) or is_iterator(key): # We allow tuples if they are hashable, whereas other Index # subclasses require scalar. # We have to explicitly exclude generators, as these are hashable. raise InvalidIndexError(key) - try: - loc = self.get_loc(key) - except KeyError: - if is_integer(key): - loc = key - else: - raise - - return self._get_values_for_loc(series, loc, key) + def _should_fallback_to_positional(self) -> bool: + """ + If an integer key is not found, should we fall back to positional indexing? + """ + if not self.nlevels: + return False + # GH#33355 + return self.levels[0]._should_fallback_to_positional() def _get_values_for_loc(self, series: "Series", loc, key): """ diff --git a/pandas/tests/indexing/multiindex/test_getitem.py b/pandas/tests/indexing/multiindex/test_getitem.py index 7e75b5324445e..54b22dbc53466 100644 --- a/pandas/tests/indexing/multiindex/test_getitem.py +++ b/pandas/tests/indexing/multiindex/test_getitem.py @@ -87,8 +87,8 @@ def test_series_getitem_returns_scalar( (lambda s: s[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"), (lambda s: s.loc[(2000, 3, 4)], KeyError, r"^\(2000, 3, 4\)$"), (lambda s: s.loc[(2000, 3, 4, 5)], IndexingError, "Too many indexers"), - (lambda s: s.__getitem__(len(s)), IndexError, "is out of bounds"), - (lambda s: s[len(s)], IndexError, "is out of bounds"), + (lambda s: s.__getitem__(len(s)), KeyError, ""), # match should include len(s) + (lambda s: s[len(s)], KeyError, ""), # match should include len(s) ( lambda s: s.iloc[len(s)], IndexError, diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py index 9d181bdcb9491..ed11af8ef68ad 100644 --- a/pandas/tests/indexing/multiindex/test_partial.py +++ b/pandas/tests/indexing/multiindex/test_partial.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from pandas import DataFrame, MultiIndex +from pandas import DataFrame, Float64Index, Int64Index, MultiIndex import pandas._testing as tm @@ -126,7 +126,32 @@ def test_partial_set(self, multiindex_year_month_day_dataframe_random_data): # this works...for now df["A"].iloc[14] = 5 - assert df["A"][14] == 5 + assert df["A"].iloc[14] == 5 + + @pytest.mark.parametrize("dtype", [int, float]) + def test_getitem_intkey_leading_level( + self, multiindex_year_month_day_dataframe_random_data, dtype + ): + # GH#33355 dont fall-back to positional when leading level is int + ymd = multiindex_year_month_day_dataframe_random_data + levels = ymd.index.levels + ymd.index = ymd.index.set_levels([levels[0].astype(dtype)] + levels[1:]) + ser = ymd["A"] + mi = ser.index + assert isinstance(mi, MultiIndex) + if dtype is int: + assert isinstance(mi.levels[0], Int64Index) + else: + assert isinstance(mi.levels[0], Float64Index) + + assert 14 not in mi.levels[0] + assert not mi.levels[0]._should_fallback_to_positional() + assert not mi._should_fallback_to_positional() + + with pytest.raises(KeyError, match="14"): + ser[14] + with pytest.raises(KeyError, match="14"): + mi.get_value(ser, 14) # --------------------------------------------------------------------- # AMBIGUOUS CASES! @@ -140,7 +165,7 @@ def test_partial_loc_missing(self, multiindex_year_month_day_dataframe_random_da tm.assert_series_equal(result, expected) # need to put in some work here - + # FIXME: dont leave commented-out # self.ymd.loc[2000, 0] = 0 # assert (self.ymd.loc[2000]['A'] == 0).all() diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 1f19244cf76d3..853b92ea91274 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -236,6 +236,7 @@ def f(name, df2): f_index ) + # FIXME: dont leave commented-out # TODO(wesm): unused? # new_df = pd.concat([f(name, df2) for name, df2 in grp], axis=1).T @@ -255,7 +256,11 @@ def test_series_setitem(self, multiindex_year_month_day_dataframe_random_data): assert notna(s.values[65:]).all() s[2000, 3, 10] = np.nan - assert isna(s[49]) + assert isna(s.iloc[49]) + + with pytest.raises(KeyError, match="49"): + # GH#33355 dont fall-back to positional when leading level is int + s[49] def test_frame_getitem_setitem_boolean(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data
- [x] closes #33355 - [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/33404
2020-04-08T19:14:26Z
2020-04-10T16:00:57Z
2020-04-10T16:00:57Z
2020-04-10T18:18:56Z
DOC: Fix heading capitalization in doc/source/whatsnew - part2 (#32550)
diff --git a/doc/source/whatsnew/v0.6.1.rst b/doc/source/whatsnew/v0.6.1.rst index d01757775d694..8eea0a07f1f79 100644 --- a/doc/source/whatsnew/v0.6.1.rst +++ b/doc/source/whatsnew/v0.6.1.rst @@ -1,8 +1,8 @@ .. _whatsnew_061: -v.0.6.1 (December 13, 2011) ---------------------------- +Version 0.6.1 (December 13, 2011) +--------------------------------- New features ~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v0.7.0.rst b/doc/source/whatsnew/v0.7.0.rst index a63cd37e47dc2..a193b8049e951 100644 --- a/doc/source/whatsnew/v0.7.0.rst +++ b/doc/source/whatsnew/v0.7.0.rst @@ -1,7 +1,7 @@ .. _whatsnew_0700: -v.0.7.0 (February 9, 2012) --------------------------- +Version 0.7.0 (February 9, 2012) +-------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.7.1.rst b/doc/source/whatsnew/v0.7.1.rst index 04b548a93c338..7082ef8ed2882 100644 --- a/doc/source/whatsnew/v0.7.1.rst +++ b/doc/source/whatsnew/v0.7.1.rst @@ -1,7 +1,7 @@ .. _whatsnew_0701: -v.0.7.1 (February 29, 2012) ---------------------------- +Version 0.7.1 (February 29, 2012) +--------------------------------- {{ header }} diff --git a/doc/source/whatsnew/v0.7.2.rst b/doc/source/whatsnew/v0.7.2.rst index ad72b081e590c..e10a7b499549b 100644 --- a/doc/source/whatsnew/v0.7.2.rst +++ b/doc/source/whatsnew/v0.7.2.rst @@ -1,7 +1,7 @@ .. _whatsnew_0702: -v.0.7.2 (March 16, 2012) ---------------------------- +Version 0.7.2 (March 16, 2012) +------------------------------ {{ header }} diff --git a/doc/source/whatsnew/v0.7.3.rst b/doc/source/whatsnew/v0.7.3.rst index 020cf3bdc2d59..5ed48c0d8d6d9 100644 --- a/doc/source/whatsnew/v0.7.3.rst +++ b/doc/source/whatsnew/v0.7.3.rst @@ -1,7 +1,7 @@ .. _whatsnew_0703: -v.0.7.3 (April 12, 2012) ------------------------- +Version 0.7.3 (April 12, 2012) +------------------------------ {{ header }} @@ -44,7 +44,7 @@ New features - Add ``kurt`` methods to Series and DataFrame for computing kurtosis -NA Boolean comparison API change +NA boolean comparison API change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Reverted some changes to how NA values (represented typically as ``NaN`` or
- [ ] Modify files v0.6.1.rst, v0.7.0.rst, v0.7.1.rst, v0.7.2.rst, v0.7.3.rst
https://api.github.com/repos/pandas-dev/pandas/pulls/33403
2020-04-08T18:24:09Z
2020-04-10T17:54:24Z
2020-04-10T17:54:24Z
2020-04-10T17:54:28Z
PERF: fastpaths in is_foo_dtype checks
diff --git a/pandas/_libs/__init__.py b/pandas/_libs/__init__.py index 141ca0645b906..f119e280f5867 100644 --- a/pandas/_libs/__init__.py +++ b/pandas/_libs/__init__.py @@ -6,9 +6,11 @@ "Timedelta", "Timestamp", "iNaT", + "Interval", ] +from pandas._libs.interval import Interval from pandas._libs.tslibs import ( NaT, NaTType, diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index b2301ab0190c7..76aefd9d5ba8f 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -7,7 +7,7 @@ import numpy as np -from pandas._libs import algos +from pandas._libs import Interval, Period, algos from pandas._libs.tslibs import conversion from pandas._typing import ArrayLike, DtypeObj @@ -396,6 +396,9 @@ def is_datetime64_dtype(arr_or_dtype) -> bool: >>> is_datetime64_dtype([1, 2, 3]) False """ + if isinstance(arr_or_dtype, np.dtype): + # GH#33400 fastpath for dtype object + return arr_or_dtype.kind == "M" return _is_dtype_type(arr_or_dtype, classes(np.datetime64)) @@ -431,6 +434,10 @@ def is_datetime64tz_dtype(arr_or_dtype) -> bool: >>> is_datetime64tz_dtype(s) True """ + if isinstance(arr_or_dtype, ExtensionDtype): + # GH#33400 fastpath for dtype object + return arr_or_dtype.kind == "M" + if arr_or_dtype is None: return False return DatetimeTZDtype.is_dtype(arr_or_dtype) @@ -463,6 +470,10 @@ def is_timedelta64_dtype(arr_or_dtype) -> bool: >>> is_timedelta64_dtype('0 days') False """ + if isinstance(arr_or_dtype, np.dtype): + # GH#33400 fastpath for dtype object + return arr_or_dtype.kind == "m" + return _is_dtype_type(arr_or_dtype, classes(np.timedelta64)) @@ -493,6 +504,10 @@ def is_period_dtype(arr_or_dtype) -> bool: >>> is_period_dtype(pd.PeriodIndex([], freq="A")) True """ + if isinstance(arr_or_dtype, ExtensionDtype): + # GH#33400 fastpath for dtype object + return arr_or_dtype.type is Period + # TODO: Consider making Period an instance of PeriodDtype if arr_or_dtype is None: return False @@ -528,6 +543,10 @@ def is_interval_dtype(arr_or_dtype) -> bool: >>> is_interval_dtype(pd.IntervalIndex([interval])) True """ + if isinstance(arr_or_dtype, ExtensionDtype): + # GH#33400 fastpath for dtype object + return arr_or_dtype.type is Interval + # TODO: Consider making Interval an instance of IntervalDtype if arr_or_dtype is None: return False @@ -561,6 +580,10 @@ def is_categorical_dtype(arr_or_dtype) -> bool: >>> is_categorical_dtype(pd.CategoricalIndex([1, 2, 3])) True """ + if isinstance(arr_or_dtype, ExtensionDtype): + # GH#33400 fastpath for dtype object + return arr_or_dtype.name == "category" + if arr_or_dtype is None: return False return CategoricalDtype.is_dtype(arr_or_dtype) @@ -938,6 +961,10 @@ def is_datetime64_any_dtype(arr_or_dtype) -> bool: >>> is_datetime64_any_dtype(pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]")) True """ + if isinstance(arr_or_dtype, (np.dtype, ExtensionDtype)): + # GH#33400 fastpath for dtype object + return arr_or_dtype.kind == "M" + if arr_or_dtype is None: return False return is_datetime64_dtype(arr_or_dtype) or is_datetime64tz_dtype(arr_or_dtype)
xref #33364, partially addresses #33368 For exposition I used the new type checking functions in parsers.pyx. For the implementation I chose `.type` and `.kind` checks in order to avoid needing the imports from `dtypes.dtypes`, which has dependencies on a bunch of other parts of the code. ``` In [1]: import pandas as pd In [2]: from pandas.core.dtypes.common import * In [3]: cat = pd.Categorical([]) In [4]: arr = np.arange(5) In [5]: %timeit is_categorical_dtype(cat.dtype) 1.57 µs ± 34.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [6]: %timeit is_cat_dtype(cat.dtype) 316 ns ± 3.78 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [7]: %timeit is_extension_array_dtype(cat.dtype) 364 ns ± 5.39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [8]: %timeit is_ea_dtype(cat.dtype) 270 ns ± 7.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [9]: %timeit is_extension_array_dtype(arr.dtype) 759 ns ± 5.16 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [10]: %timeit is_ea_dtype(arr.dtype) 199 ns ± 8.77 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/33400
2020-04-08T16:39:15Z
2020-04-17T02:33:46Z
2020-04-17T02:33:46Z
2020-04-17T03:01:07Z
ENH: Support passing compression args to gzip and bz2
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index f2152c43ceaba..df6b44ac654ce 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -285,14 +285,18 @@ chunksize : int, default ``None`` Quoting, compression, and file format +++++++++++++++++++++++++++++++++++++ -compression : {``'infer'``, ``'gzip'``, ``'bz2'``, ``'zip'``, ``'xz'``, ``None``}, default ``'infer'`` +compression : {``'infer'``, ``'gzip'``, ``'bz2'``, ``'zip'``, ``'xz'``, ``None``, ``dict``}, default ``'infer'`` For on-the-fly decompression of on-disk data. If 'infer', then use gzip, bz2, zip, or xz if filepath_or_buffer is a string ending in '.gz', '.bz2', '.zip', or '.xz', respectively, and no decompression otherwise. If using 'zip', the ZIP file must contain only one data file to be read in. - Set to ``None`` for no decompression. + Set to ``None`` for no decompression. Can also be a dict with key ``'method'`` + set to one of {``'zip'``, ``'gzip'``, ``'bz2'``}, and other keys set to + compression settings. As an example, the following could be passed for + faster compression: ``compression={'method': 'gzip', 'compresslevel': 1}``. .. versionchanged:: 0.24.0 'infer' option added and set to default. + .. versionchanged:: 1.1.0 dict option extended to support ``gzip`` and ``bz2``. thousands : str, default ``None`` Thousands separator. decimal : str, default ``'.'`` @@ -3347,6 +3351,12 @@ The compression type can be an explicit parameter or be inferred from the file e If 'infer', then use ``gzip``, ``bz2``, ``zip``, or ``xz`` if filename ends in ``'.gz'``, ``'.bz2'``, ``'.zip'``, or ``'.xz'``, respectively. +The compression parameter can also be a ``dict`` in order to pass options to the +compression protocol. It must have a ``'method'`` key set to the name +of the compression protocol, which must be one of +{``'zip'``, ``'gzip'``, ``'bz2'``}. All other key-value pairs are passed to +the underlying compression library. + .. ipython:: python df = pd.DataFrame({ @@ -3383,6 +3393,15 @@ The default is to 'infer': rt = pd.read_pickle("s1.pkl.bz2") rt +Passing options to the compression protocol in order to speed up compression: + +.. ipython:: python + + df.to_pickle( + "data.pkl.gz", + compression={"method": "gzip", 'compresslevel': 1} + ) + .. ipython:: python :suppress: diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index fc5893e401836..f7ed07848bb84 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -91,6 +91,12 @@ Other enhancements - The :meth:`DataFrame.to_feather` method now supports additional keyword arguments (e.g. to set the compression) that are added in pyarrow 0.17 (:issue:`33422`). +- :meth:`DataFrame.to_csv`, :meth:`DataFrame.to_pickle`, + and :meth:`DataFrame.to_json` now support passing a dict of + compression arguments when using the ``gzip`` and ``bz2`` protocols. + This can be used to set a custom compression level, e.g., + ``df.to_csv(path, compression={'method': 'gzip', 'compresslevel': 1}`` + (:issue:`33196`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index eb6554bf2260c..2adfd2bb9a7b3 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3096,7 +3096,8 @@ def to_csv( compression mode is 'infer' and `path_or_buf` is path-like, then detect compression mode from the following extensions: '.gz', '.bz2', '.zip' or '.xz'. (otherwise no compression). If dict given - and mode is 'zip' or inferred as 'zip', other entries passed as + and mode is one of {'zip', 'gzip', 'bz2'}, or inferred as + one of the above, other entries passed as additional compression options. .. versionchanged:: 1.0.0 @@ -3105,6 +3106,12 @@ def to_csv( and other entries as additional compression options if compression mode is 'zip'. + .. versionchanged:: 1.1.0 + + Passing compression options as keys in dict is + supported for compression modes 'gzip' and 'bz2' + as well as 'zip'. + quoting : optional constant from csv module Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format` then floats are converted to strings and thus csv.QUOTE_NONNUMERIC diff --git a/pandas/io/common.py b/pandas/io/common.py index 0fce8f5382686..ff527de79c387 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -351,8 +351,9 @@ def get_handle( 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise - no compression). If dict and compression mode is 'zip' or inferred as - 'zip', other entries passed as additional compression options. + no compression). If dict and compression mode is one of + {'zip', 'gzip', 'bz2'}, or inferred as one of the above, + other entries passed as additional compression options. .. versionchanged:: 1.0.0 @@ -360,6 +361,11 @@ def get_handle( and other keys as compression options if compression mode is 'zip'. + .. versionchanged:: 1.1.0 + + Passing compression options as keys in dict is now + supported for compression modes 'gzip' and 'bz2' as well as 'zip'. + memory_map : boolean, default False See parsers._parser_params for more information. is_text : boolean, default True @@ -394,19 +400,28 @@ def get_handle( if compression: + # GH33398 the type ignores here seem related to mypy issue #5382; + # it may be possible to remove them once that is resolved. + # GZ Compression if compression == "gzip": if is_path: - f = gzip.open(path_or_buf, mode) + f = gzip.open( + path_or_buf, mode, **compression_args # type: ignore + ) else: - f = gzip.GzipFile(fileobj=path_or_buf) + f = gzip.GzipFile( + fileobj=path_or_buf, **compression_args # type: ignore + ) # BZ Compression elif compression == "bz2": if is_path: - f = bz2.BZ2File(path_or_buf, mode) + f = bz2.BZ2File( + path_or_buf, mode, **compression_args # type: ignore + ) else: - f = bz2.BZ2File(path_or_buf) + f = bz2.BZ2File(path_or_buf, **compression_args) # type: ignore # ZIP Compression elif compression == "zip": diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index 841241d5124e0..59c9bd0a36d3d 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -143,3 +143,44 @@ def test_with_missing_lzma_runtime(): """ ) subprocess.check_output([sys.executable, "-c", code], stderr=subprocess.PIPE) + + +@pytest.mark.parametrize( + "obj", + [ + pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ), + pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"), + ], +) +@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"]) +def test_gzip_compression_level(obj, method): + # GH33196 + with tm.ensure_clean() as path: + getattr(obj, method)(path, compression="gzip") + compressed_size_default = os.path.getsize(path) + getattr(obj, method)(path, compression={"method": "gzip", "compresslevel": 1}) + compressed_size_fast = os.path.getsize(path) + assert compressed_size_default < compressed_size_fast + + +@pytest.mark.parametrize( + "obj", + [ + pd.DataFrame( + 100 * [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], + columns=["X", "Y", "Z"], + ), + pd.Series(100 * [0.123456, 0.234567, 0.567567], name="X"), + ], +) +@pytest.mark.parametrize("method", ["to_pickle", "to_json", "to_csv"]) +def test_bzip_compression_level(obj, method): + """GH33196 bzip needs file size > 100k to show a size difference between + compression levels, so here we just check if the call works when + compression is passed as a dict. + """ + with tm.ensure_clean() as path: + getattr(obj, method)(path, compression={"method": "bz2", "compresslevel": 1})
This commit closes #33196 but takes a more generic approach than the suggested solution. Instead of providing a 'fast' kwarg or global compression level setting, this commit extends the ability to pass compression settings as a dict to the gzip and bz2 compression methods. In this way, if the user wants faster compression, they can pass compression={'method': 'gzip', 'compresslevel'=1} rather than just compression='gzip'. Note: For the API to be consistent when passing paths vs. filelikes, GZipFile and gzip2.open() must accept the same kwargs. - [x] closes #33196 - [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/33398
2020-04-08T15:28:40Z
2020-04-10T22:21:10Z
2020-04-10T22:21:10Z
2020-04-10T22:21:44Z
BUG/PLT: Multiple plots with different cmap, colorbars legends use first cmap
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 33c65a146dbb5..7059e7e30c73f 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -441,6 +441,7 @@ 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`) +- Bug in :meth:`DataFrame.plot.scatter` that when adding multiple plots with different ``cmap``, colorbars alway use the first ``cmap`` (:issue:`33389`) Groupby/resample/rolling diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index bc8346fd48433..46941e437a4ce 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -902,7 +902,11 @@ def _plot_colorbar(self, ax, **kwds): # For a more detailed description of the issue # see the following link: # https://github.com/ipython/ipython/issues/11215 - img = ax.collections[0] + + # GH33389, if ax is used multiple times, we should always + # use the last one which contains the latest information + # about the ax + img = ax.collections[-1] cbar = self.fig.colorbar(img, ax=ax, **kwds) if _mpl_ge_3_0_0(): diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 4a9efe9554c6e..a657ce212cbff 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1332,6 +1332,20 @@ def test_scatter_colors(self): np.array([1, 1, 1, 1], dtype=np.float64), ) + def test_scatter_colorbar_different_cmap(self): + # GH 33389 + import matplotlib.pyplot as plt + + df = pd.DataFrame({"x": [1, 2, 3], "y": [1, 3, 2], "c": [1, 2, 3]}) + df["x2"] = df["x"] + 1 + + fig, ax = plt.subplots() + df.plot("x", "y", c="c", kind="scatter", cmap="cividis", ax=ax) + df.plot("x2", "y", c="c", kind="scatter", cmap="magma", ax=ax) + + assert ax.collections[0].cmap.name == "cividis" + assert ax.collections[1].cmap.name == "magma" + @pytest.mark.slow def test_plot_bar(self): df = DataFrame(
- [x] closes #33389 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Since this is a plot PR, just post what it looks like after the change ![Screen Shot 2020-04-08 at 3 43 54 PM](https://user-images.githubusercontent.com/9269816/78791204-d94a8a00-79af-11ea-9ebb-e216251c7908.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/33392
2020-04-08T12:46:16Z
2020-04-10T17:00:49Z
2020-04-10T17:00:49Z
2020-04-10T17:00:52Z
ENH: Add numba engine to groupby.aggregate
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index eb637c78806c0..c9ac275cc4ea7 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -660,4 +660,62 @@ def function(values): self.grouper.transform(function, engine="cython") +class AggEngine: + def setup(self): + N = 10 ** 3 + data = DataFrame( + {0: [str(i) for i in range(100)] * N, 1: list(range(100)) * N}, + columns=[0, 1], + ) + self.grouper = data.groupby(0) + + def time_series_numba(self): + def function(values, index): + total = 0 + for i, value in enumerate(values): + if i % 2: + total += value + 5 + else: + total += value * 2 + return total + + self.grouper[1].agg(function, engine="numba") + + def time_series_cython(self): + def function(values): + total = 0 + for i, value in enumerate(values): + if i % 2: + total += value + 5 + else: + total += value * 2 + return total + + self.grouper[1].agg(function, engine="cython") + + def time_dataframe_numba(self): + def function(values, index): + total = 0 + for i, value in enumerate(values): + if i % 2: + total += value + 5 + else: + total += value * 2 + return total + + self.grouper.agg(function, engine="numba") + + def time_dataframe_cython(self): + def function(values): + total = 0 + for i, value in enumerate(values): + if i % 2: + total += value + 5 + else: + total += value * 2 + return total + + self.grouper.agg(function, engine="cython") + + from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst index d7d025981f2f4..37ec7ca9c98d6 100644 --- a/doc/source/user_guide/computation.rst +++ b/doc/source/user_guide/computation.rst @@ -380,8 +380,8 @@ and their default values are set to ``False``, ``True`` and ``False`` respective .. note:: In terms of performance, **the first time a function is run using the Numba engine will be slow** - as Numba will have some function compilation overhead. However, ``rolling`` objects will cache - the function and subsequent calls will be fast. In general, the Numba engine is performant with + as Numba will have some function compilation overhead. However, the compiled functions are cached, + and subsequent calls will be fast. In general, the Numba engine is performant with a larger amount of data points (e.g. 1+ million). .. code-block:: ipython diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst index 5927f1a4175ee..c5f58425139ee 100644 --- a/doc/source/user_guide/groupby.rst +++ b/doc/source/user_guide/groupby.rst @@ -1021,6 +1021,73 @@ that is itself a series, and possibly upcast the result to a DataFrame: the output as well as set the indices. +Numba Accelerated Routines +-------------------------- + +.. versionadded:: 1.1 + +If `Numba <https://numba.pydata.org/>`__ is installed as an optional dependency, the ``transform`` and +``aggregate`` methods support ``engine='numba'`` and ``engine_kwargs`` arguments. The ``engine_kwargs`` +argument is a dictionary of keyword arguments that will be passed into the +`numba.jit decorator <https://numba.pydata.org/numba-doc/latest/reference/jit-compilation.html#numba.jit>`__. +These keyword arguments will be applied to the passed function. Currently only ``nogil``, ``nopython``, +and ``parallel`` are supported, and their default values are set to ``False``, ``True`` and ``False`` respectively. + +The function signature must start with ``values, index`` **exactly** as the data belonging to each group +will be passed into ``values``, and the group index will be passed into ``index``. + +.. warning:: + + When using ``engine='numba'``, there will be no "fall back" behavior internally. The group + data and group index will be passed as numpy arrays to the JITed user defined function, and no + alternative execution attempts will be tried. + +.. note:: + + In terms of performance, **the first time a function is run using the Numba engine will be slow** + as Numba will have some function compilation overhead. However, the compiled functions are cached, + and subsequent calls will be fast. In general, the Numba engine is performant with + a larger amount of data points (e.g. 1+ million). + +.. code-block:: ipython + + In [1]: N = 10 ** 3 + + In [2]: data = {0: [str(i) for i in range(100)] * N, 1: list(range(100)) * N} + + In [3]: df = pd.DataFrame(data, columns=[0, 1]) + + In [4]: def f_numba(values, index): + ...: total = 0 + ...: for i, value in enumerate(values): + ...: if i % 2: + ...: total += value + 5 + ...: else: + ...: total += value * 2 + ...: return total + ...: + + In [5]: def f_cython(values): + ...: total = 0 + ...: for i, value in enumerate(values): + ...: if i % 2: + ...: total += value + 5 + ...: else: + ...: total += value * 2 + ...: return total + ...: + + In [6]: groupby = df.groupby(0) + # Run the first time, compilation time will affect performance + In [7]: %timeit -r 1 -n 1 groupby.aggregate(f_numba, engine='numba') # noqa: E225 + 2.14 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) + # Function is cached and performance will improve + In [8]: %timeit groupby.aggregate(f_numba, engine='numba') + 4.93 ms ± 32.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) + + In [9]: %timeit groupby.aggregate(f_cython, engine='cython') + 18.6 ms ± 84.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) + Other useful features --------------------- diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index cd1cb0b64f74a..0f766414b20e8 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -98,7 +98,7 @@ Other enhancements This can be used to set a custom compression level, e.g., ``df.to_csv(path, compression={'method': 'gzip', 'compresslevel': 1}`` (:issue:`33196`) -- :meth:`~pandas.core.groupby.GroupBy.transform` has gained ``engine`` and ``engine_kwargs`` arguments that supports executing functions with ``Numba`` (:issue:`32854`) +- :meth:`~pandas.core.groupby.GroupBy.transform` and :meth:`~pandas.core.groupby.GroupBy.aggregate` has gained ``engine`` and ``engine_kwargs`` arguments that supports executing functions with ``Numba`` (:issue:`32854`, :issue:`33388`) - :meth:`~pandas.core.resample.Resampler.interpolate` now supports SciPy interpolation method :class:`scipy.interpolate.CubicSpline` as method ``cubicspline`` (:issue:`33670`) - diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 504de404b2509..18752cdc1642e 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -79,6 +79,7 @@ NUMBA_FUNC_CACHE, check_kwargs_and_nopython, get_jit_arguments, + is_numba_util_related_error, jit_user_function, split_for_numba, validate_udf, @@ -244,7 +245,9 @@ def apply(self, func, *args, **kwargs): axis="", ) @Appender(_shared_docs["aggregate"]) - def aggregate(self, func=None, *args, **kwargs): + def aggregate( + self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs + ): relabeling = func is None columns = None @@ -272,11 +275,18 @@ def aggregate(self, func=None, *args, **kwargs): return getattr(self, cyfunc)() if self.grouper.nkeys > 1: - return self._python_agg_general(func, *args, **kwargs) + return self._python_agg_general( + func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ) try: - return self._python_agg_general(func, *args, **kwargs) - except (ValueError, KeyError): + return self._python_agg_general( + func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ) + except (ValueError, KeyError) as err: + # Do not catch Numba errors here, we want to raise and not fall back. + if is_numba_util_related_error(str(err)): + raise err # TODO: KeyError is raised in _python_agg_general, # see see test_groupby.test_basic result = self._aggregate_named(func, *args, **kwargs) @@ -941,7 +951,9 @@ class DataFrameGroupBy(GroupBy[DataFrame]): axis="", ) @Appender(_shared_docs["aggregate"]) - def aggregate(self, func=None, *args, **kwargs): + def aggregate( + self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs + ): relabeling = func is None and is_multi_agg_with_relabel(**kwargs) if relabeling: @@ -962,6 +974,11 @@ def aggregate(self, func=None, *args, **kwargs): func = maybe_mangle_lambdas(func) + if engine == "numba": + return self._python_agg_general( + func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ) + result, how = self._aggregate(func, *args, **kwargs) if how is None: return result diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 154af3981a5ff..6924c7d320bc4 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -910,9 +910,12 @@ def _cython_agg_general( return self._wrap_aggregated_output(output) - def _python_agg_general(self, func, *args, **kwargs): + def _python_agg_general( + self, func, *args, engine="cython", engine_kwargs=None, **kwargs + ): func = self._is_builtin_func(func) - f = lambda x: func(x, *args, **kwargs) + if engine != "numba": + f = lambda x: func(x, *args, **kwargs) # iterate through "columns" ex exclusions to populate output dict output: Dict[base.OutputKey, np.ndarray] = {} @@ -923,11 +926,21 @@ def _python_agg_general(self, func, *args, **kwargs): # agg_series below assumes ngroups > 0 continue - try: - # if this function is invalid for this dtype, we will ignore it. - result, counts = self.grouper.agg_series(obj, f) - except TypeError: - continue + if engine == "numba": + result, counts = self.grouper.agg_series( + obj, + func, + *args, + engine=engine, + engine_kwargs=engine_kwargs, + **kwargs, + ) + else: + try: + # if this function is invalid for this dtype, we will ignore it. + result, counts = self.grouper.agg_series(obj, f) + except TypeError: + continue assert result is not None key = base.OutputKey(label=name, position=idx) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 8d535374a083f..3c7794fa52d86 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -54,6 +54,14 @@ get_group_index_sorter, get_indexer_dict, ) +from pandas.core.util.numba_ import ( + NUMBA_FUNC_CACHE, + check_kwargs_and_nopython, + get_jit_arguments, + jit_user_function, + split_for_numba, + validate_udf, +) class BaseGrouper: @@ -608,10 +616,16 @@ def _transform( return result - def agg_series(self, obj: Series, func): + def agg_series( + self, obj: Series, func, *args, engine="cython", engine_kwargs=None, **kwargs + ): # Caller is responsible for checking ngroups != 0 assert self.ngroups != 0 + if engine == "numba": + return self._aggregate_series_pure_python( + obj, func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs + ) if len(obj) == 0: # SeriesGrouper would raise if we were to call _aggregate_series_fast return self._aggregate_series_pure_python(obj, func) @@ -656,7 +670,18 @@ def _aggregate_series_fast(self, obj: Series, func): result, counts = grouper.get_result() return result, counts - def _aggregate_series_pure_python(self, obj: Series, func): + def _aggregate_series_pure_python( + self, obj: Series, func, *args, engine="cython", engine_kwargs=None, **kwargs + ): + + if engine == "numba": + nopython, nogil, parallel = get_jit_arguments(engine_kwargs) + check_kwargs_and_nopython(kwargs, nopython) + validate_udf(func) + cache_key = (func, "groupby_agg") + numba_func = NUMBA_FUNC_CACHE.get( + cache_key, jit_user_function(func, nopython, nogil, parallel) + ) group_index, _, ngroups = self.group_info @@ -666,7 +691,14 @@ def _aggregate_series_pure_python(self, obj: Series, func): splitter = get_splitter(obj, group_index, ngroups, axis=0) for label, group in splitter: - res = func(group) + if engine == "numba": + values, index = split_for_numba(group) + res = numba_func(values, index, *args) + if cache_key not in NUMBA_FUNC_CACHE: + NUMBA_FUNC_CACHE[cache_key] = numba_func + else: + res = func(group, *args, **kwargs) + if result is None: if isinstance(res, (Series, Index, np.ndarray)): if len(res) == 1: @@ -842,7 +874,9 @@ def groupings(self) -> "List[grouper.Grouping]": for lvl, name in zip(self.levels, self.names) ] - def agg_series(self, obj: Series, func): + def agg_series( + self, obj: Series, func, *args, engine="cython", engine_kwargs=None, **kwargs + ): # Caller is responsible for checking ngroups != 0 assert self.ngroups != 0 assert len(self.bins) > 0 # otherwise we'd get IndexError in get_result diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py index 29e74747881ae..215248f5a43c2 100644 --- a/pandas/core/util/numba_.py +++ b/pandas/core/util/numba_.py @@ -12,6 +12,25 @@ NUMBA_FUNC_CACHE: Dict[Tuple[Callable, str], Callable] = dict() +def is_numba_util_related_error(err_message: str) -> bool: + """ + Check if an error was raised from one of the numba utility functions + + For cases where a try/except block has mistakenly caught the error + and we want to re-raise + + Parameters + ---------- + err_message : str, + exception error message + + Returns + ------- + bool + """ + return "The first" in err_message or "numba does not" in err_message + + def check_kwargs_and_nopython( kwargs: Optional[Dict] = None, nopython: Optional[bool] = None ) -> None: @@ -76,7 +95,6 @@ def jit_user_function( ---------- func : function user defined function - nopython : bool nopython parameter for numba.JIT nogil : bool diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py new file mode 100644 index 0000000000000..70b0a027f1bd1 --- /dev/null +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -0,0 +1,114 @@ +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +from pandas import DataFrame +import pandas._testing as tm +from pandas.core.util.numba_ import NUMBA_FUNC_CACHE + + +@td.skip_if_no("numba", "0.46.0") +def test_correct_function_signature(): + def incorrect_function(x): + return sum(x) * 2.7 + + data = DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + with pytest.raises(ValueError, match=f"The first 2"): + data.groupby("key").agg(incorrect_function, engine="numba") + + with pytest.raises(ValueError, match=f"The first 2"): + data.groupby("key")["data"].agg(incorrect_function, engine="numba") + + +@td.skip_if_no("numba", "0.46.0") +def test_check_nopython_kwargs(): + def incorrect_function(x, **kwargs): + return sum(x) * 2.7 + + data = DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + with pytest.raises(ValueError, match="numba does not support"): + data.groupby("key").agg(incorrect_function, engine="numba", a=1) + + with pytest.raises(ValueError, match="numba does not support"): + data.groupby("key")["data"].agg(incorrect_function, engine="numba", a=1) + + +@td.skip_if_no("numba", "0.46.0") +@pytest.mark.filterwarnings("ignore:\\nThe keyword argument") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +@pytest.mark.parametrize("jit", [True, False]) +@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) +def test_numba_vs_cython(jit, pandas_obj, nogil, parallel, nopython): + def func_numba(values, index): + return np.mean(values) * 2.7 + + if jit: + # Test accepted jitted functions + import numba + + func_numba = numba.jit(func_numba) + + data = DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + ) + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + grouped = data.groupby(0) + if pandas_obj == "Series": + grouped = grouped[1] + + result = grouped.agg(func_numba, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) * 2.7, engine="cython") + + tm.assert_equal(result, expected) + + +@td.skip_if_no("numba", "0.46.0") +@pytest.mark.filterwarnings("ignore:\\nThe keyword argument") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +@pytest.mark.parametrize("jit", [True, False]) +@pytest.mark.parametrize("pandas_obj", ["Series", "DataFrame"]) +def test_cache(jit, pandas_obj, nogil, parallel, nopython): + # Test that the functions are cached correctly if we switch functions + def func_1(values, index): + return np.mean(values) - 3.4 + + def func_2(values, index): + return np.mean(values) * 2.7 + + if jit: + import numba + + func_1 = numba.jit(func_1) + func_2 = numba.jit(func_2) + + data = DataFrame( + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + ) + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + grouped = data.groupby(0) + if pandas_obj == "Series": + grouped = grouped[1] + + result = grouped.agg(func_1, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) - 3.4, engine="cython") + tm.assert_equal(result, expected) + # func_1 should be in the cache now + assert (func_1, "groupby_agg") in NUMBA_FUNC_CACHE + + # Add func_2 to the cache + result = grouped.agg(func_2, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) * 2.7, engine="cython") + tm.assert_equal(result, expected) + assert (func_2, "groupby_agg") in NUMBA_FUNC_CACHE + + # Retest func_1 which should use the cache + result = grouped.agg(func_1, engine="numba", engine_kwargs=engine_kwargs) + expected = grouped.agg(lambda x: np.mean(x) - 3.4, engine="cython") + tm.assert_equal(result, expected)
- [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry In the same spirit of #31845 and #32854, adding `engine` and `engine_kwargs` arguments to `groupby.aggreate`. This PR has some functionality that is waiting to be merged in #32854
https://api.github.com/repos/pandas-dev/pandas/pulls/33388
2020-04-08T05:48:14Z
2020-04-26T00:02:57Z
2020-04-26T00:02:57Z
2020-04-26T04:21:57Z
REF: numeric index test_indexing
diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py new file mode 100644 index 0000000000000..473e370c76f8b --- /dev/null +++ b/pandas/tests/indexes/numeric/test_indexing.py @@ -0,0 +1,237 @@ +import numpy as np +import pytest + +from pandas import Float64Index, Int64Index, Series, UInt64Index +import pandas._testing as tm + + +@pytest.fixture +def index_large(): + # large values used in UInt64Index tests where no compat needed with Int64/Float64 + large = [2 ** 63, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20, 2 ** 63 + 25] + return UInt64Index(large) + + +class TestGetLoc: + def test_get_loc_float64(self): + idx = Float64Index([0.0, 1.0, 2.0]) + for method in [None, "pad", "backfill", "nearest"]: + assert idx.get_loc(1, method) == 1 + if method is not None: + assert idx.get_loc(1, method, tolerance=0) == 1 + + for method, loc in [("pad", 1), ("backfill", 2), ("nearest", 1)]: + assert idx.get_loc(1.1, method) == loc + assert idx.get_loc(1.1, method, tolerance=0.9) == loc + + with pytest.raises(KeyError, match="^'foo'$"): + idx.get_loc("foo") + with pytest.raises(KeyError, match=r"^1\.5$"): + idx.get_loc(1.5) + with pytest.raises(KeyError, match=r"^1\.5$"): + idx.get_loc(1.5, method="pad", tolerance=0.1) + with pytest.raises(KeyError, match="^True$"): + idx.get_loc(True) + with pytest.raises(KeyError, match="^False$"): + idx.get_loc(False) + + with pytest.raises(ValueError, match="must be numeric"): + idx.get_loc(1.4, method="nearest", tolerance="foo") + + with pytest.raises(ValueError, match="must contain numeric elements"): + idx.get_loc(1.4, method="nearest", tolerance=np.array(["foo"])) + + with pytest.raises( + ValueError, match="tolerance size must match target index size" + ): + idx.get_loc(1.4, method="nearest", tolerance=np.array([1, 2])) + + def test_get_loc_na(self): + idx = Float64Index([np.nan, 1, 2]) + assert idx.get_loc(1) == 1 + assert idx.get_loc(np.nan) == 0 + + idx = Float64Index([np.nan, 1, np.nan]) + assert idx.get_loc(1) == 1 + + # FIXME: dont leave commented-out + # representable by slice [0:2:2] + # pytest.raises(KeyError, idx.slice_locs, np.nan) + sliced = idx.slice_locs(np.nan) + assert isinstance(sliced, tuple) + assert sliced == (0, 3) + + # not representable by slice + idx = Float64Index([np.nan, 1, np.nan, np.nan]) + assert idx.get_loc(1) == 1 + msg = "'Cannot get left slice bound for non-unique label: nan" + with pytest.raises(KeyError, match=msg): + idx.slice_locs(np.nan) + + def test_get_loc_missing_nan(self): + # GH#8569 + idx = Float64Index([1, 2]) + assert idx.get_loc(1) == 0 + with pytest.raises(KeyError, match=r"^3$"): + idx.get_loc(3) + with pytest.raises(KeyError, match="^nan$"): + idx.get_loc(np.nan) + with pytest.raises(TypeError, match=r"'\[nan\]' is an invalid key"): + # listlike/non-hashable raises TypeError + idx.get_loc([np.nan]) + + +class TestGetIndexer: + def test_get_indexer_float64(self): + idx = Float64Index([0.0, 1.0, 2.0]) + tm.assert_numpy_array_equal( + idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp) + ) + + target = [-0.1, 0.5, 1.1] + tm.assert_numpy_array_equal( + idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp) + ) + + def test_get_indexer_nan(self): + # GH#7820 + result = Float64Index([1, 2, np.nan]).get_indexer([np.nan]) + expected = np.array([2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_get_indexer_int64(self): + index = Int64Index(range(0, 20, 2)) + target = Int64Index(np.arange(10)) + indexer = index.get_indexer(target) + expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = Int64Index(np.arange(10)) + indexer = index.get_indexer(target, method="pad") + expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = Int64Index(np.arange(10)) + indexer = index.get_indexer(target, method="backfill") + expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + def test_get_indexer_uint64(self, index_large): + target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63) + indexer = index_large.get_indexer(target) + expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63) + indexer = index_large.get_indexer(target, method="pad") + expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63) + indexer = index_large.get_indexer(target, method="backfill") + expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(indexer, expected) + + +class TestWhere: + @pytest.mark.parametrize( + "index", + [ + Float64Index(np.arange(5, dtype="float64")), + Int64Index(range(0, 20, 2)), + UInt64Index(np.arange(5, dtype="uint64")), + ], + ) + @pytest.mark.parametrize("klass", [list, tuple, np.array, Series]) + def test_where(self, klass, index): + cond = [True] * len(index) + expected = index + result = index.where(klass(cond)) + + cond = [False] + [True] * (len(index) - 1) + expected = Float64Index([index._na_value] + index[1:].tolist()) + result = index.where(klass(cond)) + tm.assert_index_equal(result, expected) + + +class TestTake: + @pytest.mark.parametrize("klass", [Float64Index, Int64Index, UInt64Index]) + def test_take_preserve_name(self, klass): + index = klass([1, 2, 3, 4], name="foo") + taken = index.take([3, 0, 1]) + assert index.name == taken.name + + def test_take_fill_value_float64(self): + # GH 12631 + idx = Float64Index([1.0, 2.0, 3.0], name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = Float64Index([2.0, 1.0, 3.0], name="xxx") + tm.assert_index_equal(result, expected) + + # fill_value + result = idx.take(np.array([1, 0, -1]), fill_value=True) + expected = Float64Index([2.0, 1.0, np.nan], name="xxx") + tm.assert_index_equal(result, expected) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = Float64Index([2.0, 1.0, 3.0], name="xxx") + tm.assert_index_equal(result, expected) + + msg = ( + "When allow_fill=True and fill_value is not None, " + "all indices must be >= -1" + ) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + @pytest.mark.parametrize("klass", [Int64Index, UInt64Index]) + def test_take_fill_value_ints(self, klass): + # see gh-12631 + idx = klass([1, 2, 3], name="xxx") + result = idx.take(np.array([1, 0, -1])) + expected = klass([2, 1, 3], name="xxx") + tm.assert_index_equal(result, expected) + + name = klass.__name__ + msg = f"Unable to fill values because {name} cannot contain NA" + + # fill_value=True + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -1]), fill_value=True) + + # allow_fill=False + result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = klass([2, 1, 3], name="xxx") + tm.assert_index_equal(result, expected) + + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -2]), fill_value=True) + with pytest.raises(ValueError, match=msg): + idx.take(np.array([1, 0, -5]), fill_value=True) + + msg = "index -5 is out of bounds for (axis 0 with )?size 3" + with pytest.raises(IndexError, match=msg): + idx.take(np.array([1, -5])) + + +class TestContains: + def test_contains_float64_nans(self): + index = Float64Index([1.0, 2.0, np.nan]) + assert np.nan in index + + def test_contains_float64_not_nans(self): + index = Float64Index([1.0, 2.0, np.nan]) + assert 1.0 in index diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 49f3060e95388..35a1cbd141c89 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -14,6 +14,10 @@ class Numeric(Base): + def test_where(self): + # Tested in numeric.test_indexing + pass + def test_can_hold_identifiers(self): idx = self.create_index() key = idx[0] @@ -75,18 +79,6 @@ def test_index_groupby(self): expected = {ex_keys[0]: idx[[0, 5]], ex_keys[1]: idx[[1, 4]]} tm.assert_dict_equal(idx.groupby(to_groupby), expected) - @pytest.mark.parametrize("klass", [list, tuple, np.array, Series]) - def test_where(self, klass): - i = self.create_index() - cond = [True] * len(i) - expected = i - result = i.where(klass(cond)) - - cond = [False] + [True] * (len(i) - 1) - expected = Float64Index([i._na_value] + i[1:].tolist()) - result = i.where(klass(cond)) - tm.assert_index_equal(result, expected) - def test_insert(self, nulls_fixture): # GH 18295 (test missing) index = self.create_index() @@ -310,89 +302,6 @@ def test_equals_numeric(self): i2 = Float64Index([1.0, np.nan]) assert i.equals(i2) - def test_get_indexer(self): - idx = Float64Index([0.0, 1.0, 2.0]) - tm.assert_numpy_array_equal( - idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp) - ) - - target = [-0.1, 0.5, 1.1] - tm.assert_numpy_array_equal( - idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp) - ) - tm.assert_numpy_array_equal( - idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp) - ) - tm.assert_numpy_array_equal( - idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp) - ) - - def test_get_loc(self): - idx = Float64Index([0.0, 1.0, 2.0]) - for method in [None, "pad", "backfill", "nearest"]: - assert idx.get_loc(1, method) == 1 - if method is not None: - assert idx.get_loc(1, method, tolerance=0) == 1 - - for method, loc in [("pad", 1), ("backfill", 2), ("nearest", 1)]: - assert idx.get_loc(1.1, method) == loc - assert idx.get_loc(1.1, method, tolerance=0.9) == loc - - with pytest.raises(KeyError, match="^'foo'$"): - idx.get_loc("foo") - with pytest.raises(KeyError, match=r"^1\.5$"): - idx.get_loc(1.5) - with pytest.raises(KeyError, match=r"^1\.5$"): - idx.get_loc(1.5, method="pad", tolerance=0.1) - with pytest.raises(KeyError, match="^True$"): - idx.get_loc(True) - with pytest.raises(KeyError, match="^False$"): - idx.get_loc(False) - - with pytest.raises(ValueError, match="must be numeric"): - idx.get_loc(1.4, method="nearest", tolerance="foo") - - with pytest.raises(ValueError, match="must contain numeric elements"): - idx.get_loc(1.4, method="nearest", tolerance=np.array(["foo"])) - - with pytest.raises( - ValueError, match="tolerance size must match target index size" - ): - idx.get_loc(1.4, method="nearest", tolerance=np.array([1, 2])) - - def test_get_loc_na(self): - idx = Float64Index([np.nan, 1, 2]) - assert idx.get_loc(1) == 1 - assert idx.get_loc(np.nan) == 0 - - idx = Float64Index([np.nan, 1, np.nan]) - assert idx.get_loc(1) == 1 - - # representable by slice [0:2:2] - # pytest.raises(KeyError, idx.slice_locs, np.nan) - sliced = idx.slice_locs(np.nan) - assert isinstance(sliced, tuple) - assert sliced == (0, 3) - - # not representable by slice - idx = Float64Index([np.nan, 1, np.nan, np.nan]) - assert idx.get_loc(1) == 1 - msg = "'Cannot get left slice bound for non-unique label: nan" - with pytest.raises(KeyError, match=msg): - idx.slice_locs(np.nan) - - def test_get_loc_missing_nan(self): - # GH 8569 - idx = Float64Index([1, 2]) - assert idx.get_loc(1) == 0 - with pytest.raises(KeyError, match=r"^3$"): - idx.get_loc(3) - with pytest.raises(KeyError, match="^nan$"): - idx.get_loc(np.nan) - with pytest.raises(TypeError, match=r"'\[nan\]' is an invalid key"): - # listlike/non-hashable raises TypeError - idx.get_loc([np.nan]) - @pytest.mark.parametrize( "vals", [ @@ -435,14 +344,6 @@ def test_lookups_datetimelike_values(self, vals): result = ser.iat[1] assert isinstance(result, type(expected)) and result == expected - def test_contains_nans(self): - i = Float64Index([1.0, 2.0, np.nan]) - assert np.nan in i - - def test_contains_not_nans(self): - i = Float64Index([1.0, 2.0, np.nan]) - assert 1.0 in i - def test_doesnt_contain_all_the_things(self): i = Float64Index([np.nan]) assert not i.isin([0]).item() @@ -480,36 +381,6 @@ def test_fillna_float64(self): exp = Index([1.0, "obj", 3.0], name="x") tm.assert_index_equal(idx.fillna("obj"), exp) - def test_take_fill_value(self): - # GH 12631 - idx = pd.Float64Index([1.0, 2.0, 3.0], name="xxx") - result = idx.take(np.array([1, 0, -1])) - expected = pd.Float64Index([2.0, 1.0, 3.0], name="xxx") - tm.assert_index_equal(result, expected) - - # fill_value - result = idx.take(np.array([1, 0, -1]), fill_value=True) - expected = pd.Float64Index([2.0, 1.0, np.nan], name="xxx") - tm.assert_index_equal(result, expected) - - # allow_fill=False - result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) - expected = pd.Float64Index([2.0, 1.0, 3.0], name="xxx") - tm.assert_index_equal(result, expected) - - msg = ( - "When allow_fill=True and fill_value is not None, " - "all indices must be >= -1" - ) - with pytest.raises(ValueError, match=msg): - idx.take(np.array([1, 0, -2]), fill_value=True) - with pytest.raises(ValueError, match=msg): - idx.take(np.array([1, 0, -5]), fill_value=True) - - msg = "index -5 is out of bounds for (axis 0 with )?size 3" - with pytest.raises(IndexError, match=msg): - idx.take(np.array([1, -5])) - class NumericInt(Numeric): def test_view(self): @@ -617,39 +488,6 @@ def test_prevent_casting(self): result = index.astype("O") assert result.dtype == np.object_ - def test_take_preserve_name(self): - index = self._holder([1, 2, 3, 4], name="foo") - taken = index.take([3, 0, 1]) - assert index.name == taken.name - - def test_take_fill_value(self): - # see gh-12631 - idx = self._holder([1, 2, 3], name="xxx") - result = idx.take(np.array([1, 0, -1])) - expected = self._holder([2, 1, 3], name="xxx") - tm.assert_index_equal(result, expected) - - name = self._holder.__name__ - msg = f"Unable to fill values because {name} cannot contain NA" - - # fill_value=True - with pytest.raises(ValueError, match=msg): - idx.take(np.array([1, 0, -1]), fill_value=True) - - # allow_fill=False - result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) - expected = self._holder([2, 1, 3], name="xxx") - tm.assert_index_equal(result, expected) - - with pytest.raises(ValueError, match=msg): - idx.take(np.array([1, 0, -2]), fill_value=True) - with pytest.raises(ValueError, match=msg): - idx.take(np.array([1, 0, -5]), fill_value=True) - - msg = "index -5 is out of bounds for (axis 0 with )?size 3" - with pytest.raises(IndexError, match=msg): - idx.take(np.array([1, -5])) - class TestInt64Index(NumericInt): _dtype = "int64" @@ -741,29 +579,6 @@ def test_coerce_list(self): arr = Index([1, 2, 3, 4], dtype=object) assert isinstance(arr, Index) - def test_get_indexer(self): - index = self.create_index() - target = Int64Index(np.arange(10)) - indexer = index.get_indexer(target) - expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp) - tm.assert_numpy_array_equal(indexer, expected) - - target = Int64Index(np.arange(10)) - indexer = index.get_indexer(target, method="pad") - expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp) - tm.assert_numpy_array_equal(indexer, expected) - - target = Int64Index(np.arange(10)) - indexer = index.get_indexer(target, method="backfill") - expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp) - tm.assert_numpy_array_equal(indexer, expected) - - def test_get_indexer_nan(self): - # GH 7820 - result = Index([1, 2, np.nan]).get_indexer([np.nan]) - expected = np.array([2], dtype=np.intp) - tm.assert_numpy_array_equal(result, expected) - def test_intersection(self): index = self.create_index() other = Index([1, 2, 3, 4, 5]) @@ -825,22 +640,6 @@ def test_constructor(self): res = Index([1, 2 ** 63 + 1], dtype=np.uint64) tm.assert_index_equal(res, idx) - def test_get_indexer(self, index_large): - target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63) - indexer = index_large.get_indexer(target) - expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp) - tm.assert_numpy_array_equal(indexer, expected) - - target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63) - indexer = index_large.get_indexer(target, method="pad") - expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp) - tm.assert_numpy_array_equal(indexer, expected) - - target = UInt64Index(np.arange(10).astype("uint64") * 5 + 2 ** 63) - indexer = index_large.get_indexer(target, method="backfill") - expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp) - tm.assert_numpy_array_equal(indexer, expected) - def test_intersection(self, index_large): other = Index([2 ** 63, 2 ** 63 + 5, 2 ** 63 + 10, 2 ** 63 + 15, 2 ** 63 + 20]) result = index_large.intersection(other)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33387
2020-04-08T03:13:05Z
2020-04-08T13:39:40Z
2020-04-08T13:39:40Z
2020-04-08T15:09:18Z
DOC: Update roadmap for completions
diff --git a/doc/source/development/roadmap.rst b/doc/source/development/roadmap.rst index efee21b5889ed..8223edcf6f63a 100644 --- a/doc/source/development/roadmap.rst +++ b/doc/source/development/roadmap.rst @@ -141,20 +141,6 @@ ways for users to apply their own Numba-jitted functions where pandas accepts us and in groupby and window contexts). This will improve the performance of user-defined-functions in these operations by staying within compiled code. - -Documentation improvements --------------------------- - -We'd like to improve the content, structure, and presentation of the pandas documentation. -Some specific goals include - -* Overhaul the HTML theme with a modern, responsive design (:issue:`15556`) -* Improve the "Getting Started" documentation, designing and writing learning paths - for users different backgrounds (e.g. brand new to programming, familiar with - other languages like R, already familiar with Python). -* Improve the overall organization of the documentation and specific subsections - of the documentation to make navigation and finding content easier. - Performance monitoring ---------------------- @@ -203,3 +189,20 @@ should be notified of the proposal. When there's agreement that an implementation would be welcome, the roadmap should be updated to include the summary and a link to the discussion issue. + +Completed items +--------------- + +This section records now completed items from the pandas roadmap. + +Documentation improvements +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We improved the pandas documentation + +* The pandas community worked with others to build the `pydata-sphinx-theme`_, + which is now used for https://pandas.pydata.org/docs/ (:issue:`15556`). +* :ref:`getting_started` contains a number of resources intended for new + pandas users coming from a variety of backgrounds (:issue:`26831`). + +.. _pydata-sphinx-theme: https://github.com/pandas-dev/pydata-sphinx-theme
Moves "Improved documentation" to completed section. I don't think any others can be marked as done yet, though "Numba-accelerated operations" may be getting close (is that right @mroeschke?).
https://api.github.com/repos/pandas-dev/pandas/pulls/36728
2020-09-29T20:58:53Z
2020-09-30T12:37:42Z
2020-09-30T12:37:42Z
2020-09-30T12:37:44Z
CLN: private funcs in concat.py
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index f5d0c921e1006..7ad058cfeb83c 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -1,6 +1,6 @@ from collections import defaultdict import copy -from typing import Dict, List +from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Tuple, cast import numpy as np @@ -28,6 +28,9 @@ from pandas.core.internals.blocks import make_block from pandas.core.internals.managers import BlockManager +if TYPE_CHECKING: + from pandas.core.arrays.sparse.dtype import SparseDtype + def concatenate_block_managers( mgrs_indexers, axes, concat_axis: int, copy: bool @@ -344,7 +347,7 @@ def _concatenate_join_units(join_units, concat_axis, copy): return concat_values -def _get_empty_dtype_and_na(join_units): +def _get_empty_dtype_and_na(join_units: Sequence[JoinUnit]) -> Tuple[DtypeObj, Any]: """ Return dtype and N/A values to use when concatenating specified units. @@ -374,45 +377,8 @@ def _get_empty_dtype_and_na(join_units): else: dtypes[i] = unit.dtype - upcast_classes: Dict[str, List[DtypeObj]] = defaultdict(list) - null_upcast_classes: Dict[str, List[DtypeObj]] = defaultdict(list) - for dtype, unit in zip(dtypes, join_units): - if dtype is None: - continue - - if is_categorical_dtype(dtype): - upcast_cls = "category" - elif is_datetime64tz_dtype(dtype): - upcast_cls = "datetimetz" - - elif is_extension_array_dtype(dtype): - upcast_cls = "extension" - - elif issubclass(dtype.type, np.bool_): - upcast_cls = "bool" - elif issubclass(dtype.type, np.object_): - upcast_cls = "object" - elif is_datetime64_dtype(dtype): - upcast_cls = "datetime" - elif is_timedelta64_dtype(dtype): - upcast_cls = "timedelta" - elif is_sparse(dtype): - upcast_cls = dtype.subtype.name - elif is_float_dtype(dtype) or is_numeric_dtype(dtype): - upcast_cls = dtype.name - else: - upcast_cls = "float" + upcast_classes = _get_upcast_classes(join_units, dtypes) - # Null blocks should not influence upcast class selection, unless there - # are only null blocks, when same upcasting rules must be applied to - # null upcast classes. - if unit.is_na: - null_upcast_classes[upcast_cls].append(dtype) - else: - upcast_classes[upcast_cls].append(dtype) - - if not upcast_classes: - upcast_classes = null_upcast_classes # TODO: de-duplicate with maybe_promote? # create the result if "extension" in upcast_classes: @@ -441,23 +407,74 @@ def _get_empty_dtype_and_na(join_units): return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns") else: # pragma try: - g = np.find_common_type(upcast_classes, []) + common_dtype = np.find_common_type(upcast_classes, []) except TypeError: # At least one is an ExtensionArray return np.dtype(np.object_), np.nan else: - if is_float_dtype(g): - return g, g.type(np.nan) - elif is_numeric_dtype(g): + if is_float_dtype(common_dtype): + return common_dtype, common_dtype.type(np.nan) + elif is_numeric_dtype(common_dtype): if has_none_blocks: return np.dtype(np.float64), np.nan else: - return g, None + return common_dtype, None msg = "invalid dtype determination in get_concat_dtype" raise AssertionError(msg) +def _get_upcast_classes( + join_units: Sequence[JoinUnit], + dtypes: Sequence[DtypeObj], +) -> Dict[str, List[DtypeObj]]: + """Create mapping between upcast class names and lists of dtypes.""" + upcast_classes: Dict[str, List[DtypeObj]] = defaultdict(list) + null_upcast_classes: Dict[str, List[DtypeObj]] = defaultdict(list) + for dtype, unit in zip(dtypes, join_units): + if dtype is None: + continue + + upcast_cls = _select_upcast_cls_from_dtype(dtype) + # Null blocks should not influence upcast class selection, unless there + # are only null blocks, when same upcasting rules must be applied to + # null upcast classes. + if unit.is_na: + null_upcast_classes[upcast_cls].append(dtype) + else: + upcast_classes[upcast_cls].append(dtype) + + if not upcast_classes: + upcast_classes = null_upcast_classes + + return upcast_classes + + +def _select_upcast_cls_from_dtype(dtype: DtypeObj) -> str: + """Select upcast class name based on dtype.""" + if is_categorical_dtype(dtype): + return "category" + elif is_datetime64tz_dtype(dtype): + return "datetimetz" + elif is_extension_array_dtype(dtype): + return "extension" + elif issubclass(dtype.type, np.bool_): + return "bool" + elif issubclass(dtype.type, np.object_): + return "object" + elif is_datetime64_dtype(dtype): + return "datetime" + elif is_timedelta64_dtype(dtype): + return "timedelta" + elif is_sparse(dtype): + dtype = cast("SparseDtype", dtype) + return dtype.subtype.name + elif is_float_dtype(dtype) or is_numeric_dtype(dtype): + return dtype.name + else: + return "float" + + def _is_uniform_join_units(join_units: List[JoinUnit]) -> bool: """ Check if the join units consist of blocks of uniform type that can
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Refactor/cleanup ``_get_empty_dtype_and_na`` in ``pandas/core/internals/concat.py`` Extract functions, add typing.
https://api.github.com/repos/pandas-dev/pandas/pulls/36726
2020-09-29T15:51:03Z
2020-10-04T04:39:42Z
2020-10-04T04:39:42Z
2020-10-04T13:22:33Z
TYP: update setup.cfg
diff --git a/setup.cfg b/setup.cfg index d938d2ef3972a..494c7ad328648 100644 --- a/setup.cfg +++ b/setup.cfg @@ -182,9 +182,6 @@ check_untyped_defs=False [mypy-pandas.core.groupby.base] check_untyped_defs=False -[mypy-pandas.core.groupby.generic] -check_untyped_defs=False - [mypy-pandas.core.groupby.grouper] check_untyped_defs=False @@ -263,21 +260,12 @@ check_untyped_defs=False [mypy-pandas.io.clipboard] check_untyped_defs=False -[mypy-pandas.io.common] -check_untyped_defs=False - [mypy-pandas.io.excel._base] check_untyped_defs=False -[mypy-pandas.io.excel._util] -check_untyped_defs=False - [mypy-pandas.io.formats.console] check_untyped_defs=False -[mypy-pandas.io.formats.csvs] -check_untyped_defs=False - [mypy-pandas.io.formats.excel] check_untyped_defs=False
https://api.github.com/repos/pandas-dev/pandas/pulls/36725
2020-09-29T15:39:55Z
2020-09-29T17:07:02Z
2020-09-29T17:07:02Z
2020-09-29T17:17:43Z
TYP: Ignore remaining mypy errors for pandas\tests\*
diff --git a/pandas/conftest.py b/pandas/conftest.py index 604815d496f80..5fb333acd718d 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -298,7 +298,9 @@ def unique_nulls_fixture(request): # ---------------------------------------------------------------- # Classes # ---------------------------------------------------------------- -@pytest.fixture(params=[pd.Index, pd.Series], ids=["index", "series"]) +@pytest.fixture( + params=[pd.Index, pd.Series], ids=["index", "series"] # type: ignore[list-item] +) def index_or_series(request): """ Fixture to parametrize over Index and Series, made necessary by a mypy diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py index 7f03fa2a5ea0d..3b4ed4859b1cc 100644 --- a/pandas/tests/window/conftest.py +++ b/pandas/tests/window/conftest.py @@ -76,7 +76,12 @@ def nopython(request): @pytest.fixture( - params=[pytest.param("numba", marks=td.skip_if_no("numba", "0.46.0")), "cython"] + params=[ + pytest.param( + "numba", marks=td.skip_if_no("numba", "0.46.0") + ), # type: ignore[list-item] + "cython", + ] ) def engine(request): """engine keyword argument for rolling.apply""" @@ -327,7 +332,7 @@ def halflife_with_times(request): "float64", "m8[ns]", "M8[ns]", - pytest.param( + pytest.param( # type: ignore[list-item] "datetime64[ns, UTC]", marks=pytest.mark.skip( "direct creation of extension dtype datetime64[ns, UTC] " diff --git a/setup.cfg b/setup.cfg index d938d2ef3972a..45951ac3c5db0 100644 --- a/setup.cfg +++ b/setup.cfg @@ -128,9 +128,6 @@ ignore_errors=True [mypy-pandas.tests.*] check_untyped_defs=False -[mypy-pandas.conftest,pandas.tests.window.conftest] -ignore_errors=True - [mypy-pandas._testing] check_untyped_defs=False
- [ ] closes #28926 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry These are the only 3 errors outstanding in pandas\tests\* that are stopping us closing #28926 ``` pandas\conftest.py:301: error: List item 0 has incompatible type "Type[Index]"; expected "Type[PandasObject]" [list-item] pandas\tests\window\conftest.py:79: error: List item 0 has incompatible type "ParameterSet"; expected "Sequence[Collection[object]]" [list-item] pandas\tests\window\conftest.py:330: error: List item 15 has incompatible type "ParameterSet"; expected "Sequence[Collection[object]]" [list-item] ``` these appear to be from a mypy inference issue. It maybe best to `# type: ignore[list-item]` just these lines and remove the `ignore_errors=True` from setup.cfg that applies to the whole file for all error codes. if the mypy error is resolved in a future release, the `warn_unused_ignores = True` in setup.cfg means that we will be alerted and the ignores can be removed.
https://api.github.com/repos/pandas-dev/pandas/pulls/36724
2020-09-29T15:23:46Z
2020-09-29T20:30:56Z
2020-09-29T20:30:55Z
2020-09-30T11:06:32Z
DOC: Fix typo in docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index bd720151fb15e..18a9c78912ba5 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3970,7 +3970,7 @@ def reindex_like( Maximum number of consecutive labels to fill for inexact matches. tolerance : optional Maximum distance between original and new labels for inexact - matches. The values of the index at the matching locations most + matches. The values of the index at the matching locations must satisfy the equation ``abs(index[indexer] - target) <= tolerance``. Tolerance may be a scalar value, which applies the same tolerance diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 84489c1033d8c..35948a3f3dcf1 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2922,7 +2922,7 @@ def get_loc(self, key, method=None, tolerance=None): distances are broken by preferring the larger index value. tolerance : int or float, optional Maximum distance from index value for inexact matches. The value of - the index at the matching location most satisfy the equation + the index at the matching location must satisfy the equation ``abs(index[loc] - key) <= tolerance``. Returns @@ -2987,7 +2987,7 @@ def get_loc(self, key, method=None, tolerance=None): inexact matches. tolerance : optional Maximum distance between original and new labels for inexact - matches. The values of the index at the matching locations most + matches. The values of the index at the matching locations must satisfy the equation ``abs(index[indexer] - target) <= tolerance``. Tolerance may be a scalar value, which applies the same tolerance
https://api.github.com/repos/pandas-dev/pandas/pulls/36723
2020-09-29T13:54:43Z
2020-09-29T15:41:03Z
2020-09-29T15:41:03Z
2020-09-29T16:39:28Z
CI unpin flake8, only run flake8-rst in pre-commit
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 39fe509c6cd29..092515f1e450a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -46,6 +46,14 @@ repos: files: ^(environment.yml|requirements-dev.txt)$ pass_filenames: false additional_dependencies: [pyyaml] + - id: flake8-rst + name: flake8-rst + description: Run flake8 on code snippets in docstrings or RST files + language: python + entry: flake8-rst + types: [rst] + args: [--filename=*.rst] + additional_dependencies: [flake8-rst==0.7.0, flake8==3.7.9] - repo: https://github.com/asottile/yesqa rev: v1.2.2 hooks: diff --git a/ci/code_checks.sh b/ci/code_checks.sh index b8f6bd53d4a59..784d2c9a411ab 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -73,13 +73,6 @@ if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then flake8 --format="$FLAKE8_FORMAT" pandas/_libs --append-config=flake8/cython-template.cfg RET=$(($RET + $?)) ; echo $MSG "DONE" - echo "flake8-rst --version" - flake8-rst --version - - MSG='Linting code-blocks in .rst documentation' ; echo $MSG - flake8-rst doc/source --filename=*.rst --format="$FLAKE8_FORMAT" - RET=$(($RET + $?)) ; echo $MSG "DONE" - # Check that cython casting is of the form `<type>obj` as opposed to `<type> obj`; # it doesn't make a difference, but we want to be internally consistent. # Note: this grep pattern is (intended to be) equivalent to the python diff --git a/environment.yml b/environment.yml index 6e9b417beb0af..77a9c5fd4822d 100644 --- a/environment.yml +++ b/environment.yml @@ -17,9 +17,8 @@ dependencies: # code checks - black=20.8b1 - cpplint - - flake8<3.8.0 # temporary pin, GH#34150 + - flake8 - flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions - - flake8-rst>=0.6.0,<=0.7.0 # linting of code blocks in rst files - isort>=5.2.1 # check that imports are in the right order - mypy=0.782 - pre-commit @@ -113,4 +112,3 @@ dependencies: - pip: - git+https://github.com/pandas-dev/pydata-sphinx-theme.git@master - git+https://github.com/numpy/numpydoc - - pyflakes>=2.2.0 diff --git a/requirements-dev.txt b/requirements-dev.txt index e6346e6c38694..17ca6b8401501 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -8,9 +8,8 @@ asv cython>=0.29.21 black==20.8b1 cpplint -flake8<3.8.0 +flake8 flake8-comprehensions>=3.1.0 -flake8-rst>=0.6.0,<=0.7.0 isort>=5.2.1 mypy==0.782 pre-commit @@ -79,4 +78,3 @@ tabulate>=0.8.3 natsort git+https://github.com/pandas-dev/pydata-sphinx-theme.git@master git+https://github.com/numpy/numpydoc -pyflakes>=2.2.0
- [ ] closes #34150 (maybe?) - [ ] 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/36722
2020-09-29T11:33:21Z
2020-10-10T22:29:29Z
2020-10-10T22:29:29Z
2020-10-11T08:36:20Z
CLN: Remove unnecessary rolling subclass
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 34d9d9d8c00ef..25938b57d9720 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -15,7 +15,7 @@ import pandas.core.common as common from pandas.core.window.common import _doc_template, _shared_docs, zsqrt -from pandas.core.window.rolling import RollingMixin, flex_binary_moment +from pandas.core.window.rolling import BaseWindow, flex_binary_moment _bias_template = """ Parameters @@ -60,7 +60,7 @@ def get_center_of_mass( return float(comass) -class ExponentialMovingWindow(RollingMixin): +class ExponentialMovingWindow(BaseWindow): r""" Provide exponential weighted (EW) functions. diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 335fc3db5cd86..6ab42dda865e7 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -147,7 +147,9 @@ def func(arg, window, min_periods=None): return func -class _Window(ShallowMixin, SelectionMixin): +class BaseWindow(ShallowMixin, SelectionMixin): + """Provides utilities for performing windowing operations.""" + _attributes: List[str] = [ "window", "min_periods", @@ -184,10 +186,6 @@ def __init__( self.axis = obj._get_axis_number(axis) if axis is not None else None self.validate() - @property - def _constructor(self): - return Window - @property def is_datetimelike(self) -> Optional[bool]: return None @@ -862,7 +860,7 @@ def aggregate(self, func, *args, **kwargs): ) -class Window(_Window): +class Window(BaseWindow): """ Provide rolling window calculations. @@ -1040,6 +1038,10 @@ class Window(_Window): 2013-01-01 09:00:06 4.0 """ + @property + def _constructor(self): + return Window + def validate(self): super().validate() @@ -1220,13 +1222,7 @@ def std(self, ddof=1, *args, **kwargs): return zsqrt(self.var(ddof=ddof, name="std", **kwargs)) -class RollingMixin(_Window): - @property - def _constructor(self): - return Rolling - - -class RollingAndExpandingMixin(RollingMixin): +class RollingAndExpandingMixin(BaseWindow): _shared_docs["count"] = dedent( r""" @@ -1939,6 +1935,10 @@ def _on(self) -> Index: "must be a column (of DataFrame), an Index or None" ) + @property + def _constructor(self): + return Rolling + def validate(self): super().validate()
- [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/36721
2020-09-29T05:56:37Z
2020-09-29T19:53:00Z
2020-09-29T19:53:00Z
2020-09-29T20:19:48Z
EA: Tighten signature on DatetimeArray._from_sequence
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 6b051f1f73467..3e9a06a0faa17 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -296,7 +296,11 @@ def _simple_new(cls, values, freq=None, dtype=DT64NS_DTYPE): return result @classmethod - def _from_sequence( + def _from_sequence(cls, scalars, dtype=None, copy: bool = False): + return cls._from_sequence_not_strict(scalars, dtype=dtype, copy=copy) + + @classmethod + def _from_sequence_not_strict( cls, data, dtype=None, diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 016544d823ae3..43ec4fe376030 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -267,7 +267,7 @@ def __new__( name = maybe_extract_name(name, data, cls) - dtarr = DatetimeArray._from_sequence( + dtarr = DatetimeArray._from_sequence_not_strict( data, dtype=dtype, copy=copy, diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 64470da2fb910..f2354f649b1e3 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -1616,7 +1616,9 @@ def na_accum_func(values: ArrayLike, accum_func, skipna: bool) -> ArrayLike: result = result.view(orig_dtype) else: # DatetimeArray - result = type(values)._from_sequence(result, dtype=orig_dtype) + result = type(values)._simple_new( # type: ignore[attr-defined] + result, dtype=orig_dtype + ) elif skipna and not issubclass(values.dtype.type, (np.integer, np.bool_)): vals = values.copy() diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index 304e1c80a3f77..096897f62a594 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -204,7 +204,9 @@ def test_array_copy(): datetime.datetime(2000, 1, 1, tzinfo=cet), datetime.datetime(2001, 1, 1, tzinfo=cet), ], - DatetimeArray._from_sequence(["2000", "2001"], tz=cet), + DatetimeArray._from_sequence( + ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz=cet) + ), ), # timedelta ( diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 53f26de09f94e..e7605125e7420 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -71,7 +71,7 @@ def test_mixing_naive_tzaware_raises(self, meth): def test_from_pandas_array(self): arr = pd.array(np.arange(5, dtype=np.int64)) * 3600 * 10 ** 9 - result = DatetimeArray._from_sequence(arr, freq="infer") + result = DatetimeArray._from_sequence(arr)._with_freq("infer") expected = pd.date_range("1970-01-01", periods=5, freq="H")._data tm.assert_datetime_array_equal(result, expected) @@ -162,7 +162,9 @@ def test_cmp_dt64_arraylike_tznaive(self, all_compare_operators): class TestDatetimeArray: def test_astype_to_same(self): - arr = DatetimeArray._from_sequence(["2000"], tz="US/Central") + arr = DatetimeArray._from_sequence( + ["2000"], dtype=DatetimeTZDtype(tz="US/Central") + ) result = arr.astype(DatetimeTZDtype(tz="US/Central"), copy=False) assert result is arr @@ -193,7 +195,9 @@ def test_astype_int(self, dtype): tm.assert_numpy_array_equal(result, expected) def test_tz_setter_raises(self): - arr = DatetimeArray._from_sequence(["2000"], tz="US/Central") + arr = DatetimeArray._from_sequence( + ["2000"], dtype=DatetimeTZDtype(tz="US/Central") + ) with pytest.raises(AttributeError, match="tz_localize"): arr.tz = "UTC" @@ -282,7 +286,8 @@ def test_fillna_preserves_tz(self, method): fill_val = dti[1] if method == "pad" else dti[3] expected = DatetimeArray._from_sequence( - [dti[0], dti[1], fill_val, dti[3], dti[4]], freq=None, tz="US/Central" + [dti[0], dti[1], fill_val, dti[3], dti[4]], + dtype=DatetimeTZDtype(tz="US/Central"), ) result = arr.fillna(method=method) @@ -434,12 +439,16 @@ def test_shift_value_tzawareness_mismatch(self): class TestSequenceToDT64NS: def test_tz_dtype_mismatch_raises(self): - arr = DatetimeArray._from_sequence(["2000"], tz="US/Central") + arr = DatetimeArray._from_sequence( + ["2000"], dtype=DatetimeTZDtype(tz="US/Central") + ) with pytest.raises(TypeError, match="data is already tz-aware"): sequence_to_dt64ns(arr, dtype=DatetimeTZDtype(tz="UTC")) def test_tz_dtype_matches(self): - arr = DatetimeArray._from_sequence(["2000"], tz="US/Central") + arr = DatetimeArray._from_sequence( + ["2000"], dtype=DatetimeTZDtype(tz="US/Central") + ) result, _, _ = sequence_to_dt64ns(arr, dtype=DatetimeTZDtype(tz="US/Central")) tm.assert_numpy_array_equal(arr._data, result) @@ -447,6 +456,7 @@ def test_tz_dtype_matches(self): class TestReductions: @pytest.mark.parametrize("tz", [None, "US/Central"]) def test_min_max(self, tz): + dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]") arr = DatetimeArray._from_sequence( [ "2000-01-03", @@ -456,7 +466,7 @@ def test_min_max(self, tz): "2000-01-05", "2000-01-04", ], - tz=tz, + dtype=dtype, ) result = arr.min() @@ -476,7 +486,8 @@ def test_min_max(self, tz): @pytest.mark.parametrize("tz", [None, "US/Central"]) @pytest.mark.parametrize("skipna", [True, False]) def test_min_max_empty(self, skipna, tz): - arr = DatetimeArray._from_sequence([], tz=tz) + dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]") + arr = DatetimeArray._from_sequence([], dtype=dtype) result = arr.min(skipna=skipna) assert result is pd.NaT diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py index e026809f7e611..0fde1e8a2fdb8 100644 --- a/pandas/tests/extension/test_datetime.py +++ b/pandas/tests/extension/test_datetime.py @@ -181,8 +181,10 @@ def test_concat_mixed_dtypes(self, data): @pytest.mark.parametrize("obj", ["series", "frame"]) def test_unstack(self, obj): # GH-13287: can't use base test, since building the expected fails. + dtype = DatetimeTZDtype(tz="US/Central") data = DatetimeArray._from_sequence( - ["2000", "2001", "2002", "2003"], tz="US/Central" + ["2000", "2001", "2002", "2003"], + dtype=dtype, ) index = pd.MultiIndex.from_product(([["A", "B"], ["a", "b"]]), names=["a", "b"]) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 9a855a1624520..d3c79f231449a 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -16,7 +16,9 @@ class TestDatetimeIndex: - @pytest.mark.parametrize("dt_cls", [DatetimeIndex, DatetimeArray._from_sequence]) + @pytest.mark.parametrize( + "dt_cls", [DatetimeIndex, DatetimeArray._from_sequence_not_strict] + ) def test_freq_validation_with_nat(self, dt_cls): # GH#11587 make sure we get a useful error message when generate_range # raises diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 09d5d9c1677d0..2ea7602b00206 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -12,6 +12,7 @@ from pandas import ( DatetimeIndex, + DatetimeTZDtype, Index, NaT, Period, @@ -440,7 +441,9 @@ def test_nat_rfloordiv_timedelta(val, expected): DatetimeIndex(["2011-01-01", "2011-01-02"], name="x"), DatetimeIndex(["2011-01-01", "2011-01-02"], tz="US/Eastern", name="x"), DatetimeArray._from_sequence(["2011-01-01", "2011-01-02"]), - DatetimeArray._from_sequence(["2011-01-01", "2011-01-02"], tz="US/Pacific"), + DatetimeArray._from_sequence( + ["2011-01-01", "2011-01-02"], dtype=DatetimeTZDtype(tz="US/Pacific") + ), TimedeltaIndex(["1 day", "2 day"], name="x"), ], )
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry xref #33254 There are a few more steps to get DatetimeArray._from_sequence down to the ideal behavior, this is just trimming the signature down to what its supposed to be. _from_sequence_not_strict could use a better name
https://api.github.com/repos/pandas-dev/pandas/pulls/36718
2020-09-29T01:22:42Z
2020-10-02T23:14:20Z
2020-10-02T23:14:20Z
2020-10-03T00:26:03Z
CI: remove duplicated code check #36642
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 46de8d466dd11..b391871b18245 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,12 +37,6 @@ jobs: ci/code_checks.sh lint if: always() - - name: Dependencies consistency - run: | - source activate pandas-dev - ci/code_checks.sh dependencies - if: always() - - name: Checks on imported code run: | source activate pandas-dev diff --git a/ci/code_checks.sh b/ci/code_checks.sh index cb34652e11cd3..a50a71bbbad63 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -15,11 +15,10 @@ # $ ./ci/code_checks.sh code # checks on imported code # $ ./ci/code_checks.sh doctests # run doctests # $ ./ci/code_checks.sh docstrings # validate docstring errors -# $ ./ci/code_checks.sh dependencies # check that dependencies are consistent # $ ./ci/code_checks.sh typing # run static type analysis -[[ -z "$1" || "$1" == "lint" || "$1" == "patterns" || "$1" == "code" || "$1" == "doctests" || "$1" == "docstrings" || "$1" == "dependencies" || "$1" == "typing" ]] || \ - { echo "Unknown command $1. Usage: $0 [lint|patterns|code|doctests|docstrings|dependencies|typing]"; exit 9999; } +[[ -z "$1" || "$1" == "lint" || "$1" == "patterns" || "$1" == "code" || "$1" == "doctests" || "$1" == "docstrings" || "$1" == "typing" ]] || \ + { echo "Unknown command $1. Usage: $0 [lint|patterns|code|doctests|docstrings|typing]"; exit 9999; } BASE_DIR="$(dirname $0)/.." RET=0 @@ -48,31 +47,6 @@ fi ### LINTING ### if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then - echo "black --version" - black --version - - MSG='Checking black formatting' ; echo $MSG - black . --check - RET=$(($RET + $?)) ; echo $MSG "DONE" - - # `setup.cfg` contains the list of error codes that are being ignored in flake8 - - echo "flake8 --version" - flake8 --version - - # pandas/_libs/src is C code, so no need to search there. - MSG='Linting .py code' ; echo $MSG - flake8 --format="$FLAKE8_FORMAT" . - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Linting .pyx and .pxd code' ; echo $MSG - flake8 --format="$FLAKE8_FORMAT" pandas --append-config=flake8/cython.cfg - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Linting .pxi.in' ; echo $MSG - flake8 --format="$FLAKE8_FORMAT" pandas/_libs --append-config=flake8/cython-template.cfg - RET=$(($RET + $?)) ; echo $MSG "DONE" - # Check that cython casting is of the form `<type>obj` as opposed to `<type> obj`; # it doesn't make a difference, but we want to be internally consistent. # Note: this grep pattern is (intended to be) equivalent to the python @@ -125,19 +99,6 @@ if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then fi RET=$(($RET + $?)) ; echo $MSG "DONE" - echo "isort --version-number" - isort --version-number - - # Imports - Check formatting using isort see setup.cfg for settings - MSG='Check import format using isort' ; echo $MSG - ISORT_CMD="isort --quiet --check-only pandas asv_bench scripts web" - if [[ "$GITHUB_ACTIONS" == "true" ]]; then - eval $ISORT_CMD | awk '{print "##[error]" $0}'; RET=$(($RET + ${PIPESTATUS[0]})) - else - eval $ISORT_CMD - fi - RET=$(($RET + $?)) ; echo $MSG "DONE" - fi ### PATTERNS ### @@ -354,15 +315,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then fi -### DEPENDENCIES ### -if [[ -z "$CHECK" || "$CHECK" == "dependencies" ]]; then - - MSG='Check that requirements-dev.txt has been generated from environment.yml' ; echo $MSG - $BASE_DIR/scripts/generate_pip_deps_from_conda.py --compare --azure - RET=$(($RET + $?)) ; echo $MSG "DONE" - -fi - ### TYPING ### if [[ -z "$CHECK" || "$CHECK" == "typing" ]]; then @@ -374,5 +326,4 @@ if [[ -z "$CHECK" || "$CHECK" == "typing" ]]; then RET=$(($RET + $?)) ; echo $MSG "DONE" fi - exit $RET
- [x] closes #36642
https://api.github.com/repos/pandas-dev/pandas/pulls/36716
2020-09-28T20:07:54Z
2020-10-20T23:08:47Z
2020-10-20T23:08:47Z
2020-10-21T00:28:58Z
TST: implement test to_string_empty_col for Series (GH13653)
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index cce0783a3c867..68f5386fff7be 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2846,6 +2846,13 @@ def test_to_string_multindex_header(self): exp = " r1 r2\na b \n0 1 2 3" assert res == exp + def test_to_string_empty_col(self): + # GH 13653 + s = pd.Series(["", "Hello", "World", "", "", "Mooooo", "", ""]) + res = s.to_string(index=False) + exp = " \n Hello\n World\n \n \nMooooo\n \n " + assert re.match(exp, res) + class TestGenericArrayFormatter: def test_1d_array(self):
- [x] closes #13653 - [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/36715
2020-09-28T19:40:21Z
2020-09-30T02:04:41Z
2020-09-30T02:04:41Z
2020-09-30T07:10:04Z
REF: rearrange test_to_latex.py
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 7a0d305758802..d3d865158309c 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -27,65 +27,13 @@ def _dedent(string): return dedent(string).lstrip() -class TestToLatex: - @pytest.fixture - def df_short(self): - """Short dataframe for testing table/tabular/longtable LaTeX env.""" - return DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - - @pytest.fixture - def caption_table(self): - """Caption for table/tabular LaTeX environment.""" - return "a table in a \\texttt{table/tabular} environment" - - @pytest.fixture - def label_table(self): - """Label for table/tabular LaTeX environment.""" - return "tab:table_tabular" - - @pytest.fixture - def caption_longtable(self): - """Caption for longtable LaTeX environment.""" - return "a table in a \\texttt{longtable} environment" - - @pytest.fixture - def label_longtable(self): - """Label for longtable LaTeX environment.""" - return "tab:longtable" - - @pytest.fixture - def multiindex_frame(self): - """Multiindex dataframe for testing multirow LaTeX macros.""" - yield DataFrame.from_dict( - { - ("c1", 0): pd.Series({x: x for x in range(4)}), - ("c1", 1): pd.Series({x: x + 4 for x in range(4)}), - ("c2", 0): pd.Series({x: x for x in range(4)}), - ("c2", 1): pd.Series({x: x + 4 for x in range(4)}), - ("c3", 0): pd.Series({x: x for x in range(4)}), - } - ).T - - @pytest.fixture - def multicolumn_frame(self): - """Multicolumn dataframe for testing multicolumn LaTeX macros.""" - yield pd.DataFrame( - { - ("c1", 0): {x: x for x in range(5)}, - ("c1", 1): {x: x + 5 for x in range(5)}, - ("c2", 0): {x: x for x in range(5)}, - ("c2", 1): {x: x + 5 for x in range(5)}, - ("c3", 0): {x: x for x in range(5)}, - } - ) +@pytest.fixture +def df_short(): + """Short dataframe for testing table/tabular/longtable LaTeX env.""" + return DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - @pytest.fixture - def df_with_symbols(self): - """Dataframe with special characters for testing chars escaping.""" - a = "a" - b = "b" - yield DataFrame({"co$e^x$": {a: "a", b: "b"}, "co^l1": {a: "a", b: "b"}}) +class TestToLatex: def test_to_latex_to_file(self, float_frame): with tm.ensure_clean("test.tex") as path: float_frame.to_latex(path) @@ -152,10 +100,11 @@ def test_to_latex_bad_column_format(self, bad_column_format): with pytest.raises(ValueError, match=msg): df.to_latex(column_format=bad_column_format) - def test_to_latex_column_format(self, float_frame): + def test_to_latex_column_format_just_works(self, float_frame): # GH Bug #9402 float_frame.to_latex(column_format="lcr") + def test_to_latex_column_format(self): df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) result = df.to_latex(column_format="lcr") expected = _dedent( @@ -188,6 +137,45 @@ def test_to_latex_empty_tabular(self): ) assert result == expected + def test_to_latex_series(self): + s = Series(["a", "b", "c"]) + result = s.to_latex() + expected = _dedent( + r""" + \begin{tabular}{ll} + \toprule + {} & 0 \\ + \midrule + 0 & a \\ + 1 & b \\ + 2 & c \\ + \bottomrule + \end{tabular} + """ + ) + assert result == expected + + def test_to_latex_midrule_location(self): + # GH 18326 + df = pd.DataFrame({"a": [1, 2]}) + df.index.name = "foo" + result = df.to_latex(index_names=False) + expected = _dedent( + r""" + \begin{tabular}{lr} + \toprule + {} & a \\ + \midrule + 0 & 1 \\ + 1 & 2 \\ + \bottomrule + \end{tabular} + """ + ) + assert result == expected + + +class TestToLatexLongtable: def test_to_latex_empty_longtable(self): df = DataFrame() result = df.to_latex(longtable=True) @@ -203,329 +191,347 @@ def test_to_latex_empty_longtable(self): ) assert result == expected - def test_to_latex_with_formatters(self): - df = DataFrame( - { - "datetime64": [ - datetime(2016, 1, 1), - datetime(2016, 2, 5), - datetime(2016, 3, 3), - ], - "float": [1.0, 2.0, 3.0], - "int": [1, 2, 3], - "object": [(1, 2), True, False], - } - ) - - formatters = { - "datetime64": lambda x: x.strftime("%Y-%m"), - "float": lambda x: f"[{x: 4.1f}]", - "int": lambda x: f"0x{x:x}", - "object": lambda x: f"-{x!s}-", - "__index__": lambda x: f"index: {x}", - } - result = df.to_latex(formatters=dict(formatters)) - + def test_to_latex_longtable_with_index(self): + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(longtable=True) expected = _dedent( r""" - \begin{tabular}{llrrl} + \begin{longtable}{lrl} \toprule - {} & datetime64 & float & int & object \\ + {} & a & b \\ \midrule - index: 0 & 2016-01 & [ 1.0] & 0x1 & -(1, 2)- \\ - index: 1 & 2016-02 & [ 2.0] & 0x2 & -True- \\ - index: 2 & 2016-03 & [ 3.0] & 0x3 & -False- \\ + \endfirsthead + + \toprule + {} & a & b \\ + \midrule + \endhead + \midrule + \multicolumn{3}{r}{{Continued on next page}} \\ + \midrule + \endfoot + \bottomrule - \end{tabular} + \endlastfoot + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ + \end{longtable} """ ) assert result == expected - def test_to_latex_multiindex_column_tabular(self): - df = DataFrame({("x", "y"): ["a"]}) - result = df.to_latex() + def test_to_latex_longtable_without_index(self): + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(index=False, longtable=True) expected = _dedent( r""" - \begin{tabular}{ll} + \begin{longtable}{rl} \toprule - {} & x \\ - {} & y \\ + a & b \\ \midrule - 0 & a \\ + \endfirsthead + + \toprule + a & b \\ + \midrule + \endhead + \midrule + \multicolumn{2}{r}{{Continued on next page}} \\ + \midrule + \endfoot + \bottomrule - \end{tabular} + \endlastfoot + 1 & b1 \\ + 2 & b2 \\ + \end{longtable} """ ) assert result == expected - def test_to_latex_multiindex_small_tabular(self): - df = DataFrame({("x", "y"): ["a"]}) - result = df.T.to_latex() + @pytest.mark.parametrize( + "df, expected_number", + [ + (DataFrame({"a": [1, 2]}), 1), + (DataFrame({"a": [1, 2], "b": [3, 4]}), 2), + (DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}), 3), + ], + ) + def test_to_latex_longtable_continued_on_next_page(self, df, expected_number): + result = df.to_latex(index=False, longtable=True) + assert fr"\multicolumn{{{expected_number}}}" in result + + +class TestToLatexHeader: + def test_to_latex_no_header_with_index(self): + # GH 7124 + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(header=False) expected = _dedent( r""" - \begin{tabular}{lll} + \begin{tabular}{lrl} \toprule - & & 0 \\ - \midrule - x & y & a \\ + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_multiindex_tabular(self, multiindex_frame): - result = multiindex_frame.to_latex() + def test_to_latex_no_header_without_index(self): + # GH 7124 + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(index=False, header=False) expected = _dedent( r""" - \begin{tabular}{llrrrr} + \begin{tabular}{rl} \toprule - & & 0 & 1 & 2 & 3 \\ - \midrule - c1 & 0 & 0 & 1 & 2 & 3 \\ - & 1 & 4 & 5 & 6 & 7 \\ - c2 & 0 & 0 & 1 & 2 & 3 \\ - & 1 & 4 & 5 & 6 & 7 \\ - c3 & 0 & 0 & 1 & 2 & 3 \\ + 1 & b1 \\ + 2 & b2 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_multicolumn_tabular(self, multiindex_frame): - # GH 14184 - df = multiindex_frame.T - df.columns.names = ["a", "b"] - result = df.to_latex() + def test_to_latex_specified_header_with_index(self): + # GH 7124 + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(header=["AA", "BB"]) expected = _dedent( r""" - \begin{tabular}{lrrrrr} + \begin{tabular}{lrl} \toprule - a & \multicolumn{2}{l}{c1} & \multicolumn{2}{l}{c2} & c3 \\ - b & 0 & 1 & 0 & 1 & 0 \\ + {} & AA & BB \\ \midrule - 0 & 0 & 4 & 0 & 4 & 0 \\ - 1 & 1 & 5 & 1 & 5 & 1 \\ - 2 & 2 & 6 & 2 & 6 & 2 \\ - 3 & 3 & 7 & 3 & 7 & 3 \\ + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_index_has_name_tabular(self): - # GH 10660 - df = pd.DataFrame({"a": [0, 0, 1, 1], "b": list("abab"), "c": [1, 2, 3, 4]}) - result = df.set_index(["a", "b"]).to_latex() + def test_to_latex_specified_header_without_index(self): + # GH 7124 + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(header=["AA", "BB"], index=False) expected = _dedent( r""" - \begin{tabular}{llr} + \begin{tabular}{rl} \toprule - & & c \\ - a & b & \\ + AA & BB \\ \midrule - 0 & a & 1 \\ - & b & 2 \\ - 1 & a & 3 \\ - & b & 4 \\ + 1 & b1 \\ + 2 & b2 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_groupby_tabular(self): - # GH 10660 - df = pd.DataFrame({"a": [0, 0, 1, 1], "b": list("abab"), "c": [1, 2, 3, 4]}) - result = df.groupby("a").describe().to_latex() - expected = _dedent( - r""" - \begin{tabular}{lrrrrrrrr} - \toprule - {} & \multicolumn{8}{l}{c} \\ - {} & count & mean & std & min & 25\% & 50\% & 75\% & max \\ - a & & & & & & & & \\ - \midrule - 0 & 2.0 & 1.5 & 0.707107 & 1.0 & 1.25 & 1.5 & 1.75 & 2.0 \\ - 1 & 2.0 & 3.5 & 0.707107 & 3.0 & 3.25 & 3.5 & 3.75 & 4.0 \\ - \bottomrule - \end{tabular} - """ - ) - assert result == expected + @pytest.mark.parametrize( + "header, num_aliases", + [ + (["A"], 1), + (("B",), 1), + (("Col1", "Col2", "Col3"), 3), + (("Col1", "Col2", "Col3", "Col4"), 4), + ], + ) + def test_to_latex_number_of_items_in_header_missmatch_raises( + self, + header, + num_aliases, + ): + # GH 7124 + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + msg = f"Writing 2 cols but got {num_aliases} aliases" + with pytest.raises(ValueError, match=msg): + df.to_latex(header=header) - def test_to_latex_multiindex_dupe_level(self): - # see gh-14484 - # - # If an index is repeated in subsequent rows, it should be - # replaced with a blank in the created table. This should - # ONLY happen if all higher order indices (to the left) are - # equal too. In this test, 'c' has to be printed both times - # because the higher order index 'A' != 'B'. - df = pd.DataFrame( - index=pd.MultiIndex.from_tuples([("A", "c"), ("B", "c")]), columns=["col"] - ) - result = df.to_latex() + def test_to_latex_decimal(self): + # GH 12031 + df = DataFrame({"a": [1.0, 2.1], "b": ["b1", "b2"]}) + result = df.to_latex(decimal=",") expected = _dedent( r""" - \begin{tabular}{lll} + \begin{tabular}{lrl} \toprule - & & col \\ + {} & a & b \\ \midrule - A & c & NaN \\ - B & c & NaN \\ + 0 & 1,0 & b1 \\ + 1 & 2,1 & b2 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_multicolumn_default(self, multicolumn_frame): - result = multicolumn_frame.to_latex() + +class TestToLatexBold: + def test_to_latex_bold_rows(self): + # GH 16707 + df = pd.DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(bold_rows=True) expected = _dedent( r""" - \begin{tabular}{lrrrrr} + \begin{tabular}{lrl} \toprule - {} & \multicolumn{2}{l}{c1} & \multicolumn{2}{l}{c2} & c3 \\ - {} & 0 & 1 & 0 & 1 & 0 \\ + {} & a & b \\ \midrule - 0 & 0 & 5 & 0 & 5 & 0 \\ - 1 & 1 & 6 & 1 & 6 & 1 \\ - 2 & 2 & 7 & 2 & 7 & 2 \\ - 3 & 3 & 8 & 3 & 8 & 3 \\ - 4 & 4 & 9 & 4 & 9 & 4 \\ + \textbf{0} & 1 & b1 \\ + \textbf{1} & 2 & b2 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_multicolumn_false(self, multicolumn_frame): - result = multicolumn_frame.to_latex(multicolumn=False) + def test_to_latex_no_bold_rows(self): + # GH 16707 + df = pd.DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(bold_rows=False) expected = _dedent( r""" - \begin{tabular}{lrrrrr} + \begin{tabular}{lrl} \toprule - {} & c1 & & c2 & & c3 \\ - {} & 0 & 1 & 0 & 1 & 0 \\ + {} & a & b \\ \midrule - 0 & 0 & 5 & 0 & 5 & 0 \\ - 1 & 1 & 6 & 1 & 6 & 1 \\ - 2 & 2 & 7 & 2 & 7 & 2 \\ - 3 & 3 & 8 & 3 & 8 & 3 \\ - 4 & 4 & 9 & 4 & 9 & 4 \\ + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_multirow_true(self, multicolumn_frame): - result = multicolumn_frame.T.to_latex(multirow=True) + +class TestToLatexCaptionLabel: + @pytest.fixture + def caption_table(self): + """Caption for table/tabular LaTeX environment.""" + return "a table in a \\texttt{table/tabular} environment" + + @pytest.fixture + def label_table(self): + """Label for table/tabular LaTeX environment.""" + return "tab:table_tabular" + + @pytest.fixture + def caption_longtable(self): + """Caption for longtable LaTeX environment.""" + return "a table in a \\texttt{longtable} environment" + + @pytest.fixture + def label_longtable(self): + """Label for longtable LaTeX environment.""" + return "tab:longtable" + + def test_to_latex_caption_only(self, df_short, caption_table): + # GH 25436 + result = df_short.to_latex(caption=caption_table) expected = _dedent( r""" - \begin{tabular}{llrrrrr} + \begin{table} + \centering + \caption{a table in a \texttt{table/tabular} environment} + \begin{tabular}{lrl} \toprule - & & 0 & 1 & 2 & 3 & 4 \\ + {} & a & b \\ \midrule - \multirow{2}{*}{c1} & 0 & 0 & 1 & 2 & 3 & 4 \\ - & 1 & 5 & 6 & 7 & 8 & 9 \\ - \cline{1-7} - \multirow{2}{*}{c2} & 0 & 0 & 1 & 2 & 3 & 4 \\ - & 1 & 5 & 6 & 7 & 8 & 9 \\ - \cline{1-7} - c3 & 0 & 0 & 1 & 2 & 3 & 4 \\ + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ \bottomrule \end{tabular} + \end{table} """ ) assert result == expected - def test_to_latex_multicolumnrow_with_multicol_format(self, multicolumn_frame): - multicolumn_frame.index = multicolumn_frame.T.index - result = multicolumn_frame.T.to_latex( - multirow=True, - multicolumn=True, - multicolumn_format="c", - ) + def test_to_latex_label_only(self, df_short, label_table): + # GH 25436 + result = df_short.to_latex(label=label_table) expected = _dedent( r""" - \begin{tabular}{llrrrrr} + \begin{table} + \centering + \label{tab:table_tabular} + \begin{tabular}{lrl} \toprule - & & \multicolumn{2}{c}{c1} & \multicolumn{2}{c}{c2} & c3 \\ - & & 0 & 1 & 0 & 1 & 0 \\ + {} & a & b \\ \midrule - \multirow{2}{*}{c1} & 0 & 0 & 1 & 2 & 3 & 4 \\ - & 1 & 5 & 6 & 7 & 8 & 9 \\ - \cline{1-7} - \multirow{2}{*}{c2} & 0 & 0 & 1 & 2 & 3 & 4 \\ - & 1 & 5 & 6 & 7 & 8 & 9 \\ - \cline{1-7} - c3 & 0 & 0 & 1 & 2 & 3 & 4 \\ + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ \bottomrule \end{tabular} + \end{table} """ ) assert result == expected - def test_to_latex_escape_false(self, df_with_symbols): - result = df_with_symbols.to_latex(escape=False) + def test_to_latex_caption_and_label(self, df_short, caption_table, label_table): + # GH 25436 + result = df_short.to_latex(caption=caption_table, label=label_table) expected = _dedent( r""" - \begin{tabular}{lll} + \begin{table} + \centering + \caption{a table in a \texttt{table/tabular} environment} + \label{tab:table_tabular} + \begin{tabular}{lrl} \toprule - {} & co$e^x$ & co^l1 \\ + {} & a & b \\ \midrule - a & a & a \\ - b & b & b \\ + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ \bottomrule \end{tabular} + \end{table} """ ) assert result == expected - def test_to_latex_escape_default(self, df_with_symbols): - result = df_with_symbols.to_latex() # default: escape=True + def test_to_latex_longtable_caption_only(self, df_short, caption_longtable): + # GH 25436 + # test when no caption and no label is provided + # is performed by test_to_latex_longtable() + result = df_short.to_latex(longtable=True, caption=caption_longtable) expected = _dedent( r""" - \begin{tabular}{lll} + \begin{longtable}{lrl} + \caption{a table in a \texttt{longtable} environment}\\ \toprule - {} & co\$e\textasciicircum x\$ & co\textasciicircum l1 \\ + {} & a & b \\ \midrule - a & a & a \\ - b & b & b \\ - \bottomrule - \end{tabular} - """ - ) - assert result == expected - - def test_to_latex_special_escape(self): - df = DataFrame([r"a\b\c", r"^a^b^c", r"~a~b~c"]) - result = df.to_latex() - expected = _dedent( - r""" - \begin{tabular}{ll} + \endfirsthead + \caption[]{a table in a \texttt{longtable} environment} \\ \toprule - {} & 0 \\ + {} & a & b \\ \midrule - 0 & a\textbackslash b\textbackslash c \\ - 1 & \textasciicircum a\textasciicircum b\textasciicircum c \\ - 2 & \textasciitilde a\textasciitilde b\textasciitilde c \\ + \endhead + \midrule + \multicolumn{3}{r}{{Continued on next page}} \\ + \midrule + \endfoot + \bottomrule - \end{tabular} + \endlastfoot + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ + \end{longtable} """ ) assert result == expected - def test_to_latex_longtable_with_index(self): - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(longtable=True) + def test_to_latex_longtable_label_only(self, df_short, label_longtable): + # GH 25436 + result = df_short.to_latex(longtable=True, label=label_longtable) expected = _dedent( r""" \begin{longtable}{lrl} + \label{tab:longtable}\\ \toprule {} & a & b \\ \midrule @@ -549,150 +555,179 @@ def test_to_latex_longtable_with_index(self): ) assert result == expected - def test_to_latex_longtable_without_index(self): - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(index=False, longtable=True) + def test_to_latex_longtable_caption_and_label( + self, + df_short, + caption_longtable, + label_longtable, + ): + # GH 25436 + result = df_short.to_latex( + longtable=True, + caption=caption_longtable, + label=label_longtable, + ) expected = _dedent( r""" - \begin{longtable}{rl} + \begin{longtable}{lrl} + \caption{a table in a \texttt{longtable} environment} + \label{tab:longtable}\\ \toprule - a & b \\ + {} & a & b \\ \midrule \endfirsthead - + \caption[]{a table in a \texttt{longtable} environment} \\ \toprule - a & b \\ + {} & a & b \\ \midrule \endhead \midrule - \multicolumn{2}{r}{{Continued on next page}} \\ + \multicolumn{3}{r}{{Continued on next page}} \\ \midrule \endfoot \bottomrule \endlastfoot - 1 & b1 \\ - 2 & b2 \\ - \end{longtable} + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ + \end{longtable} """ ) assert result == expected - @pytest.mark.parametrize( - "df, expected_number", - [ - (DataFrame({"a": [1, 2]}), 1), - (DataFrame({"a": [1, 2], "b": [3, 4]}), 2), - (DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}), 3), - ], - ) - def test_to_latex_longtable_continued_on_next_page(self, df, expected_number): - result = df.to_latex(index=False, longtable=True) - assert fr"\multicolumn{{{expected_number}}}" in result - def test_to_latex_caption_only(self, df_short, caption_table): - # GH 25436 - result = df_short.to_latex(caption=caption_table) +class TestToLatexEscape: + @pytest.fixture + def df_with_symbols(self): + """Dataframe with special characters for testing chars escaping.""" + a = "a" + b = "b" + yield DataFrame({"co$e^x$": {a: "a", b: "b"}, "co^l1": {a: "a", b: "b"}}) + + def test_to_latex_escape_false(self, df_with_symbols): + result = df_with_symbols.to_latex(escape=False) expected = _dedent( r""" - \begin{table} - \centering - \caption{a table in a \texttt{table/tabular} environment} - \begin{tabular}{lrl} + \begin{tabular}{lll} \toprule - {} & a & b \\ + {} & co$e^x$ & co^l1 \\ \midrule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + a & a & a \\ + b & b & b \\ \bottomrule \end{tabular} - \end{table} """ ) assert result == expected - def test_to_latex_label_only(self, df_short, label_table): - # GH 25436 - result = df_short.to_latex(label=label_table) + def test_to_latex_escape_default(self, df_with_symbols): + result = df_with_symbols.to_latex() # default: escape=True expected = _dedent( r""" - \begin{table} - \centering - \label{tab:table_tabular} - \begin{tabular}{lrl} + \begin{tabular}{lll} \toprule - {} & a & b \\ + {} & co\$e\textasciicircum x\$ & co\textasciicircum l1 \\ \midrule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + a & a & a \\ + b & b & b \\ \bottomrule \end{tabular} - \end{table} """ ) assert result == expected - def test_to_latex_caption_and_label(self, df_short, caption_table, label_table): - # GH 25436 - result = df_short.to_latex(caption=caption_table, label=label_table) + def test_to_latex_special_escape(self): + df = DataFrame([r"a\b\c", r"^a^b^c", r"~a~b~c"]) + result = df.to_latex() expected = _dedent( r""" - \begin{table} - \centering - \caption{a table in a \texttt{table/tabular} environment} - \label{tab:table_tabular} - \begin{tabular}{lrl} + \begin{tabular}{ll} \toprule - {} & a & b \\ + {} & 0 \\ \midrule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + 0 & a\textbackslash b\textbackslash c \\ + 1 & \textasciicircum a\textasciicircum b\textasciicircum c \\ + 2 & \textasciitilde a\textasciitilde b\textasciitilde c \\ \bottomrule \end{tabular} - \end{table} """ ) assert result == expected - def test_to_latex_longtable_caption_only(self, df_short, caption_longtable): - # GH 25436 - # test when no caption and no label is provided - # is performed by test_to_latex_longtable() - result = df_short.to_latex(longtable=True, caption=caption_longtable) + def test_to_latex_escape_special_chars(self): + special_characters = ["&", "%", "$", "#", "_", "{", "}", "~", "^", "\\"] + df = DataFrame(data=special_characters) + result = df.to_latex() expected = _dedent( r""" - \begin{longtable}{lrl} - \caption{a table in a \texttt{longtable} environment}\\ + \begin{tabular}{ll} \toprule - {} & a & b \\ + {} & 0 \\ \midrule - \endfirsthead - \caption[]{a table in a \texttt{longtable} environment} \\ + 0 & \& \\ + 1 & \% \\ + 2 & \$ \\ + 3 & \# \\ + 4 & \_ \\ + 5 & \{ \\ + 6 & \} \\ + 7 & \textasciitilde \\ + 8 & \textasciicircum \\ + 9 & \textbackslash \\ + \bottomrule + \end{tabular} + """ + ) + assert result == expected + + def test_to_latex_specified_header_special_chars_without_escape(self): + # GH 7124 + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(header=["$A$", "$B$"], escape=False) + expected = _dedent( + r""" + \begin{tabular}{lrl} \toprule - {} & a & b \\ - \midrule - \endhead - \midrule - \multicolumn{3}{r}{{Continued on next page}} \\ + {} & $A$ & $B$ \\ \midrule - \endfoot - + 0 & 1 & b1 \\ + 1 & 2 & b2 \\ \bottomrule - \endlastfoot + \end{tabular} + """ + ) + assert result == expected + + +class TestToLatexPosition: + def test_to_latex_position(self): + the_position = "h" + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(position=the_position) + expected = _dedent( + r""" + \begin{table}[h] + \centering + \begin{tabular}{lrl} + \toprule + {} & a & b \\ + \midrule 0 & 1 & b1 \\ 1 & 2 & b2 \\ - \end{longtable} + \bottomrule + \end{tabular} + \end{table} """ ) assert result == expected - def test_to_latex_longtable_label_only(self, df_short, label_longtable): - # GH 25436 - result = df_short.to_latex(longtable=True, label=label_longtable) + def test_to_latex_longtable_position(self): + the_position = "t" + df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) + result = df.to_latex(longtable=True, position=the_position) expected = _dedent( r""" - \begin{longtable}{lrl} - \label{tab:longtable}\\ + \begin{longtable}[t]{lrl} \toprule {} & a & b \\ \midrule @@ -716,282 +751,370 @@ def test_to_latex_longtable_label_only(self, df_short, label_longtable): ) assert result == expected - def test_to_latex_longtable_caption_and_label( - self, - df_short, - caption_longtable, - label_longtable, - ): - # GH 25436 - result = df_short.to_latex( - longtable=True, - caption=caption_longtable, - label=label_longtable, + +class TestToLatexFormatters: + def test_to_latex_with_formatters(self): + df = DataFrame( + { + "datetime64": [ + datetime(2016, 1, 1), + datetime(2016, 2, 5), + datetime(2016, 3, 3), + ], + "float": [1.0, 2.0, 3.0], + "int": [1, 2, 3], + "object": [(1, 2), True, False], + } ) + + formatters = { + "datetime64": lambda x: x.strftime("%Y-%m"), + "float": lambda x: f"[{x: 4.1f}]", + "int": lambda x: f"0x{x:x}", + "object": lambda x: f"-{x!s}-", + "__index__": lambda x: f"index: {x}", + } + result = df.to_latex(formatters=dict(formatters)) + expected = _dedent( r""" - \begin{longtable}{lrl} - \caption{a table in a \texttt{longtable} environment} - \label{tab:longtable}\\ + \begin{tabular}{llrrl} \toprule - {} & a & b \\ + {} & datetime64 & float & int & object \\ \midrule - \endfirsthead - \caption[]{a table in a \texttt{longtable} environment} \\ + index: 0 & 2016-01 & [ 1.0] & 0x1 & -(1, 2)- \\ + index: 1 & 2016-02 & [ 2.0] & 0x2 & -True- \\ + index: 2 & 2016-03 & [ 3.0] & 0x3 & -False- \\ + \bottomrule + \end{tabular} + """ + ) + assert result == expected + + def test_to_latex_float_format_no_fixed_width_3decimals(self): + # GH 21625 + df = DataFrame({"x": [0.19999]}) + result = df.to_latex(float_format="%.3f") + expected = _dedent( + r""" + \begin{tabular}{lr} \toprule - {} & a & b \\ - \midrule - \endhead - \midrule - \multicolumn{3}{r}{{Continued on next page}} \\ + {} & x \\ \midrule - \endfoot - + 0 & 0.200 \\ \bottomrule - \endlastfoot - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ - \end{longtable} + \end{tabular} """ ) assert result == expected - def test_to_latex_position(self): - the_position = "h" - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(position=the_position) + def test_to_latex_float_format_no_fixed_width_integer(self): + # GH 22270 + df = DataFrame({"x": [100.0]}) + result = df.to_latex(float_format="%.0f") expected = _dedent( r""" - \begin{table}[h] - \centering - \begin{tabular}{lrl} + \begin{tabular}{lr} \toprule - {} & a & b \\ + {} & x \\ \midrule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + 0 & 100 \\ \bottomrule \end{tabular} - \end{table} """ ) assert result == expected - def test_to_latex_longtable_position(self): - the_position = "t" - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(longtable=True, position=the_position) + +class TestToLatexMultiindex: + @pytest.fixture + def multiindex_frame(self): + """Multiindex dataframe for testing multirow LaTeX macros.""" + yield DataFrame.from_dict( + { + ("c1", 0): pd.Series({x: x for x in range(4)}), + ("c1", 1): pd.Series({x: x + 4 for x in range(4)}), + ("c2", 0): pd.Series({x: x for x in range(4)}), + ("c2", 1): pd.Series({x: x + 4 for x in range(4)}), + ("c3", 0): pd.Series({x: x for x in range(4)}), + } + ).T + + @pytest.fixture + def multicolumn_frame(self): + """Multicolumn dataframe for testing multicolumn LaTeX macros.""" + yield pd.DataFrame( + { + ("c1", 0): {x: x for x in range(5)}, + ("c1", 1): {x: x + 5 for x in range(5)}, + ("c2", 0): {x: x for x in range(5)}, + ("c2", 1): {x: x + 5 for x in range(5)}, + ("c3", 0): {x: x for x in range(5)}, + } + ) + + def test_to_latex_multindex_header(self): + # GH 16718 + df = pd.DataFrame({"a": [0], "b": [1], "c": [2], "d": [3]}) + df = df.set_index(["a", "b"]) + observed = df.to_latex(header=["r1", "r2"]) expected = _dedent( r""" - \begin{longtable}[t]{lrl} + \begin{tabular}{llrr} \toprule - {} & a & b \\ + & & r1 & r2 \\ + a & b & & \\ \midrule - \endfirsthead + 0 & 1 & 2 & 3 \\ + \bottomrule + \end{tabular} + """ + ) + assert observed == expected + def test_to_latex_multiindex_empty_name(self): + # GH 18669 + mi = pd.MultiIndex.from_product([[1, 2]], names=[""]) + df = pd.DataFrame(-1, index=mi, columns=range(4)) + observed = df.to_latex() + expected = _dedent( + r""" + \begin{tabular}{lrrrr} \toprule - {} & a & b \\ - \midrule - \endhead - \midrule - \multicolumn{3}{r}{{Continued on next page}} \\ + & 0 & 1 & 2 & 3 \\ + {} & & & & \\ \midrule - \endfoot - + 1 & -1 & -1 & -1 & -1 \\ + 2 & -1 & -1 & -1 & -1 \\ \bottomrule - \endlastfoot - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ - \end{longtable} + \end{tabular} """ ) - assert result == expected + assert observed == expected - def test_to_latex_escape_special_chars(self): - special_characters = ["&", "%", "$", "#", "_", "{", "}", "~", "^", "\\"] - df = DataFrame(data=special_characters) + def test_to_latex_multiindex_column_tabular(self): + df = DataFrame({("x", "y"): ["a"]}) result = df.to_latex() expected = _dedent( r""" \begin{tabular}{ll} \toprule - {} & 0 \\ + {} & x \\ + {} & y \\ \midrule - 0 & \& \\ - 1 & \% \\ - 2 & \$ \\ - 3 & \# \\ - 4 & \_ \\ - 5 & \{ \\ - 6 & \} \\ - 7 & \textasciitilde \\ - 8 & \textasciicircum \\ - 9 & \textbackslash \\ + 0 & a \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_no_header_with_index(self): - # GH 7124 - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(header=False) + def test_to_latex_multiindex_small_tabular(self): + df = DataFrame({("x", "y"): ["a"]}).T + result = df.to_latex() expected = _dedent( r""" - \begin{tabular}{lrl} + \begin{tabular}{lll} \toprule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + & & 0 \\ + \midrule + x & y & a \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_no_header_without_index(self): - # GH 7124 - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(index=False, header=False) + def test_to_latex_multiindex_tabular(self, multiindex_frame): + result = multiindex_frame.to_latex() + expected = _dedent( + r""" + \begin{tabular}{llrrrr} + \toprule + & & 0 & 1 & 2 & 3 \\ + \midrule + c1 & 0 & 0 & 1 & 2 & 3 \\ + & 1 & 4 & 5 & 6 & 7 \\ + c2 & 0 & 0 & 1 & 2 & 3 \\ + & 1 & 4 & 5 & 6 & 7 \\ + c3 & 0 & 0 & 1 & 2 & 3 \\ + \bottomrule + \end{tabular} + """ + ) + assert result == expected + + def test_to_latex_multicolumn_tabular(self, multiindex_frame): + # GH 14184 + df = multiindex_frame.T + df.columns.names = ["a", "b"] + result = df.to_latex() expected = _dedent( r""" - \begin{tabular}{rl} + \begin{tabular}{lrrrrr} \toprule - 1 & b1 \\ - 2 & b2 \\ + a & \multicolumn{2}{l}{c1} & \multicolumn{2}{l}{c2} & c3 \\ + b & 0 & 1 & 0 & 1 & 0 \\ + \midrule + 0 & 0 & 4 & 0 & 4 & 0 \\ + 1 & 1 & 5 & 1 & 5 & 1 \\ + 2 & 2 & 6 & 2 & 6 & 2 \\ + 3 & 3 & 7 & 3 & 7 & 3 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_specified_header_with_index(self): - # GH 7124 - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(header=["AA", "BB"]) + def test_to_latex_index_has_name_tabular(self): + # GH 10660 + df = pd.DataFrame({"a": [0, 0, 1, 1], "b": list("abab"), "c": [1, 2, 3, 4]}) + result = df.set_index(["a", "b"]).to_latex() expected = _dedent( r""" - \begin{tabular}{lrl} + \begin{tabular}{llr} \toprule - {} & AA & BB \\ + & & c \\ + a & b & \\ \midrule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + 0 & a & 1 \\ + & b & 2 \\ + 1 & a & 3 \\ + & b & 4 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_specified_header_without_index(self): - # GH 7124 - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(header=["AA", "BB"], index=False) + def test_to_latex_groupby_tabular(self): + # GH 10660 + df = pd.DataFrame({"a": [0, 0, 1, 1], "b": list("abab"), "c": [1, 2, 3, 4]}) + result = df.groupby("a").describe().to_latex() expected = _dedent( r""" - \begin{tabular}{rl} + \begin{tabular}{lrrrrrrrr} \toprule - AA & BB \\ + {} & \multicolumn{8}{l}{c} \\ + {} & count & mean & std & min & 25\% & 50\% & 75\% & max \\ + a & & & & & & & & \\ \midrule - 1 & b1 \\ - 2 & b2 \\ + 0 & 2.0 & 1.5 & 0.707107 & 1.0 & 1.25 & 1.5 & 1.75 & 2.0 \\ + 1 & 2.0 & 3.5 & 0.707107 & 3.0 & 3.25 & 3.5 & 3.75 & 4.0 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_specified_header_special_chars_without_escape(self): - # GH 7124 - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(header=["$A$", "$B$"], escape=False) + def test_to_latex_multiindex_dupe_level(self): + # see gh-14484 + # + # If an index is repeated in subsequent rows, it should be + # replaced with a blank in the created table. This should + # ONLY happen if all higher order indices (to the left) are + # equal too. In this test, 'c' has to be printed both times + # because the higher order index 'A' != 'B'. + df = pd.DataFrame( + index=pd.MultiIndex.from_tuples([("A", "c"), ("B", "c")]), columns=["col"] + ) + result = df.to_latex() expected = _dedent( r""" - \begin{tabular}{lrl} + \begin{tabular}{lll} \toprule - {} & $A$ & $B$ \\ + & & col \\ \midrule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + A & c & NaN \\ + B & c & NaN \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_number_of_items_in_header_missmatch_raises(self): - # GH 7124 - df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - msg = "Writing 2 cols but got 1 aliases" - with pytest.raises(ValueError, match=msg): - df.to_latex(header=["A"]) - - def test_to_latex_decimal(self): - # GH 12031 - df = DataFrame({"a": [1.0, 2.1], "b": ["b1", "b2"]}) - result = df.to_latex(decimal=",") + def test_to_latex_multicolumn_default(self, multicolumn_frame): + result = multicolumn_frame.to_latex() expected = _dedent( r""" - \begin{tabular}{lrl} + \begin{tabular}{lrrrrr} \toprule - {} & a & b \\ + {} & \multicolumn{2}{l}{c1} & \multicolumn{2}{l}{c2} & c3 \\ + {} & 0 & 1 & 0 & 1 & 0 \\ \midrule - 0 & 1,0 & b1 \\ - 1 & 2,1 & b2 \\ + 0 & 0 & 5 & 0 & 5 & 0 \\ + 1 & 1 & 6 & 1 & 6 & 1 \\ + 2 & 2 & 7 & 2 & 7 & 2 \\ + 3 & 3 & 8 & 3 & 8 & 3 \\ + 4 & 4 & 9 & 4 & 9 & 4 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_series(self): - s = Series(["a", "b", "c"]) - result = s.to_latex() + def test_to_latex_multicolumn_false(self, multicolumn_frame): + result = multicolumn_frame.to_latex(multicolumn=False) expected = _dedent( r""" - \begin{tabular}{ll} + \begin{tabular}{lrrrrr} \toprule - {} & 0 \\ + {} & c1 & & c2 & & c3 \\ + {} & 0 & 1 & 0 & 1 & 0 \\ \midrule - 0 & a \\ - 1 & b \\ - 2 & c \\ + 0 & 0 & 5 & 0 & 5 & 0 \\ + 1 & 1 & 6 & 1 & 6 & 1 \\ + 2 & 2 & 7 & 2 & 7 & 2 \\ + 3 & 3 & 8 & 3 & 8 & 3 \\ + 4 & 4 & 9 & 4 & 9 & 4 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_bold_rows(self): - # GH 16707 - df = pd.DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(bold_rows=True) + def test_to_latex_multirow_true(self, multicolumn_frame): + result = multicolumn_frame.T.to_latex(multirow=True) expected = _dedent( r""" - \begin{tabular}{lrl} + \begin{tabular}{llrrrrr} \toprule - {} & a & b \\ + & & 0 & 1 & 2 & 3 & 4 \\ \midrule - \textbf{0} & 1 & b1 \\ - \textbf{1} & 2 & b2 \\ + \multirow{2}{*}{c1} & 0 & 0 & 1 & 2 & 3 & 4 \\ + & 1 & 5 & 6 & 7 & 8 & 9 \\ + \cline{1-7} + \multirow{2}{*}{c2} & 0 & 0 & 1 & 2 & 3 & 4 \\ + & 1 & 5 & 6 & 7 & 8 & 9 \\ + \cline{1-7} + c3 & 0 & 0 & 1 & 2 & 3 & 4 \\ \bottomrule \end{tabular} """ ) assert result == expected - def test_to_latex_no_bold_rows(self): - # GH 16707 - df = pd.DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) - result = df.to_latex(bold_rows=False) + def test_to_latex_multicolumnrow_with_multicol_format(self, multicolumn_frame): + multicolumn_frame.index = multicolumn_frame.T.index + result = multicolumn_frame.T.to_latex( + multirow=True, + multicolumn=True, + multicolumn_format="c", + ) expected = _dedent( r""" - \begin{tabular}{lrl} + \begin{tabular}{llrrrrr} \toprule - {} & a & b \\ + & & \multicolumn{2}{c}{c1} & \multicolumn{2}{c}{c2} & c3 \\ + & & 0 & 1 & 0 & 1 & 0 \\ \midrule - 0 & 1 & b1 \\ - 1 & 2 & b2 \\ + \multirow{2}{*}{c1} & 0 & 0 & 1 & 2 & 3 & 4 \\ + & 1 & 5 & 6 & 7 & 8 & 9 \\ + \cline{1-7} + \multirow{2}{*}{c2} & 0 & 0 & 1 & 2 & 3 & 4 \\ + & 1 & 5 & 6 & 7 & 8 & 9 \\ + \cline{1-7} + c3 & 0 & 0 & 1 & 2 & 3 & 4 \\ \bottomrule \end{tabular} """ @@ -1061,7 +1184,8 @@ def test_to_latex_multiindex_nans(self, one_row): def test_to_latex_non_string_index(self): # GH 19981 - observed = pd.DataFrame([[1, 2, 3]] * 2).set_index([0, 1]).to_latex() + df = pd.DataFrame([[1, 2, 3]] * 2).set_index([0, 1]) + result = df.to_latex() expected = _dedent( r""" \begin{tabular}{llr} @@ -1075,100 +1199,8 @@ def test_to_latex_non_string_index(self): \end{tabular} """ ) - assert observed == expected - - def test_to_latex_midrule_location(self): - # GH 18326 - df = pd.DataFrame({"a": [1, 2]}) - df.index.name = "foo" - result = df.to_latex(index_names=False) - expected = _dedent( - r""" - \begin{tabular}{lr} - \toprule - {} & a \\ - \midrule - 0 & 1 \\ - 1 & 2 \\ - \bottomrule - \end{tabular} - """ - ) - assert result == expected - - def test_to_latex_multiindex_empty_name(self): - # GH 18669 - mi = pd.MultiIndex.from_product([[1, 2]], names=[""]) - df = pd.DataFrame(-1, index=mi, columns=range(4)) - observed = df.to_latex() - expected = _dedent( - r""" - \begin{tabular}{lrrrr} - \toprule - & 0 & 1 & 2 & 3 \\ - {} & & & & \\ - \midrule - 1 & -1 & -1 & -1 & -1 \\ - 2 & -1 & -1 & -1 & -1 \\ - \bottomrule - \end{tabular} - """ - ) - assert observed == expected - - def test_to_latex_float_format_no_fixed_width_3decimals(self): - # GH 21625 - df = DataFrame({"x": [0.19999]}) - result = df.to_latex(float_format="%.3f") - expected = _dedent( - r""" - \begin{tabular}{lr} - \toprule - {} & x \\ - \midrule - 0 & 0.200 \\ - \bottomrule - \end{tabular} - """ - ) - assert result == expected - - def test_to_latex_float_format_no_fixed_width_integer(self): - # GH 22270 - df = DataFrame({"x": [100.0]}) - result = df.to_latex(float_format="%.0f") - expected = _dedent( - r""" - \begin{tabular}{lr} - \toprule - {} & x \\ - \midrule - 0 & 100 \\ - \bottomrule - \end{tabular} - """ - ) assert result == expected - def test_to_latex_multindex_header(self): - # GH 16718 - df = pd.DataFrame({"a": [0], "b": [1], "c": [2], "d": [3]}) - df = df.set_index(["a", "b"]) - observed = df.to_latex(header=["r1", "r2"]) - expected = _dedent( - r""" - \begin{tabular}{llrr} - \toprule - & & r1 & r2 \\ - a & b & & \\ - \midrule - 0 & 1 & 2 & 3 \\ - \bottomrule - \end{tabular} - """ - ) - assert observed == expected - class TestTableBuilder: @pytest.fixture
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Rearranged tests in ``test_to_latex.py`` to the corresponding classes. Sorry for the messy diffs. All I did (except to small commits cd92db9 and 2b66e2f) was rearrangement of the tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/36714
2020-09-28T19:18:21Z
2020-09-30T12:38:18Z
2020-09-30T12:38:18Z
2020-10-04T13:25:48Z
CLN: pandas/core/indexing.py
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index fc1b9bee9ba03..ac4ff25081bb5 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1,4 +1,5 @@ -from typing import TYPE_CHECKING, Hashable, List, Tuple, Union +from contextlib import suppress +from typing import TYPE_CHECKING, Any, Hashable, List, Sequence, Tuple, Union import warnings import numpy as np @@ -610,17 +611,13 @@ def _get_setitem_indexer(self, key): ax = self.obj._get_axis(0) if isinstance(ax, ABCMultiIndex) and self.name != "iloc": - try: - return ax.get_loc(key) - except (TypeError, KeyError, InvalidIndexError): + with suppress(TypeError, KeyError, InvalidIndexError): # TypeError e.g. passed a bool - pass + return ax.get_loc(key) if isinstance(key, tuple): - try: + with suppress(IndexingError): return self._convert_tuple(key, is_setter=True) - except IndexingError: - pass if isinstance(key, range): return list(key) @@ -707,9 +704,8 @@ def _has_valid_tuple(self, key: Tuple): """ Check the key for valid keys across my indexer. """ + self._validate_key_length(key) for i, k in enumerate(key): - if i >= self.ndim: - raise IndexingError("Too many indexers") try: self._validate_key(k, i) except ValueError as err: @@ -740,13 +736,17 @@ def _convert_tuple(self, key, is_setter: bool = False): else: keyidx.append(slice(None)) else: + self._validate_key_length(key) for i, k in enumerate(key): - if i >= self.ndim: - raise IndexingError("Too many indexers") idx = self._convert_to_indexer(k, axis=i, is_setter=is_setter) keyidx.append(idx) + return tuple(keyidx) + def _validate_key_length(self, key: Sequence[Any]) -> None: + if len(key) > self.ndim: + raise IndexingError("Too many indexers") + def _getitem_tuple_same_dim(self, tup: Tuple): """ Index with indexers that should return an object of the same dimension @@ -782,14 +782,10 @@ def _getitem_lowerdim(self, tup: Tuple): # ...but iloc should handle the tuple as simple integer-location # instead of checking it as multiindex representation (GH 13797) if isinstance(ax0, ABCMultiIndex) and self.name != "iloc": - try: - result = self._handle_lowerdim_multi_index_axis0(tup) - return result - except IndexingError: - pass + with suppress(IndexingError): + return self._handle_lowerdim_multi_index_axis0(tup) - if len(tup) > self.ndim: - raise IndexingError("Too many indexers. handle elsewhere") + self._validate_key_length(tup) for i, key in enumerate(tup): if is_label_like(key): @@ -834,11 +830,8 @@ def _getitem_nested_tuple(self, tup: Tuple): if self.name != "loc": # This should never be reached, but lets be explicit about it raise ValueError("Too many indices") - try: - result = self._handle_lowerdim_multi_index_axis0(tup) - return result - except IndexingError: - pass + with suppress(IndexingError): + return self._handle_lowerdim_multi_index_axis0(tup) # this is a series with a multi-index specified a tuple of # selectors @@ -877,11 +870,9 @@ def __getitem__(self, key): if type(key) is tuple: key = tuple(com.apply_if_callable(x, self.obj) for x in key) if self._is_scalar_access(key): - try: - return self.obj._get_value(*key, takeable=self._takeable) - except (KeyError, IndexError, AttributeError): + with suppress(KeyError, IndexError, AttributeError): # AttributeError for IntervalTree get_value - pass + return self.obj._get_value(*key, takeable=self._takeable) return self._getitem_tuple(key) else: # we by definition only have the 0th axis @@ -1052,10 +1043,8 @@ def _getitem_iterable(self, key, axis: int): ) def _getitem_tuple(self, tup: Tuple): - try: + with suppress(IndexingError): return self._getitem_lowerdim(tup) - except IndexingError: - pass # no multi-index, so validate all of the indexers self._has_valid_tuple(tup) @@ -1082,7 +1071,7 @@ def _handle_lowerdim_multi_index_axis0(self, tup: Tuple): except KeyError as ek: # raise KeyError if number of indexers match # else IndexingError will be raised - if len(tup) <= self.obj.index.nlevels and len(tup) > self.ndim: + if self.ndim < len(tup) <= self.obj.index.nlevels: raise ek raise IndexingError("No label returned") @@ -1295,8 +1284,6 @@ def _validate_read_indexer( If at least one key was requested but none was found, and raise_missing=True. """ - ax = self.obj._get_axis(axis) - if len(key) == 0: return @@ -1309,6 +1296,8 @@ def _validate_read_indexer( axis_name = self.obj._get_axis_name(axis) raise KeyError(f"None of [{key}] are in the [{axis_name}]") + ax = self.obj._get_axis(axis) + # We (temporarily) allow for some missing keys with .loc, except in # some cases (e.g. setting) in which "raise_missing" will be False if raise_missing: @@ -1391,21 +1380,22 @@ def _has_valid_setitem_indexer(self, indexer) -> bool: """ if isinstance(indexer, dict): raise IndexError("iloc cannot enlarge its target object") - else: - if not isinstance(indexer, tuple): - indexer = _tuplify(self.ndim, indexer) - for ax, i in zip(self.obj.axes, indexer): - if isinstance(i, slice): - # should check the stop slice? - pass - elif is_list_like_indexer(i): - # should check the elements? - pass - elif is_integer(i): - if i >= len(ax): - raise IndexError("iloc cannot enlarge its target object") - elif isinstance(i, dict): + + if not isinstance(indexer, tuple): + indexer = _tuplify(self.ndim, indexer) + + for ax, i in zip(self.obj.axes, indexer): + if isinstance(i, slice): + # should check the stop slice? + pass + elif is_list_like_indexer(i): + # should check the elements? + pass + elif is_integer(i): + if i >= len(ax): raise IndexError("iloc cannot enlarge its target object") + elif isinstance(i, dict): + raise IndexError("iloc cannot enlarge its target object") return True @@ -1453,10 +1443,8 @@ def _validate_integer(self, key: int, axis: int) -> None: def _getitem_tuple(self, tup: Tuple): self._has_valid_tuple(tup) - try: + with suppress(IndexingError): return self._getitem_lowerdim(tup) - except IndexingError: - pass return self._getitem_tuple_same_dim(tup) @@ -2286,15 +2274,10 @@ def maybe_convert_ix(*args): """ We likely want to take the cross-product. """ - ixify = True for arg in args: if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)): - ixify = False - - if ixify: - return np.ix_(*args) - else: - return args + return args + return np.ix_(*args) def is_nested_tuple(tup, labels) -> bool:
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Slight clean-up of ``pandas/core/indexing.py``. - Use ``suppress`` instead of ``try/except/pass`` (starting from Python 3.7) - Slight rearrangement of statements - Extract method ``_validate_key_length``
https://api.github.com/repos/pandas-dev/pandas/pulls/36713
2020-09-28T18:27:50Z
2020-10-07T03:23:20Z
2020-10-07T03:23:20Z
2020-10-07T09:46:13Z
Fix small typo in timedeltas error message
diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 791d5095283ba..372eac29bad9e 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -93,7 +93,7 @@ def to_timedelta(arg, unit=None, errors="raise"): unit = parse_timedelta_unit(unit) if errors not in ("ignore", "raise", "coerce"): - raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'}") + raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'.") if unit in {"Y", "y", "M"}: raise ValueError(
Small typo fix - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/36711
2020-09-28T18:10:00Z
2020-09-28T23:07:51Z
2020-09-28T23:07:51Z
2020-09-28T23:07:59Z
BUG: df.diff axis=1 mixed dtypes
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9b2540a1ce043..79a5d6cb458e0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -100,6 +100,7 @@ is_dict_like, is_dtype_equal, is_extension_array_dtype, + is_float, is_float_dtype, is_hashable, is_integer, @@ -4458,7 +4459,34 @@ def _replace_columnwise( return res.__finalize__(self) @doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"]) - def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> DataFrame: + def shift( + self, periods=1, freq=None, axis=0, fill_value=lib.no_default + ) -> DataFrame: + axis = self._get_axis_number(axis) + + ncols = len(self.columns) + if axis == 1 and periods != 0 and fill_value is lib.no_default and ncols > 0: + # We will infer fill_value to match the closest column + + if periods > 0: + result = self.iloc[:, :-periods] + for col in range(min(ncols, abs(periods))): + # TODO(EA2D): doing this in a loop unnecessary with 2D EAs + # Define filler inside loop so we get a copy + filler = self.iloc[:, 0].shift(len(self)) + result.insert(0, col, filler, allow_duplicates=True) + else: + result = self.iloc[:, -periods:] + for col in range(min(ncols, abs(periods))): + # Define filler inside loop so we get a copy + filler = self.iloc[:, -1].shift(len(self)) + result.insert( + len(result.columns), col, filler, allow_duplicates=True + ) + + result.columns = self.columns.copy() + return result + return super().shift( periods=periods, freq=freq, axis=axis, fill_value=fill_value ) @@ -7208,13 +7236,13 @@ def melt( Difference with previous column >>> df.diff(axis=1) - a b c - 0 NaN 0.0 0.0 - 1 NaN -1.0 3.0 - 2 NaN -1.0 7.0 - 3 NaN -1.0 13.0 - 4 NaN 0.0 20.0 - 5 NaN 2.0 28.0 + a b c + 0 NaN 0 0 + 1 NaN -1 3 + 2 NaN -1 7 + 3 NaN -1 13 + 4 NaN 0 20 + 5 NaN 2 28 Difference with 3rd previous row @@ -7248,12 +7276,15 @@ def melt( ), ) def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: + if not isinstance(periods, int): + if not (is_float(periods) and periods.is_integer()): + raise ValueError("periods must be an integer") + periods = int(periods) bm_axis = self._get_block_manager_axis(axis) - self._consolidate_inplace() if bm_axis == 0 and periods != 0: - return self.T.diff(periods, axis=0).T + return self - self.shift(periods, axis=axis) # type: ignore[operator] new_data = self._mgr.diff(n=periods, axis=bm_axis) return self._constructor(new_data) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6f0aa70625c1d..60cf2a8998fc6 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9244,11 +9244,11 @@ def shift( >>> df.shift(periods=1, axis="columns") Col1 Col2 Col3 - 2020-01-01 NaN 10.0 13.0 - 2020-01-02 NaN 20.0 23.0 - 2020-01-03 NaN 15.0 18.0 - 2020-01-04 NaN 30.0 33.0 - 2020-01-05 NaN 45.0 48.0 + 2020-01-01 NaN 10 13 + 2020-01-02 NaN 20 23 + 2020-01-03 NaN 15 18 + 2020-01-04 NaN 30 33 + 2020-01-05 NaN 45 48 >>> df.shift(periods=3, fill_value=0) Col1 Col2 Col3 diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index f2480adce89b4..a7a9a77bab3bc 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -557,8 +557,12 @@ def interpolate(self, **kwargs) -> "BlockManager": return self.apply("interpolate", **kwargs) def shift(self, periods: int, axis: int, fill_value) -> "BlockManager": + if fill_value is lib.no_default: + fill_value = None + if axis == 0 and self.ndim == 2 and self.nblocks > 1: # GH#35488 we need to watch out for multi-block cases + # We only get here with fill_value not-lib.no_default ncols = self.shape[0] if periods > 0: indexer = [-1] * periods + list(range(ncols - periods)) diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 83a5f43c2a340..e2161013c0166 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -444,7 +444,7 @@ def wide_to_long( 8 3 3 2.1 2.9 >>> l = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', - ... sep='_', suffix='\w+') + ... sep='_', suffix=r'\w+') >>> l ... # doctest: +NORMALIZE_WHITESPACE ht diff --git a/pandas/tests/frame/methods/test_diff.py b/pandas/tests/frame/methods/test_diff.py index 0486fb2d588b6..42586c14092f2 100644 --- a/pandas/tests/frame/methods/test_diff.py +++ b/pandas/tests/frame/methods/test_diff.py @@ -7,6 +7,11 @@ class TestDataFrameDiff: + def test_diff_requires_integer(self): + df = pd.DataFrame(np.random.randn(2, 2)) + with pytest.raises(ValueError, match="periods must be an integer"): + df.diff(1.5) + def test_diff(self, datetime_frame): the_diff = datetime_frame.diff(1) @@ -31,9 +36,7 @@ def test_diff(self, datetime_frame): df = pd.DataFrame({"y": pd.Series([2]), "z": pd.Series([3])}) df.insert(0, "x", 1) result = df.diff(axis=1) - expected = pd.DataFrame( - {"x": np.nan, "y": pd.Series(1), "z": pd.Series(1)} - ).astype("float64") + expected = pd.DataFrame({"x": np.nan, "y": pd.Series(1), "z": pd.Series(1)}) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("tz", [None, "UTC"]) @@ -116,19 +119,13 @@ def test_diff_axis(self): df.diff(axis=0), DataFrame([[np.nan, np.nan], [2.0, 2.0]]) ) - @pytest.mark.xfail( - reason="GH#32995 needs to operate column-wise or do inference", - raises=AssertionError, - ) def test_diff_period(self): # GH#32995 Don't pass an incorrect axis - # TODO(EA2D): this bug wouldn't have happened with 2D EA pi = pd.date_range("2016-01-01", periods=3).to_period("D") df = pd.DataFrame({"A": pi}) result = df.diff(1, axis=1) - # TODO: should we make Block.diff do type inference? or maybe algos.diff? expected = (df - pd.NaT).astype(object) tm.assert_frame_equal(result, expected) @@ -141,6 +138,14 @@ def test_diff_axis1_mixed_dtypes(self): result = df.diff(axis=1) tm.assert_frame_equal(result, expected) + # GH#21437 mixed-float-dtypes + df = pd.DataFrame( + {"a": np.arange(3, dtype="float32"), "b": np.arange(3, dtype="float64")} + ) + result = df.diff(axis=1) + expected = pd.DataFrame({"a": df["a"] * np.nan, "b": df["b"] * 0}) + tm.assert_frame_equal(result, expected) + def test_diff_axis1_mixed_dtypes_large_periods(self): # GH#32995 operate column-wise when we have mixed dtypes and axis=1 df = pd.DataFrame({"A": range(3), "B": 2 * np.arange(3, dtype=np.float64)})
- [ ] 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/36710
2020-09-28T18:00:46Z
2020-10-07T03:29:17Z
2020-10-07T03:29:17Z
2020-10-07T03:31:26Z
Fix delim_whitespace behavior in read_table, read_csv
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index afc0046ec6822..ae4d5ea692066 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -416,6 +416,7 @@ I/O - Bug in :meth:`read_csv` with ``engine='python'`` truncating data if multiple items present in first row and first element started with BOM (:issue:`36343`) - Removed ``private_key`` and ``verbose`` from :func:`read_gbq` as they are no longer supported in ``pandas-gbq`` (:issue:`34654`, :issue:`30200`) - Bumped minimum pytables version to 3.5.1 to avoid a ``ValueError`` in :meth:`read_hdf` (:issue:`24839`) +- Bug in :func:`read_table` and :func:`read_csv` when ``delim_whitespace=True`` and ``sep=default`` (:issue:`36583`) - Bug in :meth:`read_parquet` with fixed offset timezones. String representation of timezones was not recognized (:issue:`35997`, :issue:`36004`) Plotting diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index dd3588faedf7a..ede4fdc5e1d8b 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -542,7 +542,7 @@ def _read(filepath_or_buffer: FilePathOrBuffer, kwds): ) def read_csv( filepath_or_buffer: FilePathOrBuffer, - sep=",", + sep=lib.no_default, delimiter=None, # Column and Index Locations and Names header="infer", @@ -600,93 +600,14 @@ def read_csv( float_precision=None, storage_options: StorageOptions = None, ): - # gh-23761 - # - # When a dialect is passed, it overrides any of the overlapping - # parameters passed in directly. We don't want to warn if the - # default parameters were passed in (since it probably means - # that the user didn't pass them in explicitly in the first place). - # - # "delimiter" is the annoying corner case because we alias it to - # "sep" before doing comparison to the dialect values later on. - # Thus, we need a flag to indicate that we need to "override" - # the comparison to dialect values by checking if default values - # for BOTH "delimiter" and "sep" were provided. - default_sep = "," - - if dialect is not None: - sep_override = delimiter is None and sep == default_sep - kwds = dict(sep_override=sep_override) - else: - kwds = dict() - - # Alias sep -> delimiter. - if delimiter is None: - delimiter = sep + kwds = locals() + del kwds["filepath_or_buffer"] + del kwds["sep"] - if delim_whitespace and delimiter != default_sep: - raise ValueError( - "Specified a delimiter with both sep and " - "delim_whitespace=True; you can only specify one." - ) - - if engine is not None: - engine_specified = True - else: - engine = "c" - engine_specified = False - - kwds.update( - delimiter=delimiter, - engine=engine, - dialect=dialect, - compression=compression, - engine_specified=engine_specified, - doublequote=doublequote, - escapechar=escapechar, - quotechar=quotechar, - quoting=quoting, - skipinitialspace=skipinitialspace, - lineterminator=lineterminator, - header=header, - index_col=index_col, - names=names, - prefix=prefix, - skiprows=skiprows, - skipfooter=skipfooter, - na_values=na_values, - true_values=true_values, - false_values=false_values, - keep_default_na=keep_default_na, - thousands=thousands, - comment=comment, - decimal=decimal, - parse_dates=parse_dates, - keep_date_col=keep_date_col, - dayfirst=dayfirst, - date_parser=date_parser, - cache_dates=cache_dates, - nrows=nrows, - iterator=iterator, - chunksize=chunksize, - converters=converters, - dtype=dtype, - usecols=usecols, - verbose=verbose, - encoding=encoding, - squeeze=squeeze, - memory_map=memory_map, - float_precision=float_precision, - na_filter=na_filter, - delim_whitespace=delim_whitespace, - warn_bad_lines=warn_bad_lines, - error_bad_lines=error_bad_lines, - low_memory=low_memory, - mangle_dupe_cols=mangle_dupe_cols, - infer_datetime_format=infer_datetime_format, - skip_blank_lines=skip_blank_lines, - storage_options=storage_options, + kwds_defaults = _check_defaults_read( + dialect, delimiter, delim_whitespace, engine, sep, defaults={"delimiter": ","} ) + kwds.update(kwds_defaults) return _read(filepath_or_buffer, kwds) @@ -700,7 +621,7 @@ def read_csv( ) def read_table( filepath_or_buffer: FilePathOrBuffer, - sep="\t", + sep=lib.no_default, delimiter=None, # Column and Index Locations and Names header="infer", @@ -757,17 +678,16 @@ def read_table( memory_map=False, float_precision=None, ): - # TODO: validation duplicated in read_csv - if delim_whitespace and (delimiter is not None or sep != "\t"): - raise ValueError( - "Specified a delimiter with both sep and " - "delim_whitespace=True; you can only specify one." - ) - if delim_whitespace: - # In this case sep is not used so we set it to the read_csv - # default to avoid a ValueError - sep = "," - return read_csv(**locals()) + kwds = locals() + del kwds["filepath_or_buffer"] + del kwds["sep"] + + kwds_defaults = _check_defaults_read( + dialect, delimiter, delim_whitespace, engine, sep, defaults={"delimiter": "\t"} + ) + kwds.update(kwds_defaults) + + return _read(filepath_or_buffer, kwds) def read_fwf( @@ -3782,3 +3702,92 @@ def _make_reader(self, f): self.skiprows, self.infer_nrows, ) + + +def _check_defaults_read( + dialect: Union[str, csv.Dialect], + delimiter: Union[str, object], + delim_whitespace: bool, + engine: str, + sep: Union[str, object], + defaults: Dict[str, Any], +): + """Check default values of input parameters of read_csv, read_table. + + Parameters + ---------- + dialect : str or csv.Dialect + If provided, this parameter will override values (default or not) for the + following parameters: `delimiter`, `doublequote`, `escapechar`, + `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to + override values, a ParserWarning will be issued. See csv.Dialect + documentation for more details. + delimiter : str or object + Alias for sep. + delim_whitespace : bool + Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be + used as the sep. Equivalent to setting ``sep='\\s+'``. If this option + is set to True, nothing should be passed in for the ``delimiter`` + parameter. + engine : {{'c', 'python'}} + Parser engine to use. The C engine is faster while the python engine is + currently more feature-complete. + sep : str or object + A delimiter provided by the user (str) or a sentinel value, i.e. + pandas._libs.lib.no_default. + defaults: dict + Default values of input parameters. + + Returns + ------- + kwds : dict + Input parameters with correct values. + + Raises + ------ + ValueError : If a delimiter was specified with ``sep`` (or ``delimiter``) and + ``delim_whitespace=True``. + """ + # fix types for sep, delimiter to Union(str, Any) + delim_default = defaults["delimiter"] + kwds: Dict[str, Any] = {} + # gh-23761 + # + # When a dialect is passed, it overrides any of the overlapping + # parameters passed in directly. We don't want to warn if the + # default parameters were passed in (since it probably means + # that the user didn't pass them in explicitly in the first place). + # + # "delimiter" is the annoying corner case because we alias it to + # "sep" before doing comparison to the dialect values later on. + # Thus, we need a flag to indicate that we need to "override" + # the comparison to dialect values by checking if default values + # for BOTH "delimiter" and "sep" were provided. + if dialect is not None: + kwds["sep_override"] = (delimiter is None) and ( + sep is lib.no_default or sep == delim_default + ) + + # Alias sep -> delimiter. + if delimiter is None: + delimiter = sep + + if delim_whitespace and (delimiter is not lib.no_default): + raise ValueError( + "Specified a delimiter with both sep and " + "delim_whitespace=True; you can only specify one." + ) + + if delimiter is lib.no_default: + # assign default separator value + kwds["delimiter"] = delim_default + else: + kwds["delimiter"] = delimiter + + if engine is not None: + kwds["engine_specified"] = True + else: + kwds["engine"] = "c" + kwds["engine_specified"] = False + + return kwds diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 78c2f2bce5a02..a6a9e5c5610f2 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -2211,7 +2211,8 @@ def test_read_table_delim_whitespace_default_sep(all_parsers): tm.assert_frame_equal(result, expected) -def test_read_table_delim_whitespace_non_default_sep(all_parsers): +@pytest.mark.parametrize("delimiter", [",", "\t"]) +def test_read_csv_delim_whitespace_non_default_sep(all_parsers, delimiter): # GH: 35958 f = StringIO("a b c\n1 -2 -3\n4 5 6") parser = all_parsers @@ -2220,4 +2221,23 @@ def test_read_table_delim_whitespace_non_default_sep(all_parsers): "delim_whitespace=True; you can only specify one." ) with pytest.raises(ValueError, match=msg): - parser.read_table(f, delim_whitespace=True, sep=",") + parser.read_csv(f, delim_whitespace=True, sep=delimiter) + + with pytest.raises(ValueError, match=msg): + parser.read_csv(f, delim_whitespace=True, delimiter=delimiter) + + +@pytest.mark.parametrize("delimiter", [",", "\t"]) +def test_read_table_delim_whitespace_non_default_sep(all_parsers, delimiter): + # GH: 35958 + f = StringIO("a b c\n1 -2 -3\n4 5 6") + parser = all_parsers + msg = ( + "Specified a delimiter with both sep and " + "delim_whitespace=True; you can only specify one." + ) + with pytest.raises(ValueError, match=msg): + parser.read_table(f, delim_whitespace=True, sep=delimiter) + + with pytest.raises(ValueError, match=msg): + parser.read_table(f, delim_whitespace=True, delimiter=delimiter)
- [x] closes #36583 - [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/36709
2020-09-28T17:22:46Z
2020-10-08T00:46:51Z
2020-10-08T00:46:50Z
2020-10-08T00:46:57Z
CI, CLN remove unnecessary noqa statements, add CI check
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7f669ee77c3eb..d0c9f12614d0d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -43,3 +43,7 @@ repos: entry: python -m scripts.generate_pip_deps_from_conda files: ^(environment.yml|requirements-dev.txt)$ pass_filenames: false +- repo: https://github.com/asottile/yesqa + rev: v1.2.2 + hooks: + - id: yesqa diff --git a/asv_bench/benchmarks/pandas_vb_common.py b/asv_bench/benchmarks/pandas_vb_common.py index 23286343d7367..7bd4d639633b3 100644 --- a/asv_bench/benchmarks/pandas_vb_common.py +++ b/asv_bench/benchmarks/pandas_vb_common.py @@ -15,7 +15,7 @@ # Compatibility import for the testing module try: - import pandas._testing as tm # noqa + import pandas._testing as tm except ImportError: import pandas.util.testing as tm # noqa diff --git a/asv_bench/benchmarks/tslibs/offsets.py b/asv_bench/benchmarks/tslibs/offsets.py index fc1efe63307b2..0aea8332398b1 100644 --- a/asv_bench/benchmarks/tslibs/offsets.py +++ b/asv_bench/benchmarks/tslibs/offsets.py @@ -9,7 +9,7 @@ from pandas import offsets try: - import pandas.tseries.holiday # noqa + import pandas.tseries.holiday except ImportError: pass diff --git a/doc/source/conf.py b/doc/source/conf.py index 04540f7e6ec95..15e7a13ff5b72 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -146,7 +146,7 @@ # built documents. # # The short X.Y version. -import pandas # noqa: E402 isort:skip +import pandas # isort:skip # version = '%s r%s' % (pandas.__version__, svn_version()) version = str(pandas.__version__) @@ -441,14 +441,14 @@ # Add custom Documenter to handle attributes/methods of an AccessorProperty # eg pandas.Series.str and pandas.Series.dt (see GH9322) -import sphinx # noqa: E402 isort:skip -from sphinx.util import rpartition # noqa: E402 isort:skip -from sphinx.ext.autodoc import ( # noqa: E402 isort:skip +import sphinx # isort:skip +from sphinx.util import rpartition # isort:skip +from sphinx.ext.autodoc import ( # isort:skip AttributeDocumenter, Documenter, MethodDocumenter, ) -from sphinx.ext.autosummary import Autosummary # noqa: E402 isort:skip +from sphinx.ext.autosummary import Autosummary # isort:skip class AccessorDocumenter(MethodDocumenter): diff --git a/pandas/_typing.py b/pandas/_typing.py index 16d81c0d39cbe..7678d1bf12d8b 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -27,16 +27,16 @@ # and use a string literal forward reference to it in subsequent types # https://mypy.readthedocs.io/en/latest/common_issues.html#import-cycles if TYPE_CHECKING: - from pandas._libs import Period, Timedelta, Timestamp # noqa: F401 + from pandas._libs import Period, Timedelta, Timestamp - from pandas.core.dtypes.dtypes import ExtensionDtype # noqa: F401 + from pandas.core.dtypes.dtypes import ExtensionDtype - from pandas import Interval # noqa: F401 + from pandas import Interval from pandas.core.arrays.base import ExtensionArray # noqa: F401 - from pandas.core.frame import DataFrame # noqa: F401 + from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame # noqa: F401 - from pandas.core.indexes.base import Index # noqa: F401 - from pandas.core.series import Series # noqa: F401 + from pandas.core.indexes.base import Index + from pandas.core.series import Series # array-like diff --git a/pandas/api/types/__init__.py b/pandas/api/types/__init__.py index 3495b493707c2..fb1abdd5b18ec 100644 --- a/pandas/api/types/__init__.py +++ b/pandas/api/types/__init__.py @@ -4,7 +4,7 @@ from pandas._libs.lib import infer_dtype -from pandas.core.dtypes.api import * # noqa: F403, F401 +from pandas.core.dtypes.api import * # noqa: F401, F403 from pandas.core.dtypes.concat import union_categoricals from pandas.core.dtypes.dtypes import ( CategoricalDtype, diff --git a/pandas/conftest.py b/pandas/conftest.py index 3865d287c6905..5ac5e3670f69f 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1226,7 +1226,7 @@ def ip(): from IPython.core.interactiveshell import InteractiveShell # GH#35711 make sure sqlite history file handle is not leaked - from traitlets.config import Config # noqa: F401 isort:skip + from traitlets.config import Config # isort:skip c = Config() c.HistoryManager.hist_file = ":memory:" diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index c3710196a8611..33659fe2f397d 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -34,7 +34,7 @@ from .masked import BaseMaskedArray, BaseMaskedDtype if TYPE_CHECKING: - import pyarrow # noqa: F401 + import pyarrow class FloatingDtype(BaseMaskedDtype): @@ -82,7 +82,7 @@ def __from_arrow__( """ Construct FloatingArray from pyarrow Array/ChunkedArray. """ - import pyarrow # noqa: F811 + import pyarrow from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask diff --git a/pandas/io/common.py b/pandas/io/common.py index f177e08ac0089..c147ae9fd0aa8 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -53,7 +53,7 @@ if TYPE_CHECKING: - from io import IOBase # noqa: F401 + from io import IOBase def is_url(url) -> bool: diff --git a/pandas/io/formats/console.py b/pandas/io/formats/console.py index bed29e1fd4792..50e69f7e8b435 100644 --- a/pandas/io/formats/console.py +++ b/pandas/io/formats/console.py @@ -69,7 +69,7 @@ def check_main(): return not hasattr(main, "__file__") or get_option("mode.sim_interactive") try: - return __IPYTHON__ or check_main() # noqa + return __IPYTHON__ or check_main() except NameError: return check_main() @@ -83,7 +83,7 @@ def in_ipython_frontend(): bool """ try: - ip = get_ipython() # noqa + ip = get_ipython() return "zmq" in str(type(ip)).lower() except NameError: pass diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py index e8e41d4325103..5c6ce23707781 100644 --- a/pandas/io/formats/info.py +++ b/pandas/io/formats/info.py @@ -12,7 +12,7 @@ from pandas.io.formats.printing import pprint_thing if TYPE_CHECKING: - from pandas.core.series import Series # noqa: F401 + from pandas.core.series import Series def _put_str(s: Union[str, Dtype], space: int) -> str: diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py index 84146a5d732e1..2b4c86b3c4406 100644 --- a/pandas/io/json/_table_schema.py +++ b/pandas/io/json/_table_schema.py @@ -26,7 +26,7 @@ import pandas.core.common as com if TYPE_CHECKING: - from pandas.core.indexes.multi import MultiIndex # noqa: F401 + from pandas.core.indexes.multi import MultiIndex loads = json.loads diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d62480baed71e..ef9a4526a3fab 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -57,7 +57,7 @@ from pandas.io.formats.printing import adjoin, pprint_thing if TYPE_CHECKING: - from tables import Col, File, Node # noqa:F401 + from tables import Col, File, Node # versioning attribute diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py index 893a6286f74d4..caf53b5be971a 100644 --- a/pandas/io/sas/sasreader.py +++ b/pandas/io/sas/sasreader.py @@ -9,7 +9,7 @@ from pandas.io.common import get_filepath_or_buffer, stringify_path if TYPE_CHECKING: - from pandas import DataFrame # noqa: F401 + from pandas import DataFrame # TODO(PY38): replace with Protocol in Python 3.8 diff --git a/pandas/plotting/_matplotlib/__init__.py b/pandas/plotting/_matplotlib/__init__.py index 27b1d55fe1bd6..33011e6a66cac 100644 --- a/pandas/plotting/_matplotlib/__init__.py +++ b/pandas/plotting/_matplotlib/__init__.py @@ -29,7 +29,7 @@ from pandas.plotting._matplotlib.tools import table if TYPE_CHECKING: - from pandas.plotting._matplotlib.core import MPLPlot # noqa: F401 + from pandas.plotting._matplotlib.core import MPLPlot PLOT_CLASSES: Dict[str, Type["MPLPlot"]] = { "line": LinePlot, diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index f8faac6a6a026..64cd43c230f28 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -26,7 +26,7 @@ if TYPE_CHECKING: from matplotlib.axes import Axes - from pandas import Index, Series # noqa:F401 + from pandas import Index, Series # --------------------------------------------------------------------- # Plotting functions and monkey patches diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index aed0c360fc7ce..832957dd73ec7 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -17,7 +17,7 @@ if TYPE_CHECKING: from matplotlib.axes import Axes from matplotlib.axis import Axis - from matplotlib.lines import Line2D # noqa:F401 + from matplotlib.lines import Line2D from matplotlib.table import Table diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index e200f13652a84..1eef86980f974 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -213,7 +213,7 @@ def test_constructor(self): # - when the first is an integer dtype and the second is not # - when the resulting codes are all -1/NaN with tm.assert_produces_warning(None): - c_old = Categorical([0, 1, 2, 0, 1, 2], categories=["a", "b", "c"]) # noqa + c_old = Categorical([0, 1, 2, 0, 1, 2], categories=["a", "b", "c"]) with tm.assert_produces_warning(None): c_old = Categorical([0, 1, 2, 0, 1, 2], categories=[3, 4, 5]) # noqa diff --git a/pandas/tests/arrays/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py index 735b062eae80e..e23fbb16190ea 100644 --- a/pandas/tests/arrays/categorical/test_repr.py +++ b/pandas/tests/arrays/categorical/test_repr.py @@ -320,7 +320,7 @@ def test_categorical_repr_timedelta(self): c = Categorical(idx.append(idx), categories=idx) exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days] -Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa +Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" assert repr(c) == exp @@ -347,13 +347,13 @@ def test_categorical_repr_timedelta_ordered(self): idx = timedelta_range("1 days", periods=5) c = Categorical(idx, ordered=True) exp = """[1 days, 2 days, 3 days, 4 days, 5 days] -Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa +Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" assert repr(c) == exp c = Categorical(idx.append(idx), categories=idx, ordered=True) exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days] -Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa +Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" assert repr(c) == exp diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py index 2d6e657debdb2..517dc4a2c3d8b 100644 --- a/pandas/tests/arrays/sparse/test_libsparse.py +++ b/pandas/tests/arrays/sparse/test_libsparse.py @@ -452,7 +452,7 @@ def test_check_integrity(self): # 0-length OK # TODO: index variables are not used...is that right? - index = BlockIndex(0, locs, lengths) # noqa + index = BlockIndex(0, locs, lengths) # also OK even though empty index = BlockIndex(1, locs, lengths) # noqa diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index cca64a6bf487c..bce1695b56a99 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -48,7 +48,7 @@ ) for engine in ENGINES ) -) # noqa +) def engine(request): return request.param @@ -1885,7 +1885,7 @@ def test_global_scope(self, engine, parser): ) def test_no_new_locals(self, engine, parser): - x = 1 # noqa + x = 1 lcls = locals().copy() pd.eval("x + 1", local_dict=lcls, engine=engine, parser=parser) lcls2 = locals().copy() @@ -1995,8 +1995,8 @@ def test_bool_ops_fails_on_scalars(lhs, cmp, rhs, engine, parser): gen = {int: lambda: np.random.randint(10), float: np.random.randn} mid = gen[lhs]() # noqa - lhs = gen[lhs]() # noqa - rhs = gen[rhs]() # noqa + lhs = gen[lhs]() + rhs = gen[rhs]() ex1 = f"lhs {cmp} mid {cmp} rhs" ex2 = f"lhs {cmp} mid and mid {cmp} rhs" diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index e40a12f7bc8d1..c6c54ccb357d5 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1495,7 +1495,7 @@ def test_nan_to_nat_conversions(): @td.skip_if_no_scipy @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") -def test_is_scipy_sparse(spmatrix): # noqa: F811 +def test_is_scipy_sparse(spmatrix): assert is_scipy_sparse(spmatrix([[0, 1]])) assert not is_scipy_sparse(np.array([1])) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index b947be705a329..507d01f5b900c 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1091,7 +1091,7 @@ def test_getitem_setitem_float_labels(self): cp.iloc[1.0:5] = 0 with pytest.raises(TypeError, match=msg): - result = cp.iloc[1.0:5] == 0 # noqa + result = cp.iloc[1.0:5] == 0 assert result.values.all() assert (cp.iloc[0:1] == df.iloc[0:1]).values.all() diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 4a85da72bc8b1..1e404c572dd51 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -78,7 +78,7 @@ def test_consolidate_inplace(self, float_frame): def test_values_consolidate(self, float_frame): float_frame["E"] = 7.0 assert not float_frame._mgr.is_consolidated() - _ = float_frame.values # noqa + _ = float_frame.values assert float_frame._mgr.is_consolidated() def test_modify_values(self, float_frame): diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 2994482fa5139..024403189409c 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -633,9 +633,7 @@ def test_chained_cmp_and_in(self): res = df.query( "a < b < c and a not in b not in c", engine=engine, parser=parser ) - ind = ( - (df.a < df.b) & (df.b < df.c) & ~df.b.isin(df.a) & ~df.c.isin(df.b) - ) # noqa + ind = (df.a < df.b) & (df.b < df.c) & ~df.b.isin(df.a) & ~df.c.isin(df.b) expec = df[ind] tm.assert_frame_equal(res, expec) diff --git a/pandas/tests/indexes/categorical/test_formats.py b/pandas/tests/indexes/categorical/test_formats.py index a5607224f6448..45089fd876ffc 100644 --- a/pandas/tests/indexes/categorical/test_formats.py +++ b/pandas/tests/indexes/categorical/test_formats.py @@ -18,7 +18,7 @@ def test_string_categorical_index_repr(self): expected = """CategoricalIndex(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], - categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" # noqa + categories=['a', 'bb', 'ccc'], ordered=False, dtype='category')""" assert repr(idx) == expected @@ -49,7 +49,7 @@ def test_string_categorical_index_repr(self): expected = """CategoricalIndex(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], - categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" assert repr(idx) == expected @@ -84,7 +84,7 @@ def test_string_categorical_index_repr(self): 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう'], - categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa + categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" assert repr(idx) == expected diff --git a/pandas/tests/indexes/multi/test_formats.py b/pandas/tests/indexes/multi/test_formats.py index 792dcf4c535e3..c1de7f79c2d2e 100644 --- a/pandas/tests/indexes/multi/test_formats.py +++ b/pandas/tests/indexes/multi/test_formats.py @@ -206,5 +206,5 @@ def test_tuple_width(self, wide_multi_index): ('abc', 10, '2000-01-01 00:33:17', '2000-01-01 00:33:17', ...), ('abc', 10, '2000-01-01 00:33:18', '2000-01-01 00:33:18', ...), ('abc', 10, '2000-01-01 00:33:19', '2000-01-01 00:33:19', ...)], - names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'], length=2000)""" # noqa + names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'], length=2000)""" assert result == expected diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py index 423bbed831b87..a1e5cc33ef2f6 100644 --- a/pandas/tests/indexes/multi/test_sorting.py +++ b/pandas/tests/indexes/multi/test_sorting.py @@ -119,7 +119,7 @@ def test_unsortedindex(): def test_unsortedindex_doc_examples(): - # https://pandas.pydata.org/pandas-docs/stable/advanced.html#sorting-a-multiindex # noqa + # https://pandas.pydata.org/pandas-docs/stable/advanced.html#sorting-a-multiindex dfm = DataFrame( {"jim": [0, 0, 1, 1], "joe": ["x", "x", "z", "y"], "jolie": np.random.rand(4)} ) diff --git a/pandas/tests/indexing/test_callable.py b/pandas/tests/indexing/test_callable.py index bf51c3e5d1695..b98c9a3df0438 100644 --- a/pandas/tests/indexing/test_callable.py +++ b/pandas/tests/indexing/test_callable.py @@ -17,11 +17,11 @@ def test_frame_loc_callable(self): res = df.loc[lambda x: x.A > 2] tm.assert_frame_equal(res, df.loc[df.A > 2]) - res = df.loc[lambda x: x.A > 2] # noqa: E231 - tm.assert_frame_equal(res, df.loc[df.A > 2]) # noqa: E231 + res = df.loc[lambda x: x.A > 2] + tm.assert_frame_equal(res, df.loc[df.A > 2]) - res = df.loc[lambda x: x.A > 2] # noqa: E231 - tm.assert_frame_equal(res, df.loc[df.A > 2]) # noqa: E231 + res = df.loc[lambda x: x.A > 2] + tm.assert_frame_equal(res, df.loc[df.A > 2]) res = df.loc[lambda x: x.B == "b", :] tm.assert_frame_equal(res, df.loc[df.B == "b", :]) @@ -90,8 +90,8 @@ def test_frame_loc_callable_labels(self): res = df.loc[lambda x: ["A", "C"]] tm.assert_frame_equal(res, df.loc[["A", "C"]]) - res = df.loc[lambda x: ["A", "C"]] # noqa: E231 - tm.assert_frame_equal(res, df.loc[["A", "C"]]) # noqa: E231 + res = df.loc[lambda x: ["A", "C"]] + tm.assert_frame_equal(res, df.loc[["A", "C"]]) res = df.loc[lambda x: ["A", "C"], :] tm.assert_frame_equal(res, df.loc[["A", "C"], :]) diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 8d66a16fc2b7a..476d75f7d239d 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -12,7 +12,7 @@ import pandas._testing as tm jinja2 = pytest.importorskip("jinja2") -from pandas.io.formats.style import Styler, _get_level_lengths # noqa # isort:skip +from pandas.io.formats.style import Styler, _get_level_lengths # isort:skip class TestStyler: diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 9278e64cc911f..822342113f62a 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -987,7 +987,7 @@ def test_round_trip_exception_(self): ], ) def test_url(self, field, dtype): - url = "https://api.github.com/repos/pandas-dev/pandas/issues?per_page=5" # noqa + url = "https://api.github.com/repos/pandas-dev/pandas/issues?per_page=5" result = read_json(url, convert_dates=True) assert result[field].dtype == dtype diff --git a/pandas/tests/io/parser/test_index_col.py b/pandas/tests/io/parser/test_index_col.py index 9f425168540ba..4d64f2bf411bd 100644 --- a/pandas/tests/io/parser/test_index_col.py +++ b/pandas/tests/io/parser/test_index_col.py @@ -21,7 +21,7 @@ def test_index_col_named(all_parsers, with_header): KORD3,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000 KORD4,19990127, 21:00:00, 21:18:00, -0.9900, 2.0100, 3.6000, 0.0000, 270.0000 KORD5,19990127, 22:00:00, 21:56:00, -0.5900, 1.7100, 5.1000, 0.0000, 290.0000 -KORD6,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000""" # noqa +KORD6,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000""" header = "ID,date,NominalTime,ActualTime,TDew,TAir,Windspeed,Precip,WindDir\n" if with_header: diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index ccb2efbd2c630..c1938db12a0bc 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -52,8 +52,8 @@ read_hdf, ) -from pandas.io import pytables as pytables # noqa: E402 isort:skip -from pandas.io.pytables import TableIterator # noqa: E402 isort:skip +from pandas.io import pytables as pytables # isort:skip +from pandas.io.pytables import TableIterator # isort:skip _default_compressor = "blosc" @@ -512,7 +512,7 @@ def check(mode): # context if mode in ["r", "r+"]: with pytest.raises(IOError): - with HDFStore(path, mode=mode) as store: # noqa + with HDFStore(path, mode=mode) as store: pass else: with HDFStore(path, mode=mode) as store: @@ -2350,7 +2350,7 @@ def test_same_name_scoping(self, setup_path): store.put("df", df, format="table") expected = df[df.index > pd.Timestamp("20130105")] - import datetime # noqa + import datetime result = store.select("df", "index>datetime.datetime(2013,1,5)") tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index c1e63f512b53e..cef5d28b8ccf0 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -9,7 +9,7 @@ import pandas as pd import pandas._testing as tm -from pandas.io.feather_format import read_feather, to_feather # noqa: E402 isort:skip +from pandas.io.feather_format import read_feather, to_feather # isort:skip pyarrow = pytest.importorskip("pyarrow") diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py index 9d179d983ceeb..65e174cd32e22 100644 --- a/pandas/tests/io/test_gcs.py +++ b/pandas/tests/io/test_gcs.py @@ -14,7 +14,7 @@ def gcs_buffer(monkeypatch): """Emulate GCS using a binary buffer.""" from fsspec import AbstractFileSystem, registry - registry.target.clear() # noqa # remove state + registry.target.clear() # remove state gcs_buffer = BytesIO() gcs_buffer.close = lambda: True @@ -33,7 +33,7 @@ def open(*args, **kwargs): def test_read_csv_gcs(gcs_buffer): from fsspec import registry - registry.target.clear() # noqa # remove state + registry.target.clear() # remove state df1 = DataFrame( { @@ -55,7 +55,7 @@ def test_read_csv_gcs(gcs_buffer): def test_to_csv_gcs(gcs_buffer): from fsspec import registry - registry.target.clear() # noqa # remove state + registry.target.clear() # remove state df1 = DataFrame( { @@ -84,7 +84,7 @@ def test_to_csv_compression_encoding_gcs(gcs_buffer, compression_only, encoding) """ from fsspec import registry - registry.target.clear() # noqa # remove state + registry.target.clear() # remove state df = tm.makeDataFrame() # reference of compressed and encoded file @@ -120,7 +120,7 @@ def test_to_parquet_gcs_new_file(monkeypatch, tmpdir): """Regression test for writing to a not-yet-existent GCS Parquet file.""" from fsspec import AbstractFileSystem, registry - registry.target.clear() # noqa # remove state + registry.target.clear() # remove state df1 = DataFrame( { "int": [1, 3], diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index b7c8ca7e0c49f..f7b25f8c0eeac 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -24,14 +24,14 @@ ) try: - import pyarrow # noqa + import pyarrow _HAVE_PYARROW = True except ImportError: _HAVE_PYARROW = False try: - import fastparquet # noqa + import fastparquet _HAVE_FASTPARQUET = True except ImportError: @@ -818,7 +818,7 @@ def test_partition_cols_supported(self, fp, df_full): compression=None, ) assert os.path.exists(path) - import fastparquet # noqa: F811 + import fastparquet actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 2 @@ -835,7 +835,7 @@ def test_partition_cols_string(self, fp, df_full): compression=None, ) assert os.path.exists(path) - import fastparquet # noqa: F811 + import fastparquet actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 1 @@ -852,7 +852,7 @@ def test_partition_on_supported(self, fp, df_full): partition_on=partition_cols, ) assert os.path.exists(path) - import fastparquet # noqa: F811 + import fastparquet actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 2 diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index ca4c2bdcc2fe1..bdb86d2dd846f 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -3448,7 +3448,7 @@ def test_xlabel_ylabel_dataframe_subplots( def _generate_4_axes_via_gridspec(): import matplotlib as mpl - import matplotlib.gridspec # noqa + import matplotlib.gridspec import matplotlib.pyplot as plt gs = mpl.gridspec.GridSpec(2, 2) diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index d1c3ad508d877..583110cc4ba70 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -135,7 +135,7 @@ def test_constructor_with_stringoffset(self): # converted to Chicago tz result = Timestamp("2013-11-01 00:00:00-0500", tz="America/Chicago") assert result.value == Timestamp("2013-11-01 05:00").value - expected = "Timestamp('2013-11-01 00:00:00-0500', tz='America/Chicago')" # noqa + expected = "Timestamp('2013-11-01 00:00:00-0500', tz='America/Chicago')" assert repr(result) == expected assert result == eval(repr(result)) diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index 3aaecc37df56c..32e1220f83f40 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -486,7 +486,7 @@ def test_categorical_series_repr_timedelta_ordered(self): 3 4 days 4 5 days dtype: category -Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa +Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" assert repr(s) == exp diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index f7f3f1fa0c13d..17d7527a2b687 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -21,7 +21,7 @@ def test_get_callable_name(): def fn(x): return x - lambda_ = lambda x: x # noqa: E731 + lambda_ = lambda x: x part1 = partial(fn) part2 = partial(part1) diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index b32c5e91af295..c03e8e26952e5 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -20,7 +20,7 @@ def import_module(name): try: return importlib.import_module(name) - except ModuleNotFoundError: # noqa + except ModuleNotFoundError: pytest.skip(f"skipping as {name} not available") @@ -117,7 +117,7 @@ def test_pandas_gbq(df): @tm.network def test_pandas_datareader(): - pandas_datareader = import_module("pandas_datareader") # noqa + pandas_datareader = import_module("pandas_datareader") pandas_datareader.DataReader("F", "quandl", "2017-01-01", "2017-02-01") @@ -125,7 +125,7 @@ def test_pandas_datareader(): @pytest.mark.filterwarnings("ignore:can't resolve:ImportWarning") def test_geopandas(): - geopandas = import_module("geopandas") # noqa + geopandas = import_module("geopandas") fp = geopandas.datasets.get_path("naturalearth_lowres") assert geopandas.read_file(fp) is not None @@ -135,7 +135,7 @@ def test_geopandas(): @pytest.mark.filterwarnings("ignore:RangeIndex.* is deprecated:DeprecationWarning") def test_pyarrow(df): - pyarrow = import_module("pyarrow") # noqa + pyarrow = import_module("pyarrow") table = pyarrow.Table.from_pandas(df) result = table.to_pandas() tm.assert_frame_equal(result, df) diff --git a/pandas/tests/test_errors.py b/pandas/tests/test_errors.py index 6a1a74c73288f..6207b886b95c7 100644 --- a/pandas/tests/test_errors.py +++ b/pandas/tests/test_errors.py @@ -2,7 +2,7 @@ from pandas.errors import AbstractMethodError -import pandas as pd # noqa +import pandas as pd @pytest.mark.parametrize( diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index 7971379ca60c1..8b15358834066 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -35,19 +35,19 @@ # script. Setting here before matplotlib is loaded. # We don't warn for the number of open plots, as none is actually being opened os.environ["MPLBACKEND"] = "Template" -import matplotlib # noqa: E402 isort:skip +import matplotlib # isort:skip matplotlib.rc("figure", max_open_warning=10000) -import numpy # noqa: E402 isort:skip +import numpy # isort:skip BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_PATH)) -import pandas # noqa: E402 isort:skip +import pandas # isort:skip sys.path.insert(1, os.path.join(BASE_PATH, "doc", "sphinxext")) -from numpydoc.validate import validate, Docstring # noqa: E402 isort:skip +from numpydoc.validate import validate, Docstring # isort:skip PRIVATE_CLASSES = ["NDFrame", "IndexOpsMixin"] diff --git a/setup.py b/setup.py index 8e25705c1f4c3..9a9d12ce4d2ba 100755 --- a/setup.py +++ b/setup.py @@ -51,8 +51,8 @@ def is_platform_mac(): # The import of Extension must be after the import of Cython, otherwise # we do not get the appropriately patched class. # See https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html # noqa -from distutils.extension import Extension # noqa: E402 isort:skip -from distutils.command.build import build # noqa: E402 isort:skip +from distutils.extension import Extension # isort:skip +from distutils.command.build import build # isort:skip if _CYTHON_INSTALLED: from Cython.Distutils.old_build_ext import old_build_ext as _build_ext
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` This changes loads of files, but most changes are quite trivial
https://api.github.com/repos/pandas-dev/pandas/pulls/36707
2020-09-28T17:00:05Z
2020-10-02T23:06:54Z
2020-10-02T23:06:54Z
2020-10-03T06:20:20Z
CI: npdev new exception message
diff --git a/pandas/tests/arithmetic/common.py b/pandas/tests/arithmetic/common.py index 755fbd0d9036c..cd8dd102dc27c 100644 --- a/pandas/tests/arithmetic/common.py +++ b/pandas/tests/arithmetic/common.py @@ -76,6 +76,13 @@ def assert_invalid_comparison(left, right, box): "Cannot compare type", "not supported between", "invalid type promotion", + ( + # GH#36706 npdev 1.20.0 2020-09-28 + r"The DTypes <class 'numpy.dtype\[datetime64\]'> and " + r"<class 'numpy.dtype\[int64\]'> do not have a common DType. " + "For example they cannot be stored in a single array unless the " + "dtype is `object`." + ), ] ) with pytest.raises(TypeError, match=msg): diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 6dd8d890e8a4b..b3aa5e403e795 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -53,6 +53,11 @@ def check(df, df2): msgs = [ r"Invalid comparison between dtype=datetime64\[ns\] and ndarray", "invalid type promotion", + ( + # npdev 1.20.0 + r"The DTypes <class 'numpy.dtype\[.*\]'> and " + r"<class 'numpy.dtype\[.*\]'> do not have a common DType." + ), ] msg = "|".join(msgs) with pytest.raises(TypeError, match=msg):
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/36706
2020-09-28T16:08:56Z
2020-09-28T21:36:32Z
2020-09-28T21:36:32Z
2020-09-30T21:13:54Z
CLN: remove unnecessary CategoricalIndex._convert_arr_indexer
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index c798ae0bd4e4d..d3167189dbcc6 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -24,7 +24,6 @@ from pandas.core import accessor from pandas.core.arrays.categorical import Categorical, contains -import pandas.core.common as com from pandas.core.construction import extract_array import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name @@ -574,15 +573,6 @@ def _convert_list_indexer(self, keyarr): return self.get_indexer(keyarr) - @doc(Index._convert_arr_indexer) - def _convert_arr_indexer(self, keyarr): - keyarr = com.asarray_tuplesafe(keyarr) - - if self.categories._defer_to_indexing: - return keyarr - - return self._shallow_copy(keyarr) - @doc(Index._maybe_cast_slice_bound) def _maybe_cast_slice_bound(self, label, side, kind): if kind == "loc":
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/36705
2020-09-28T15:58:40Z
2020-09-30T01:56:35Z
2020-09-30T01:56:35Z
2020-09-30T02:46:40Z
CLN: Format doc code blocks
diff --git a/doc/source/development/code_style.rst b/doc/source/development/code_style.rst index 11d0c35f92ff5..387f65ea583a0 100644 --- a/doc/source/development/code_style.rst +++ b/doc/source/development/code_style.rst @@ -172,5 +172,6 @@ Reading from a url .. code-block:: python from pandas.io.common import urlopen - with urlopen('http://www.google.com') as url: + + with urlopen("http://www.google.com") as url: raw_text = url.read() diff --git a/doc/source/development/developer.rst b/doc/source/development/developer.rst index fbd83af3de82e..bdbcf5ca337b8 100644 --- a/doc/source/development/developer.rst +++ b/doc/source/development/developer.rst @@ -71,11 +71,13 @@ descriptor format for these as is follows: .. code-block:: python index = pd.RangeIndex(0, 10, 2) - {'kind': 'range', - 'name': index.name, - 'start': index.start, - 'stop': index.stop, - 'step': index.step} + { + "kind": "range", + "name": index.name, + "start": index.start, + "stop": index.stop, + "step": index.step, + } Other index types must be serialized as data columns along with the other DataFrame columns. The metadata for these is a string indicating the name of diff --git a/doc/source/development/internals.rst b/doc/source/development/internals.rst index 8f1c3d5d818c2..cec385dd087db 100644 --- a/doc/source/development/internals.rst +++ b/doc/source/development/internals.rst @@ -68,8 +68,9 @@ integer **codes** (until version 0.24 named *labels*), and the level **names**: .. ipython:: python - index = pd.MultiIndex.from_product([range(3), ['one', 'two']], - names=['first', 'second']) + index = pd.MultiIndex.from_product( + [range(3), ["one", "two"]], names=["first", "second"] + ) index index.levels index.codes diff --git a/doc/source/user_guide/categorical.rst b/doc/source/user_guide/categorical.rst index 9da5d2a9fc92f..926c2d9be74c2 100644 --- a/doc/source/user_guide/categorical.rst +++ b/doc/source/user_guide/categorical.rst @@ -58,7 +58,7 @@ By converting an existing ``Series`` or column to a ``category`` dtype: .. ipython:: python df = pd.DataFrame({"A": ["a", "b", "c", "a"]}) - df["B"] = df["A"].astype('category') + df["B"] = df["A"].astype("category") df By using special functions, such as :func:`~pandas.cut`, which groups data into @@ -66,18 +66,19 @@ discrete bins. See the :ref:`example on tiling <reshaping.tile.cut>` in the docs .. ipython:: python - df = pd.DataFrame({'value': np.random.randint(0, 100, 20)}) + df = pd.DataFrame({"value": np.random.randint(0, 100, 20)}) labels = ["{0} - {1}".format(i, i + 9) for i in range(0, 100, 10)] - df['group'] = pd.cut(df.value, range(0, 105, 10), right=False, labels=labels) + df["group"] = pd.cut(df.value, range(0, 105, 10), right=False, labels=labels) df.head(10) By passing a :class:`pandas.Categorical` object to a ``Series`` or assigning it to a ``DataFrame``. .. ipython:: python - raw_cat = pd.Categorical(["a", "b", "c", "a"], categories=["b", "c", "d"], - ordered=False) + raw_cat = pd.Categorical( + ["a", "b", "c", "a"], categories=["b", "c", "d"], ordered=False + ) s = pd.Series(raw_cat) s df = pd.DataFrame({"A": ["a", "b", "c", "a"]}) @@ -100,7 +101,7 @@ This can be done during construction by specifying ``dtype="category"`` in the ` .. ipython:: python - df = pd.DataFrame({'A': list('abca'), 'B': list('bccd')}, dtype="category") + df = pd.DataFrame({"A": list("abca"), "B": list("bccd")}, dtype="category") df.dtypes Note that the categories present in each column differ; the conversion is done column by column, so @@ -108,24 +109,24 @@ only labels present in a given column are categories: .. ipython:: python - df['A'] - df['B'] + df["A"] + df["B"] Analogously, all columns in an existing ``DataFrame`` can be batch converted using :meth:`DataFrame.astype`: .. ipython:: python - df = pd.DataFrame({'A': list('abca'), 'B': list('bccd')}) - df_cat = df.astype('category') + df = pd.DataFrame({"A": list("abca"), "B": list("bccd")}) + df_cat = df.astype("category") df_cat.dtypes This conversion is likewise done column by column: .. ipython:: python - df_cat['A'] - df_cat['B'] + df_cat["A"] + df_cat["B"] Controlling behavior @@ -143,9 +144,9 @@ of :class:`~pandas.api.types.CategoricalDtype`. .. ipython:: python from pandas.api.types import CategoricalDtype + s = pd.Series(["a", "b", "c", "a"]) - cat_type = CategoricalDtype(categories=["b", "c", "d"], - ordered=True) + cat_type = CategoricalDtype(categories=["b", "c", "d"], ordered=True) s_cat = s.astype(cat_type) s_cat @@ -155,12 +156,12 @@ are consistent among all columns. .. ipython:: python from pandas.api.types import CategoricalDtype - df = pd.DataFrame({'A': list('abca'), 'B': list('bccd')}) - cat_type = CategoricalDtype(categories=list('abcd'), - ordered=True) + + df = pd.DataFrame({"A": list("abca"), "B": list("bccd")}) + cat_type = CategoricalDtype(categories=list("abcd"), ordered=True) df_cat = df.astype(cat_type) - df_cat['A'] - df_cat['B'] + df_cat["A"] + df_cat["B"] .. note:: @@ -175,8 +176,7 @@ during normal constructor mode: .. ipython:: python splitter = np.random.choice([0, 1], 5, p=[0.5, 0.5]) - s = pd.Series(pd.Categorical.from_codes(splitter, - categories=["train", "test"])) + s = pd.Series(pd.Categorical.from_codes(splitter, categories=["train", "test"])) Regaining original data @@ -189,7 +189,7 @@ To get back to the original ``Series`` or NumPy array, use s = pd.Series(["a", "b", "c", "a"]) s - s2 = s.astype('category') + s2 = s.astype("category") s2 s2.astype(str) np.asarray(s2) @@ -223,8 +223,9 @@ by default. .. ipython:: python from pandas.api.types import CategoricalDtype - CategoricalDtype(['a', 'b', 'c']) - CategoricalDtype(['a', 'b', 'c'], ordered=True) + + CategoricalDtype(["a", "b", "c"]) + CategoricalDtype(["a", "b", "c"], ordered=True) CategoricalDtype() A :class:`~pandas.api.types.CategoricalDtype` can be used in any place pandas @@ -248,19 +249,19 @@ unordered categoricals, the order of the ``categories`` is not considered. .. ipython:: python - c1 = CategoricalDtype(['a', 'b', 'c'], ordered=False) + c1 = CategoricalDtype(["a", "b", "c"], ordered=False) # Equal, since order is not considered when ordered=False - c1 == CategoricalDtype(['b', 'c', 'a'], ordered=False) + c1 == CategoricalDtype(["b", "c", "a"], ordered=False) # Unequal, since the second CategoricalDtype is ordered - c1 == CategoricalDtype(['a', 'b', 'c'], ordered=True) + c1 == CategoricalDtype(["a", "b", "c"], ordered=True) All instances of ``CategoricalDtype`` compare equal to the string ``'category'``. .. ipython:: python - c1 == 'category' + c1 == "category" .. warning:: @@ -303,8 +304,7 @@ It's also possible to pass in the categories in a specific order: .. ipython:: python - s = pd.Series(pd.Categorical(["a", "b", "c", "a"], - categories=["c", "b", "a"])) + s = pd.Series(pd.Categorical(["a", "b", "c", "a"], categories=["c", "b", "a"])) s.cat.categories s.cat.ordered @@ -322,7 +322,7 @@ It's also possible to pass in the categories in a specific order: .. ipython:: python - s = pd.Series(list('babc')).astype(CategoricalDtype(list('abcd'))) + s = pd.Series(list("babc")).astype(CategoricalDtype(list("abcd"))) s # categories @@ -348,7 +348,7 @@ Renaming categories is done by assigning new values to the s = s.cat.rename_categories([1, 2, 3]) s # You can also pass a dict-like object to map the renaming - s = s.cat.rename_categories({1: 'x', 2: 'y', 3: 'z'}) + s = s.cat.rename_categories({1: "x", 2: "y", 3: "z"}) s .. note:: @@ -409,8 +409,7 @@ Removing unused categories can also be done: .. ipython:: python - s = pd.Series(pd.Categorical(["a", "b", "a"], - categories=["a", "b", "c", "d"])) + s = pd.Series(pd.Categorical(["a", "b", "a"], categories=["a", "b", "c", "d"])) s s.cat.remove_unused_categories() @@ -446,9 +445,7 @@ meaning and certain operations are possible. If the categorical is unordered, `` s = pd.Series(pd.Categorical(["a", "b", "c", "a"], ordered=False)) s.sort_values(inplace=True) - s = pd.Series(["a", "b", "c", "a"]).astype( - CategoricalDtype(ordered=True) - ) + s = pd.Series(["a", "b", "c", "a"]).astype(CategoricalDtype(ordered=True)) s.sort_values(inplace=True) s s.min(), s.max() @@ -514,18 +511,20 @@ The ordering of the categorical is determined by the ``categories`` of that colu .. ipython:: python - dfs = pd.DataFrame({'A': pd.Categorical(list('bbeebbaa'), - categories=['e', 'a', 'b'], - ordered=True), - 'B': [1, 2, 1, 2, 2, 1, 2, 1]}) - dfs.sort_values(by=['A', 'B']) + dfs = pd.DataFrame( + { + "A": pd.Categorical(list("bbeebbaa"), categories=["e", "a", "b"], ordered=True), + "B": [1, 2, 1, 2, 2, 1, 2, 1], + } + ) + dfs.sort_values(by=["A", "B"]) Reordering the ``categories`` changes a future sort. .. ipython:: python - dfs['A'] = dfs['A'].cat.reorder_categories(['a', 'b', 'e']) - dfs.sort_values(by=['A', 'B']) + dfs["A"] = dfs["A"].cat.reorder_categories(["a", "b", "e"]) + dfs.sort_values(by=["A", "B"]) Comparisons ----------- @@ -550,15 +549,9 @@ categories or a categorical with any list-like object, will raise a ``TypeError` .. ipython:: python - cat = pd.Series([1, 2, 3]).astype( - CategoricalDtype([3, 2, 1], ordered=True) - ) - cat_base = pd.Series([2, 2, 2]).astype( - CategoricalDtype([3, 2, 1], ordered=True) - ) - cat_base2 = pd.Series([2, 2, 2]).astype( - CategoricalDtype(ordered=True) - ) + cat = pd.Series([1, 2, 3]).astype(CategoricalDtype([3, 2, 1], ordered=True)) + cat_base = pd.Series([2, 2, 2]).astype(CategoricalDtype([3, 2, 1], ordered=True)) + cat_base2 = pd.Series([2, 2, 2]).astype(CategoricalDtype(ordered=True)) cat cat_base @@ -607,8 +600,8 @@ When you compare two unordered categoricals with the same categories, the order .. ipython:: python - c1 = pd.Categorical(['a', 'b'], categories=['a', 'b'], ordered=False) - c2 = pd.Categorical(['a', 'b'], categories=['b', 'a'], ordered=False) + c1 = pd.Categorical(["a", "b"], categories=["a", "b"], ordered=False) + c2 = pd.Categorical(["a", "b"], categories=["b", "a"], ordered=False) c1 == c2 Operations @@ -622,23 +615,21 @@ even if some categories are not present in the data: .. ipython:: python - s = pd.Series(pd.Categorical(["a", "b", "c", "c"], - categories=["c", "a", "b", "d"])) + s = pd.Series(pd.Categorical(["a", "b", "c", "c"], categories=["c", "a", "b", "d"])) s.value_counts() Groupby will also show "unused" categories: .. ipython:: python - cats = pd.Categorical(["a", "b", "b", "b", "c", "c", "c"], - categories=["a", "b", "c", "d"]) + cats = pd.Categorical( + ["a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c", "d"] + ) df = pd.DataFrame({"cats": cats, "values": [1, 2, 2, 2, 3, 4, 5]}) df.groupby("cats").mean() cats2 = pd.Categorical(["a", "a", "b", "b"], categories=["a", "b", "c"]) - df2 = pd.DataFrame({"cats": cats2, - "B": ["c", "d", "c", "d"], - "values": [1, 2, 3, 4]}) + df2 = pd.DataFrame({"cats": cats2, "B": ["c", "d", "c", "d"], "values": [1, 2, 3, 4]}) df2.groupby(["cats", "B"]).mean() @@ -647,10 +638,8 @@ Pivot tables: .. ipython:: python raw_cat = pd.Categorical(["a", "a", "b", "b"], categories=["a", "b", "c"]) - df = pd.DataFrame({"A": raw_cat, - "B": ["c", "d", "c", "d"], - "values": [1, 2, 3, 4]}) - pd.pivot_table(df, values='values', index=['A', 'B']) + df = pd.DataFrame({"A": raw_cat, "B": ["c", "d", "c", "d"], "values": [1, 2, 3, 4]}) + pd.pivot_table(df, values="values", index=["A", "B"]) Data munging ------------ @@ -668,8 +657,7 @@ If the slicing operation returns either a ``DataFrame`` or a column of type .. ipython:: python idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) - cats = pd.Series(["a", "b", "b", "b", "c", "c", "c"], - dtype="category", index=idx) + cats = pd.Series(["a", "b", "b", "b", "c", "c", "c"], dtype="category", index=idx) values = [1, 2, 2, 2, 3, 4, 5] df = pd.DataFrame({"cats": cats, "values": values}, index=idx) df.iloc[2:4, :] @@ -714,13 +702,13 @@ an appropriate type: .. ipython:: python - str_s = pd.Series(list('aabb')) - str_cat = str_s.astype('category') + str_s = pd.Series(list("aabb")) + str_cat = str_s.astype("category") str_cat str_cat.str.contains("a") - date_s = pd.Series(pd.date_range('1/1/2015', periods=5)) - date_cat = date_s.astype('category') + date_s = pd.Series(pd.date_range("1/1/2015", periods=5)) + date_cat = date_s.astype("category") date_cat date_cat.dt.day @@ -758,8 +746,7 @@ value is included in the ``categories``: .. ipython:: python idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) - cats = pd.Categorical(["a", "a", "a", "a", "a", "a", "a"], - categories=["a", "b"]) + cats = pd.Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"]) values = [1, 1, 1, 1, 1, 1, 1] df = pd.DataFrame({"cats": cats, "values": values}, index=idx) @@ -777,8 +764,7 @@ Setting values by assigning categorical data will also check that the ``categori df.loc["j":"k", "cats"] = pd.Categorical(["a", "a"], categories=["a", "b"]) df try: - df.loc["j":"k", "cats"] = pd.Categorical(["b", "b"], - categories=["a", "b", "c"]) + df.loc["j":"k", "cats"] = pd.Categorical(["b", "b"], categories=["a", "b", "c"]) except ValueError as e: print("ValueError:", str(e)) @@ -809,12 +795,12 @@ dtypes will likely have higher memory usage. Use ``.astype`` or from pandas.api.types import union_categoricals # same categories - s1 = pd.Series(['a', 'b'], dtype='category') - s2 = pd.Series(['a', 'b', 'a'], dtype='category') + s1 = pd.Series(["a", "b"], dtype="category") + s2 = pd.Series(["a", "b", "a"], dtype="category") pd.concat([s1, s2]) # different categories - s3 = pd.Series(['b', 'c'], dtype='category') + s3 = pd.Series(["b", "c"], dtype="category") pd.concat([s1, s3]) # Output dtype is inferred based on categories values @@ -822,7 +808,7 @@ dtypes will likely have higher memory usage. Use ``.astype`` or float_cats = pd.Series([3.0, 4.0], dtype="category") pd.concat([int_cats, float_cats]) - pd.concat([s1, s3]).astype('category') + pd.concat([s1, s3]).astype("category") union_categoricals([s1.array, s3.array]) The following table summarizes the results of merging ``Categoricals``: @@ -853,6 +839,7 @@ the categories being combined. .. ipython:: python from pandas.api.types import union_categoricals + a = pd.Categorical(["b", "c"]) b = pd.Categorical(["a", "b"]) union_categoricals([a, b]) @@ -900,8 +887,8 @@ the resulting array will always be a plain ``Categorical``: .. ipython:: python - a = pd.Series(["b", "c"], dtype='category') - b = pd.Series(["a", "b"], dtype='category') + a = pd.Series(["b", "c"], dtype="category") + b = pd.Series(["a", "b"], dtype="category") union_categoricals([a, b]) .. note:: @@ -946,7 +933,8 @@ relevant columns back to ``category`` and assign the right categories and catego .. ipython:: python import io - s = pd.Series(pd.Categorical(['a', 'b', 'b', 'a', 'a', 'd'])) + + s = pd.Series(pd.Categorical(["a", "b", "b", "a", "a", "d"])) # rename the categories s.cat.categories = ["very good", "good", "bad"] # reorder the categories and add missing categories @@ -959,9 +947,9 @@ relevant columns back to ``category`` and assign the right categories and catego df2["cats"] # Redo the category df2["cats"] = df2["cats"].astype("category") - df2["cats"].cat.set_categories(["very bad", "bad", "medium", - "good", "very good"], - inplace=True) + df2["cats"].cat.set_categories( + ["very bad", "bad", "medium", "good", "very good"], inplace=True + ) df2.dtypes df2["cats"] @@ -1029,13 +1017,13 @@ an ``object`` dtype is a constant times the length of the data. .. ipython:: python - s = pd.Series(['foo', 'bar'] * 1000) + s = pd.Series(["foo", "bar"] * 1000) # object dtype s.nbytes # category dtype - s.astype('category').nbytes + s.astype("category").nbytes .. note:: @@ -1044,13 +1032,13 @@ an ``object`` dtype is a constant times the length of the data. .. ipython:: python - s = pd.Series(['foo%04d' % i for i in range(2000)]) + s = pd.Series(["foo%04d" % i for i in range(2000)]) # object dtype s.nbytes # category dtype - s.astype('category').nbytes + s.astype("category").nbytes ``Categorical`` is not a ``numpy`` array @@ -1085,8 +1073,8 @@ To check if a Series contains Categorical data, use ``hasattr(s, 'cat')``: .. ipython:: python - hasattr(pd.Series(['a'], dtype='category'), 'cat') - hasattr(pd.Series(['a']), 'cat') + hasattr(pd.Series(["a"], dtype="category"), "cat") + hasattr(pd.Series(["a"]), "cat") Using NumPy functions on a ``Series`` of type ``category`` should not work as ``Categoricals`` are not numeric data (even in the case that ``.categories`` is numeric). @@ -1113,9 +1101,9 @@ You can use ``fillna`` to handle missing values before applying a function. .. ipython:: python - df = pd.DataFrame({"a": [1, 2, 3, 4], - "b": ["a", "b", "c", "d"], - "cats": pd.Categorical([1, 2, 3, 2])}) + df = pd.DataFrame( + {"a": [1, 2, 3, 4], "b": ["a", "b", "c", "d"], "cats": pd.Categorical([1, 2, 3, 2])} + ) df.apply(lambda row: type(row["cats"]), axis=1) df.apply(lambda col: col.dtype, axis=0) diff --git a/doc/source/user_guide/integer_na.rst b/doc/source/user_guide/integer_na.rst index a45d7a4fa1547..acee1638570f7 100644 --- a/doc/source/user_guide/integer_na.rst +++ b/doc/source/user_guide/integer_na.rst @@ -112,7 +112,7 @@ dtype if needed. s.iloc[1:3] # operate with other dtypes - s + s.iloc[1:3].astype('Int8') + s + s.iloc[1:3].astype("Int8") # coerce when needed s + 0.01 @@ -121,7 +121,7 @@ These dtypes can operate as part of of ``DataFrame``. .. ipython:: python - df = pd.DataFrame({'A': s, 'B': [1, 1, 3], 'C': list('aab')}) + df = pd.DataFrame({"A": s, "B": [1, 1, 3], "C": list("aab")}) df df.dtypes @@ -130,15 +130,15 @@ These dtypes can be merged & reshaped & casted. .. ipython:: python - pd.concat([df[['A']], df[['B', 'C']]], axis=1).dtypes - df['A'].astype(float) + pd.concat([df[["A"]], df[["B", "C"]]], axis=1).dtypes + df["A"].astype(float) Reduction and groupby operations such as 'sum' work as well. .. ipython:: python df.sum() - df.groupby('B').A.sum() + df.groupby("B").A.sum() Scalar NA Value --------------- diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst index 563fc941294d1..d222297abc70b 100644 --- a/doc/source/user_guide/options.rst +++ b/doc/source/user_guide/options.rst @@ -17,6 +17,7 @@ You can get/set options directly as attributes of the top-level ``options`` attr .. ipython:: python import pandas as pd + pd.options.display.max_rows pd.options.display.max_rows = 999 pd.options.display.max_rows @@ -77,9 +78,9 @@ are available from the pandas namespace. To change an option, call .. ipython:: python - pd.get_option('mode.sim_interactive') - pd.set_option('mode.sim_interactive', True) - pd.get_option('mode.sim_interactive') + pd.get_option("mode.sim_interactive") + pd.set_option("mode.sim_interactive", True) + pd.get_option("mode.sim_interactive") **Note:** The option 'mode.sim_interactive' is mostly used for debugging purposes. @@ -135,8 +136,9 @@ More information can be found in the `ipython documentation .. code-block:: python import pandas as pd - pd.set_option('display.max_rows', 999) - pd.set_option('precision', 5) + + pd.set_option("display.max_rows", 999) + pd.set_option("precision", 5) .. _options.frequently_used: @@ -151,27 +153,27 @@ lines are replaced by an ellipsis. .. ipython:: python df = pd.DataFrame(np.random.randn(7, 2)) - pd.set_option('max_rows', 7) + pd.set_option("max_rows", 7) df - pd.set_option('max_rows', 5) + pd.set_option("max_rows", 5) df - pd.reset_option('max_rows') + pd.reset_option("max_rows") Once the ``display.max_rows`` is exceeded, the ``display.min_rows`` options determines how many rows are shown in the truncated repr. .. ipython:: python - pd.set_option('max_rows', 8) - pd.set_option('min_rows', 4) + pd.set_option("max_rows", 8) + pd.set_option("min_rows", 4) # below max_rows -> all rows shown df = pd.DataFrame(np.random.randn(7, 2)) df # above max_rows -> only min_rows (4) rows shown df = pd.DataFrame(np.random.randn(9, 2)) df - pd.reset_option('max_rows') - pd.reset_option('min_rows') + pd.reset_option("max_rows") + pd.reset_option("min_rows") ``display.expand_frame_repr`` allows for the representation of dataframes to stretch across pages, wrapped over the full column vs row-wise. @@ -179,11 +181,11 @@ dataframes to stretch across pages, wrapped over the full column vs row-wise. .. ipython:: python df = pd.DataFrame(np.random.randn(5, 10)) - pd.set_option('expand_frame_repr', True) + pd.set_option("expand_frame_repr", True) df - pd.set_option('expand_frame_repr', False) + pd.set_option("expand_frame_repr", False) df - pd.reset_option('expand_frame_repr') + pd.reset_option("expand_frame_repr") ``display.large_repr`` lets you select whether to display dataframes that exceed ``max_columns`` or ``max_rows`` as a truncated frame, or as a summary. @@ -191,26 +193,32 @@ dataframes to stretch across pages, wrapped over the full column vs row-wise. .. ipython:: python df = pd.DataFrame(np.random.randn(10, 10)) - pd.set_option('max_rows', 5) - pd.set_option('large_repr', 'truncate') + pd.set_option("max_rows", 5) + pd.set_option("large_repr", "truncate") df - pd.set_option('large_repr', 'info') + pd.set_option("large_repr", "info") df - pd.reset_option('large_repr') - pd.reset_option('max_rows') + pd.reset_option("large_repr") + pd.reset_option("max_rows") ``display.max_colwidth`` sets the maximum width of columns. Cells of this length or longer will be truncated with an ellipsis. .. ipython:: python - df = pd.DataFrame(np.array([['foo', 'bar', 'bim', 'uncomfortably long string'], - ['horse', 'cow', 'banana', 'apple']])) - pd.set_option('max_colwidth', 40) + df = pd.DataFrame( + np.array( + [ + ["foo", "bar", "bim", "uncomfortably long string"], + ["horse", "cow", "banana", "apple"], + ] + ) + ) + pd.set_option("max_colwidth", 40) df - pd.set_option('max_colwidth', 6) + pd.set_option("max_colwidth", 6) df - pd.reset_option('max_colwidth') + pd.reset_option("max_colwidth") ``display.max_info_columns`` sets a threshold for when by-column info will be given. @@ -218,11 +226,11 @@ will be given. .. ipython:: python df = pd.DataFrame(np.random.randn(10, 10)) - pd.set_option('max_info_columns', 11) + pd.set_option("max_info_columns", 11) df.info() - pd.set_option('max_info_columns', 5) + pd.set_option("max_info_columns", 5) df.info() - pd.reset_option('max_info_columns') + pd.reset_option("max_info_columns") ``display.max_info_rows``: ``df.info()`` will usually show null-counts for each column. For large frames this can be quite slow. ``max_info_rows`` and ``max_info_cols`` @@ -233,11 +241,11 @@ can specify the option ``df.info(null_counts=True)`` to override on showing a pa df = pd.DataFrame(np.random.choice([0, 1, np.nan], size=(10, 10))) df - pd.set_option('max_info_rows', 11) + pd.set_option("max_info_rows", 11) df.info() - pd.set_option('max_info_rows', 5) + pd.set_option("max_info_rows", 5) df.info() - pd.reset_option('max_info_rows') + pd.reset_option("max_info_rows") ``display.precision`` sets the output display precision in terms of decimal places. This is only a suggestion. @@ -245,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("precision", 7) df - pd.set_option('precision', 4) + pd.set_option("precision", 4) df ``display.chop_threshold`` sets at what level pandas rounds to zero when @@ -257,26 +265,27 @@ precision at which the number is stored. .. ipython:: python df = pd.DataFrame(np.random.randn(6, 6)) - pd.set_option('chop_threshold', 0) + pd.set_option("chop_threshold", 0) df - pd.set_option('chop_threshold', .5) + pd.set_option("chop_threshold", 0.5) df - pd.reset_option('chop_threshold') + pd.reset_option("chop_threshold") ``display.colheader_justify`` controls the justification of the headers. The options are 'right', and 'left'. .. ipython:: python - df = pd.DataFrame(np.array([np.random.randn(6), - np.random.randint(1, 9, 6) * .1, - np.zeros(6)]).T, - columns=['A', 'B', 'C'], dtype='float') - pd.set_option('colheader_justify', 'right') + df = pd.DataFrame( + np.array([np.random.randn(6), np.random.randint(1, 9, 6) * 0.1, np.zeros(6)]).T, + columns=["A", "B", "C"], + dtype="float", + ) + pd.set_option("colheader_justify", "right") df - pd.set_option('colheader_justify', 'left') + pd.set_option("colheader_justify", "left") df - pd.reset_option('colheader_justify') + pd.reset_option("colheader_justify") @@ -481,9 +490,9 @@ For instance: import numpy as np pd.set_eng_float_format(accuracy=3, use_eng_prefix=True) - s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) - s / 1.e3 - s / 1.e6 + s = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"]) + s / 1.0e3 + s / 1.0e6 .. ipython:: python :suppress: @@ -510,7 +519,7 @@ If a DataFrame or Series contains these characters, the default output mode may .. ipython:: python - df = pd.DataFrame({'国籍': ['UK', '日本'], '名前': ['Alice', 'しのぶ']}) + df = pd.DataFrame({"国籍": ["UK", "日本"], "名前": ["Alice", "しのぶ"]}) df .. image:: ../_static/option_unicode01.png @@ -521,7 +530,7 @@ times than the standard ``len`` function. .. ipython:: python - pd.set_option('display.unicode.east_asian_width', True) + pd.set_option("display.unicode.east_asian_width", True) df .. image:: ../_static/option_unicode02.png @@ -533,7 +542,7 @@ By default, an "Ambiguous" character's width, such as "¡" (inverted exclamation .. ipython:: python - df = pd.DataFrame({'a': ['xxx', '¡¡'], 'b': ['yyy', '¡¡']}) + df = pd.DataFrame({"a": ["xxx", "¡¡"], "b": ["yyy", "¡¡"]}) df .. image:: ../_static/option_unicode03.png @@ -545,7 +554,7 @@ However, setting this option incorrectly for your terminal will cause these char .. ipython:: python - pd.set_option('display.unicode.ambiguous_as_wide', True) + pd.set_option("display.unicode.ambiguous_as_wide", True) df .. image:: ../_static/option_unicode04.png @@ -553,8 +562,8 @@ However, setting this option incorrectly for your terminal will cause these char .. ipython:: python :suppress: - pd.set_option('display.unicode.east_asian_width', False) - pd.set_option('display.unicode.ambiguous_as_wide', False) + pd.set_option("display.unicode.east_asian_width", False) + pd.set_option("display.unicode.ambiguous_as_wide", False) .. _options.table_schema: @@ -567,7 +576,7 @@ by default. False by default, this can be enabled globally with the .. ipython:: python - pd.set_option('display.html.table_schema', True) + pd.set_option("display.html.table_schema", True) Only ``'display.max_rows'`` are serialized and published. @@ -575,4 +584,4 @@ Only ``'display.max_rows'`` are serialized and published. .. ipython:: python :suppress: - pd.reset_option('display.html.table_schema') + pd.reset_option("display.html.table_schema") diff --git a/doc/source/user_guide/reshaping.rst b/doc/source/user_guide/reshaping.rst index e6797512ce3cf..2061185b25416 100644 --- a/doc/source/user_guide/reshaping.rst +++ b/doc/source/user_guide/reshaping.rst @@ -18,14 +18,18 @@ Reshaping by pivoting DataFrame objects import pandas._testing as tm + def unpivot(frame): N, K = frame.shape - data = {'value': frame.to_numpy().ravel('F'), - 'variable': np.asarray(frame.columns).repeat(N), - 'date': np.tile(np.asarray(frame.index), K)} - columns = ['date', 'variable', 'value'] + data = { + "value": frame.to_numpy().ravel("F"), + "variable": np.asarray(frame.columns).repeat(N), + "date": np.tile(np.asarray(frame.index), K), + } + columns = ["date", "variable", "value"] return pd.DataFrame(data, columns=columns) + df = unpivot(tm.makeTimeDataFrame(3)) Data is often stored in so-called "stacked" or "record" format: @@ -41,12 +45,15 @@ For the curious here is how the above ``DataFrame`` was created: import pandas._testing as tm + def unpivot(frame): N, K = frame.shape - data = {'value': frame.to_numpy().ravel('F'), - 'variable': np.asarray(frame.columns).repeat(N), - 'date': np.tile(np.asarray(frame.index), K)} - return pd.DataFrame(data, columns=['date', 'variable', 'value']) + data = { + "value": frame.to_numpy().ravel("F"), + "variable": np.asarray(frame.columns).repeat(N), + "date": np.tile(np.asarray(frame.index), K), + } + return pd.DataFrame(data, columns=["date", "variable", "value"]) df = unpivot(tm.makeTimeDataFrame(3)) @@ -55,7 +62,7 @@ To select out everything for variable ``A`` we could do: .. ipython:: python - df[df['variable'] == 'A'] + df[df["variable"] == "A"] But suppose we wish to do time series operations with the variables. A better representation would be where the ``columns`` are the unique variables and an @@ -65,7 +72,7 @@ top level function :func:`~pandas.pivot`): .. ipython:: python - df.pivot(index='date', columns='variable', values='value') + df.pivot(index="date", columns="variable", values="value") If the ``values`` argument is omitted, and the input ``DataFrame`` has more than one column of values which are not used as column or index inputs to ``pivot``, @@ -75,15 +82,15 @@ column: .. ipython:: python - df['value2'] = df['value'] * 2 - pivoted = df.pivot(index='date', columns='variable') + df["value2"] = df["value"] * 2 + pivoted = df.pivot(index="date", columns="variable") pivoted You can then select subsets from the pivoted ``DataFrame``: .. ipython:: python - pivoted['value2'] + pivoted["value2"] Note that this returns a view on the underlying data in the case where the data are homogeneously-typed. @@ -121,12 +128,16 @@ from the hierarchical indexing section: .. ipython:: python - tuples = list(zip(*[['bar', 'bar', 'baz', 'baz', - 'foo', 'foo', 'qux', 'qux'], - ['one', 'two', 'one', 'two', - 'one', 'two', 'one', 'two']])) - index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) - df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B']) + tuples = list( + zip( + *[ + ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + ) + ) + index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"]) + df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=["A", "B"]) df2 = df[:4] df2 @@ -163,7 +174,7 @@ the level numbers: .. ipython:: python - stacked.unstack('second') + stacked.unstack("second") .. image:: ../_static/reshaping_unstack_0.png @@ -174,8 +185,8 @@ will result in a **sorted** copy of the original ``DataFrame`` or ``Series``: .. ipython:: python - index = pd.MultiIndex.from_product([[2, 1], ['a', 'b']]) - df = pd.DataFrame(np.random.randn(4), index=index, columns=['A']) + index = pd.MultiIndex.from_product([[2, 1], ["a", "b"]]) + df = pd.DataFrame(np.random.randn(4), index=index, columns=["A"]) df all(df.unstack().stack() == df.sort_index()) @@ -193,15 +204,19 @@ processed individually. .. ipython:: python - columns = pd.MultiIndex.from_tuples([ - ('A', 'cat', 'long'), ('B', 'cat', 'long'), - ('A', 'dog', 'short'), ('B', 'dog', 'short')], - names=['exp', 'animal', 'hair_length'] + columns = pd.MultiIndex.from_tuples( + [ + ("A", "cat", "long"), + ("B", "cat", "long"), + ("A", "dog", "short"), + ("B", "dog", "short"), + ], + names=["exp", "animal", "hair_length"], ) df = pd.DataFrame(np.random.randn(4, 4), columns=columns) df - df.stack(level=['animal', 'hair_length']) + df.stack(level=["animal", "hair_length"]) The list of levels can contain either level names or level numbers (but not a mixture of the two). @@ -222,12 +237,12 @@ calling ``sort_index``, of course). Here is a more complex example: .. ipython:: python - columns = pd.MultiIndex.from_tuples([('A', 'cat'), ('B', 'dog'), - ('B', 'cat'), ('A', 'dog')], - names=['exp', 'animal']) - index = pd.MultiIndex.from_product([('bar', 'baz', 'foo', 'qux'), - ('one', 'two')], - names=['first', 'second']) + columns = pd.MultiIndex.from_tuples( + [("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")], names=["exp", "animal"] + ) + index = pd.MultiIndex.from_product( + [("bar", "baz", "foo", "qux"), ("one", "two")], names=["first", "second"] + ) df = pd.DataFrame(np.random.randn(8, 4), index=index, columns=columns) df2 = df.iloc[[0, 1, 2, 4, 5, 7]] df2 @@ -237,8 +252,8 @@ which level in the columns to stack: .. ipython:: python - df2.stack('exp') - df2.stack('animal') + df2.stack("exp") + df2.stack("animal") Unstacking can result in missing values if subgroups do not have the same set of labels. By default, missing values will be replaced with the default @@ -288,13 +303,17 @@ For instance, .. ipython:: python - cheese = pd.DataFrame({'first': ['John', 'Mary'], - 'last': ['Doe', 'Bo'], - 'height': [5.5, 6.0], - 'weight': [130, 150]}) + cheese = pd.DataFrame( + { + "first": ["John", "Mary"], + "last": ["Doe", "Bo"], + "height": [5.5, 6.0], + "weight": [130, 150], + } + ) cheese - cheese.melt(id_vars=['first', 'last']) - cheese.melt(id_vars=['first', 'last'], var_name='quantity') + cheese.melt(id_vars=["first", "last"]) + cheese.melt(id_vars=["first", "last"], var_name="quantity") When transforming a DataFrame using :func:`~pandas.melt`, the index will be ignored. The original index values can be kept around by setting the ``ignore_index`` parameter to ``False`` (default is ``True``). This will however duplicate them. @@ -302,15 +321,19 @@ When transforming a DataFrame using :func:`~pandas.melt`, the index will be igno .. ipython:: python - index = pd.MultiIndex.from_tuples([('person', 'A'), ('person', 'B')]) - cheese = pd.DataFrame({'first': ['John', 'Mary'], - 'last': ['Doe', 'Bo'], - 'height': [5.5, 6.0], - 'weight': [130, 150]}, - index=index) + index = pd.MultiIndex.from_tuples([("person", "A"), ("person", "B")]) + cheese = pd.DataFrame( + { + "first": ["John", "Mary"], + "last": ["Doe", "Bo"], + "height": [5.5, 6.0], + "weight": [130, 150], + }, + index=index, + ) cheese - cheese.melt(id_vars=['first', 'last']) - cheese.melt(id_vars=['first', 'last'], ignore_index=False) + cheese.melt(id_vars=["first", "last"]) + cheese.melt(id_vars=["first", "last"], ignore_index=False) Another way to transform is to use the :func:`~pandas.wide_to_long` panel data convenience function. It is less flexible than :func:`~pandas.melt`, but more @@ -318,12 +341,15 @@ user-friendly. .. ipython:: python - dft = pd.DataFrame({"A1970": {0: "a", 1: "b", 2: "c"}, - "A1980": {0: "d", 1: "e", 2: "f"}, - "B1970": {0: 2.5, 1: 1.2, 2: .7}, - "B1980": {0: 3.2, 1: 1.3, 2: .1}, - "X": dict(zip(range(3), np.random.randn(3))) - }) + dft = pd.DataFrame( + { + "A1970": {0: "a", 1: "b", 2: "c"}, + "A1980": {0: "d", 1: "e", 2: "f"}, + "B1970": {0: 2.5, 1: 1.2, 2: 0.7}, + "B1980": {0: 3.2, 1: 1.3, 2: 0.1}, + "X": dict(zip(range(3), np.random.randn(3))), + } + ) dft["id"] = dft.index dft pd.wide_to_long(dft, ["A", "B"], i="id", j="year") @@ -380,23 +406,27 @@ Consider a data set like this: .. ipython:: python import datetime - df = pd.DataFrame({'A': ['one', 'one', 'two', 'three'] * 6, - 'B': ['A', 'B', 'C'] * 8, - 'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4, - 'D': np.random.randn(24), - 'E': np.random.randn(24), - 'F': [datetime.datetime(2013, i, 1) for i in range(1, 13)] - + [datetime.datetime(2013, i, 15) for i in range(1, 13)]}) + + df = pd.DataFrame( + { + "A": ["one", "one", "two", "three"] * 6, + "B": ["A", "B", "C"] * 8, + "C": ["foo", "foo", "foo", "bar", "bar", "bar"] * 4, + "D": np.random.randn(24), + "E": np.random.randn(24), + "F": [datetime.datetime(2013, i, 1) for i in range(1, 13)] + + [datetime.datetime(2013, i, 15) for i in range(1, 13)], + } + ) df We can produce pivot tables from this data very easily: .. ipython:: python - pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C']) - pd.pivot_table(df, values='D', index=['B'], columns=['A', 'C'], aggfunc=np.sum) - pd.pivot_table(df, values=['D', 'E'], index=['B'], columns=['A', 'C'], - aggfunc=np.sum) + pd.pivot_table(df, values="D", index=["A", "B"], columns=["C"]) + pd.pivot_table(df, values="D", index=["B"], columns=["A", "C"], aggfunc=np.sum) + pd.pivot_table(df, values=["D", "E"], index=["B"], columns=["A", "C"], aggfunc=np.sum) The result object is a ``DataFrame`` having potentially hierarchical indexes on the rows and columns. If the ``values`` column name is not given, the pivot table @@ -405,22 +435,21 @@ hierarchy in the columns: .. ipython:: python - pd.pivot_table(df, index=['A', 'B'], columns=['C']) + pd.pivot_table(df, index=["A", "B"], columns=["C"]) Also, you can use ``Grouper`` for ``index`` and ``columns`` keywords. For detail of ``Grouper``, see :ref:`Grouping with a Grouper specification <groupby.specify>`. .. ipython:: python - pd.pivot_table(df, values='D', index=pd.Grouper(freq='M', key='F'), - columns='C') + pd.pivot_table(df, values="D", index=pd.Grouper(freq="M", key="F"), columns="C") You can render a nice output of the table omitting the missing values by calling ``to_string`` if you wish: .. ipython:: python - table = pd.pivot_table(df, index=['A', 'B'], columns=['C']) - print(table.to_string(na_rep='')) + table = pd.pivot_table(df, index=["A", "B"], columns=["C"]) + print(table.to_string(na_rep="")) Note that ``pivot_table`` is also available as an instance method on DataFrame, i.e. :meth:`DataFrame.pivot_table`. @@ -436,7 +465,7 @@ rows and columns: .. ipython:: python - df.pivot_table(index=['A', 'B'], columns='C', margins=True, aggfunc=np.std) + df.pivot_table(index=["A", "B"], columns="C", margins=True, aggfunc=np.std) .. _reshaping.crosstabulations: @@ -470,30 +499,31 @@ For example: .. ipython:: python - foo, bar, dull, shiny, one, two = 'foo', 'bar', 'dull', 'shiny', 'one', 'two' + foo, bar, dull, shiny, one, two = "foo", "bar", "dull", "shiny", "one", "two" a = np.array([foo, foo, bar, bar, foo, foo], dtype=object) b = np.array([one, one, two, one, two, one], dtype=object) c = np.array([dull, dull, shiny, dull, dull, shiny], dtype=object) - pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c']) + pd.crosstab(a, [b, c], rownames=["a"], colnames=["b", "c"]) If ``crosstab`` receives only two Series, it will provide a frequency table. .. ipython:: python - df = pd.DataFrame({'A': [1, 2, 2, 2, 2], 'B': [3, 3, 4, 4, 4], - 'C': [1, 1, np.nan, 1, 1]}) + df = pd.DataFrame( + {"A": [1, 2, 2, 2, 2], "B": [3, 3, 4, 4, 4], "C": [1, 1, np.nan, 1, 1]} + ) df - pd.crosstab(df['A'], df['B']) + pd.crosstab(df["A"], df["B"]) ``crosstab`` can also be implemented to ``Categorical`` data. .. ipython:: python - foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c']) - bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f']) + foo = pd.Categorical(["a", "b"], categories=["a", "b", "c"]) + bar = pd.Categorical(["d", "e"], categories=["d", "e", "f"]) pd.crosstab(foo, bar) If you want to include **all** of data categories even if the actual data does @@ -513,13 +543,13 @@ using the ``normalize`` argument: .. ipython:: python - pd.crosstab(df['A'], df['B'], normalize=True) + pd.crosstab(df["A"], df["B"], normalize=True) ``normalize`` can also normalize values within each row or within each column: .. ipython:: python - pd.crosstab(df['A'], df['B'], normalize='columns') + pd.crosstab(df["A"], df["B"], normalize="columns") ``crosstab`` can also be passed a third ``Series`` and an aggregation function (``aggfunc``) that will be applied to the values of the third ``Series`` within @@ -527,7 +557,7 @@ each group defined by the first two ``Series``: .. ipython:: python - pd.crosstab(df['A'], df['B'], values=df['C'], aggfunc=np.sum) + pd.crosstab(df["A"], df["B"], values=df["C"], aggfunc=np.sum) Adding margins ~~~~~~~~~~~~~~ @@ -536,8 +566,9 @@ Finally, one can also add margins or normalize this output. .. ipython:: python - pd.crosstab(df['A'], df['B'], values=df['C'], aggfunc=np.sum, normalize=True, - margins=True) + pd.crosstab( + df["A"], df["B"], values=df["C"], aggfunc=np.sum, normalize=True, margins=True + ) .. _reshaping.tile: .. _reshaping.tile.cut: @@ -581,19 +612,19 @@ values, can derive a ``DataFrame`` containing ``k`` columns of 1s and 0s using .. ipython:: python - df = pd.DataFrame({'key': list('bbacab'), 'data1': range(6)}) + df = pd.DataFrame({"key": list("bbacab"), "data1": range(6)}) - pd.get_dummies(df['key']) + pd.get_dummies(df["key"]) Sometimes it's useful to prefix the column names, for example when merging the result with the original ``DataFrame``: .. ipython:: python - dummies = pd.get_dummies(df['key'], prefix='key') + dummies = pd.get_dummies(df["key"], prefix="key") dummies - df[['data1']].join(dummies) + df[["data1"]].join(dummies) This function is often used along with discretization functions like ``cut``: @@ -615,8 +646,7 @@ variables (categorical in the statistical sense, those with ``object`` or .. ipython:: python - df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['c', 'c', 'b'], - 'C': [1, 2, 3]}) + df = pd.DataFrame({"A": ["a", "b", "a"], "B": ["c", "c", "b"], "C": [1, 2, 3]}) pd.get_dummies(df) All non-object columns are included untouched in the output. You can control @@ -624,7 +654,7 @@ the columns that are encoded with the ``columns`` keyword. .. ipython:: python - pd.get_dummies(df, columns=['A']) + pd.get_dummies(df, columns=["A"]) Notice that the ``B`` column is still included in the output, it just hasn't been encoded. You can drop ``B`` before calling ``get_dummies`` if you don't @@ -641,11 +671,11 @@ the prefix separator. You can specify ``prefix`` and ``prefix_sep`` in 3 ways: .. ipython:: python - simple = pd.get_dummies(df, prefix='new_prefix') + simple = pd.get_dummies(df, prefix="new_prefix") simple - from_list = pd.get_dummies(df, prefix=['from_A', 'from_B']) + from_list = pd.get_dummies(df, prefix=["from_A", "from_B"]) from_list - from_dict = pd.get_dummies(df, prefix={'B': 'from_B', 'A': 'from_A'}) + from_dict = pd.get_dummies(df, prefix={"B": "from_B", "A": "from_A"}) from_dict Sometimes it will be useful to only keep k-1 levels of a categorical @@ -654,7 +684,7 @@ You can switch to this mode by turn on ``drop_first``. .. ipython:: python - s = pd.Series(list('abcaa')) + s = pd.Series(list("abcaa")) pd.get_dummies(s) @@ -664,7 +694,7 @@ When a column contains only one level, it will be omitted in the result. .. ipython:: python - df = pd.DataFrame({'A': list('aaaaa'), 'B': list('ababc')}) + df = pd.DataFrame({"A": list("aaaaa"), "B": list("ababc")}) pd.get_dummies(df) @@ -675,7 +705,7 @@ To choose another dtype, use the ``dtype`` argument: .. ipython:: python - df = pd.DataFrame({'A': list('abc'), 'B': [1.1, 2.2, 3.3]}) + df = pd.DataFrame({"A": list("abc"), "B": [1.1, 2.2, 3.3]}) pd.get_dummies(df, dtype=bool).dtypes @@ -689,7 +719,7 @@ To encode 1-d values as an enumerated type use :func:`~pandas.factorize`: .. ipython:: python - x = pd.Series(['A', 'A', np.nan, 'B', 3.14, np.inf]) + x = pd.Series(["A", "A", np.nan, "B", 3.14, np.inf]) x labels, uniques = pd.factorize(x) labels @@ -733,11 +763,12 @@ DataFrame will be pivoted in the answers below. np.random.seed([3, 1415]) n = 20 - cols = np.array(['key', 'row', 'item', 'col']) - df = cols + pd.DataFrame((np.random.randint(5, size=(n, 4)) - // [2, 1, 2, 1]).astype(str)) + cols = np.array(["key", "row", "item", "col"]) + df = cols + pd.DataFrame( + (np.random.randint(5, size=(n, 4)) // [2, 1, 2, 1]).astype(str) + ) df.columns = cols - df = df.join(pd.DataFrame(np.random.rand(n, 2).round(2)).add_prefix('val')) + df = df.join(pd.DataFrame(np.random.rand(n, 2).round(2)).add_prefix("val")) df @@ -762,24 +793,21 @@ This solution uses :func:`~pandas.pivot_table`. Also note that .. ipython:: python - df.pivot_table( - values='val0', index='row', columns='col', aggfunc='mean') + df.pivot_table(values="val0", index="row", columns="col", aggfunc="mean") Note that we can also replace the missing values by using the ``fill_value`` parameter. .. ipython:: python - df.pivot_table( - values='val0', index='row', columns='col', aggfunc='mean', fill_value=0) + df.pivot_table(values="val0", index="row", columns="col", aggfunc="mean", fill_value=0) Also note that we can pass in other aggregation functions as well. For example, we can also pass in ``sum``. .. ipython:: python - df.pivot_table( - values='val0', index='row', columns='col', aggfunc='sum', fill_value=0) + df.pivot_table(values="val0", index="row", columns="col", aggfunc="sum", fill_value=0) Another aggregation we can do is calculate the frequency in which the columns and rows occur together a.k.a. "cross tabulation". To do this, we can pass @@ -787,7 +815,7 @@ and rows occur together a.k.a. "cross tabulation". To do this, we can pass .. ipython:: python - df.pivot_table(index='row', columns='col', fill_value=0, aggfunc='size') + df.pivot_table(index="row", columns="col", fill_value=0, aggfunc="size") Pivoting with multiple aggregations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -797,24 +825,21 @@ We can also perform multiple aggregations. For example, to perform both a .. ipython:: python - df.pivot_table( - values='val0', index='row', columns='col', aggfunc=['mean', 'sum']) + df.pivot_table(values="val0", index="row", columns="col", aggfunc=["mean", "sum"]) Note to aggregate over multiple value columns, we can pass in a list to the ``values`` parameter. .. ipython:: python - df.pivot_table( - values=['val0', 'val1'], index='row', columns='col', aggfunc=['mean']) + df.pivot_table(values=["val0", "val1"], index="row", columns="col", aggfunc=["mean"]) Note to subdivide over multiple columns we can pass in a list to the ``columns`` parameter. .. ipython:: python - df.pivot_table( - values=['val0'], index='row', columns=['item', 'col'], aggfunc=['mean']) + df.pivot_table(values=["val0"], index="row", columns=["item", "col"], aggfunc=["mean"]) .. _reshaping.explode: @@ -827,28 +852,28 @@ Sometimes the values in a column are list-like. .. ipython:: python - keys = ['panda1', 'panda2', 'panda3'] - values = [['eats', 'shoots'], ['shoots', 'leaves'], ['eats', 'leaves']] - df = pd.DataFrame({'keys': keys, 'values': values}) + keys = ["panda1", "panda2", "panda3"] + values = [["eats", "shoots"], ["shoots", "leaves"], ["eats", "leaves"]] + df = pd.DataFrame({"keys": keys, "values": values}) df We can 'explode' the ``values`` column, transforming each list-like to a separate row, by using :meth:`~Series.explode`. This will replicate the index values from the original row: .. ipython:: python - df['values'].explode() + df["values"].explode() You can also explode the column in the ``DataFrame``. .. ipython:: python - df.explode('values') + df.explode("values") :meth:`Series.explode` will replace empty lists with ``np.nan`` and preserve scalar entries. The dtype of the resulting ``Series`` is always ``object``. .. ipython:: python - s = pd.Series([[1, 2, 3], 'foo', [], ['a', 'b']]) + s = pd.Series([[1, 2, 3], "foo", [], ["a", "b"]]) s s.explode() @@ -856,12 +881,11 @@ Here is a typical usecase. You have comma separated strings in a column and want .. ipython:: python - df = pd.DataFrame([{'var1': 'a,b,c', 'var2': 1}, - {'var1': 'd,e,f', 'var2': 2}]) + df = pd.DataFrame([{"var1": "a,b,c", "var2": 1}, {"var1": "d,e,f", "var2": 2}]) df Creating a long form DataFrame is now straightforward using explode and chained operations .. ipython:: python - df.assign(var1=df.var1.str.split(',')).explode('var1') + df.assign(var1=df.var1.str.split(",")).explode("var1") diff --git a/doc/source/user_guide/timedeltas.rst b/doc/source/user_guide/timedeltas.rst index 3979ad1f3e949..971a415088220 100644 --- a/doc/source/user_guide/timedeltas.rst +++ b/doc/source/user_guide/timedeltas.rst @@ -25,33 +25,33 @@ You can construct a ``Timedelta`` scalar through various arguments, including `I import datetime # strings - pd.Timedelta('1 days') - pd.Timedelta('1 days 00:00:00') - pd.Timedelta('1 days 2 hours') - pd.Timedelta('-1 days 2 min 3us') + pd.Timedelta("1 days") + pd.Timedelta("1 days 00:00:00") + pd.Timedelta("1 days 2 hours") + pd.Timedelta("-1 days 2 min 3us") # like datetime.timedelta # note: these MUST be specified as keyword arguments pd.Timedelta(days=1, seconds=1) # integers with a unit - pd.Timedelta(1, unit='d') + pd.Timedelta(1, unit="d") # from a datetime.timedelta/np.timedelta64 pd.Timedelta(datetime.timedelta(days=1, seconds=1)) - pd.Timedelta(np.timedelta64(1, 'ms')) + pd.Timedelta(np.timedelta64(1, "ms")) # negative Timedeltas have this string repr # to be more consistent with datetime.timedelta conventions - pd.Timedelta('-1us') + pd.Timedelta("-1us") # a NaT - pd.Timedelta('nan') - pd.Timedelta('nat') + pd.Timedelta("nan") + pd.Timedelta("nat") # ISO 8601 Duration strings - pd.Timedelta('P0DT0H1M0S') - pd.Timedelta('P0DT0H0M0.000000123S') + pd.Timedelta("P0DT0H1M0S") + pd.Timedelta("P0DT0H0M0.000000123S") :ref:`DateOffsets<timeseries.offsets>` (``Day, Hour, Minute, Second, Milli, Micro, Nano``) can also be used in construction. @@ -63,8 +63,9 @@ Further, operations among the scalars yield another scalar ``Timedelta``. .. ipython:: python - pd.Timedelta(pd.offsets.Day(2)) + pd.Timedelta(pd.offsets.Second(2)) +\ - pd.Timedelta('00:00:00.000123') + pd.Timedelta(pd.offsets.Day(2)) + pd.Timedelta(pd.offsets.Second(2)) + pd.Timedelta( + "00:00:00.000123" + ) to_timedelta ~~~~~~~~~~~~ @@ -78,21 +79,21 @@ You can parse a single string to a Timedelta: .. ipython:: python - pd.to_timedelta('1 days 06:05:01.00003') - pd.to_timedelta('15.5us') + pd.to_timedelta("1 days 06:05:01.00003") + pd.to_timedelta("15.5us") or a list/array of strings: .. ipython:: python - pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan']) + pd.to_timedelta(["1 days 06:05:01.00003", "15.5us", "nan"]) The ``unit`` keyword argument specifies the unit of the Timedelta: .. ipython:: python - pd.to_timedelta(np.arange(5), unit='s') - pd.to_timedelta(np.arange(5), unit='d') + pd.to_timedelta(np.arange(5), unit="s") + pd.to_timedelta(np.arange(5), unit="d") .. _timedeltas.limitations: @@ -118,11 +119,11 @@ subtraction operations on ``datetime64[ns]`` Series, or ``Timestamps``. .. ipython:: python - s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) + s = pd.Series(pd.date_range("2012-1-1", periods=3, freq="D")) td = pd.Series([pd.Timedelta(days=i) for i in range(3)]) - df = pd.DataFrame({'A': s, 'B': td}) + df = pd.DataFrame({"A": s, "B": td}) df - df['C'] = df['A'] + df['B'] + df["C"] = df["A"] + df["B"] df df.dtypes @@ -165,10 +166,10 @@ Operands can also appear in a reversed order (a singular object operated with a .. ipython:: python - A = s - pd.Timestamp('20120101') - pd.Timedelta('00:05:05') - B = s - pd.Series(pd.date_range('2012-1-2', periods=3, freq='D')) + A = s - pd.Timestamp("20120101") - pd.Timedelta("00:05:05") + B = s - pd.Series(pd.date_range("2012-1-2", periods=3, freq="D")) - df = pd.DataFrame({'A': A, 'B': B}) + df = pd.DataFrame({"A": A, "B": B}) df df.min() @@ -192,17 +193,17 @@ You can fillna on timedeltas, passing a timedelta to get a particular value. .. ipython:: python y.fillna(pd.Timedelta(0)) - y.fillna(pd.Timedelta(10, unit='s')) - y.fillna(pd.Timedelta('-1 days, 00:00:05')) + y.fillna(pd.Timedelta(10, unit="s")) + y.fillna(pd.Timedelta("-1 days, 00:00:05")) You can also negate, multiply and use ``abs`` on ``Timedeltas``: .. ipython:: python - td1 = pd.Timedelta('-1 days 2 hours 3 seconds') + td1 = pd.Timedelta("-1 days 2 hours 3 seconds") td1 -1 * td1 - - td1 + -td1 abs(td1) .. _timedeltas.timedeltas_reductions: @@ -215,12 +216,13 @@ Numeric reduction operation for ``timedelta64[ns]`` will return ``Timedelta`` ob .. ipython:: python - y2 = pd.Series(pd.to_timedelta(['-1 days +00:00:05', 'nat', - '-1 days +00:00:05', '1 days'])) + y2 = pd.Series( + pd.to_timedelta(["-1 days +00:00:05", "nat", "-1 days +00:00:05", "1 days"]) + ) y2 y2.mean() y2.median() - y2.quantile(.1) + y2.quantile(0.1) y2.sum() .. _timedeltas.timedeltas_convert: @@ -234,8 +236,8 @@ Note that division by the NumPy scalar is true division, while astyping is equiv .. ipython:: python - december = pd.Series(pd.date_range('20121201', periods=4)) - january = pd.Series(pd.date_range('20130101', periods=4)) + december = pd.Series(pd.date_range("20121201", periods=4)) + january = pd.Series(pd.date_range("20130101", periods=4)) td = january - december td[2] += datetime.timedelta(minutes=5, seconds=3) @@ -243,15 +245,15 @@ Note that division by the NumPy scalar is true division, while astyping is equiv td # to days - td / np.timedelta64(1, 'D') - td.astype('timedelta64[D]') + td / np.timedelta64(1, "D") + td.astype("timedelta64[D]") # to seconds - td / np.timedelta64(1, 's') - td.astype('timedelta64[s]') + td / np.timedelta64(1, "s") + td.astype("timedelta64[s]") # to months (these are constant months) - td / np.timedelta64(1, 'M') + td / np.timedelta64(1, "M") Dividing or multiplying a ``timedelta64[ns]`` Series by an integer or integer Series yields another ``timedelta64[ns]`` dtypes Series. @@ -305,7 +307,7 @@ You can access the value of the fields for a scalar ``Timedelta`` directly. .. ipython:: python - tds = pd.Timedelta('31 days 5 min 3 sec') + tds = pd.Timedelta("31 days 5 min 3 sec") tds.days tds.seconds (-tds).seconds @@ -325,9 +327,9 @@ You can convert a ``Timedelta`` to an `ISO 8601 Duration`_ string with the .. ipython:: python - pd.Timedelta(days=6, minutes=50, seconds=3, - milliseconds=10, microseconds=10, - nanoseconds=12).isoformat() + pd.Timedelta( + days=6, minutes=50, seconds=3, milliseconds=10, microseconds=10, nanoseconds=12 + ).isoformat() .. _ISO 8601 Duration: https://en.wikipedia.org/wiki/ISO_8601#Durations @@ -344,15 +346,21 @@ or ``np.timedelta64`` objects. Passing ``np.nan/pd.NaT/nat`` will represent miss .. ipython:: python - pd.TimedeltaIndex(['1 days', '1 days, 00:00:05', np.timedelta64(2, 'D'), - datetime.timedelta(days=2, seconds=2)]) + pd.TimedeltaIndex( + [ + "1 days", + "1 days, 00:00:05", + np.timedelta64(2, "D"), + datetime.timedelta(days=2, seconds=2), + ] + ) The string 'infer' can be passed in order to set the frequency of the index as the inferred frequency upon creation: .. ipython:: python - pd.TimedeltaIndex(['0 days', '10 days', '20 days'], freq='infer') + pd.TimedeltaIndex(["0 days", "10 days", "20 days"], freq="infer") Generating ranges of time deltas ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -363,24 +371,24 @@ calendar day: .. ipython:: python - pd.timedelta_range(start='1 days', periods=5) + pd.timedelta_range(start="1 days", periods=5) Various combinations of ``start``, ``end``, and ``periods`` can be used with ``timedelta_range``: .. ipython:: python - pd.timedelta_range(start='1 days', end='5 days') + pd.timedelta_range(start="1 days", end="5 days") - pd.timedelta_range(end='10 days', periods=4) + pd.timedelta_range(end="10 days", periods=4) The ``freq`` parameter can passed a variety of :ref:`frequency aliases <timeseries.offset_aliases>`: .. ipython:: python - pd.timedelta_range(start='1 days', end='2 days', freq='30T') + pd.timedelta_range(start="1 days", end="2 days", freq="30T") - pd.timedelta_range(start='1 days', periods=5, freq='2D5H') + pd.timedelta_range(start="1 days", periods=5, freq="2D5H") Specifying ``start``, ``end``, and ``periods`` will generate a range of evenly spaced @@ -389,9 +397,9 @@ in the resulting ``TimedeltaIndex``: .. ipython:: python - pd.timedelta_range('0 days', '4 days', periods=5) + pd.timedelta_range("0 days", "4 days", periods=5) - pd.timedelta_range('0 days', '4 days', periods=10) + pd.timedelta_range("0 days", "4 days", periods=10) Using the TimedeltaIndex ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -401,23 +409,22 @@ Similarly to other of the datetime-like indices, ``DatetimeIndex`` and ``PeriodI .. ipython:: python - s = pd.Series(np.arange(100), - index=pd.timedelta_range('1 days', periods=100, freq='h')) + s = pd.Series(np.arange(100), index=pd.timedelta_range("1 days", periods=100, freq="h")) s Selections work similarly, with coercion on string-likes and slices: .. ipython:: python - s['1 day':'2 day'] - s['1 day 01:00:00'] - s[pd.Timedelta('1 day 1h')] + s["1 day":"2 day"] + s["1 day 01:00:00"] + s[pd.Timedelta("1 day 1h")] Furthermore you can use partial string selection and the range will be inferred: .. ipython:: python - s['1 day':'1 day 5 hours'] + s["1 day":"1 day 5 hours"] Operations ~~~~~~~~~~ @@ -426,9 +433,9 @@ Finally, the combination of ``TimedeltaIndex`` with ``DatetimeIndex`` allow cert .. ipython:: python - tdi = pd.TimedeltaIndex(['1 days', pd.NaT, '2 days']) + tdi = pd.TimedeltaIndex(["1 days", pd.NaT, "2 days"]) tdi.to_list() - dti = pd.date_range('20130101', periods=3) + dti = pd.date_range("20130101", periods=3) dti.to_list() (dti + tdi).to_list() (dti - tdi).to_list() @@ -440,22 +447,22 @@ Similarly to frequency conversion on a ``Series`` above, you can convert these i .. ipython:: python - tdi / np.timedelta64(1, 's') - tdi.astype('timedelta64[s]') + tdi / np.timedelta64(1, "s") + tdi.astype("timedelta64[s]") Scalars type ops work as well. These can potentially return a *different* type of index. .. ipython:: python # adding or timedelta and date -> datelike - tdi + pd.Timestamp('20130101') + tdi + pd.Timestamp("20130101") # subtraction of a date and a timedelta -> datelike # note that trying to subtract a date from a Timedelta will raise an exception - (pd.Timestamp('20130101') - tdi).to_list() + (pd.Timestamp("20130101") - tdi).to_list() # timedelta + timedelta -> timedelta - tdi + pd.Timedelta('10 days') + tdi + pd.Timedelta("10 days") # division can result in a Timedelta if the divisor is an integer tdi / 2 @@ -472,4 +479,4 @@ Similar to :ref:`timeseries resampling <timeseries.resampling>`, we can resample .. ipython:: python - s.resample('D').mean() + s.resample("D").mean() diff --git a/setup.cfg b/setup.cfg index d938d2ef3972a..656bd82a2b65e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -33,6 +33,7 @@ exclude = env # exclude asv benchmark environments from linting [flake8-rst] +max-line-length = 88 bootstrap = import numpy as np import pandas as pd
Trying to make code blocks in documentation black compliant. Also a small update to the flake8-rst config making max-line-length equal to 88.
https://api.github.com/repos/pandas-dev/pandas/pulls/36700
2020-09-28T03:43:03Z
2020-09-29T20:29:25Z
2020-09-29T20:29:25Z
2020-10-01T08:08:54Z
CLN: Remove unused fixtures
diff --git a/pandas/conftest.py b/pandas/conftest.py index 604815d496f80..889bd2bed3504 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -174,14 +174,6 @@ def axis(request): axis_frame = axis -@pytest.fixture(params=[0, "index"], ids=lambda x: f"axis {repr(x)}") -def axis_series(request): - """ - Fixture for returning the axis numbers of a Series. - """ - return request.param - - @pytest.fixture(params=[True, False, None]) def observed(request): """ @@ -1239,15 +1231,6 @@ def spmatrix(request): return getattr(sparse, request.param + "_matrix") -@pytest.fixture(params=list(tm.cython_table)) -def cython_table_items(request): - """ - Yields a tuple of a function and its corresponding name. Correspond to - the list of aggregator "Cython functions" used on selected table items. - """ - return request.param - - @pytest.fixture( params=[ getattr(pd.offsets, o) diff --git a/pandas/tests/arrays/boolean/test_construction.py b/pandas/tests/arrays/boolean/test_construction.py index 2f5c61304d415..c9e96c437964f 100644 --- a/pandas/tests/arrays/boolean/test_construction.py +++ b/pandas/tests/arrays/boolean/test_construction.py @@ -7,14 +7,6 @@ from pandas.core.arrays.boolean import coerce_to_array -@pytest.fixture -def data(): - return pd.array( - [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False], - dtype="boolean", - ) - - def test_boolean_array_constructor(): values = np.array([True, False, True, False], dtype="bool") mask = np.array([False, False, False, True], dtype="bool") diff --git a/pandas/tests/arrays/boolean/test_function.py b/pandas/tests/arrays/boolean/test_function.py index 49a832f8dda20..1547f08fa66b0 100644 --- a/pandas/tests/arrays/boolean/test_function.py +++ b/pandas/tests/arrays/boolean/test_function.py @@ -5,14 +5,6 @@ import pandas._testing as tm -@pytest.fixture -def data(): - return pd.array( - [True, False] * 4 + [np.nan] + [True, False] * 44 + [np.nan] + [True, False], - dtype="boolean", - ) - - @pytest.mark.parametrize( "ufunc", [np.add, np.logical_or, np.logical_and, np.logical_xor] ) diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index f18117cfd3d1f..a2a9bb2c4b039 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -14,11 +14,6 @@ from pandas.core.arrays.sparse import SparseArray, SparseDtype -@pytest.fixture(params=["integer", "block"]) -def kind(request): - return request.param - - class TestSparseArray: def setup_method(self, method): self.arr_data = np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6]) diff --git a/pandas/tests/indexes/interval/test_setops.py b/pandas/tests/indexes/interval/test_setops.py index e3e5070064aff..562497b29af12 100644 --- a/pandas/tests/indexes/interval/test_setops.py +++ b/pandas/tests/indexes/interval/test_setops.py @@ -5,11 +5,6 @@ import pandas._testing as tm -@pytest.fixture(scope="class", params=[None, "foo"]) -def name(request): - return request.param - - def monotonic_index(start, end, dtype="int64", closed="right"): return IntervalIndex.from_breaks(np.arange(start, end, dtype=dtype), closed=closed) diff --git a/pandas/tests/resample/conftest.py b/pandas/tests/resample/conftest.py index fa53e49269f8b..cb62263b885aa 100644 --- a/pandas/tests/resample/conftest.py +++ b/pandas/tests/resample/conftest.py @@ -34,12 +34,6 @@ def downsample_method(request): return request.param -@pytest.fixture(params=upsample_methods) -def upsample_method(request): - """Fixture for parametrization of Grouper upsample methods.""" - return request.param - - @pytest.fixture(params=resample_methods) def resample_method(request): """Fixture for parametrization of Grouper resample methods."""
https://api.github.com/repos/pandas-dev/pandas/pulls/36699
2020-09-28T02:30:15Z
2020-09-30T00:13:03Z
2020-09-30T00:13:03Z
2020-09-30T00:20:19Z
DEPR: is_all_dates
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 88ad1dde5c9b0..290983659f93b 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -214,6 +214,8 @@ Deprecations - :meth:`DataFrame.lookup` is deprecated and will be removed in a future version, use :meth:`DataFrame.melt` and :meth:`DataFrame.loc` instead (:issue:`18682`) - The :meth:`Index.to_native_types` is deprecated. Use ``.astype(str)`` instead (:issue:`28867`) - Deprecated indexing :class:`DataFrame` rows with datetime-like strings ``df[string]``, use ``df.loc[string]`` instead (:issue:`36179`) +- Deprecated casting an object-dtype index of ``datetime`` objects to :class:`DatetimeIndex` in the :class:`Series` constructor (:issue:`23598`) +- Deprecated :meth:`Index.is_all_dates` (:issue:`27744`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 18a9c78912ba5..6f0aa70625c1d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9528,7 +9528,13 @@ def truncate( # if we have a date index, convert to dates, otherwise # treat like a slice - if ax.is_all_dates: + if ax._is_all_dates: + if is_object_dtype(ax.dtype): + warnings.warn( + "Treating object-dtype Index of date objects as DatetimeIndex " + "is deprecated, will be removed in a future version.", + FutureWarning, + ) from pandas.core.tools.datetimes import to_datetime before = to_datetime(before) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 35948a3f3dcf1..8ee09d8ad9be3 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2086,12 +2086,25 @@ def inferred_type(self) -> str_t: return lib.infer_dtype(self._values, skipna=False) @cache_readonly - def is_all_dates(self) -> bool: + def _is_all_dates(self) -> bool: """ Whether or not the index values only consist of dates. """ return is_datetime_array(ensure_object(self._values)) + @cache_readonly + def is_all_dates(self): + """ + Whether or not the index values only consist of dates. + """ + warnings.warn( + "Index.is_all_dates is deprecated, will be removed in a future version. " + "check index.inferred_type instead", + FutureWarning, + stacklevel=2, + ) + return self._is_all_dates + # -------------------------------------------------------------------- # Pickle Methods diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index e2f59ceb41db5..3d2820976a6af 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -98,7 +98,7 @@ class DatetimeIndexOpsMixin(ExtensionIndex): _hasnans = hasnans # for index / array -agnostic code @property - def is_all_dates(self) -> bool: + def _is_all_dates(self) -> bool: return True # ------------------------------------------------------------------------ diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 6b877b378a140..8855d987af745 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1092,7 +1092,7 @@ def func(self, other, sort=sort): # -------------------------------------------------------------------- @property - def is_all_dates(self) -> bool: + def _is_all_dates(self) -> bool: """ This is False even when left/right contain datetime-like objects, as the check is done on the Interval itself diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 1de392f6fc03f..c0b32c79435ed 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1733,7 +1733,7 @@ def to_flat_index(self): return Index(self._values, tupleize_cols=False) @property - def is_all_dates(self) -> bool: + def _is_all_dates(self) -> bool: return False def is_lexsorted(self) -> bool: diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 574c9adc31808..34bbaca06cc08 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -149,7 +149,7 @@ def _assert_safe_casting(cls, data, subarr): pass @property - def is_all_dates(self) -> bool: + def _is_all_dates(self) -> bool: """ Checks that all the labels are datetime objects. """ diff --git a/pandas/core/missing.py b/pandas/core/missing.py index f4182027e9e04..c2926debcb6d6 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -199,7 +199,7 @@ def interpolate_1d( return yvalues if method == "time": - if not getattr(xvalues, "is_all_dates", None): + if not getattr(xvalues, "_is_all_dates", None): # if not issubclass(xvalues.dtype.type, np.datetime64): raise ValueError( "time-weighted interpolation only works " @@ -327,7 +327,7 @@ def _interpolate_scipy_wrapper( "piecewise_polynomial": _from_derivatives, } - if getattr(x, "is_all_dates", False): + if getattr(x, "_is_all_dates", False): # GH 5975, scipy.interp1d can't handle datetime64s x, new_x = x._values.astype("i8"), new_x.astype("i8") diff --git a/pandas/core/series.py b/pandas/core/series.py index 41c3e8fa9d246..d2c702d924136 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -409,14 +409,20 @@ def _set_axis(self, axis: int, labels, fastpath: bool = False) -> None: if not fastpath: labels = ensure_index(labels) - is_all_dates = labels.is_all_dates - if is_all_dates: + if labels._is_all_dates: if not isinstance(labels, (DatetimeIndex, PeriodIndex, TimedeltaIndex)): try: labels = DatetimeIndex(labels) # need to set here because we changed the index if fastpath: self._mgr.set_axis(axis, labels) + warnings.warn( + "Automatically casting object-dtype Index of datetimes to " + "DatetimeIndex is deprecated and will be removed in a " + "future version. Explicitly cast to DatetimeIndex instead.", + FutureWarning, + stacklevel=3, + ) except (tslibs.OutOfBoundsDatetime, ValueError): # labels may exceeds datetime bounds, # or not be a DatetimeIndex diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 0c64ea824996f..f806325d60eca 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1238,7 +1238,7 @@ def get_label(i): # would be too close together. condition = ( not self._use_dynamic_x() - and (data.index.is_all_dates and self.use_index) + and (data.index._is_all_dates and self.use_index) and (not self.subplots or (self.subplots and self.sharex)) ) diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index b81f0f27e60ad..17a1c69858c11 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -871,7 +871,7 @@ def test_is_all_dates(self): pd.Timestamp("2017-01-01 00:00:00"), pd.Timestamp("2018-01-01 00:00:00") ) year_2017_index = pd.IntervalIndex([year_2017]) - assert not year_2017_index.is_all_dates + assert not year_2017_index._is_all_dates @pytest.mark.parametrize("key", [[5], (2, 3)]) def test_get_value_non_scalar_errors(self, key): diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py index b48f09457b96c..184cedea7dc5c 100644 --- a/pandas/tests/indexes/multi/test_equivalence.py +++ b/pandas/tests/indexes/multi/test_equivalence.py @@ -202,7 +202,7 @@ def test_is_(): def test_is_all_dates(idx): - assert not idx.is_all_dates + assert not idx._is_all_dates def test_is_numeric(idx): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 7cafdb61fcb31..77585f4003fe9 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1153,7 +1153,8 @@ def test_is_object(self, index, expected): indirect=["index"], ) def test_is_all_dates(self, index, expected): - assert index.is_all_dates is expected + with tm.assert_produces_warning(FutureWarning): + assert index.is_all_dates is expected def test_summary(self, index): self._check_method_works(Index._summary, index) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 0cc61cd7df389..7d5fea232817d 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -554,15 +554,17 @@ def test_string_slice(self): # string indexing against datetimelike with object # dtype should properly raises KeyError df = DataFrame([1], Index([pd.Timestamp("2011-01-01")], dtype=object)) - assert df.index.is_all_dates + assert df.index._is_all_dates with pytest.raises(KeyError, match="'2011'"): df["2011"] with pytest.raises(KeyError, match="'2011'"): - df.loc["2011", 0] + with tm.assert_produces_warning(FutureWarning): + # This does an is_all_dates check + df.loc["2011", 0] df = DataFrame() - assert not df.index.is_all_dates + assert not df.index._is_all_dates with pytest.raises(KeyError, match="'2011'"): df["2011"] diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 0942c79837e7c..10c9475401059 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -2384,10 +2384,16 @@ def test_series(self, setup_path): ts = tm.makeTimeSeries() self._check_roundtrip(ts, tm.assert_series_equal, path=setup_path) - ts2 = Series(ts.index, Index(ts.index, dtype=object)) + with tm.assert_produces_warning(FutureWarning): + # auto-casting object->DatetimeIndex deprecated + ts2 = Series(ts.index, Index(ts.index, dtype=object)) self._check_roundtrip(ts2, tm.assert_series_equal, path=setup_path) - ts3 = Series(ts.values, Index(np.asarray(ts.index, dtype=object), dtype=object)) + with tm.assert_produces_warning(FutureWarning): + # auto-casting object->DatetimeIndex deprecated + ts3 = Series( + ts.values, Index(np.asarray(ts.index, dtype=object), dtype=object) + ) self._check_roundtrip( ts3, tm.assert_series_equal, path=setup_path, check_index_type=False ) diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 203750757e28d..181d7de43d945 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -52,4 +52,4 @@ def test_set_index_makes_timeseries(self): s = Series(range(10)) s.index = idx - assert s.index.is_all_dates + assert s.index._is_all_dates diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 1b5fddaf14335..4ad4917533422 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -94,11 +94,11 @@ def test_scalar_conversion(self): def test_constructor(self, datetime_series): with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): empty_series = Series() - assert datetime_series.index.is_all_dates + assert datetime_series.index._is_all_dates # Pass in Series derived = Series(datetime_series) - assert derived.index.is_all_dates + assert derived.index._is_all_dates assert tm.equalContents(derived.index, datetime_series.index) # Ensure new index is not created @@ -109,9 +109,9 @@ def test_constructor(self, datetime_series): assert mixed.dtype == np.object_ assert mixed[1] is np.NaN - assert not empty_series.index.is_all_dates + assert not empty_series.index._is_all_dates with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): - assert not Series().index.is_all_dates + assert not Series().index._is_all_dates # exception raised is of type Exception with pytest.raises(Exception, match="Data must be 1-dimensional"): diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index b861b37b49f89..3aaecc37df56c 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -184,7 +184,9 @@ def test_timeseries_repr_object_dtype(self): index = Index( [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)], dtype=object ) - ts = Series(np.random.randn(len(index)), index) + with tm.assert_produces_warning(FutureWarning): + # Index.is_all_dates deprecated + ts = Series(np.random.randn(len(index)), index) repr(ts) ts = tm.makeTimeSeries(1000) diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 15b6481c08a61..bab3853e3bd1d 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -9,8 +9,10 @@ class TestTimeSeries: def test_timeseries_coercion(self): idx = tm.makeDateIndex(10000) - ser = Series(np.random.randn(len(idx)), idx.astype(object)) - assert ser.index.is_all_dates + with tm.assert_produces_warning(FutureWarning): + ser = Series(np.random.randn(len(idx)), idx.astype(object)) + with tm.assert_produces_warning(FutureWarning): + assert ser.index.is_all_dates assert isinstance(ser.index, DatetimeIndex) def test_contiguous_boolean_preserve_freq(self): diff --git a/pandas/tests/window/moments/test_moments_rolling_apply.py b/pandas/tests/window/moments/test_moments_rolling_apply.py index e48d88b365d8d..e9e672e1d3dae 100644 --- a/pandas/tests/window/moments/test_moments_rolling_apply.py +++ b/pandas/tests/window/moments/test_moments_rolling_apply.py @@ -122,13 +122,16 @@ def test_center_reindex_series(raw, series): s = [f"x{x:d}" for x in range(12)] minp = 10 - series_xp = ( - series.reindex(list(series.index) + s) - .rolling(window=25, min_periods=minp) - .apply(f, raw=raw) - .shift(-12) - .reindex(series.index) - ) + warn = None if raw else FutureWarning + with tm.assert_produces_warning(warn, check_stacklevel=False): + # GH#36697 is_all_dates deprecated + series_xp = ( + series.reindex(list(series.index) + s) + .rolling(window=25, min_periods=minp) + .apply(f, raw=raw) + .shift(-12) + .reindex(series.index) + ) series_rs = series.rolling(window=25, min_periods=minp, center=True).apply( f, raw=raw ) @@ -140,12 +143,15 @@ def test_center_reindex_frame(raw, frame): s = [f"x{x:d}" for x in range(12)] minp = 10 - frame_xp = ( - frame.reindex(list(frame.index) + s) - .rolling(window=25, min_periods=minp) - .apply(f, raw=raw) - .shift(-12) - .reindex(frame.index) - ) + warn = None if raw else FutureWarning + with tm.assert_produces_warning(warn, check_stacklevel=False): + # GH#36697 is_all_dates deprecated + frame_xp = ( + frame.reindex(list(frame.index) + s) + .rolling(window=25, min_periods=minp) + .apply(f, raw=raw) + .shift(-12) + .reindex(frame.index) + ) frame_rs = frame.rolling(window=25, min_periods=minp, center=True).apply(f, raw=raw) tm.assert_frame_equal(frame_xp, frame_rs)
- [x] closes #23598 - [x] closes #27744 - [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/36697
2020-09-28T01:30:00Z
2020-09-30T02:17:40Z
2020-09-30T02:17:40Z
2020-11-30T09:59:37Z
TYP: mostly datetimelike
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 41c4de51fc2e1..9db22df20e66d 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -288,6 +288,7 @@ class Categorical(NDArrayBackedExtensionArray, PandasObject, ObjectStringArrayMi # tolist is not actually deprecated, just suppressed in the __dir__ _deprecations = PandasObject._deprecations | frozenset(["tolist"]) _typ = "categorical" + _can_hold_na = True def __init__( self, values, categories=None, ordered=None, dtype=None, fastpath=False @@ -1268,10 +1269,10 @@ def __setstate__(self, state): setattr(self, k, v) @property - def nbytes(self): + def nbytes(self) -> int: return self._codes.nbytes + self.dtype.categories.values.nbytes - def memory_usage(self, deep=False): + def memory_usage(self, deep: bool = False) -> int: """ Memory usage of my values @@ -2144,10 +2145,6 @@ def equals(self, other: object) -> bool: return np.array_equal(self._codes, other_codes) return False - @property - def _can_hold_na(self): - return True - @classmethod def _concat_same_type(self, to_concat): from pandas.core.dtypes.concat import union_categoricals diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 0f723546fb4c2..83a9c0ba61c2d 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -117,7 +117,9 @@ class AttributesMixin: _data: np.ndarray @classmethod - def _simple_new(cls, values: np.ndarray, **kwargs): + def _simple_new( + cls, values: np.ndarray, freq: Optional[BaseOffset] = None, dtype=None + ): raise AbstractMethodError(cls) @property diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 6b051f1f73467..cd5449058fb33 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -6,6 +6,7 @@ from pandas._libs import lib, tslib from pandas._libs.tslibs import ( + BaseOffset, NaT, NaTType, Resolution, @@ -283,7 +284,9 @@ def __init__(self, values, dtype=DT64NS_DTYPE, freq=None, copy=False): type(self)._validate_frequency(self, freq) @classmethod - def _simple_new(cls, values, freq=None, dtype=DT64NS_DTYPE): + def _simple_new( + cls, values, freq: Optional[BaseOffset] = None, dtype=DT64NS_DTYPE + ) -> "DatetimeArray": assert isinstance(values, np.ndarray) if values.dtype != DT64NS_DTYPE: assert values.dtype == "i8" diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 372ef7df9dc3a..15f2842e39875 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -174,11 +174,13 @@ def __init__(self, values, freq=None, dtype=None, copy=False): self._dtype = PeriodDtype(freq) @classmethod - def _simple_new(cls, values: np.ndarray, freq=None, **kwargs) -> "PeriodArray": + def _simple_new( + cls, values: np.ndarray, freq: Optional[BaseOffset] = None, dtype=None + ) -> "PeriodArray": # alias for PeriodArray.__init__ assertion_msg = "Should be numpy array of type i8" assert isinstance(values, np.ndarray) and values.dtype == "i8", assertion_msg - return cls(values, freq=freq, **kwargs) + return cls(values, freq=freq, dtype=dtype) @classmethod def _from_sequence( diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index bf8b93b5a4164..9ea34d4680748 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -308,7 +308,7 @@ def value_counts(self, dropna=False): return value_counts(self._ndarray, dropna=dropna).astype("Int64") - def memory_usage(self, deep=False): + def memory_usage(self, deep: bool = False) -> int: result = self._ndarray.nbytes if deep: return result + lib.memory_usage_of_objects(self._ndarray) diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 145380ecce9fd..6ca57e7872910 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -1,10 +1,11 @@ from datetime import timedelta -from typing import List, Union +from typing import List, Optional, Union import numpy as np from pandas._libs import lib, tslibs from pandas._libs.tslibs import ( + BaseOffset, NaT, NaTType, Period, @@ -45,8 +46,8 @@ from pandas.core.ops.common import unpack_zerodim_and_defer -def _field_accessor(name, alias, docstring=None): - def f(self): +def _field_accessor(name: str, alias: str, docstring: str): + def f(self) -> np.ndarray: values = self.asi8 result = get_timedelta_field(values, alias) if self._hasnans: @@ -121,7 +122,7 @@ def _box_func(self, x) -> Union[Timedelta, NaTType]: return Timedelta(x, unit="ns") @property - def dtype(self): + def dtype(self) -> np.dtype: """ The dtype for the TimedeltaArray. @@ -196,7 +197,9 @@ def __init__(self, values, dtype=TD64NS_DTYPE, freq=lib.no_default, copy=False): type(self)._validate_frequency(self, freq) @classmethod - def _simple_new(cls, values, freq=None, dtype=TD64NS_DTYPE): + def _simple_new( + cls, values, freq: Optional[BaseOffset] = None, dtype=TD64NS_DTYPE + ) -> "TimedeltaArray": assert dtype == TD64NS_DTYPE, dtype assert isinstance(values, np.ndarray), type(values) if values.dtype != TD64NS_DTYPE: @@ -211,8 +214,13 @@ def _simple_new(cls, values, freq=None, dtype=TD64NS_DTYPE): @classmethod def _from_sequence( - cls, data, dtype=TD64NS_DTYPE, copy=False, freq=lib.no_default, unit=None - ): + cls, + data, + dtype=TD64NS_DTYPE, + copy: bool = False, + freq=lib.no_default, + unit=None, + ) -> "TimedeltaArray": if dtype: _validate_td64_dtype(dtype) @@ -240,7 +248,9 @@ def _from_sequence( return result @classmethod - def _generate_range(cls, start, end, periods, freq, closed=None): + def _generate_range( + cls, start, end, periods, freq, closed=None + ) -> "TimedeltaArray": periods = dtl.validate_periods(periods) if freq is None and any(x is None for x in [periods, start, end]): @@ -298,7 +308,7 @@ def _maybe_clear_freq(self): # ---------------------------------------------------------------- # Array-Like / EA-Interface Methods - def astype(self, dtype, copy=True): + def astype(self, dtype, copy: bool = True): # We handle # --> timedelta64[ns] # --> timedelta64 @@ -461,7 +471,7 @@ def _addsub_object_array(self, other, op): ) from err @unpack_zerodim_and_defer("__mul__") - def __mul__(self, other): + def __mul__(self, other) -> "TimedeltaArray": if is_scalar(other): # numpy will accept float and int, raise TypeError for others result = self._data * other @@ -737,22 +747,22 @@ def __rdivmod__(self, other): res2 = other - res1 * self return res1, res2 - def __neg__(self): + def __neg__(self) -> "TimedeltaArray": if self.freq is not None: return type(self)(-self._data, freq=-self.freq) return type(self)(-self._data) - def __pos__(self): + def __pos__(self) -> "TimedeltaArray": return type(self)(self._data, freq=self.freq) - def __abs__(self): + def __abs__(self) -> "TimedeltaArray": # Note: freq is not preserved return type(self)(np.abs(self._data)) # ---------------------------------------------------------------- # Conversion Methods - Vectorized analogues of Timedelta methods - def total_seconds(self): + def total_seconds(self) -> np.ndarray: """ Return total duration of each element expressed in seconds. diff --git a/pandas/core/base.py b/pandas/core/base.py index 4d5cddc086b2a..a50181c1be2f0 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1347,7 +1347,7 @@ def memory_usage(self, deep=False): Parameters ---------- - deep : bool + deep : bool, default False Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption. diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 3d2820976a6af..23cc93b9ecb33 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -105,7 +105,7 @@ def _is_all_dates(self) -> bool: # Abstract data attributes @property - def values(self): + def values(self) -> np.ndarray: # Note: PeriodArray overrides this to return an ndarray of objects. return self._data._data diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 900d3f9f1866b..27b60747015de 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -60,7 +60,7 @@ def _new_PeriodIndex(cls, **d): @inherit_names( - ["strftime", "to_timestamp", "start_time", "end_time"] + PeriodArray._field_ops, + ["strftime", "start_time", "end_time"] + PeriodArray._field_ops, PeriodArray, wrap=True, ) @@ -149,12 +149,18 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): # -------------------------------------------------------------------- # methods that dispatch to array and wrap result in PeriodIndex + # These are defined here instead of via inherit_names for mypy @doc(PeriodArray.asfreq) def asfreq(self, freq=None, how: str = "E") -> "PeriodIndex": arr = self._data.asfreq(freq, how) return type(self)._simple_new(arr, name=self.name) + @doc(PeriodArray.to_timestamp) + def to_timestamp(self, freq=None, how="start") -> DatetimeIndex: + arr = self._data.to_timestamp(freq, how) + return DatetimeIndex._simple_new(arr, name=self.name) + # ------------------------------------------------------------------------ # Index Constructors @@ -244,11 +250,11 @@ def _simple_new(cls, values: PeriodArray, name: Label = None): # Data @property - def values(self): + def values(self) -> np.ndarray: return np.asarray(self) @property - def _has_complex_internals(self): + def _has_complex_internals(self) -> bool: # used to avoid libreduction code paths, which raise or require conversion return True @@ -402,7 +408,7 @@ def asof_locs(self, where, mask: np.ndarray) -> np.ndarray: return result @doc(Index.astype) - def astype(self, dtype, copy=True, how="start"): + def astype(self, dtype, copy: bool = True, how="start"): dtype = pandas_dtype(dtype) if is_datetime64_any_dtype(dtype): @@ -421,7 +427,7 @@ def is_full(self) -> bool: """ if len(self) == 0: return True - if not self.is_monotonic: + if not self.is_monotonic_increasing: raise ValueError("Index is not monotonic") values = self.asi8 return ((values[1:] - values[:-1]) < 2).all() @@ -432,7 +438,7 @@ def inferred_type(self) -> str: # indexing return "period" - def insert(self, loc, item): + def insert(self, loc: int, item): if not isinstance(item, Period) or self.freq != item.freq: return self.astype(object).insert(loc, item) @@ -706,7 +712,7 @@ def _union(self, other, sort): # ------------------------------------------------------------------------ - def memory_usage(self, deep=False): + def memory_usage(self, deep: bool = False) -> int: result = super().memory_usage(deep=deep) if hasattr(self, "_cache") and "_int64index" in self._cache: result += self._int64index.memory_usage(deep=deep) diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 20ebc80c7e0af..854c4e33eca01 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -184,7 +184,7 @@ def _formatter_func(self): # ------------------------------------------------------------------- @doc(Index.astype) - def astype(self, dtype, copy=True): + def astype(self, dtype, copy: bool = True): dtype = pandas_dtype(dtype) if is_timedelta64_dtype(dtype) and not is_timedelta64_ns_dtype(dtype): # Have to repeat the check for 'timedelta64' (not ns) dtype diff --git a/pandas/core/series.py b/pandas/core/series.py index d2c702d924136..fca1b6b08b434 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -394,7 +394,7 @@ def _constructor_expanddim(self) -> Type["DataFrame"]: # types @property - def _can_hold_na(self): + def _can_hold_na(self) -> bool: return self._mgr._can_hold_na _index = None @@ -4904,10 +4904,7 @@ def to_timestamp(self, freq=None, how="start", copy=True) -> "Series": if not isinstance(self.index, PeriodIndex): raise TypeError(f"unsupported Type {type(self.index).__name__}") - # error: "PeriodIndex" has no attribute "to_timestamp" - new_index = self.index.to_timestamp( # type: ignore[attr-defined] - freq=freq, how=how - ) + new_index = self.index.to_timestamp(freq=freq, how=how) return self._constructor(new_values, index=new_index).__finalize__( self, method="to_timestamp" ) diff --git a/pandas/tests/extension/arrow/arrays.py b/pandas/tests/extension/arrow/arrays.py index 8a18f505058bc..5e930b7b22f30 100644 --- a/pandas/tests/extension/arrow/arrays.py +++ b/pandas/tests/extension/arrow/arrays.py @@ -68,6 +68,8 @@ def construct_array_type(cls) -> Type["ArrowStringArray"]: class ArrowExtensionArray(ExtensionArray): + _data: pa.ChunkedArray + @classmethod def from_scalars(cls, values): arr = pa.chunked_array([pa.array(np.asarray(values))]) @@ -129,7 +131,7 @@ def __or__(self, other): return self._boolean_op(other, operator.or_) @property - def nbytes(self): + def nbytes(self) -> int: return sum( x.size for chunk in self._data.chunks
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/36696
2020-09-28T01:25:33Z
2020-10-01T09:05:44Z
2020-10-01T09:05:44Z
2020-10-01T14:50:56Z
API: Deprecate regex=True default in Series.str.replace
diff --git a/doc/source/user_guide/text.rst b/doc/source/user_guide/text.rst index 2b27d37904599..9dd4fb68ae26a 100644 --- a/doc/source/user_guide/text.rst +++ b/doc/source/user_guide/text.rst @@ -255,7 +255,7 @@ i.e., from the end of the string to the beginning of the string: s2.str.rsplit("_", expand=True, n=1) -``replace`` by default replaces `regular expressions +``replace`` optionally uses `regular expressions <https://docs.python.org/3/library/re.html>`__: .. ipython:: python @@ -265,35 +265,27 @@ i.e., from the end of the string to the beginning of the string: dtype="string", ) s3 - s3.str.replace("^.a|dog", "XX-XX ", case=False) + s3.str.replace("^.a|dog", "XX-XX ", case=False, regex=True) -Some caution must be taken to keep regular expressions in mind! For example, the -following code will cause trouble because of the regular expression meaning of -``$``: - -.. ipython:: python - - # Consider the following badly formatted financial data - dollars = pd.Series(["12", "-$10", "$10,000"], dtype="string") - - # This does what you'd naively expect: - dollars.str.replace("$", "") +.. warning:: - # But this doesn't: - dollars.str.replace("-$", "-") + Some caution must be taken when dealing with regular expressions! The current behavior + is to treat single character patterns as literal strings, even when ``regex`` is set + to ``True``. This behavior is deprecated and will be removed in a future version so + that the ``regex`` keyword is always respected. - # We need to escape the special character (for >1 len patterns) - dollars.str.replace(r"-\$", "-") +.. versionchanged:: 1.2.0 -If you do want literal replacement of a string (equivalent to -:meth:`str.replace`), you can set the optional ``regex`` parameter to -``False``, rather than escaping each character. In this case both ``pat`` -and ``repl`` must be strings: +If you want literal replacement of a string (equivalent to :meth:`str.replace`), you +can set the optional ``regex`` parameter to ``False``, rather than escaping each +character. In this case both ``pat`` and ``repl`` must be strings: .. ipython:: python + dollars = pd.Series(["12", "-$10", "$10,000"], dtype="string") + # These lines are equivalent - dollars.str.replace(r"-\$", "-") + dollars.str.replace(r"-\$", "-", regex=True) dollars.str.replace("-$", "-", regex=False) The ``replace`` method can also take a callable as replacement. It is called @@ -310,7 +302,10 @@ positional argument (a regex object) and return a string. return m.group(0)[::-1] - pd.Series(["foo 123", "bar baz", np.nan], dtype="string").str.replace(pat, repl) + pd.Series( + ["foo 123", "bar baz", np.nan], + dtype="string" + ).str.replace(pat, repl, regex=True) # Using regex groups pat = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)" @@ -320,7 +315,9 @@ positional argument (a regex object) and return a string. return m.group("two").swapcase() - pd.Series(["Foo Bar Baz", np.nan], dtype="string").str.replace(pat, repl) + pd.Series(["Foo Bar Baz", np.nan], dtype="string").str.replace( + pat, repl, regex=True + ) The ``replace`` method also accepts a compiled regular expression object from :func:`re.compile` as a pattern. All flags should be included in the @@ -331,7 +328,7 @@ compiled regular expression object. import re regex_pat = re.compile(r"^.a|dog", flags=re.IGNORECASE) - s3.str.replace(regex_pat, "XX-XX ") + s3.str.replace(regex_pat, "XX-XX ", regex=True) Including a ``flags`` argument when calling ``replace`` with a compiled regular expression object will raise a ``ValueError``. diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 2f462b16ddf78..d8ae229dc354c 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -287,6 +287,7 @@ Deprecations - Deprecated indexing :class:`DataFrame` rows with datetime-like strings ``df[string]``, use ``df.loc[string]`` instead (:issue:`36179`) - Deprecated casting an object-dtype index of ``datetime`` objects to :class:`DatetimeIndex` in the :class:`Series` constructor (:issue:`23598`) - Deprecated :meth:`Index.is_all_dates` (:issue:`27744`) +- The default value of ``regex`` for :meth:`Series.str.replace` will change from ``True`` to ``False`` in a future release. In addition, single character regular expressions will *not* be treated as literal strings when ``regex=True`` is set. (:issue:`24804`) - Deprecated automatic alignment on comparison operations between :class:`DataFrame` and :class:`Series`, do ``frame, ser = frame.align(ser, axis=1, copy=False)`` before e.g. ``frame == ser`` (:issue:`28759`) - :meth:`Rolling.count` with ``min_periods=None`` will default to the size of the window in a future version (:issue:`31302`) - Deprecated slice-indexing on timezone-aware :class:`DatetimeIndex` with naive ``datetime`` objects, to match scalar indexing behavior (:issue:`36148`) diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index e2161013c0166..bcdb223415813 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -483,7 +483,7 @@ def melt_stub(df, stub: str, i, j, value_vars, sep: str): var_name=j, ) newdf[j] = Categorical(newdf[j]) - newdf[j] = newdf[j].str.replace(re.escape(stub + sep), "") + newdf[j] = newdf[j].str.replace(re.escape(stub + sep), "", regex=True) # GH17627 Cast numerics suffixes to int/float newdf[j] = to_numeric(newdf[j], errors="ignore") diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index cae8cc1baf1df..df37cd47a9e7c 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -1170,7 +1170,7 @@ def fullmatch(self, pat, case=True, flags=0, na=None): return self._wrap_result(result, fill_value=na, returns_string=False) @forbid_nonstring_types(["bytes"]) - def replace(self, pat, repl, n=-1, case=None, flags=0, regex=True): + def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None): r""" Replace each occurrence of pattern/regex in the Series/Index. @@ -1288,6 +1288,20 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=True): 2 NaN dtype: object """ + if regex is None: + if isinstance(pat, str) and any(c in pat for c in ".+*|^$?[](){}\\"): + # warn only in cases where regex behavior would differ from literal + msg = ( + "The default value of regex will change from True to False " + "in a future version." + ) + if len(pat) == 1: + msg += ( + " In addition, single character regular expressions will" + "*not* be treated as literal strings when regex=True." + ) + warnings.warn(msg, FutureWarning, stacklevel=3) + regex = True result = self._array._str_replace( pat, repl, n=n, case=case, flags=flags, regex=regex ) diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index e255d46e81851..79d6fc22aba97 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -449,3 +449,14 @@ def test_replace_with_compiled_regex(self): result = s.replace({regex: "z"}, regex=True) expected = pd.Series(["z", "b", "c"]) tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("pattern", ["^.$", "."]) + def test_str_replace_regex_default_raises_warning(self, pattern): + # https://github.com/pandas-dev/pandas/pull/24809 + s = pd.Series(["a", "b", "c"]) + msg = r"The default value of regex will change from True to False" + if len(pattern) == 1: + msg += r".*single character regular expressions.*not.*literal strings" + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False) as w: + s.str.replace(pattern, "") + assert re.match(msg, str(w[0].message)) diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 6ad55639ae5d8..61df5d4d5fdd6 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -984,11 +984,11 @@ def test_casemethods(self): def test_replace(self): values = Series(["fooBAD__barBAD", np.nan]) - result = values.str.replace("BAD[_]*", "") + result = values.str.replace("BAD[_]*", "", regex=True) exp = Series(["foobar", np.nan]) tm.assert_series_equal(result, exp) - result = values.str.replace("BAD[_]*", "", n=1) + result = values.str.replace("BAD[_]*", "", n=1, regex=True) exp = Series(["foobarBAD", np.nan]) tm.assert_series_equal(result, exp) @@ -997,7 +997,7 @@ def test_replace(self): ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0] ) - rs = Series(mixed).str.replace("BAD[_]*", "") + rs = Series(mixed).str.replace("BAD[_]*", "", regex=True) xp = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) @@ -1005,7 +1005,9 @@ def test_replace(self): # flags + unicode values = Series([b"abcd,\xc3\xa0".decode("utf-8")]) exp = Series([b"abcd, \xc3\xa0".decode("utf-8")]) - result = values.str.replace(r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE) + result = values.str.replace( + r"(?<=\w),(?=\w)", ", ", flags=re.UNICODE, regex=True + ) tm.assert_series_equal(result, exp) # GH 13438 @@ -1023,7 +1025,7 @@ def test_replace_callable(self): # test with callable repl = lambda m: m.group(0).swapcase() - result = values.str.replace("[a-z][A-Z]{2}", repl, n=2) + result = values.str.replace("[a-z][A-Z]{2}", repl, n=2, regex=True) exp = Series(["foObaD__baRbaD", np.nan]) tm.assert_series_equal(result, exp) @@ -1049,7 +1051,7 @@ def test_replace_callable(self): values = Series(["Foo Bar Baz", np.nan]) pat = r"(?P<first>\w+) (?P<middle>\w+) (?P<last>\w+)" repl = lambda m: m.group("middle").swapcase() - result = values.str.replace(pat, repl) + result = values.str.replace(pat, repl, regex=True) exp = Series(["bAR", np.nan]) tm.assert_series_equal(result, exp) @@ -1059,11 +1061,11 @@ def test_replace_compiled_regex(self): # test with compiled regex pat = re.compile(r"BAD[_]*") - result = values.str.replace(pat, "") + result = values.str.replace(pat, "", regex=True) exp = Series(["foobar", np.nan]) tm.assert_series_equal(result, exp) - result = values.str.replace(pat, "", n=1) + result = values.str.replace(pat, "", n=1, regex=True) exp = Series(["foobarBAD", np.nan]) tm.assert_series_equal(result, exp) @@ -1072,7 +1074,7 @@ def test_replace_compiled_regex(self): ["aBAD", np.nan, "bBAD", True, datetime.today(), "fooBAD", None, 1, 2.0] ) - rs = Series(mixed).str.replace(pat, "") + rs = Series(mixed).str.replace(pat, "", regex=True) xp = Series(["a", np.nan, "b", np.nan, np.nan, "foo", np.nan, np.nan, np.nan]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) @@ -1110,7 +1112,7 @@ def test_replace_literal(self): # GH16808 literal replace (regex=False vs regex=True) values = Series(["f.o", "foo", np.nan]) exp = Series(["bao", "bao", np.nan]) - result = values.str.replace("f.", "ba") + result = values.str.replace("f.", "ba", regex=True) tm.assert_series_equal(result, exp) exp = Series(["bao", "foo", np.nan]) @@ -3044,7 +3046,7 @@ def test_pipe_failures(self): tm.assert_series_equal(result, exp) - result = s.str.replace("|", " ") + result = s.str.replace("|", " ", regex=False) exp = Series(["A B C"]) tm.assert_series_equal(result, exp) @@ -3345,7 +3347,7 @@ def test_replace_moar(self): ) tm.assert_series_equal(result, expected) - result = s.str.replace("^.a|dog", "XX-XX ", case=False) + result = s.str.replace("^.a|dog", "XX-XX ", case=False, regex=True) expected = Series( [ "A",
From some old discussion it looks like there was interest in changing the default value of regex from True to False within Series.str.replace. I think this makes sense since it would align this method with others within pandas along with the standard library, and would also make fixing https://github.com/pandas-dev/pandas/issues/24804 slightly less disruptive. I'm assuming this would warrant a deprecation note in the next whatsnew? I think this part of the docs will need to be updated: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html#splitting-and-replacing-strings https://github.com/pandas-dev/pandas/pull/24809
https://api.github.com/repos/pandas-dev/pandas/pulls/36695
2020-09-28T00:58:54Z
2020-10-10T23:01:24Z
2020-10-10T23:01:24Z
2020-10-10T23:01:27Z
ENH: DatetimeArray/PeriodArray median
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 83a9c0ba61c2d..1f11ca6d4cc8b 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1556,6 +1556,28 @@ def mean(self, skipna=True): # Don't have to worry about NA `result`, since no NA went in. return self._box_func(result) + def median(self, axis: Optional[int] = None, skipna: bool = True, *args, **kwargs): + nv.validate_median(args, kwargs) + + if axis is not None and abs(axis) >= self.ndim: + raise ValueError("abs(axis) must be less than ndim") + + if self.size == 0: + if self.ndim == 1 or axis is None: + return NaT + shape = list(self.shape) + del shape[axis] + shape = [1 if x == 0 else x for x in shape] + result = np.empty(shape, dtype="i8") + result.fill(iNaT) + return self._from_backing_data(result) + + mask = self.isna() + result = nanops.nanmedian(self.asi8, axis=axis, skipna=skipna, mask=mask) + if axis is None or self.ndim == 1: + return self._box_func(result) + return self._from_backing_data(result.astype("i8")) + DatetimeLikeArrayMixin._add_comparison_ops() diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index c97c7da375fd4..f85e3e716bbf9 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -393,19 +393,6 @@ def std( result = nanops.nanstd(self._data, axis=axis, skipna=skipna, ddof=ddof) return Timedelta(result) - def median( - self, - axis=None, - out=None, - overwrite_input: bool = False, - keepdims: bool = False, - skipna: bool = True, - ): - nv.validate_median( - (), dict(out=out, overwrite_input=overwrite_input, keepdims=keepdims) - ) - return nanops.nanmedian(self._data, axis=axis, skipna=skipna) - # ---------------------------------------------------------------- # Rendering Methods diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index e7605125e7420..9f136b4979bb7 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -454,8 +454,9 @@ def test_tz_dtype_matches(self): class TestReductions: - @pytest.mark.parametrize("tz", [None, "US/Central"]) - def test_min_max(self, tz): + @pytest.fixture + def arr1d(self, tz_naive_fixture): + tz = tz_naive_fixture dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]") arr = DatetimeArray._from_sequence( [ @@ -468,6 +469,11 @@ def test_min_max(self, tz): ], dtype=dtype, ) + return arr + + def test_min_max(self, arr1d): + arr = arr1d + tz = arr.tz result = arr.min() expected = pd.Timestamp("2000-01-02", tz=tz) @@ -493,3 +499,70 @@ def test_min_max_empty(self, skipna, tz): result = arr.max(skipna=skipna) assert result is pd.NaT + + @pytest.mark.parametrize("tz", [None, "US/Central"]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_median_empty(self, skipna, tz): + dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]") + arr = DatetimeArray._from_sequence([], dtype=dtype) + result = arr.median(skipna=skipna) + assert result is pd.NaT + + arr = arr.reshape(0, 3) + result = arr.median(axis=0, skipna=skipna) + expected = type(arr)._from_sequence([pd.NaT, pd.NaT, pd.NaT], dtype=arr.dtype) + tm.assert_equal(result, expected) + + result = arr.median(axis=1, skipna=skipna) + expected = type(arr)._from_sequence([pd.NaT], dtype=arr.dtype) + tm.assert_equal(result, expected) + + def test_median(self, arr1d): + arr = arr1d + + result = arr.median() + assert result == arr[0] + result = arr.median(skipna=False) + assert result is pd.NaT + + result = arr.dropna().median(skipna=False) + assert result == arr[0] + + result = arr.median(axis=0) + assert result == arr[0] + + def test_median_axis(self, arr1d): + arr = arr1d + assert arr.median(axis=0) == arr.median() + assert arr.median(axis=0, skipna=False) is pd.NaT + + msg = r"abs\(axis\) must be less than ndim" + with pytest.raises(ValueError, match=msg): + arr.median(axis=1) + + @pytest.mark.filterwarnings("ignore:All-NaN slice encountered:RuntimeWarning") + def test_median_2d(self, arr1d): + arr = arr1d.reshape(1, -1) + + # axis = None + assert arr.median() == arr1d.median() + assert arr.median(skipna=False) is pd.NaT + + # axis = 0 + result = arr.median(axis=0) + expected = arr1d + tm.assert_equal(result, expected) + + # Since column 3 is all-NaT, we get NaT there with or without skipna + result = arr.median(axis=0, skipna=False) + expected = arr1d + tm.assert_equal(result, expected) + + # axis = 1 + result = arr.median(axis=1) + expected = type(arr)._from_sequence([arr1d.median()]) + tm.assert_equal(result, expected) + + result = arr.median(axis=1, skipna=False) + expected = type(arr)._from_sequence([pd.NaT], dtype=arr.dtype) + tm.assert_equal(result, expected) diff --git a/pandas/tests/reductions/test_stat_reductions.py b/pandas/tests/reductions/test_stat_reductions.py index 59dbcb9ab9fa0..fd2746672a0eb 100644 --- a/pandas/tests/reductions/test_stat_reductions.py +++ b/pandas/tests/reductions/test_stat_reductions.py @@ -96,7 +96,7 @@ def _check_stat_op( string_series_[5:15] = np.NaN # mean, idxmax, idxmin, min, and max are valid for dates - if name not in ["max", "min", "mean"]: + if name not in ["max", "min", "mean", "median"]: ds = Series(pd.date_range("1/1/2001", periods=10)) with pytest.raises(TypeError): f(ds)
- [x] closes #33760 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry nanops.nanmedian needs to be re-worked, and there's a lot more we can do to share reduction tests. saving for separate branches.
https://api.github.com/repos/pandas-dev/pandas/pulls/36694
2020-09-28T00:42:32Z
2020-10-07T03:28:11Z
2020-10-07T03:28:11Z
2020-10-07T15:00:51Z
CLN: OrderedDict->dict
diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index 5f627aeade47c..938f57f504b04 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -17,7 +17,6 @@ and methods that are spread throughout the codebase. This module will make it easier to adjust to future upstream changes in the analogous numpy signatures. """ -from collections import OrderedDict from distutils.version import LooseVersion from typing import Any, Dict, Optional, Union @@ -117,7 +116,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs): return skipna -ARGSORT_DEFAULTS: "OrderedDict[str, Optional[Union[int, str]]]" = OrderedDict() +ARGSORT_DEFAULTS: Dict[str, Optional[Union[int, str]]] = {} ARGSORT_DEFAULTS["axis"] = -1 ARGSORT_DEFAULTS["kind"] = "quicksort" ARGSORT_DEFAULTS["order"] = None @@ -133,7 +132,7 @@ def validate_argmax_with_skipna(skipna, args, kwargs): # two different signatures of argsort, this second validation # for when the `kind` param is supported -ARGSORT_DEFAULTS_KIND: "OrderedDict[str, Optional[int]]" = OrderedDict() +ARGSORT_DEFAULTS_KIND: Dict[str, Optional[int]] = {} ARGSORT_DEFAULTS_KIND["axis"] = -1 ARGSORT_DEFAULTS_KIND["order"] = None validate_argsort_kind = CompatValidator( @@ -178,7 +177,7 @@ def validate_clip_with_axis(axis, args, kwargs): return axis -CUM_FUNC_DEFAULTS: "OrderedDict[str, Any]" = OrderedDict() +CUM_FUNC_DEFAULTS: Dict[str, Any] = {} CUM_FUNC_DEFAULTS["dtype"] = None CUM_FUNC_DEFAULTS["out"] = None validate_cum_func = CompatValidator( @@ -204,7 +203,7 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name): return skipna -ALLANY_DEFAULTS: "OrderedDict[str, Optional[bool]]" = OrderedDict() +ALLANY_DEFAULTS: Dict[str, Optional[bool]] = {} ALLANY_DEFAULTS["dtype"] = None ALLANY_DEFAULTS["out"] = None ALLANY_DEFAULTS["keepdims"] = False @@ -241,13 +240,13 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name): ROUND_DEFAULTS, fname="round", method="both", max_fname_arg_count=1 ) -SORT_DEFAULTS: "OrderedDict[str, Optional[Union[int, str]]]" = OrderedDict() +SORT_DEFAULTS: Dict[str, Optional[Union[int, str]]] = {} SORT_DEFAULTS["axis"] = -1 SORT_DEFAULTS["kind"] = "quicksort" SORT_DEFAULTS["order"] = None validate_sort = CompatValidator(SORT_DEFAULTS, fname="sort", method="kwargs") -STAT_FUNC_DEFAULTS: "OrderedDict[str, Optional[Any]]" = OrderedDict() +STAT_FUNC_DEFAULTS: Dict[str, Optional[Any]] = {} STAT_FUNC_DEFAULTS["dtype"] = None STAT_FUNC_DEFAULTS["out"] = None @@ -281,13 +280,13 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name): MEDIAN_DEFAULTS, fname="median", method="both", max_fname_arg_count=1 ) -STAT_DDOF_FUNC_DEFAULTS: "OrderedDict[str, Optional[bool]]" = OrderedDict() +STAT_DDOF_FUNC_DEFAULTS: Dict[str, Optional[bool]] = {} STAT_DDOF_FUNC_DEFAULTS["dtype"] = None STAT_DDOF_FUNC_DEFAULTS["out"] = None STAT_DDOF_FUNC_DEFAULTS["keepdims"] = False validate_stat_ddof_func = CompatValidator(STAT_DDOF_FUNC_DEFAULTS, method="kwargs") -TAKE_DEFAULTS: "OrderedDict[str, Optional[str]]" = OrderedDict() +TAKE_DEFAULTS: Dict[str, Optional[str]] = {} TAKE_DEFAULTS["out"] = None TAKE_DEFAULTS["mode"] = "raise" validate_take = CompatValidator(TAKE_DEFAULTS, fname="take", method="kwargs") diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 3f859bb4ee39e..5c6a47c57970b 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from datetime import datetime from itertools import chain import warnings @@ -1225,7 +1224,7 @@ def test_agg_reduce(self, axis, float_frame): tm.assert_frame_equal(result, expected) # dict input with scalars - func = OrderedDict([(name1, "mean"), (name2, "sum")]) + func = dict([(name1, "mean"), (name2, "sum")]) result = float_frame.agg(func, axis=axis) expected = Series( [ @@ -1237,7 +1236,7 @@ def test_agg_reduce(self, axis, float_frame): tm.assert_series_equal(result, expected) # dict input with lists - func = OrderedDict([(name1, ["mean"]), (name2, ["sum"])]) + func = dict([(name1, ["mean"]), (name2, ["sum"])]) result = float_frame.agg(func, axis=axis) expected = DataFrame( { @@ -1253,10 +1252,10 @@ def test_agg_reduce(self, axis, float_frame): tm.assert_frame_equal(result, expected) # dict input with lists with multiple - func = OrderedDict([(name1, ["mean", "sum"]), (name2, ["sum", "max"])]) + func = dict([(name1, ["mean", "sum"]), (name2, ["sum", "max"])]) result = float_frame.agg(func, axis=axis) expected = DataFrame( - OrderedDict( + dict( [ ( name1, diff --git a/pandas/tests/frame/methods/test_select_dtypes.py b/pandas/tests/frame/methods/test_select_dtypes.py index fe7baebcf0cf7..4599761909c33 100644 --- a/pandas/tests/frame/methods/test_select_dtypes.py +++ b/pandas/tests/frame/methods/test_select_dtypes.py @@ -1,5 +1,3 @@ -from collections import OrderedDict - import numpy as np import pytest @@ -202,9 +200,8 @@ def test_select_dtypes_include_exclude_mixed_scalars_lists(self): def test_select_dtypes_duplicate_columns(self): # GH20839 - odict = OrderedDict df = DataFrame( - odict( + dict( [ ("a", list("abc")), ("b", list(range(1, 4))), diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index f3e3ef9bae5c6..53d417dc10014 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from datetime import timedelta import numpy as np @@ -50,10 +49,9 @@ def test_empty_frame_dtypes(self): norows_int_df.dtypes, pd.Series(np.dtype("int32"), index=list("abc")) ) - odict = OrderedDict - df = pd.DataFrame(odict([("a", 1), ("b", True), ("c", 1.0)]), index=[1, 2, 3]) + df = pd.DataFrame(dict([("a", 1), ("b", True), ("c", 1.0)]), index=[1, 2, 3]) ex_dtypes = pd.Series( - odict([("a", np.int64), ("b", np.bool_), ("c", np.float64)]) + dict([("a", np.int64), ("b", np.bool_), ("c", np.float64)]) ) tm.assert_series_equal(df.dtypes, ex_dtypes) @@ -85,17 +83,16 @@ def test_datetime_with_tz_dtypes(self): def test_dtypes_are_correct_after_column_slice(self): # GH6525 df = pd.DataFrame(index=range(5), columns=list("abc"), dtype=np.float_) - odict = OrderedDict tm.assert_series_equal( df.dtypes, - pd.Series(odict([("a", np.float_), ("b", np.float_), ("c", np.float_)])), + pd.Series(dict([("a", np.float_), ("b", np.float_), ("c", np.float_)])), ) tm.assert_series_equal( - df.iloc[:, 2:].dtypes, pd.Series(odict([("c", np.float_)])) + df.iloc[:, 2:].dtypes, pd.Series(dict([("c", np.float_)])) ) tm.assert_series_equal( df.dtypes, - pd.Series(odict([("a", np.float_), ("b", np.float_), ("c", np.float_)])), + pd.Series(dict([("a", np.float_), ("b", np.float_), ("c", np.float_)])), ) def test_dtypes_gh8722(self, float_string_frame): diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 1d73d1e35728b..2567f704a4a8d 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from datetime import date, datetime import itertools import operator @@ -165,7 +164,7 @@ def create_mgr(descr, item_shape=None): offset = 0 mgr_items = [] - block_placements = OrderedDict() + block_placements = {} for d in descr.split(";"): d = d.strip() if not len(d): diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 13152f01abb04..9278e64cc911f 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1,4 +1,3 @@ -from collections import OrderedDict import datetime from datetime import timedelta from io import StringIO @@ -470,7 +469,7 @@ def test_blocks_compat_GH9037(self): index = pd.DatetimeIndex(list(index), freq=None) df_mixed = DataFrame( - OrderedDict( + dict( float_1=[ -0.92077639, 0.77434435, diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 73aa01cff84fa..e4af5d93ff771 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from datetime import datetime import numpy as np @@ -428,7 +427,7 @@ def test_agg_misc(): msg = r"Column\(s\) \['result1', 'result2'\] do not exist" for t in cases: with pytest.raises(pd.core.base.SpecificationError, match=msg): - t[["A", "B"]].agg(OrderedDict([("result1", np.sum), ("result2", np.mean)])) + t[["A", "B"]].agg(dict([("result1", np.sum), ("result2", np.mean)])) # agg with different hows expected = pd.concat( @@ -438,7 +437,7 @@ def test_agg_misc(): [("A", "sum"), ("A", "std"), ("B", "mean"), ("B", "std")] ) for t in cases: - result = t.agg(OrderedDict([("A", ["sum", "std"]), ("B", ["mean", "std"])])) + result = t.agg(dict([("A", ["sum", "std"]), ("B", ["mean", "std"])])) tm.assert_frame_equal(result, expected, check_like=True) # equivalent of using a selection list / or not diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 4fd3c688b8771..aee503235d36c 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from datetime import date, datetime, timedelta import random import re @@ -1931,7 +1930,7 @@ def test_merge_index_types(index): result = left.merge(right, on=["index_col"]) expected = DataFrame( - OrderedDict([("left_data", [1, 2]), ("right_data", [1.0, 2.0])]), index=index + dict([("left_data", [1, 2]), ("right_data", [1.0, 2.0])]), index=index ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 7d6611722d8b5..b0f6a8ef0c517 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -1,4 +1,4 @@ -from collections import OrderedDict, abc, deque +from collections import abc, deque import datetime as dt from datetime import datetime from decimal import Decimal @@ -2609,9 +2609,7 @@ def test_concat_odered_dict(self): [pd.Series(range(3)), pd.Series(range(4))], keys=["First", "Another"] ) result = pd.concat( - OrderedDict( - [("First", pd.Series(range(3))), ("Another", pd.Series(range(4)))] - ) + dict([("First", pd.Series(range(3))), ("Another", pd.Series(range(4)))]) ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py index 82e0e52c089a2..537bedfd1a6b9 100644 --- a/pandas/tests/reshape/test_get_dummies.py +++ b/pandas/tests/reshape/test_get_dummies.py @@ -1,5 +1,3 @@ -from collections import OrderedDict - import numpy as np import pytest @@ -569,9 +567,7 @@ def test_dataframe_dummies_preserve_categorical_dtype(self, dtype, ordered): @pytest.mark.parametrize("sparse", [True, False]) def test_get_dummies_dont_sparsify_all_columns(self, sparse): # GH18914 - df = DataFrame.from_dict( - OrderedDict([("GDP", [1, 2]), ("Nation", ["AB", "CD"])]) - ) + df = DataFrame.from_dict(dict([("GDP", [1, 2]), ("Nation", ["AB", "CD"])])) df = get_dummies(df, columns=["Nation"], sparse=sparse) df2 = df.reindex(columns=["GDP"]) diff --git a/pandas/tests/window/test_api.py b/pandas/tests/window/test_api.py index 2c3d8b4608806..eb14ecfba1f51 100644 --- a/pandas/tests/window/test_api.py +++ b/pandas/tests/window/test_api.py @@ -1,5 +1,3 @@ -from collections import OrderedDict - import numpy as np import pytest @@ -335,8 +333,6 @@ def test_multiple_agg_funcs(func, window_size, expected_vals): ) expected = pd.DataFrame(expected_vals, index=index, columns=columns) - result = window.agg( - OrderedDict((("low", ["mean", "max"]), ("high", ["mean", "min"]))) - ) + result = window.agg(dict((("low", ["mean", "max"]), ("high", ["mean", "min"])))) tm.assert_frame_equal(result, expected)
- [x] closes #30469 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Grepping for OrderedDict in *.py files I see 84 more usages, but AFAICT these are all explicitly checking for the class, so I'm considering this as closing #30469.
https://api.github.com/repos/pandas-dev/pandas/pulls/36693
2020-09-27T22:28:56Z
2020-09-29T22:48:23Z
2020-09-29T22:48:23Z
2020-09-29T22:48:29Z
BUG: DatetimeIndex.shift(1) with empty index
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 031c74b1cc367..3111277bed634 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -252,7 +252,8 @@ Datetimelike - Bug in :meth:`DatetimeIndex.slice_locs` where ``datetime.date`` objects were not accepted (:issue:`34077`) - Bug in :meth:`DatetimeIndex.searchsorted`, :meth:`TimedeltaIndex.searchsorted`, :meth:`PeriodIndex.searchsorted`, and :meth:`Series.searchsorted` with ``datetime64``, ``timedelta64`` or ``Period`` dtype placement of ``NaT`` values being inconsistent with ``NumPy`` (:issue:`36176`, :issue:`36254`) - Inconsistency in :class:`DatetimeArray`, :class:`TimedeltaArray`, and :class:`PeriodArray` setitem casting arrays of strings to datetimelike scalars but not scalar strings (:issue:`36261`) -- +- Bug in :class:`DatetimeIndex.shift` incorrectly raising when shifting empty indexes (:issue:`14811`) + Timedelta ^^^^^^^^^ diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index c90610bdd920c..0f723546fb4c2 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1276,8 +1276,8 @@ def _time_shift(self, periods, freq=None): result = self + offset return result - if periods == 0: - # immutable so OK + if periods == 0 or len(self) == 0: + # GH#14811 empty case return self.copy() if self.freq is None: diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py index ac3320c6f9fa0..f667e5a610419 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/datetimelike.py @@ -32,6 +32,11 @@ def test_shift_identity(self): idx = self.create_index() tm.assert_index_equal(idx, idx.shift(0)) + def test_shift_empty(self): + # GH#14811 + idx = self.create_index()[:0] + tm.assert_index_equal(idx, idx.shift(1)) + def test_str(self): # test the string repr diff --git a/pandas/tests/indexes/datetimes/test_shift.py b/pandas/tests/indexes/datetimes/test_shift.py index 8724bfeb05c4d..a2a673ed5d9e0 100644 --- a/pandas/tests/indexes/datetimes/test_shift.py +++ b/pandas/tests/indexes/datetimes/test_shift.py @@ -151,3 +151,9 @@ def test_shift_bmonth(self): with tm.assert_produces_warning(pd.errors.PerformanceWarning): shifted = rng.shift(1, freq=pd.offsets.CDay()) assert shifted[0] == rng[0] + pd.offsets.CDay() + + def test_shift_empty(self): + # GH#14811 + dti = date_range(start="2016-10-21", end="2016-10-21", freq="BM") + result = dti.shift(1) + tm.assert_index_equal(result, dti)
- [x] closes #14811 - [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/36691
2020-09-27T22:13:20Z
2020-09-30T02:12:04Z
2020-09-30T02:12:04Z
2020-09-30T02:42:51Z
BUG: Don't ignore na_rep in DataFrame.to_html
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index cdd8e50d98077..0d83abc0d81cc 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -414,7 +414,6 @@ Strings - Bug in :func:`to_numeric` raising a ``TypeError`` when attempting to convert a string dtype :class:`Series` containing only numeric strings and ``NA`` (:issue:`37262`) - - Interval ^^^^^^^^ @@ -465,6 +464,7 @@ I/O - Bug in :func:`read_table` and :func:`read_csv` when ``delim_whitespace=True`` and ``sep=default`` (:issue:`36583`) - Bug in :meth:`to_json` with ``lines=True`` and ``orient='records'`` the last line of the record is not appended with 'new line character' (:issue:`36888`) - Bug in :meth:`read_parquet` with fixed offset timezones. String representation of timezones was not recognized (:issue:`35997`, :issue:`36004`) +- Bug in :meth:`DataFrame.to_html`, :meth:`DataFrame.to_string`, and :meth:`DataFrame.to_latex` ignoring the ``na_rep`` argument when ``float_format`` was also specified (:issue:`9046`, :issue:`13828`) - Bug in output rendering of complex numbers showing too many trailing zeros (:issue:`36799`) - Bug in :class:`HDFStore` threw a ``TypeError`` when exporting an empty :class:`DataFrame` with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 6f4bd2ed8c73a..3c759f477899b 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -40,6 +40,7 @@ from pandas._libs.tslibs import NaT, Timedelta, Timestamp, iNaT from pandas._libs.tslibs.nattype import NaTType from pandas._typing import ( + ArrayLike, CompressionOptions, FilePathOrBuffer, FloatFormatType, @@ -104,7 +105,7 @@ index : bool, optional, default True Whether to print index (row) labels. na_rep : str, optional, default 'NaN' - String representation of NAN to use. + String representation of ``NaN`` to use. formatters : list, tuple or dict of one-param. functions, optional Formatter functions to apply to columns' elements by position or name. @@ -112,7 +113,12 @@ List/tuple must be of length equal to the number of columns. float_format : one-parameter function, optional, default None Formatter function to apply to columns' elements if they are - floats. The result of this function must be a unicode string. + floats. This function must return a unicode string and will be + applied only to the non-``NaN`` elements, with ``NaN`` being + handled by ``na_rep``. + + .. versionchanged:: 1.2.0 + sparsify : bool, optional, default True Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. @@ -1364,8 +1370,19 @@ def get_result_as_array(self) -> np.ndarray: Returns the float values converted into strings using the parameters given at initialisation, as a numpy array """ + + def format_with_na_rep(values: ArrayLike, formatter: Callable, na_rep: str): + mask = isna(values) + formatted = np.array( + [ + formatter(val) if not m else na_rep + for val, m in zip(values.ravel(), mask.ravel()) + ] + ).reshape(values.shape) + return formatted + if self.formatter is not None: - return np.array([self.formatter(x) for x in self.values]) + return format_with_na_rep(self.values, self.formatter, self.na_rep) if self.fixed_width: threshold = get_option("display.chop_threshold") @@ -1386,13 +1403,7 @@ def format_values_with(float_format): # separate the wheat from the chaff values = self.values is_complex = is_complex_dtype(values) - mask = isna(values) - values = np.array(values, dtype="object") - values[mask] = na_rep - imask = (~mask).ravel() - values.flat[imask] = np.array( - [formatter(val) for val in values.ravel()[imask]] - ) + values = format_with_na_rep(values, formatter, na_rep) if self.fixed_width: if is_complex: @@ -1454,10 +1465,6 @@ def format_values_with(float_format): return formatted_values def _format_strings(self) -> List[str]: - # shortcut - if self.formatter is not None: - return [self.formatter(x) for x in self.values] - return list(self.get_result_as_array()) diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index 18cbd7186e931..f5781fff15932 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -820,3 +820,38 @@ def test_html_repr_min_rows(datapath, max_rows, min_rows, expected): with option_context("display.max_rows", max_rows, "display.min_rows", min_rows): result = df._repr_html_() assert result == expected + + +@pytest.mark.parametrize("na_rep", ["NaN", "Ted"]) +def test_to_html_na_rep_and_float_format(na_rep): + # https://github.com/pandas-dev/pandas/issues/13828 + df = DataFrame( + [ + ["A", 1.2225], + ["A", None], + ], + columns=["Group", "Data"], + ) + result = df.to_html(na_rep=na_rep, float_format="{:.2f}".format) + expected = f"""<table border="1" class="dataframe"> + <thead> + <tr style="text-align: right;"> + <th></th> + <th>Group</th> + <th>Data</th> + </tr> + </thead> + <tbody> + <tr> + <th>0</th> + <td>A</td> + <td>1.22</td> + </tr> + <tr> + <th>1</th> + <td>A</td> + <td>{na_rep}</td> + </tr> + </tbody> +</table>""" + assert result == expected diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 855e69dee7db4..7cf7ed3f77609 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -1431,3 +1431,24 @@ def test_get_strrow_multindex_multicolumn(self, row_num, expected): ) assert row_string_converter.get_strrow(row_num=row_num) == expected + + @pytest.mark.parametrize("na_rep", ["NaN", "Ted"]) + def test_to_latex_na_rep_and_float_format(self, na_rep): + df = DataFrame( + [ + ["A", 1.2225], + ["A", None], + ], + columns=["Group", "Data"], + ) + result = df.to_latex(na_rep=na_rep, float_format="{:.2f}".format) + expected = f"""\\begin{{tabular}}{{llr}} +\\toprule +{{}} & Group & Data \\\\ +\\midrule +0 & A & 1.22 \\\\ +1 & A & {na_rep} \\\\ +\\bottomrule +\\end{{tabular}} +""" + assert result == expected diff --git a/pandas/tests/io/formats/test_to_string.py b/pandas/tests/io/formats/test_to_string.py index 7944a0ea67a5f..a1ed1ba2e8bf5 100644 --- a/pandas/tests/io/formats/test_to_string.py +++ b/pandas/tests/io/formats/test_to_string.py @@ -220,3 +220,14 @@ def test_nullable_int_to_string(any_nullable_int_dtype): 1 1 2 <NA>""" assert result == expected + + +@pytest.mark.parametrize("na_rep", ["NaN", "Ted"]) +def test_to_string_na_rep_and_float_format(na_rep): + # GH 13828 + df = DataFrame([["A", 1.2225], ["A", None]], columns=["Group", "Data"]) + result = df.to_string(na_rep=na_rep, float_format="{:.2f}".format) + expected = f""" Group Data +0 A 1.22 +1 A {na_rep}""" + assert result == expected
- [x] closes #13828 - [x] closes #9046 - [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/36690
2020-09-27T21:58:25Z
2020-10-24T02:49:09Z
2020-10-24T02:49:08Z
2020-10-24T02:51:30Z
DOC: Start v1.1.4 release notes
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index 933ed3cb8babf..848121f822383 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -24,6 +24,7 @@ Version 1.1 .. toctree:: :maxdepth: 2 + v1.1.4 v1.1.3 v1.1.2 v1.1.1 diff --git a/doc/source/whatsnew/v1.1.3.rst b/doc/source/whatsnew/v1.1.3.rst index 2323afbe00e5d..e752eb54d0c15 100644 --- a/doc/source/whatsnew/v1.1.3.rst +++ b/doc/source/whatsnew/v1.1.3.rst @@ -75,4 +75,4 @@ Other Contributors ~~~~~~~~~~~~ -.. contributors:: v1.1.2..v1.1.3|HEAD +.. contributors:: v1.1.2..v1.1.3 diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst new file mode 100644 index 0000000000000..e63912ebc8fee --- /dev/null +++ b/doc/source/whatsnew/v1.1.4.rst @@ -0,0 +1,42 @@ +.. _whatsnew_114: + +What's new in 1.1.4 (??) +------------------------ + +These are the changes in pandas 1.1.4. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- + +.. _whatsnew_114.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_114.bug_fixes: + +Bug fixes +~~~~~~~~~ +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_114.other: + +Other +~~~~~ +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_114.contributors: + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v1.1.3..v1.1.4|HEAD
I think this requires the v1.1.3 tag in order to pass
https://api.github.com/repos/pandas-dev/pandas/pulls/36689
2020-09-27T21:55:44Z
2020-10-05T20:05:44Z
2020-10-05T20:05:44Z
2020-10-05T20:16:33Z