title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
DOC: update the Series.dt.dayofweek docstring
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index e6e0544bfa22b..7f46f609aebef 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -544,8 +544,41 @@ def date(self): weekofyear = _field_accessor('weekofyear', 'woy', "The week ordinal of the year") week = weekofyear - dayofweek = _field_accessor('dayofweek', 'dow', - "The day of the week with Monday=0, Sunday=6") + _dayofweek_doc = """ + The day of the week with Monday=0, Sunday=6. + + Return the day of the week. It is assumed the week starts on + Monday, which is denoted by 0 and ends on Sunday which is denoted + by 6. This method is available on both Series with datetime + values (using the `dt` accessor) or DatetimeIndex. + + See Also + -------- + Series.dt.dayofweek : Alias. + Series.dt.weekday : Alias. + Series.dt.day_name : Returns the name of the day of the week. + + Returns + ------- + Series or Index + Containing integers indicating the day number. + + Examples + -------- + >>> s = pd.date_range('2016-12-31', '2017-01-08', freq='D').to_series() + >>> s.dt.dayofweek + 2016-12-31 5 + 2017-01-01 6 + 2017-01-02 0 + 2017-01-03 1 + 2017-01-04 2 + 2017-01-05 3 + 2017-01-06 4 + 2017-01-07 5 + 2017-01-08 6 + Freq: D, dtype: int64 + """ + dayofweek = _field_accessor('dayofweek', 'dow', _dayofweek_doc) weekday = dayofweek weekday_name = _field_accessor(
- [ ] closes #xxxx - [ ] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Original changes moved from #20230 (the fork of that PR does not exist anymore, so can't edit)
https://api.github.com/repos/pandas-dev/pandas/pulls/21823
2018-07-08T23:05:11Z
2018-07-09T18:46:00Z
2018-07-09T18:46:00Z
2018-07-09T18:46:00Z
BUG/API: to_datetime preserves UTC offsets when parsing datetime strings
diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py index eada401d2930b..2c98cc1659519 100644 --- a/asv_bench/benchmarks/timeseries.py +++ b/asv_bench/benchmarks/timeseries.py @@ -343,6 +343,25 @@ def time_iso8601_tz_spaceformat(self): to_datetime(self.strings_tz_space) +class ToDatetimeNONISO8601(object): + + goal_time = 0.2 + + def setup(self): + N = 10000 + half = int(N / 2) + ts_string_1 = 'March 1, 2018 12:00:00+0400' + ts_string_2 = 'March 1, 2018 12:00:00+0500' + self.same_offset = [ts_string_1] * N + self.diff_offset = [ts_string_1] * half + [ts_string_2] * half + + def time_same_offset(self): + to_datetime(self.same_offset) + + def time_different_offset(self): + to_datetime(self.diff_offset) + + class ToDatetimeFormat(object): goal_time = 0.2 diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 42e286f487a7d..d2d5d40393b62 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -224,6 +224,62 @@ For situations where you need an ``ndarray`` of ``Interval`` objects, use np.asarray(idx) idx.values.astype(object) +.. _whatsnew_0240.api.timezone_offset_parsing: + +Parsing Datetime Strings with Timezone Offsets +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Previously, parsing datetime strings with UTC offsets with :func:`to_datetime` +or :class:`DatetimeIndex` would automatically convert the datetime to UTC +without timezone localization. This is inconsistent from parsing the same +datetime string with :class:`Timestamp` which would preserve the UTC +offset in the ``tz`` attribute. Now, :func:`to_datetime` preserves the UTC +offset in the ``tz`` attribute when all the datetime strings have the same +UTC offset (:issue:`17697`, :issue:`11736`) + +*Previous Behavior*: + +.. code-block:: ipython + + + In [2]: pd.to_datetime("2015-11-18 15:30:00+05:30") + Out[2]: Timestamp('2015-11-18 10:00:00') + + In [3]: pd.Timestamp("2015-11-18 15:30:00+05:30") + Out[3]: Timestamp('2015-11-18 15:30:00+0530', tz='pytz.FixedOffset(330)') + + # Different UTC offsets would automatically convert the datetimes to UTC (without a UTC timezone) + In [4]: pd.to_datetime(["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30"]) + Out[4]: DatetimeIndex(['2015-11-18 10:00:00', '2015-11-18 10:00:00'], dtype='datetime64[ns]', freq=None) + +*Current Behavior*: + +.. ipython:: python + + pd.to_datetime("2015-11-18 15:30:00+05:30") + pd.Timestamp("2015-11-18 15:30:00+05:30") + +Parsing datetime strings with the same UTC offset will preserve the UTC offset in the ``tz`` + +.. ipython:: python + + pd.to_datetime(["2015-11-18 15:30:00+05:30"] * 2) + +Parsing datetime strings with different UTC offsets will now create an Index of +``datetime.datetime`` objects with different UTC offsets + +.. ipython:: python + + idx = pd.to_datetime(["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30"]) + idx + idx[0] + idx[1] + +Passing ``utc=True`` will mimic the previous behavior but will correctly indicate +that the dates have been converted to UTC + +.. ipython:: python + pd.to_datetime(["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30"], utc=True) .. _whatsnew_0240.api.datetimelike.normalize: @@ -439,6 +495,7 @@ Datetimelike - Fixed bug where two :class:`DateOffset` objects with different ``normalize`` attributes could evaluate as equal (:issue:`21404`) - Fixed bug where :meth:`Timestamp.resolution` incorrectly returned 1-microsecond ``timedelta`` instead of 1-nanosecond :class:`Timedelta` (:issue:`21336`,:issue:`21365`) +- Bug in :func:`to_datetime` that did not consistently return an :class:`Index` when ``box=True`` was specified (:issue:`21864`) Timedelta ^^^^^^^^^ diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index acf6cd4b74362..76e3d6e92d31e 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -19,6 +19,7 @@ import numpy as np cnp.import_array() import pytz +from dateutil.tz import tzlocal, tzutc as dateutil_utc from util cimport (is_integer_object, is_float_object, is_string_object, @@ -328,7 +329,7 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'): if unit == 'ns': if issubclass(values.dtype.type, np.integer): return values.astype('M8[ns]') - return array_to_datetime(values.astype(object), errors=errors) + return array_to_datetime(values.astype(object), errors=errors)[0] m = cast_from_unit(None, unit) @@ -457,9 +458,43 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', dayfirst=False, yearfirst=False, format=None, utc=None, require_iso8601=False): + """ + Converts a 1D array of date-like values to a numpy array of either: + 1) datetime64[ns] data + 2) datetime.datetime objects, if OutOfBoundsDatetime or TypeError + is encountered + + Also returns a pytz.FixedOffset if an array of strings with the same + timezone offset is passed and utc=True is not passed. Otherwise, None + is returned + + Handles datetime.date, datetime.datetime, np.datetime64 objects, numeric, + strings + + Parameters + ---------- + values : ndarray of object + date-like objects to convert + errors : str, default 'raise' + error behavior when parsing + dayfirst : bool, default False + dayfirst parsing behavior when encountering datetime strings + yearfirst : bool, default False + yearfirst parsing behavior when encountering datetime strings + format : str, default None + format of the string to parse + utc : bool, default None + indicator whether the dates should be UTC + require_iso8601 : bool, default False + indicator whether the datetime string should be iso8601 + + Returns + ------- + tuple (ndarray, tzoffset) + """ cdef: Py_ssize_t i, n = len(values) - object val, py_dt + object val, py_dt, tz, tz_out = None ndarray[int64_t] iresult ndarray[object] oresult npy_datetimestruct dts @@ -467,11 +502,14 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', bint seen_integer = 0 bint seen_string = 0 bint seen_datetime = 0 + bint seen_datetime_offset = 0 bint is_raise = errors=='raise' bint is_ignore = errors=='ignore' bint is_coerce = errors=='coerce' _TSObject _ts int out_local=0, out_tzoffset=0 + float offset_seconds + set out_tzoffset_vals = set() # specify error conditions assert is_raise or is_ignore or is_coerce @@ -584,7 +622,7 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', raise ValueError("time data {val} doesn't match " "format specified" .format(val=val)) - return values + return values, tz_out try: py_dt = parse_datetime_string(val, dayfirst=dayfirst, @@ -595,6 +633,30 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', continue raise TypeError("invalid string coercion to datetime") + # If the dateutil parser returned tzinfo, capture it + # to check if all arguments have the same tzinfo + tz = py_dt.tzinfo + if tz is not None: + seen_datetime_offset = 1 + if tz == dateutil_utc(): + # dateutil.tz.tzutc has no offset-like attribute + # Just add the 0 offset explicitly + out_tzoffset_vals.add(0) + elif tz == tzlocal(): + # is comparison fails unlike other dateutil.tz + # objects. Also, dateutil.tz.tzlocal has no + # _offset attribute like tzoffset + offset_seconds = tz._dst_offset.total_seconds() + out_tzoffset_vals.add(offset_seconds) + else: + # dateutil.tz.tzoffset objects cannot be hashed + # store the total_seconds() instead + offset_seconds = tz._offset.total_seconds() + out_tzoffset_vals.add(offset_seconds) + else: + # Add a marker for naive string, to track if we are + # parsing mixed naive and aware strings + out_tzoffset_vals.add('naive') try: _ts = convert_datetime_to_tsobject(py_dt, None) iresult[i] = _ts.value @@ -614,8 +676,17 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', # where we left off value = dtstruct_to_dt64(&dts) if out_local == 1: + seen_datetime_offset = 1 + # Store the out_tzoffset in seconds + # since we store the total_seconds of + # dateutil.tz.tzoffset objects + out_tzoffset_vals.add(out_tzoffset * 60.) tz = pytz.FixedOffset(out_tzoffset) value = tz_convert_single(value, tz, 'UTC') + else: + # Add a marker for naive string, to track if we are + # parsing mixed naive and aware strings + out_tzoffset_vals.add('naive') iresult[i] = value try: check_dts_bounds(&dts) @@ -631,7 +702,7 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', raise ValueError("time data {val} doesn't " "match format specified" .format(val=val)) - return values + return values, tz_out raise else: @@ -657,7 +728,21 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', else: raise TypeError - return result + if seen_datetime_offset and not utc_convert: + # GH 17697 + # 1) If all the offsets are equal, return one offset for + # the parsed dates to (maybe) pass to DatetimeIndex + # 2) If the offsets are different, then force the parsing down the + # object path where an array of datetimes + # (with individual dateutil.tzoffsets) are returned + is_same_offsets = len(out_tzoffset_vals) == 1 + if not is_same_offsets: + return array_to_datetime_object(values, is_raise, + dayfirst, yearfirst) + else: + tz_offset = out_tzoffset_vals.pop() + tz_out = pytz.FixedOffset(tz_offset / 60.) + return result, tz_out except OutOfBoundsDatetime: if is_raise: raise @@ -679,36 +764,67 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', oresult[i] = val.item() else: oresult[i] = val - return oresult + return oresult, tz_out except TypeError: - oresult = np.empty(n, dtype=object) + return array_to_datetime_object(values, is_raise, dayfirst, yearfirst) - for i in range(n): - val = values[i] - if checknull_with_nat(val): - oresult[i] = val - elif is_string_object(val): - if len(val) == 0 or val in nat_strings: - oresult[i] = 'NaT' - continue +cdef array_to_datetime_object(ndarray[object] values, bint is_raise, + dayfirst=False, yearfirst=False): + """ + Fall back function for array_to_datetime - try: - oresult[i] = parse_datetime_string(val, dayfirst=dayfirst, - yearfirst=yearfirst) - pydatetime_to_dt64(oresult[i], &dts) - check_dts_bounds(&dts) - except Exception: - if is_raise: - raise - return values - # oresult[i] = val - else: + Attempts to parse datetime strings with dateutil to return an array + of datetime objects + + Parameters + ---------- + values : ndarray of object + date-like objects to convert + is_raise : bool + error behavior when parsing + dayfirst : bool, default False + dayfirst parsing behavior when encountering datetime strings + yearfirst : bool, default False + yearfirst parsing behavior when encountering datetime strings + + Returns + ------- + tuple (ndarray, None) + """ + cdef: + Py_ssize_t i, n = len(values) + object val, + ndarray[object] oresult + npy_datetimestruct dts + + oresult = np.empty(n, dtype=object) + + # We return an object array and only attempt to parse: + # 1) NaT or NaT-like values + # 2) datetime strings, which we return as datetime.datetime + for i in range(n): + val = values[i] + if checknull_with_nat(val): + oresult[i] = val + elif is_string_object(val): + if len(val) == 0 or val in nat_strings: + oresult[i] = 'NaT' + continue + try: + oresult[i] = parse_datetime_string(val, dayfirst=dayfirst, + yearfirst=yearfirst) + pydatetime_to_dt64(oresult[i], &dts) + check_dts_bounds(&dts) + except (ValueError, OverflowError): if is_raise: raise - return values - - return oresult + return values, None + else: + if is_raise: + raise + return values, None + return oresult, None cdef inline bint _parse_today_now(str val, int64_t* iresult): diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index ead7b39309f5e..e369679d2146f 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -918,7 +918,7 @@ def try_datetime(v): # GH19671 v = tslib.array_to_datetime(v, require_iso8601=True, - errors='raise') + errors='raise')[0] except ValueError: # we might have a sequence of the same-datetimes with tz's diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index be042c9bf8ab0..90a083557a662 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -23,7 +23,8 @@ is_float, is_list_like, is_scalar, - is_numeric_dtype) + is_numeric_dtype, + is_object_dtype) from pandas.core.dtypes.generic import ( ABCIndexClass, ABCSeries, ABCDataFrame) @@ -266,7 +267,7 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None, result = arg if result is None and (format is None or infer_datetime_format): - result = tslib.array_to_datetime( + result, tz_parsed = tslib.array_to_datetime( arg, errors=errors, utc=tz == 'utc', @@ -274,9 +275,16 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None, yearfirst=yearfirst, require_iso8601=require_iso8601 ) + if tz_parsed is not None and box: + return DatetimeIndex._simple_new(result, name=name, + tz=tz_parsed) - if is_datetime64_dtype(result) and box: - result = DatetimeIndex(result, tz=tz, name=name) + if box: + if is_datetime64_dtype(result): + return DatetimeIndex(result, tz=tz, name=name) + elif is_object_dtype(result): + from pandas import Index + return Index(result, name=name) return result except ValueError as e: @@ -404,7 +412,7 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, datetime.datetime objects as well). box : boolean, default True - - If True returns a DatetimeIndex + - If True returns a DatetimeIndex or Index-like object - If False returns ndarray of values. format : string, default None strftime to parse time, eg "%d/%m/%Y", note that "%f" will parse @@ -696,7 +704,7 @@ def calc(carg): parsed = parsing.try_parse_year_month_day(carg / 10000, carg / 100 % 100, carg % 100) - return tslib.array_to_datetime(parsed, errors=errors) + return tslib.array_to_datetime(parsed, errors=errors)[0] def calc_with_mask(carg, mask): result = np.empty(carg.shape, dtype='M8[ns]') diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index 3ad25ae73109e..9e3b606f31973 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -154,7 +154,7 @@ def test_to_csv_from_csv5(self): self.tzframe.to_csv(path) result = pd.read_csv(path, index_col=0, parse_dates=['A']) - converter = lambda c: to_datetime(result[c]).dt.tz_localize( + converter = lambda c: to_datetime(result[c]).dt.tz_convert( 'UTC').dt.tz_convert(self.tzframe[c].dt.tz) result['B'] = converter('B') result['C'] = converter('C') @@ -1027,12 +1027,11 @@ def test_to_csv_with_dst_transitions(self): time_range = np.array(range(len(i)), dtype='int64') df = DataFrame({'A': time_range}, index=i) df.to_csv(path, index=True) - # we have to reconvert the index as we # don't parse the tz's result = read_csv(path, index_col=0) - result.index = to_datetime(result.index).tz_localize( - 'UTC').tz_convert('Europe/London') + result.index = to_datetime(result.index, utc=True).tz_convert( + 'Europe/London') assert_frame_equal(result, df) # GH11619 @@ -1043,9 +1042,9 @@ def test_to_csv_with_dst_transitions(self): with ensure_clean('csv_date_format_with_dst') as path: df.to_csv(path, index=True) result = read_csv(path, index_col=0) - result.index = to_datetime(result.index).tz_localize( - 'UTC').tz_convert('Europe/Paris') - result['idx'] = to_datetime(result['idx']).astype( + result.index = to_datetime(result.index, utc=True).tz_convert( + 'Europe/Paris') + result['idx'] = to_datetime(result['idx'], utc=True).astype( 'datetime64[ns, Europe/Paris]') assert_frame_equal(result, df) diff --git a/pandas/tests/indexes/datetimes/test_arithmetic.py b/pandas/tests/indexes/datetimes/test_arithmetic.py index 4ce2b1dd4fd86..1e54e6563d598 100644 --- a/pandas/tests/indexes/datetimes/test_arithmetic.py +++ b/pandas/tests/indexes/datetimes/test_arithmetic.py @@ -423,13 +423,13 @@ def test_dti_shift_tzaware(self, tz_naive_fixture): tm.assert_index_equal(idx.shift(0, freq='H'), idx) tm.assert_index_equal(idx.shift(3, freq='H'), idx) - idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-01 11:00' + idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00'], name='xxx', tz=tz) tm.assert_index_equal(idx.shift(0, freq='H'), idx) - exp = pd.DatetimeIndex(['2011-01-01 13:00', '2011-01-01 14:00' + exp = pd.DatetimeIndex(['2011-01-01 13:00', '2011-01-01 14:00', '2011-01-01 15:00'], name='xxx', tz=tz) tm.assert_index_equal(idx.shift(3, freq='H'), exp) - exp = pd.DatetimeIndex(['2011-01-01 07:00', '2011-01-01 08:00' + exp = pd.DatetimeIndex(['2011-01-01 07:00', '2011-01-01 08:00', '2011-01-01 09:00'], name='xxx', tz=tz) tm.assert_index_equal(idx.shift(-3, freq='H'), exp) diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 3697d183d2fc6..67eb81336f648 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -317,8 +317,8 @@ def test_dti_tz_localize_nonexistent_raise_coerce(self): result = index.tz_localize(tz=tz, errors='coerce') test_times = ['2015-03-08 01:00-05:00', 'NaT', '2015-03-08 03:00-04:00'] - dti = DatetimeIndex(test_times) - expected = dti.tz_localize('UTC').tz_convert('US/Eastern') + dti = to_datetime(test_times, utc=True) + expected = dti.tz_convert('US/Eastern') tm.assert_index_equal(result, expected) @pytest.mark.parametrize('tz', [pytz.timezone('US/Eastern'), diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index fa9f9fc90387a..72e5358f21966 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -7,6 +7,7 @@ import dateutil import numpy as np from dateutil.parser import parse +from dateutil.tz.tz import tzoffset from datetime import datetime, time from distutils.version import LooseVersion @@ -483,7 +484,7 @@ def test_to_datetime_tz_psycopg2(self, cache): # dtype coercion i = pd.DatetimeIndex([ - '2000-01-01 08:00:00+00:00' + '2000-01-01 08:00:00' ], tz=psycopg2.tz.FixedOffsetTimezone(offset=-300, name=None)) assert is_datetime64_ns_dtype(i) @@ -577,6 +578,48 @@ def test_week_without_day_and_calendar_year(self, date, format): with tm.assert_raises_regex(ValueError, msg): pd.to_datetime(date, format=format) + def test_iso_8601_strings_with_same_offset(self): + # GH 17697, 11736 + ts_str = "2015-11-18 15:30:00+05:30" + result = to_datetime(ts_str) + expected = Timestamp(ts_str) + assert result == expected + + expected = DatetimeIndex([Timestamp(ts_str)] * 2) + result = to_datetime([ts_str] * 2) + tm.assert_index_equal(result, expected) + + result = DatetimeIndex([ts_str] * 2) + tm.assert_index_equal(result, expected) + + def test_iso_8601_strings_with_different_offsets(self): + # GH 17697, 11736 + ts_strings = ["2015-11-18 15:30:00+05:30", + "2015-11-18 16:30:00+06:30", + NaT] + result = to_datetime(ts_strings) + expected = np.array([datetime(2015, 11, 18, 15, 30, + tzinfo=tzoffset(None, 19800)), + datetime(2015, 11, 18, 16, 30, + tzinfo=tzoffset(None, 23400)), + NaT], + dtype=object) + # GH 21864 + expected = Index(expected) + tm.assert_index_equal(result, expected) + + result = to_datetime(ts_strings, utc=True) + expected = DatetimeIndex([Timestamp(2015, 11, 18, 10), + Timestamp(2015, 11, 18, 10), + NaT], tz='UTC') + tm.assert_index_equal(result, expected) + + def test_non_iso_strings_with_tz_offset(self): + result = to_datetime(['March 1, 2018 12:00:00+0400'] * 2) + expected = DatetimeIndex([datetime(2018, 3, 1, 12, + tzinfo=pytz.FixedOffset(240))] * 2) + tm.assert_index_equal(result, expected) + class TestToDatetimeUnit(object): @pytest.mark.parametrize('cache', [True, False]) @@ -978,14 +1021,19 @@ def test_to_datetime_types(self, cache): # assert result == expected @pytest.mark.parametrize('cache', [True, False]) - def test_to_datetime_unprocessable_input(self, cache): + @pytest.mark.parametrize('box, klass, assert_method', [ + [True, Index, 'assert_index_equal'], + [False, np.array, 'assert_numpy_array_equal'] + ]) + def test_to_datetime_unprocessable_input(self, cache, box, klass, + assert_method): # GH 4928 - tm.assert_numpy_array_equal( - to_datetime([1, '1'], errors='ignore', cache=cache), - np.array([1, '1'], dtype='O') - ) + # GH 21864 + result = to_datetime([1, '1'], errors='ignore', cache=cache, box=box) + expected = klass(np.array([1, '1'], dtype='O')) + getattr(tm, assert_method)(result, expected) pytest.raises(TypeError, to_datetime, [1, '1'], errors='raise', - cache=cache) + cache=cache, box=box) def test_to_datetime_other_datetime64_units(self): # 5/25/2012 @@ -1031,7 +1079,7 @@ def test_string_na_nat_conversion(self, cache): else: expected[i] = parse_date(val) - result = tslib.array_to_datetime(strings) + result = tslib.array_to_datetime(strings)[0] tm.assert_almost_equal(result, expected) result2 = to_datetime(strings, cache=cache) @@ -1046,7 +1094,9 @@ def test_string_na_nat_conversion(self, cache): cache=cache)) result = to_datetime(malformed, errors='ignore', cache=cache) - tm.assert_numpy_array_equal(result, malformed) + # GH 21864 + expected = Index(malformed) + tm.assert_index_equal(result, expected) pytest.raises(ValueError, to_datetime, malformed, errors='raise', cache=cache) @@ -1495,23 +1545,19 @@ def test_parsers_time(self): assert res == expected_arr @pytest.mark.parametrize('cache', [True, False]) - def test_parsers_timezone_minute_offsets_roundtrip(self, cache): + @pytest.mark.parametrize('dt_string, tz, dt_string_repr', [ + ('2013-01-01 05:45+0545', pytz.FixedOffset(345), + "Timestamp('2013-01-01 05:45:00+0545', tz='pytz.FixedOffset(345)')"), + ('2013-01-01 05:30+0530', pytz.FixedOffset(330), + "Timestamp('2013-01-01 05:30:00+0530', tz='pytz.FixedOffset(330)')")]) + def test_parsers_timezone_minute_offsets_roundtrip(self, cache, dt_string, + tz, dt_string_repr): # GH11708 base = to_datetime("2013-01-01 00:00:00", cache=cache) - dt_strings = [ - ('2013-01-01 05:45+0545', - "Asia/Katmandu", - "Timestamp('2013-01-01 05:45:00+0545', tz='Asia/Katmandu')"), - ('2013-01-01 05:30+0530', - "Asia/Kolkata", - "Timestamp('2013-01-01 05:30:00+0530', tz='Asia/Kolkata')") - ] - - for dt_string, tz, dt_string_repr in dt_strings: - dt_time = to_datetime(dt_string, cache=cache) - assert base == dt_time - converted_time = dt_time.tz_localize('UTC').tz_convert(tz) - assert dt_string_repr == repr(converted_time) + base = base.tz_localize('UTC').tz_convert(tz) + dt_time = to_datetime(dt_string, cache=cache) + assert base == dt_time + assert dt_string_repr == repr(dt_time) @pytest.fixture(params=['D', 's', 'ms', 'us', 'ns']) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index a59836eb70d24..762b04cc3bd4f 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -2324,7 +2324,7 @@ def test_concat_datetime_timezone(self): '2011-01-01 01:00:00+01:00', '2011-01-01 02:00:00+01:00'], freq='H' - ).tz_localize('UTC').tz_convert('Europe/Paris') + ).tz_convert('UTC').tz_convert('Europe/Paris') expected = pd.DataFrame([[1, 1], [2, 2], [3, 3]], index=exp_idx, columns=['a', 'b']) @@ -2342,7 +2342,7 @@ def test_concat_datetime_timezone(self): '2010-12-31 23:00:00+00:00', '2011-01-01 00:00:00+00:00', '2011-01-01 01:00:00+00:00'] - ).tz_localize('UTC') + ) expected = pd.DataFrame([[np.nan, 1], [np.nan, 2], [np.nan, 3], [1, np.nan], [2, np.nan], [3, np.nan]], diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 7ce2aaf7d7fbb..796c637434353 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -332,7 +332,8 @@ def test_datetime64_dtype_array_returned(self): dt_index = pd.to_datetime(['2015-01-03T00:00:00.000000000+0000', '2015-01-01T00:00:00.000000000+0000', - '2015-01-01T00:00:00.000000000+0000']) + '2015-01-01T00:00:00.000000000+0000'], + box=False) result = algos.unique(dt_index) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 31e5bd88523d2..b7530da36ed8b 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -668,16 +668,15 @@ def test_value_counts_datetime64(self, klass): s = klass(df['dt'].copy()) s.name = None - - idx = pd.to_datetime(['2010-01-01 00:00:00Z', - '2008-09-09 00:00:00Z', - '2009-01-01 00:00:00Z']) + idx = pd.to_datetime(['2010-01-01 00:00:00', + '2008-09-09 00:00:00', + '2009-01-01 00:00:00']) expected_s = Series([3, 2, 1], index=idx) tm.assert_series_equal(s.value_counts(), expected_s) - expected = np_array_datetime64_compat(['2010-01-01 00:00:00Z', - '2009-01-01 00:00:00Z', - '2008-09-09 00:00:00Z'], + expected = np_array_datetime64_compat(['2010-01-01 00:00:00', + '2009-01-01 00:00:00', + '2008-09-09 00:00:00'], dtype='datetime64[ns]') if isinstance(s, Index): tm.assert_index_equal(s.unique(), DatetimeIndex(expected)) diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index d664a9060b684..1f70d09e43b37 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -2681,8 +2681,8 @@ def test_resample_with_dst_time_change(self): '2016-03-14 13:00:00-05:00', '2016-03-15 01:00:00-05:00', '2016-03-15 13:00:00-05:00'] - index = pd.DatetimeIndex(expected_index_values, - tz='UTC').tz_convert('America/Chicago') + index = pd.to_datetime(expected_index_values, utc=True).tz_convert( + 'America/Chicago') expected = pd.DataFrame([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0], index=index) diff --git a/pandas/tests/tslibs/test_array_to_datetime.py b/pandas/tests/tslibs/test_array_to_datetime.py index eb77e52e7c91d..915687304bfe2 100644 --- a/pandas/tests/tslibs/test_array_to_datetime.py +++ b/pandas/tests/tslibs/test_array_to_datetime.py @@ -3,6 +3,8 @@ import numpy as np import pytest +import pytz +from dateutil.tz.tz import tzoffset from pandas._libs import tslib from pandas.compat.numpy import np_array_datetime64_compat @@ -52,7 +54,7 @@ def test_parsers_iso8601_invalid(self, date_str): class TestArrayToDatetime(object): def test_parsing_valid_dates(self): arr = np.array(['01-01-2013', '01-02-2013'], dtype=object) - result = tslib.array_to_datetime(arr) + result, _ = tslib.array_to_datetime(arr) expected = ['2013-01-01T00:00:00.000000000-0000', '2013-01-02T00:00:00.000000000-0000'] tm.assert_numpy_array_equal( @@ -60,38 +62,60 @@ def test_parsing_valid_dates(self): np_array_datetime64_compat(expected, dtype='M8[ns]')) arr = np.array(['Mon Sep 16 2013', 'Tue Sep 17 2013'], dtype=object) - result = tslib.array_to_datetime(arr) + result, _ = tslib.array_to_datetime(arr) expected = ['2013-09-16T00:00:00.000000000-0000', '2013-09-17T00:00:00.000000000-0000'] tm.assert_numpy_array_equal( result, np_array_datetime64_compat(expected, dtype='M8[ns]')) - @pytest.mark.parametrize('dt_string', [ - '01-01-2013 08:00:00+08:00', - '2013-01-01T08:00:00.000000000+0800', - '2012-12-31T16:00:00.000000000-0800', - '12-31-2012 23:00:00-01:00']) - def test_parsing_timezone_offsets(self, dt_string): + @pytest.mark.parametrize('dt_string, expected_tz', [ + ['01-01-2013 08:00:00+08:00', pytz.FixedOffset(480)], + ['2013-01-01T08:00:00.000000000+0800', pytz.FixedOffset(480)], + ['2012-12-31T16:00:00.000000000-0800', pytz.FixedOffset(-480)], + ['12-31-2012 23:00:00-01:00', pytz.FixedOffset(-60)]]) + def test_parsing_timezone_offsets(self, dt_string, expected_tz): # All of these datetime strings with offsets are equivalent # to the same datetime after the timezone offset is added arr = np.array(['01-01-2013 00:00:00'], dtype=object) - expected = tslib.array_to_datetime(arr) + expected, _ = tslib.array_to_datetime(arr) arr = np.array([dt_string], dtype=object) - result = tslib.array_to_datetime(arr) + result, result_tz = tslib.array_to_datetime(arr) tm.assert_numpy_array_equal(result, expected) + assert result_tz is expected_tz + + def test_parsing_non_iso_timezone_offset(self): + dt_string = '01-01-2013T00:00:00.000000000+0000' + arr = np.array([dt_string], dtype=object) + result, result_tz = tslib.array_to_datetime(arr) + expected = np.array([np.datetime64('2013-01-01 00:00:00.000000000')]) + tm.assert_numpy_array_equal(result, expected) + assert result_tz is pytz.FixedOffset(0) + + def test_parsing_different_timezone_offsets(self): + # GH 17697 + data = ["2015-11-18 15:30:00+05:30", "2015-11-18 15:30:00+06:30"] + data = np.array(data, dtype=object) + result, result_tz = tslib.array_to_datetime(data) + expected = np.array([datetime(2015, 11, 18, 15, 30, + tzinfo=tzoffset(None, 19800)), + datetime(2015, 11, 18, 15, 30, + tzinfo=tzoffset(None, 23400))], + dtype=object) + tm.assert_numpy_array_equal(result, expected) + assert result_tz is None def test_number_looking_strings_not_into_datetime(self): # GH#4601 # These strings don't look like datetimes so they shouldn't be # attempted to be converted arr = np.array(['-352.737091', '183.575577'], dtype=object) - result = tslib.array_to_datetime(arr, errors='ignore') + result, _ = tslib.array_to_datetime(arr, errors='ignore') tm.assert_numpy_array_equal(result, arr) arr = np.array(['1', '2', '3', '4', '5'], dtype=object) - result = tslib.array_to_datetime(arr, errors='ignore') + result, _ = tslib.array_to_datetime(arr, errors='ignore') tm.assert_numpy_array_equal(result, arr) @pytest.mark.parametrize('invalid_date', [ @@ -105,13 +129,13 @@ def test_coerce_outside_ns_bounds(self, invalid_date): with pytest.raises(ValueError): tslib.array_to_datetime(arr, errors='raise') - result = tslib.array_to_datetime(arr, errors='coerce') + result, _ = tslib.array_to_datetime(arr, errors='coerce') expected = np.array([tslib.iNaT], dtype='M8[ns]') tm.assert_numpy_array_equal(result, expected) def test_coerce_outside_ns_bounds_one_valid(self): arr = np.array(['1/1/1000', '1/1/2000'], dtype=object) - result = tslib.array_to_datetime(arr, errors='coerce') + result, _ = tslib.array_to_datetime(arr, errors='coerce') expected = [tslib.iNaT, '2000-01-01T00:00:00.000000000-0000'] tm.assert_numpy_array_equal( @@ -123,11 +147,11 @@ def test_coerce_of_invalid_datetimes(self): # Without coercing, the presence of any invalid dates prevents # any values from being converted - result = tslib.array_to_datetime(arr, errors='ignore') + result, _ = tslib.array_to_datetime(arr, errors='ignore') tm.assert_numpy_array_equal(result, arr) # With coercing, the invalid dates becomes iNaT - result = tslib.array_to_datetime(arr, errors='coerce') + result, _ = tslib.array_to_datetime(arr, errors='coerce') expected = ['2013-01-01T00:00:00.000000000-0000', tslib.iNaT, tslib.iNaT]
- [x] closes #17697 - [x] closes #11736 - [x] closes #21864 - [x] precursor to fixing #15938 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This PR makes `to_datetime(ts_string_with_offset)` and `DatetimeIndex([ts_string_with_offset])` to now match `Timestamp(ts_string_with_offset)` ``` This branch In [2]: Timestamp("2015-11-18 15:30:00+05:30") Out[2]: Timestamp('2015-11-18 15:30:00+0530', tz='pytz.FixedOffset(330)') In [3]: to_datetime("2015-11-18 15:30:00+05:30") Out[3]: Timestamp('2015-11-18 15:30:00+0530', tz='pytz.FixedOffset(330)') In [4]: DatetimeIndex(["2015-11-18 15:30:00+05:30"]) Out[4]: DatetimeIndex(['2015-11-18 15:30:00+05:30'], dtype='datetime64[ns, pytz.FixedOffset(330)]', freq=None) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/21822
2018-07-08T22:28:14Z
2018-07-30T10:30:02Z
2018-07-30T10:30:01Z
2018-08-01T20:40:28Z
DOC: Improve the docstring of Timedelta.asm8
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index a76ebc8000e54..b9405b15a0980 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -829,7 +829,37 @@ cdef class _Timedelta(timedelta): @property def asm8(self): - """ return a numpy timedelta64 array view of myself """ + """ + Return a numpy timedelta64 array scalar view. + + Provides access to the array scalar view (i.e. a combination of the + value and the units) associated with the numpy.timedelta64().view(), + including a 64-bit integer representation of the timedelta in + nanoseconds (Python int compatible). + + Returns + ------- + numpy timedelta64 array scalar view + Array scalar view of the timedelta in nanoseconds. + + Examples + -------- + >>> td = pd.Timedelta('1 days 2 min 3 us 42 ns') + >>> td.asm8 + numpy.timedelta64(86520000003042,'ns') + + >>> td = pd.Timedelta('2 min 3 s') + >>> td.asm8 + numpy.timedelta64(123000000000,'ns') + + >>> td = pd.Timedelta('3 ms 5 us') + >>> td.asm8 + numpy.timedelta64(3005000,'ns') + + >>> td = pd.Timedelta(42, unit='ns') + >>> td.asm8 + numpy.timedelta64(42,'ns') + """ return np.int64(self.value).view('m8[ns]') @property
- [ ] closes #xxxx - [ ] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry ``` ################################################################################ ###################### Docstring (pandas.Timedelta.asm8) ###################### ################################################################################ Return a numpy timedelta64 array view. Provides access to the array view associated with the numpy.timedelta64().view() including a 64-bit integer representation of the timedelta in nanoseconds (Python int compatible). Returns ------- numpy timedelta64 array view Array view of the timedelta in nanoseconds. Examples -------- >>> td = pd.Timedelta('1 days 2 min 3 us 42 ns') >>> td.asm8 numpy.timedelta64(86520000003042,'ns') >>> td = pd.Timedelta('2 min 3 s') >>> td.asm8 numpy.timedelta64(123000000000,'ns') >>> td = pd.Timedelta('3 ms 5 us') >>> td.asm8 numpy.timedelta64(3005000,'ns') >>> td = pd.Timedelta(42, unit='ns') >>> td.asm8 numpy.timedelta64(42,'ns') ################################################################################ ################################## Validation ################################## ################################################################################ ```
https://api.github.com/repos/pandas-dev/pandas/pulls/21821
2018-07-08T21:44:39Z
2018-07-10T10:36:23Z
2018-07-10T10:36:23Z
2018-07-10T22:00:53Z
CLN: reorg groupby to multiple modules
diff --git a/pandas/core/api.py b/pandas/core/api.py index fa58e932ead13..92586235df93c 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -7,7 +7,7 @@ from pandas.core.algorithms import factorize, unique, value_counts from pandas.core.dtypes.missing import isna, isnull, notna, notnull from pandas.core.arrays import Categorical -from pandas.core.groupby.groupby import Grouper +from pandas.core.groupby import Grouper from pandas.io.formats.format import set_eng_float_format from pandas.core.index import (Index, CategoricalIndex, Int64Index, UInt64Index, RangeIndex, Float64Index, diff --git a/pandas/core/base.py b/pandas/core/base.py index 4ea8c43b640fb..1226662824eb5 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -648,53 +648,6 @@ def _is_builtin_func(self, arg): return self._builtin_table.get(arg, arg) -class GroupByMixin(object): - """ provide the groupby facilities to the mixed object """ - - @staticmethod - def _dispatch(name, *args, **kwargs): - """ dispatch to apply """ - - def outer(self, *args, **kwargs): - def f(x): - x = self._shallow_copy(x, groupby=self._groupby) - return getattr(x, name)(*args, **kwargs) - return self._groupby.apply(f) - outer.__name__ = name - return outer - - def _gotitem(self, key, ndim, subset=None): - """ - sub-classes to define - return a sliced object - - Parameters - ---------- - key : string / list of selections - ndim : 1,2 - requested ndim of result - subset : object, default None - subset to act on - """ - # create a new object to prevent aliasing - if subset is None: - subset = self.obj - - # we need to make a shallow copy of ourselves - # with the same groupby - kwargs = dict([(attr, getattr(self, attr)) - for attr in self._attributes]) - self = self.__class__(subset, - groupby=self._groupby[key], - parent=self, - **kwargs) - self._reset_cache() - if subset.ndim == 2: - if is_scalar(key) and key in subset or is_list_like(key): - self._selection = key - return self - - class IndexOpsMixin(object): """ common ops mixin to support a unified interface / docs for Series / Index diff --git a/pandas/core/groupby/__init__.py b/pandas/core/groupby/__init__.py index 4b2ebdf16b89b..6f90fd1cff7e6 100644 --- a/pandas/core/groupby/__init__.py +++ b/pandas/core/groupby/__init__.py @@ -1,4 +1,4 @@ -# flake8: noqa -from pandas.core.groupby.groupby import ( - Grouper, GroupBy, SeriesGroupBy, DataFrameGroupBy -) +from pandas.core.groupby.groupby import GroupBy # flake8: noqa +from pandas.core.groupby.generic import ( + SeriesGroupBy, DataFrameGroupBy, PanelGroupBy) # flake8: noqa +from pandas.core.groupby.grouper import Grouper # flake8: noqa diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py new file mode 100644 index 0000000000000..b2c5a8cff9c1b --- /dev/null +++ b/pandas/core/groupby/base.py @@ -0,0 +1,160 @@ +""" +Provide basic components for groupby. These defintiions +hold the whitelist of methods that are exposed on the +SeriesGroupBy and the DataFrameGroupBy objects. +""" + +import types +from pandas.util._decorators import make_signature +from pandas.core.dtypes.common import is_scalar, is_list_like + + +class GroupByMixin(object): + """ provide the groupby facilities to the mixed object """ + + @staticmethod + def _dispatch(name, *args, **kwargs): + """ dispatch to apply """ + + def outer(self, *args, **kwargs): + def f(x): + x = self._shallow_copy(x, groupby=self._groupby) + return getattr(x, name)(*args, **kwargs) + return self._groupby.apply(f) + outer.__name__ = name + return outer + + def _gotitem(self, key, ndim, subset=None): + """ + sub-classes to define + return a sliced object + + Parameters + ---------- + key : string / list of selections + ndim : 1,2 + requested ndim of result + subset : object, default None + subset to act on + """ + # create a new object to prevent aliasing + if subset is None: + subset = self.obj + + # we need to make a shallow copy of ourselves + # with the same groupby + kwargs = dict([(attr, getattr(self, attr)) + for attr in self._attributes]) + self = self.__class__(subset, + groupby=self._groupby[key], + parent=self, + **kwargs) + self._reset_cache() + if subset.ndim == 2: + if is_scalar(key) and key in subset or is_list_like(key): + self._selection = key + return self + + +# special case to prevent duplicate plots when catching exceptions when +# forwarding methods from NDFrames +plotting_methods = frozenset(['plot', 'boxplot', 'hist']) + +common_apply_whitelist = frozenset([ + 'last', 'first', + 'head', 'tail', 'median', + 'mean', 'sum', 'min', 'max', + 'cumcount', 'ngroup', + 'resample', + 'rank', 'quantile', + 'fillna', + 'mad', + 'any', 'all', + 'take', + 'idxmax', 'idxmin', + 'shift', 'tshift', + 'ffill', 'bfill', + 'pct_change', 'skew', + 'corr', 'cov', 'diff', +]) | plotting_methods + +series_apply_whitelist = ((common_apply_whitelist | + {'nlargest', 'nsmallest', + 'is_monotonic_increasing', + 'is_monotonic_decreasing'}) - + {'boxplot'}) | frozenset(['dtype', 'unique']) + +dataframe_apply_whitelist = ((common_apply_whitelist | + frozenset(['dtypes', 'corrwith'])) - + {'boxplot'}) + +cython_transforms = frozenset(['cumprod', 'cumsum', 'shift', + 'cummin', 'cummax']) + +cython_cast_blacklist = frozenset(['rank', 'count', 'size']) + + +def whitelist_method_generator(base, klass, whitelist): + """ + Yields all GroupBy member defs for DataFrame/Series names in whitelist. + + Parameters + ---------- + base : class + base class + klass : class + class where members are defined. + Should be Series or DataFrame + whitelist : list + list of names of klass methods to be constructed + + Returns + ------- + The generator yields a sequence of strings, each suitable for exec'ing, + that define implementations of the named methods for DataFrameGroupBy + or SeriesGroupBy. + + Since we don't want to override methods explicitly defined in the + base class, any such name is skipped. + """ + + method_wrapper_template = \ + """def %(name)s(%(sig)s) : + \""" + %(doc)s + \""" + f = %(self)s.__getattr__('%(name)s') + return f(%(args)s)""" + property_wrapper_template = \ + """@property +def %(name)s(self) : + \""" + %(doc)s + \""" + return self.__getattr__('%(name)s')""" + + for name in whitelist: + # don't override anything that was explicitly defined + # in the base class + if hasattr(base, name): + continue + # ugly, but we need the name string itself in the method. + f = getattr(klass, name) + doc = f.__doc__ + doc = doc if type(doc) == str else '' + if isinstance(f, types.MethodType): + wrapper_template = method_wrapper_template + decl, args = make_signature(f) + # pass args by name to f because otherwise + # GroupBy._make_wrapper won't know whether + # we passed in an axis parameter. + args_by_name = ['{0}={0}'.format(arg) for arg in args[1:]] + params = {'name': name, + 'doc': doc, + 'sig': ','.join(decl), + 'self': args[0], + 'args': ','.join(args_by_name)} + else: + wrapper_template = property_wrapper_template + params = {'name': name, 'doc': doc} + yield wrapper_template % params diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py new file mode 100644 index 0000000000000..78631bfae9e01 --- /dev/null +++ b/pandas/core/groupby/generic.py @@ -0,0 +1,1660 @@ +""" +Define the SeriesGroupBy, DataFrameGroupBy, and PanelGroupBy +classes that hold the groupby interfaces (and some implementations). + +These are user facing as the result of the ``df.groupby(...)`` operations, +which here returns a DataFrameGroupBy object. +""" + +import collections +import warnings +import copy +from textwrap import dedent +from functools import partial + +import numpy as np + +from pandas._libs import lib, Timestamp +from pandas.util._decorators import Substitution, Appender +from pandas import compat + +import pandas.core.common as com +from pandas.core.panel import Panel +from pandas.compat import lzip, map + +from pandas.core.series import Series +from pandas.core.generic import _shared_docs +from pandas.core.groupby.groupby import ( + GroupBy, _apply_docs, _transform_template) +from pandas.core.generic import NDFrame +from pandas.core.groupby import base +from pandas.core.dtypes.common import ( + is_scalar, + is_bool, + is_datetimelike, + is_numeric_dtype, + is_integer_dtype, + is_interval_dtype, + _ensure_platform_int, + _ensure_int64) +from pandas.core.dtypes.missing import isna, notna +import pandas.core.algorithms as algorithms +from pandas.core.frame import DataFrame +from pandas.core.dtypes.cast import maybe_downcast_to_dtype +from pandas.core.base import SpecificationError, DataError +from pandas.core.index import Index, MultiIndex, CategoricalIndex +from pandas.core.arrays.categorical import Categorical +from pandas.core.internals import BlockManager, make_block + +from pandas.plotting._core import boxplot_frame_groupby + + +class NDFrameGroupBy(GroupBy): + + def _iterate_slices(self): + if self.axis == 0: + # kludge + if self._selection is None: + slice_axis = self.obj.columns + else: + slice_axis = self._selection_list + slicer = lambda x: self.obj[x] + else: + slice_axis = self.obj.index + slicer = self.obj.xs + + for val in slice_axis: + if val in self.exclusions: + continue + yield val, slicer(val) + + def _cython_agg_general(self, how, alt=None, numeric_only=True, + min_count=-1): + new_items, new_blocks = self._cython_agg_blocks( + how, alt=alt, numeric_only=numeric_only, min_count=min_count) + return self._wrap_agged_blocks(new_items, new_blocks) + + def _wrap_agged_blocks(self, items, blocks): + obj = self._obj_with_exclusions + + new_axes = list(obj._data.axes) + + # more kludge + if self.axis == 0: + new_axes[0], new_axes[1] = new_axes[1], self.grouper.result_index + else: + new_axes[self.axis] = self.grouper.result_index + + # Make sure block manager integrity check passes. + assert new_axes[0].equals(items) + new_axes[0] = items + + mgr = BlockManager(blocks, new_axes) + + new_obj = type(obj)(mgr) + + return self._post_process_cython_aggregate(new_obj) + + _block_agg_axis = 0 + + def _cython_agg_blocks(self, how, alt=None, numeric_only=True, + min_count=-1): + # TODO: the actual managing of mgr_locs is a PITA + # here, it should happen via BlockManager.combine + + data, agg_axis = self._get_data_to_aggregate() + + if numeric_only: + data = data.get_numeric_data(copy=False) + + new_blocks = [] + new_items = [] + deleted_items = [] + for block in data.blocks: + + locs = block.mgr_locs.as_array + try: + result, _ = self.grouper.aggregate( + block.values, how, axis=agg_axis, min_count=min_count) + except NotImplementedError: + # generally if we have numeric_only=False + # and non-applicable functions + # try to python agg + + if alt is None: + # we cannot perform the operation + # in an alternate way, exclude the block + deleted_items.append(locs) + continue + + # call our grouper again with only this block + from pandas.core.groupby.groupby import groupby + + obj = self.obj[data.items[locs]] + s = groupby(obj, self.grouper) + result = s.aggregate(lambda x: alt(x, axis=self.axis)) + newb = result._data.blocks[0] + + finally: + + # see if we can cast the block back to the original dtype + result = block._try_coerce_and_cast_result(result) + newb = block.make_block(result) + + new_items.append(locs) + new_blocks.append(newb) + + if len(new_blocks) == 0: + raise DataError('No numeric types to aggregate') + + # reset the locs in the blocks to correspond to our + # current ordering + indexer = np.concatenate(new_items) + new_items = data.items.take(np.sort(indexer)) + + if len(deleted_items): + + # we need to adjust the indexer to account for the + # items we have removed + # really should be done in internals :< + + deleted = np.concatenate(deleted_items) + ai = np.arange(len(data)) + mask = np.zeros(len(data)) + mask[deleted] = 1 + indexer = (ai - mask.cumsum())[indexer] + + offset = 0 + for b in new_blocks: + loc = len(b.mgr_locs) + b.mgr_locs = indexer[offset:(offset + loc)] + offset += loc + + return new_items, new_blocks + + def _get_data_to_aggregate(self): + obj = self._obj_with_exclusions + if self.axis == 0: + return obj.swapaxes(0, 1)._data, 1 + else: + return obj._data, self.axis + + def _post_process_cython_aggregate(self, obj): + # undoing kludge from below + if self.axis == 0: + obj = obj.swapaxes(0, 1) + return obj + + def aggregate(self, arg, *args, **kwargs): + + _level = kwargs.pop('_level', None) + result, how = self._aggregate(arg, _level=_level, *args, **kwargs) + if how is None: + return result + + if result is None: + + # grouper specific aggregations + if self.grouper.nkeys > 1: + return self._python_agg_general(arg, *args, **kwargs) + else: + + # try to treat as if we are passing a list + try: + assert not args and not kwargs + result = self._aggregate_multiple_funcs( + [arg], _level=_level, _axis=self.axis) + result.columns = Index( + result.columns.levels[0], + name=self._selected_obj.columns.name) + except Exception: + result = self._aggregate_generic(arg, *args, **kwargs) + + if not self.as_index: + self._insert_inaxis_grouper_inplace(result) + result.index = np.arange(len(result)) + + return result._convert(datetime=True) + + agg = aggregate + + def _aggregate_generic(self, func, *args, **kwargs): + if self.grouper.nkeys != 1: + raise AssertionError('Number of keys must be 1') + + axis = self.axis + obj = self._obj_with_exclusions + + result = {} + if axis != obj._info_axis_number: + try: + for name, data in self: + result[name] = self._try_cast(func(data, *args, **kwargs), + data) + except Exception: + return self._aggregate_item_by_item(func, *args, **kwargs) + else: + for name in self.indices: + try: + data = self.get_group(name, obj=obj) + result[name] = self._try_cast(func(data, *args, **kwargs), + data) + except Exception: + wrapper = lambda x: func(x, *args, **kwargs) + result[name] = data.apply(wrapper, axis=axis) + + return self._wrap_generic_output(result, obj) + + def _wrap_aggregated_output(self, output, names=None): + raise com.AbstractMethodError(self) + + def _aggregate_item_by_item(self, func, *args, **kwargs): + # only for axis==0 + + obj = self._obj_with_exclusions + result = {} + cannot_agg = [] + errors = None + for item in obj: + try: + data = obj[item] + colg = SeriesGroupBy(data, selection=item, + grouper=self.grouper) + result[item] = self._try_cast( + colg.aggregate(func, *args, **kwargs), data) + except ValueError: + cannot_agg.append(item) + continue + except TypeError as e: + cannot_agg.append(item) + errors = e + continue + + result_columns = obj.columns + if cannot_agg: + result_columns = result_columns.drop(cannot_agg) + + # GH6337 + if not len(result_columns) and errors is not None: + raise errors + + return DataFrame(result, columns=result_columns) + + def _decide_output_index(self, output, labels): + if len(output) == len(labels): + output_keys = labels + else: + output_keys = sorted(output) + try: + output_keys.sort() + except Exception: # pragma: no cover + pass + + if isinstance(labels, MultiIndex): + output_keys = MultiIndex.from_tuples(output_keys, + names=labels.names) + + return output_keys + + def _wrap_applied_output(self, keys, values, not_indexed_same=False): + from pandas.core.index import _all_indexes_same + from pandas.core.tools.numeric import to_numeric + + if len(keys) == 0: + return DataFrame(index=keys) + + key_names = self.grouper.names + + # GH12824. + def first_not_none(values): + try: + return next(com._not_none(*values)) + except StopIteration: + return None + + v = first_not_none(values) + + if v is None: + # GH9684. If all values are None, then this will throw an error. + # We'd prefer it return an empty dataframe. + return DataFrame() + elif isinstance(v, DataFrame): + return self._concat_objects(keys, values, + not_indexed_same=not_indexed_same) + elif self.grouper.groupings is not None: + if len(self.grouper.groupings) > 1: + key_index = self.grouper.result_index + + else: + ping = self.grouper.groupings[0] + if len(keys) == ping.ngroups: + key_index = ping.group_index + key_index.name = key_names[0] + + key_lookup = Index(keys) + indexer = key_lookup.get_indexer(key_index) + + # reorder the values + values = [values[i] for i in indexer] + else: + + key_index = Index(keys, name=key_names[0]) + + # don't use the key indexer + if not self.as_index: + key_index = None + + # make Nones an empty object + v = first_not_none(values) + if v is None: + return DataFrame() + elif isinstance(v, NDFrame): + values = [ + x if x is not None else + v._constructor(**v._construct_axes_dict()) + for x in values + ] + + v = values[0] + + if isinstance(v, (np.ndarray, Index, Series)): + if isinstance(v, Series): + applied_index = self._selected_obj._get_axis(self.axis) + all_indexed_same = _all_indexes_same([ + x.index for x in values + ]) + singular_series = (len(values) == 1 and + applied_index.nlevels == 1) + + # GH3596 + # provide a reduction (Frame -> Series) if groups are + # unique + if self.squeeze: + + # assign the name to this series + if singular_series: + values[0].name = keys[0] + + # GH2893 + # we have series in the values array, we want to + # produce a series: + # if any of the sub-series are not indexed the same + # OR we don't have a multi-index and we have only a + # single values + return self._concat_objects( + keys, values, not_indexed_same=not_indexed_same + ) + + # still a series + # path added as of GH 5545 + elif all_indexed_same: + from pandas.core.reshape.concat import concat + return concat(values) + + if not all_indexed_same: + # GH 8467 + return self._concat_objects( + keys, values, not_indexed_same=True, + ) + + try: + if self.axis == 0: + # GH6124 if the list of Series have a consistent name, + # then propagate that name to the result. + index = v.index.copy() + if index.name is None: + # Only propagate the series name to the result + # if all series have a consistent name. If the + # series do not have a consistent name, do + # nothing. + names = {v.name for v in values} + if len(names) == 1: + index.name = list(names)[0] + + # normally use vstack as its faster than concat + # and if we have mi-columns + if (isinstance(v.index, MultiIndex) or + key_index is None or + isinstance(key_index, MultiIndex)): + stacked_values = np.vstack(map(np.asarray, values)) + result = DataFrame(stacked_values, index=key_index, + columns=index) + else: + # GH5788 instead of stacking; concat gets the + # dtypes correct + from pandas.core.reshape.concat import concat + result = concat(values, keys=key_index, + names=key_index.names, + axis=self.axis).unstack() + result.columns = index + else: + stacked_values = np.vstack(map(np.asarray, values)) + result = DataFrame(stacked_values.T, index=v.index, + columns=key_index) + + except (ValueError, AttributeError): + # GH1738: values is list of arrays of unequal lengths fall + # through to the outer else caluse + return Series(values, index=key_index, + name=self._selection_name) + + # if we have date/time like in the original, then coerce dates + # as we are stacking can easily have object dtypes here + so = self._selected_obj + if (so.ndim == 2 and so.dtypes.apply(is_datetimelike).any()): + result = result.apply( + lambda x: to_numeric(x, errors='ignore')) + date_cols = self._selected_obj.select_dtypes( + include=['datetime', 'timedelta']).columns + date_cols = date_cols.intersection(result.columns) + result[date_cols] = (result[date_cols] + ._convert(datetime=True, + coerce=True)) + else: + result = result._convert(datetime=True) + + return self._reindex_output(result) + + # values are not series or array-like but scalars + else: + # only coerce dates if we find at least 1 datetime + coerce = any(isinstance(x, Timestamp) for x in values) + # self._selection_name not passed through to Series as the + # result should not take the name of original selection + # of columns + return (Series(values, index=key_index) + ._convert(datetime=True, + coerce=coerce)) + + else: + # Handle cases like BinGrouper + return self._concat_objects(keys, values, + not_indexed_same=not_indexed_same) + + def _transform_general(self, func, *args, **kwargs): + from pandas.core.reshape.concat import concat + + applied = [] + obj = self._obj_with_exclusions + gen = self.grouper.get_iterator(obj, axis=self.axis) + fast_path, slow_path = self._define_paths(func, *args, **kwargs) + + path = None + for name, group in gen: + object.__setattr__(group, 'name', name) + + if path is None: + # Try slow path and fast path. + try: + path, res = self._choose_path(fast_path, slow_path, group) + except TypeError: + return self._transform_item_by_item(obj, fast_path) + except ValueError: + msg = 'transform must return a scalar value for each group' + raise ValueError(msg) + else: + res = path(group) + + if isinstance(res, Series): + + # we need to broadcast across the + # other dimension; this will preserve dtypes + # GH14457 + if not np.prod(group.shape): + continue + elif res.index.is_(obj.index): + r = concat([res] * len(group.columns), axis=1) + r.columns = group.columns + r.index = group.index + else: + r = DataFrame( + np.concatenate([res.values] * len(group.index) + ).reshape(group.shape), + columns=group.columns, index=group.index) + + applied.append(r) + else: + applied.append(res) + + concat_index = obj.columns if self.axis == 0 else obj.index + concatenated = concat(applied, join_axes=[concat_index], + axis=self.axis, verify_integrity=False) + return self._set_result_index_ordered(concatenated) + + @Substitution(klass='DataFrame', selected='') + @Appender(_transform_template) + def transform(self, func, *args, **kwargs): + + # optimized transforms + func = self._is_cython_func(func) or func + if isinstance(func, compat.string_types): + if func in base.cython_transforms: + # cythonized transform + return getattr(self, func)(*args, **kwargs) + else: + # cythonized aggregation and merge + result = getattr(self, func)(*args, **kwargs) + else: + return self._transform_general(func, *args, **kwargs) + + # a reduction transform + if not isinstance(result, DataFrame): + return self._transform_general(func, *args, **kwargs) + + obj = self._obj_with_exclusions + + # nuiscance columns + if not result.columns.equals(obj.columns): + return self._transform_general(func, *args, **kwargs) + + return self._transform_fast(result, obj, func) + + def _transform_fast(self, result, obj, func_nm): + """ + Fast transform path for aggregations + """ + # if there were groups with no observations (Categorical only?) + # try casting data to original dtype + cast = self._transform_should_cast(func_nm) + + # for each col, reshape to to size of original frame + # by take operation + ids, _, ngroup = self.grouper.group_info + output = [] + for i, _ in enumerate(result.columns): + res = algorithms.take_1d(result.iloc[:, i].values, ids) + if cast: + res = self._try_cast(res, obj.iloc[:, i]) + output.append(res) + + return DataFrame._from_arrays(output, columns=result.columns, + index=obj.index) + + def _define_paths(self, func, *args, **kwargs): + if isinstance(func, compat.string_types): + fast_path = lambda group: getattr(group, func)(*args, **kwargs) + slow_path = lambda group: group.apply( + lambda x: getattr(x, func)(*args, **kwargs), axis=self.axis) + else: + fast_path = lambda group: func(group, *args, **kwargs) + slow_path = lambda group: group.apply( + lambda x: func(x, *args, **kwargs), axis=self.axis) + return fast_path, slow_path + + def _choose_path(self, fast_path, slow_path, group): + path = slow_path + res = slow_path(group) + + # if we make it here, test if we can use the fast path + try: + res_fast = fast_path(group) + + # compare that we get the same results + if res.shape == res_fast.shape: + res_r = res.values.ravel() + res_fast_r = res_fast.values.ravel() + mask = notna(res_r) + if (res_r[mask] == res_fast_r[mask]).all(): + path = fast_path + + except Exception: + pass + return path, res + + def _transform_item_by_item(self, obj, wrapper): + # iterate through columns + output = {} + inds = [] + for i, col in enumerate(obj): + try: + output[col] = self[col].transform(wrapper) + inds.append(i) + except Exception: + pass + + if len(output) == 0: # pragma: no cover + raise TypeError('Transform function invalid for data types') + + columns = obj.columns + if len(output) < len(obj.columns): + columns = columns.take(inds) + + return DataFrame(output, index=obj.index, columns=columns) + + def filter(self, func, dropna=True, *args, **kwargs): # noqa + """ + Return a copy of a DataFrame excluding elements from groups that + do not satisfy the boolean criterion specified by func. + + Parameters + ---------- + f : function + Function to apply to each subframe. Should return True or False. + dropna : Drop groups that do not pass the filter. True by default; + if False, groups that evaluate False are filled with NaNs. + + Notes + ----- + Each subframe is endowed the attribute 'name' in case you need to know + which group you are working on. + + Examples + -------- + >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', + ... 'foo', 'bar'], + ... 'B' : [1, 2, 3, 4, 5, 6], + ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) + >>> grouped = df.groupby('A') + >>> grouped.filter(lambda x: x['B'].mean() > 3.) + A B C + 1 bar 2 5.0 + 3 bar 4 1.0 + 5 bar 6 9.0 + + Returns + ------- + filtered : DataFrame + """ + + indices = [] + + obj = self._selected_obj + gen = self.grouper.get_iterator(obj, axis=self.axis) + + for name, group in gen: + object.__setattr__(group, 'name', name) + + res = func(group, *args, **kwargs) + + try: + res = res.squeeze() + except AttributeError: # allow e.g., scalars and frames to pass + pass + + # interpret the result of the filter + if is_bool(res) or (is_scalar(res) and isna(res)): + if res and notna(res): + indices.append(self._get_index(name)) + else: + # non scalars aren't allowed + raise TypeError("filter function returned a %s, " + "but expected a scalar bool" % + type(res).__name__) + + return self._apply_filter(indices, dropna) + + +class SeriesGroupBy(GroupBy): + # + # Make class defs of attributes on SeriesGroupBy whitelist + + _apply_whitelist = base.series_apply_whitelist + for _def_str in base.whitelist_method_generator( + GroupBy, Series, _apply_whitelist): + exec(_def_str) + + @property + def _selection_name(self): + """ + since we are a series, we by definition only have + a single name, but may be the result of a selection or + the name of our object + """ + if self._selection is None: + return self.obj.name + else: + return self._selection + + _agg_doc = dedent(""" + Examples + -------- + + >>> s = pd.Series([1, 2, 3, 4]) + + >>> s + 0 1 + 1 2 + 2 3 + 3 4 + dtype: int64 + + >>> s.groupby([1, 1, 2, 2]).min() + 1 1 + 2 3 + dtype: int64 + + >>> s.groupby([1, 1, 2, 2]).agg('min') + 1 1 + 2 3 + dtype: int64 + + >>> s.groupby([1, 1, 2, 2]).agg(['min', 'max']) + min max + 1 1 2 + 2 3 4 + + See also + -------- + pandas.Series.groupby.apply + pandas.Series.groupby.transform + pandas.Series.aggregate + + """) + + @Appender(_apply_docs['template'] + .format(input='series', + examples=_apply_docs['series_examples'])) + def apply(self, func, *args, **kwargs): + return super(SeriesGroupBy, self).apply(func, *args, **kwargs) + + @Appender(_agg_doc) + @Appender(_shared_docs['aggregate'] % dict( + klass='Series', + versionadded='', + axis='')) + def aggregate(self, func_or_funcs, *args, **kwargs): + _level = kwargs.pop('_level', None) + if isinstance(func_or_funcs, compat.string_types): + return getattr(self, func_or_funcs)(*args, **kwargs) + + if isinstance(func_or_funcs, collections.Iterable): + # Catch instances of lists / tuples + # but not the class list / tuple itself. + ret = self._aggregate_multiple_funcs(func_or_funcs, + (_level or 0) + 1) + else: + cyfunc = self._is_cython_func(func_or_funcs) + if cyfunc and not args and not kwargs: + return getattr(self, cyfunc)() + + if self.grouper.nkeys > 1: + return self._python_agg_general(func_or_funcs, *args, **kwargs) + + try: + return self._python_agg_general(func_or_funcs, *args, **kwargs) + except Exception: + result = self._aggregate_named(func_or_funcs, *args, **kwargs) + + index = Index(sorted(result), name=self.grouper.names[0]) + ret = Series(result, index=index) + + if not self.as_index: # pragma: no cover + print('Warning, ignoring as_index=True') + + # _level handled at higher + if not _level and isinstance(ret, dict): + from pandas import concat + ret = concat(ret, axis=1) + return ret + + agg = aggregate + + def _aggregate_multiple_funcs(self, arg, _level): + if isinstance(arg, dict): + + # show the deprecation, but only if we + # have not shown a higher level one + # GH 15931 + if isinstance(self._selected_obj, Series) and _level <= 1: + warnings.warn( + ("using a dict on a Series for aggregation\n" + "is deprecated and will be removed in a future " + "version"), + FutureWarning, stacklevel=3) + + columns = list(arg.keys()) + arg = list(arg.items()) + elif any(isinstance(x, (tuple, list)) for x in arg): + arg = [(x, x) if not isinstance(x, (tuple, list)) else x + for x in arg] + + # indicated column order + columns = lzip(*arg)[0] + else: + # list of functions / function names + columns = [] + for f in arg: + if isinstance(f, compat.string_types): + columns.append(f) + else: + # protect against callables without names + columns.append(com._get_callable_name(f)) + arg = lzip(columns, arg) + + results = {} + for name, func in arg: + obj = self + if name in results: + raise SpecificationError('Function names must be unique, ' + 'found multiple named %s' % name) + + # reset the cache so that we + # only include the named selection + if name in self._selected_obj: + obj = copy.copy(obj) + obj._reset_cache() + obj._selection = name + results[name] = obj.aggregate(func) + + if any(isinstance(x, DataFrame) for x in compat.itervalues(results)): + # let higher level handle + if _level: + return results + + return DataFrame(results, columns=columns) + + def _wrap_output(self, output, index, names=None): + """ common agg/transform wrapping logic """ + output = output[self._selection_name] + + if names is not None: + return DataFrame(output, index=index, columns=names) + else: + name = self._selection_name + if name is None: + name = self._selected_obj.name + return Series(output, index=index, name=name) + + def _wrap_aggregated_output(self, output, names=None): + return self._wrap_output(output=output, + index=self.grouper.result_index, + names=names) + + def _wrap_transformed_output(self, output, names=None): + return self._wrap_output(output=output, + index=self.obj.index, + names=names) + + def _wrap_applied_output(self, keys, values, not_indexed_same=False): + if len(keys) == 0: + # GH #6265 + return Series([], name=self._selection_name, index=keys) + + def _get_index(): + if self.grouper.nkeys > 1: + index = MultiIndex.from_tuples(keys, names=self.grouper.names) + else: + index = Index(keys, name=self.grouper.names[0]) + return index + + if isinstance(values[0], dict): + # GH #823 + index = _get_index() + result = DataFrame(values, index=index).stack() + result.name = self._selection_name + return result + + if isinstance(values[0], (Series, dict)): + return self._concat_objects(keys, values, + not_indexed_same=not_indexed_same) + elif isinstance(values[0], DataFrame): + # possible that Series -> DataFrame by applied function + return self._concat_objects(keys, values, + not_indexed_same=not_indexed_same) + else: + # GH #6265 + return Series(values, index=_get_index(), + name=self._selection_name) + + def _aggregate_named(self, func, *args, **kwargs): + result = {} + + for name, group in self: + group.name = name + output = func(group, *args, **kwargs) + if isinstance(output, (Series, Index, np.ndarray)): + raise Exception('Must produce aggregated value') + result[name] = self._try_cast(output, group) + + return result + + @Substitution(klass='Series', selected='A.') + @Appender(_transform_template) + def transform(self, func, *args, **kwargs): + func = self._is_cython_func(func) or func + + # if string function + if isinstance(func, compat.string_types): + if func in base.cython_transforms: + # cythonized transform + return getattr(self, func)(*args, **kwargs) + else: + # cythonized aggregation and merge + return self._transform_fast( + lambda: getattr(self, func)(*args, **kwargs), func) + + # reg transform + klass = self._selected_obj.__class__ + results = [] + wrapper = lambda x: func(x, *args, **kwargs) + for name, group in self: + object.__setattr__(group, 'name', name) + res = wrapper(group) + + if hasattr(res, 'values'): + res = res.values + + indexer = self._get_index(name) + s = klass(res, indexer) + results.append(s) + + from pandas.core.reshape.concat import concat + result = concat(results).sort_index() + + # we will only try to coerce the result type if + # we have a numeric dtype, as these are *always* udfs + # the cython take a different path (and casting) + dtype = self._selected_obj.dtype + if is_numeric_dtype(dtype): + result = maybe_downcast_to_dtype(result, dtype) + + result.name = self._selected_obj.name + result.index = self._selected_obj.index + return result + + def _transform_fast(self, func, func_nm): + """ + fast version of transform, only applicable to + builtin/cythonizable functions + """ + if isinstance(func, compat.string_types): + func = getattr(self, func) + + ids, _, ngroup = self.grouper.group_info + cast = self._transform_should_cast(func_nm) + out = algorithms.take_1d(func().values, ids) + if cast: + out = self._try_cast(out, self.obj) + return Series(out, index=self.obj.index, name=self.obj.name) + + def filter(self, func, dropna=True, *args, **kwargs): # noqa + """ + Return a copy of a Series excluding elements from groups that + do not satisfy the boolean criterion specified by func. + + Parameters + ---------- + func : function + To apply to each group. Should return True or False. + dropna : Drop groups that do not pass the filter. True by default; + if False, groups that evaluate False are filled with NaNs. + + Examples + -------- + >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', + ... 'foo', 'bar'], + ... 'B' : [1, 2, 3, 4, 5, 6], + ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) + >>> grouped = df.groupby('A') + >>> df.groupby('A').B.filter(lambda x: x.mean() > 3.) + 1 2 + 3 4 + 5 6 + Name: B, dtype: int64 + + Returns + ------- + filtered : Series + """ + if isinstance(func, compat.string_types): + wrapper = lambda x: getattr(x, func)(*args, **kwargs) + else: + wrapper = lambda x: func(x, *args, **kwargs) + + # Interpret np.nan as False. + def true_and_notna(x, *args, **kwargs): + b = wrapper(x, *args, **kwargs) + return b and notna(b) + + try: + indices = [self._get_index(name) for name, group in self + if true_and_notna(group)] + except ValueError: + raise TypeError("the filter must return a boolean result") + except TypeError: + raise TypeError("the filter must return a boolean result") + + filtered = self._apply_filter(indices, dropna) + return filtered + + def nunique(self, dropna=True): + """ Returns number of unique elements in the group """ + ids, _, _ = self.grouper.group_info + + val = self.obj.get_values() + + try: + sorter = np.lexsort((val, ids)) + except TypeError: # catches object dtypes + assert val.dtype == object, \ + 'val.dtype must be object, got %s' % val.dtype + val, _ = algorithms.factorize(val, sort=False) + sorter = np.lexsort((val, ids)) + _isna = lambda a: a == -1 + else: + _isna = isna + + ids, val = ids[sorter], val[sorter] + + # group boundaries are where group ids change + # unique observations are where sorted values change + idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] + inc = np.r_[1, val[1:] != val[:-1]] + + # 1st item of each group is a new unique observation + mask = _isna(val) + if dropna: + inc[idx] = 1 + inc[mask] = 0 + else: + inc[mask & np.r_[False, mask[:-1]]] = 0 + inc[idx] = 1 + + out = np.add.reduceat(inc, idx).astype('int64', copy=False) + if len(ids): + # NaN/NaT group exists if the head of ids is -1, + # so remove it from res and exclude its index from idx + if ids[0] == -1: + res = out[1:] + idx = idx[np.flatnonzero(idx)] + else: + res = out + else: + res = out[1:] + ri = self.grouper.result_index + + # we might have duplications among the bins + if len(res) != len(ri): + res, out = np.zeros(len(ri), dtype=out.dtype), res + res[ids[idx]] = out + + return Series(res, + index=ri, + name=self._selection_name) + + @Appender(Series.describe.__doc__) + def describe(self, **kwargs): + result = self.apply(lambda x: x.describe(**kwargs)) + if self.axis == 1: + return result.T + return result.unstack() + + def value_counts(self, normalize=False, sort=True, ascending=False, + bins=None, dropna=True): + + from pandas.core.reshape.tile import cut + from pandas.core.reshape.merge import _get_join_indexers + + if bins is not None and not np.iterable(bins): + # scalar bins cannot be done at top level + # in a backward compatible way + return self.apply(Series.value_counts, + normalize=normalize, + sort=sort, + ascending=ascending, + bins=bins) + + ids, _, _ = self.grouper.group_info + val = self.obj.get_values() + + # groupby removes null keys from groupings + mask = ids != -1 + ids, val = ids[mask], val[mask] + + if bins is None: + lab, lev = algorithms.factorize(val, sort=True) + llab = lambda lab, inc: lab[inc] + else: + + # lab is a Categorical with categories an IntervalIndex + lab = cut(Series(val), bins, include_lowest=True) + lev = lab.cat.categories + lab = lev.take(lab.cat.codes) + llab = lambda lab, inc: lab[inc]._multiindex.labels[-1] + + if is_interval_dtype(lab): + # TODO: should we do this inside II? + sorter = np.lexsort((lab.left, lab.right, ids)) + else: + sorter = np.lexsort((lab, ids)) + + ids, lab = ids[sorter], lab[sorter] + + # group boundaries are where group ids change + idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] + + # new values are where sorted labels change + lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1)) + inc = np.r_[True, lchanges] + inc[idx] = True # group boundaries are also new values + out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts + + # num. of times each group should be repeated + rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx)) + + # multi-index components + labels = list(map(rep, self.grouper.recons_labels)) + [llab(lab, inc)] + levels = [ping.group_index for ping in self.grouper.groupings] + [lev] + names = self.grouper.names + [self._selection_name] + + if dropna: + mask = labels[-1] != -1 + if mask.all(): + dropna = False + else: + out, labels = out[mask], [label[mask] for label in labels] + + if normalize: + out = out.astype('float') + d = np.diff(np.r_[idx, len(ids)]) + if dropna: + m = ids[lab == -1] + np.add.at(d, m, -1) + acc = rep(d)[mask] + else: + acc = rep(d) + out /= acc + + if sort and bins is None: + cat = ids[inc][mask] if dropna else ids[inc] + sorter = np.lexsort((out if ascending else -out, cat)) + out, labels[-1] = out[sorter], labels[-1][sorter] + + if bins is None: + mi = MultiIndex(levels=levels, labels=labels, names=names, + verify_integrity=False) + + if is_integer_dtype(out): + out = _ensure_int64(out) + return Series(out, index=mi, name=self._selection_name) + + # for compat. with libgroupby.value_counts need to ensure every + # bin is present at every index level, null filled with zeros + diff = np.zeros(len(out), dtype='bool') + for lab in labels[:-1]: + diff |= np.r_[True, lab[1:] != lab[:-1]] + + ncat, nbin = diff.sum(), len(levels[-1]) + + left = [np.repeat(np.arange(ncat), nbin), + np.tile(np.arange(nbin), ncat)] + + right = [diff.cumsum() - 1, labels[-1]] + + _, idx = _get_join_indexers(left, right, sort=False, how='left') + out = np.where(idx != -1, out[idx], 0) + + if sort: + sorter = np.lexsort((out if ascending else -out, left[0])) + out, left[-1] = out[sorter], left[-1][sorter] + + # build the multi-index w/ full levels + labels = list(map(lambda lab: np.repeat(lab[diff], nbin), labels[:-1])) + labels.append(left[-1]) + + mi = MultiIndex(levels=levels, labels=labels, names=names, + verify_integrity=False) + + if is_integer_dtype(out): + out = _ensure_int64(out) + return Series(out, index=mi, name=self._selection_name) + + def count(self): + """ Compute count of group, excluding missing values """ + ids, _, ngroups = self.grouper.group_info + val = self.obj.get_values() + + mask = (ids != -1) & ~isna(val) + ids = _ensure_platform_int(ids) + out = np.bincount(ids[mask], minlength=ngroups or 0) + + return Series(out, + index=self.grouper.result_index, + name=self._selection_name, + dtype='int64') + + def _apply_to_column_groupbys(self, func): + """ return a pass thru """ + return func(self) + + def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None): + """Calculate percent change of each value to previous entry in group""" + filled = getattr(self, fill_method)(limit=limit) + shifted = filled.shift(periods=periods, freq=freq) + + return (filled / shifted) - 1 + + +class DataFrameGroupBy(NDFrameGroupBy): + + _apply_whitelist = base.dataframe_apply_whitelist + + # + # Make class defs of attributes on DataFrameGroupBy whitelist. + for _def_str in base.whitelist_method_generator( + GroupBy, DataFrame, _apply_whitelist): + exec(_def_str) + + _block_agg_axis = 1 + + _agg_doc = dedent(""" + Examples + -------- + + >>> df = pd.DataFrame({'A': [1, 1, 2, 2], + ... 'B': [1, 2, 3, 4], + ... 'C': np.random.randn(4)}) + + >>> df + A B C + 0 1 1 0.362838 + 1 1 2 0.227877 + 2 2 3 1.267767 + 3 2 4 -0.562860 + + The aggregation is for each column. + + >>> df.groupby('A').agg('min') + B C + A + 1 1 0.227877 + 2 3 -0.562860 + + Multiple aggregations + + >>> df.groupby('A').agg(['min', 'max']) + B C + min max min max + A + 1 1 2 0.227877 0.362838 + 2 3 4 -0.562860 1.267767 + + Select a column for aggregation + + >>> df.groupby('A').B.agg(['min', 'max']) + min max + A + 1 1 2 + 2 3 4 + + Different aggregations per column + + >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'}) + B C + min max sum + A + 1 1 2 0.590716 + 2 3 4 0.704907 + + See also + -------- + pandas.DataFrame.groupby.apply + pandas.DataFrame.groupby.transform + pandas.DataFrame.aggregate + + """) + + @Appender(_agg_doc) + @Appender(_shared_docs['aggregate'] % dict( + klass='DataFrame', + versionadded='', + axis='')) + def aggregate(self, arg, *args, **kwargs): + return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs) + + agg = aggregate + + def _gotitem(self, key, ndim, subset=None): + """ + sub-classes to define + return a sliced object + + Parameters + ---------- + key : string / list of selections + ndim : 1,2 + requested ndim of result + subset : object, default None + subset to act on + """ + + if ndim == 2: + if subset is None: + subset = self.obj + return DataFrameGroupBy(subset, self.grouper, selection=key, + grouper=self.grouper, + exclusions=self.exclusions, + as_index=self.as_index) + elif ndim == 1: + if subset is None: + subset = self.obj[key] + return SeriesGroupBy(subset, selection=key, + grouper=self.grouper) + + raise AssertionError("invalid ndim for _gotitem") + + def _wrap_generic_output(self, result, obj): + result_index = self.grouper.levels[0] + + if self.axis == 0: + return DataFrame(result, index=obj.columns, + columns=result_index).T + else: + return DataFrame(result, index=obj.index, + columns=result_index) + + def _get_data_to_aggregate(self): + obj = self._obj_with_exclusions + if self.axis == 1: + return obj.T._data, 1 + else: + return obj._data, 1 + + def _insert_inaxis_grouper_inplace(self, result): + # zip in reverse so we can always insert at loc 0 + izip = zip(* map(reversed, ( + self.grouper.names, + self.grouper.get_group_levels(), + [grp.in_axis for grp in self.grouper.groupings]))) + + for name, lev, in_axis in izip: + if in_axis: + result.insert(0, name, lev) + + def _wrap_aggregated_output(self, output, names=None): + agg_axis = 0 if self.axis == 1 else 1 + agg_labels = self._obj_with_exclusions._get_axis(agg_axis) + + output_keys = self._decide_output_index(output, agg_labels) + + if not self.as_index: + result = DataFrame(output, columns=output_keys) + self._insert_inaxis_grouper_inplace(result) + result = result._consolidate() + else: + index = self.grouper.result_index + result = DataFrame(output, index=index, columns=output_keys) + + if self.axis == 1: + result = result.T + + return self._reindex_output(result)._convert(datetime=True) + + def _wrap_transformed_output(self, output, names=None): + return DataFrame(output, index=self.obj.index) + + def _wrap_agged_blocks(self, items, blocks): + if not self.as_index: + index = np.arange(blocks[0].values.shape[-1]) + mgr = BlockManager(blocks, [items, index]) + result = DataFrame(mgr) + + self._insert_inaxis_grouper_inplace(result) + result = result._consolidate() + else: + index = self.grouper.result_index + mgr = BlockManager(blocks, [items, index]) + result = DataFrame(mgr) + + if self.axis == 1: + result = result.T + + return self._reindex_output(result)._convert(datetime=True) + + def _reindex_output(self, result): + """ + If we have categorical groupers, then we want to make sure that + we have a fully reindex-output to the levels. These may have not + participated in the groupings (e.g. may have all been + nan groups); + + This can re-expand the output space + """ + + # we need to re-expand the output space to accomodate all values + # whether observed or not in the cartesian product of our groupes + groupings = self.grouper.groupings + if groupings is None: + return result + elif len(groupings) == 1: + return result + + # if we only care about the observed values + # we are done + elif self.observed: + return result + + # reindexing only applies to a Categorical grouper + elif not any(isinstance(ping.grouper, (Categorical, CategoricalIndex)) + for ping in groupings): + return result + + levels_list = [ping.group_index for ping in groupings] + index, _ = MultiIndex.from_product( + levels_list, names=self.grouper.names).sortlevel() + + if self.as_index: + d = {self.obj._get_axis_name(self.axis): index, 'copy': False} + return result.reindex(**d) + + # GH 13204 + # Here, the categorical in-axis groupers, which need to be fully + # expanded, are columns in `result`. An idea is to do: + # result = result.set_index(self.grouper.names) + # .reindex(index).reset_index() + # but special care has to be taken because of possible not-in-axis + # groupers. + # So, we manually select and drop the in-axis grouper columns, + # reindex `result`, and then reset the in-axis grouper columns. + + # Select in-axis groupers + in_axis_grps = [(i, ping.name) for (i, ping) + in enumerate(groupings) if ping.in_axis] + g_nums, g_names = zip(*in_axis_grps) + + result = result.drop(labels=list(g_names), axis=1) + + # Set a temp index and reindex (possibly expanding) + result = result.set_index(self.grouper.result_index + ).reindex(index, copy=False) + + # Reset in-axis grouper columns + # (using level numbers `g_nums` because level names may not be unique) + result = result.reset_index(level=g_nums) + + return result.reset_index(drop=True) + + def _iterate_column_groupbys(self): + for i, colname in enumerate(self._selected_obj.columns): + yield colname, SeriesGroupBy(self._selected_obj.iloc[:, i], + selection=colname, + grouper=self.grouper, + exclusions=self.exclusions) + + def _apply_to_column_groupbys(self, func): + from pandas.core.reshape.concat import concat + return concat( + (func(col_groupby) for _, col_groupby + in self._iterate_column_groupbys()), + keys=self._selected_obj.columns, axis=1) + + def _fill(self, direction, limit=None): + """Overridden method to join grouped columns in output""" + res = super(DataFrameGroupBy, self)._fill(direction, limit=limit) + output = collections.OrderedDict( + (grp.name, grp.grouper) for grp in self.grouper.groupings) + + from pandas import concat + return concat((self._wrap_transformed_output(output), res), axis=1) + + def count(self): + """ Compute count of group, excluding missing values """ + from pandas.core.dtypes.missing import _isna_ndarraylike as _isna + + data, _ = self._get_data_to_aggregate() + ids, _, ngroups = self.grouper.group_info + mask = ids != -1 + + val = ((mask & ~_isna(np.atleast_2d(blk.get_values()))) + for blk in data.blocks) + loc = (blk.mgr_locs for blk in data.blocks) + + counter = partial( + lib.count_level_2d, labels=ids, max_bin=ngroups, axis=1) + blk = map(make_block, map(counter, val), loc) + + return self._wrap_agged_blocks(data.items, list(blk)) + + def nunique(self, dropna=True): + """ + Return DataFrame with number of distinct observations per group for + each column. + + .. versionadded:: 0.20.0 + + Parameters + ---------- + dropna : boolean, default True + Don't include NaN in the counts. + + Returns + ------- + nunique: DataFrame + + Examples + -------- + >>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam', + ... 'ham', 'ham'], + ... 'value1': [1, 5, 5, 2, 5, 5], + ... 'value2': list('abbaxy')}) + >>> df + id value1 value2 + 0 spam 1 a + 1 egg 5 b + 2 egg 5 b + 3 spam 2 a + 4 ham 5 x + 5 ham 5 y + + >>> df.groupby('id').nunique() + id value1 value2 + id + egg 1 1 1 + ham 1 1 2 + spam 1 2 1 + + # check for rows with the same id but conflicting values + >>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any()) + id value1 value2 + 0 spam 1 a + 3 spam 2 a + 4 ham 5 x + 5 ham 5 y + """ + + obj = self._selected_obj + + def groupby_series(obj, col=None): + return SeriesGroupBy(obj, + selection=col, + grouper=self.grouper).nunique(dropna=dropna) + + if isinstance(obj, Series): + results = groupby_series(obj) + else: + from pandas.core.reshape.concat import concat + results = [groupby_series(obj[col], col) for col in obj.columns] + results = concat(results, axis=1) + + if not self.as_index: + results.index = com._default_index(len(results)) + return results + + boxplot = boxplot_frame_groupby + + +class PanelGroupBy(NDFrameGroupBy): + + def aggregate(self, arg, *args, **kwargs): + return super(PanelGroupBy, self).aggregate(arg, *args, **kwargs) + + agg = aggregate + + def _iterate_slices(self): + if self.axis == 0: + # kludge + if self._selection is None: + slice_axis = self._selected_obj.items + else: + slice_axis = self._selection_list + slicer = lambda x: self._selected_obj[x] + else: + raise NotImplementedError("axis other than 0 is not supported") + + for val in slice_axis: + if val in self.exclusions: + continue + + yield val, slicer(val) + + def aggregate(self, arg, *args, **kwargs): + """ + Aggregate using input function or dict of {column -> function} + + Parameters + ---------- + arg : function or dict + Function to use for aggregating groups. If a function, must either + work when passed a Panel or when passed to Panel.apply. If + pass a dict, the keys must be DataFrame column names + + Returns + ------- + aggregated : Panel + """ + if isinstance(arg, compat.string_types): + return getattr(self, arg)(*args, **kwargs) + + return self._aggregate_generic(arg, *args, **kwargs) + + def _wrap_generic_output(self, result, obj): + if self.axis == 0: + new_axes = list(obj.axes) + new_axes[0] = self.grouper.result_index + elif self.axis == 1: + x, y, z = obj.axes + new_axes = [self.grouper.result_index, z, x] + else: + x, y, z = obj.axes + new_axes = [self.grouper.result_index, y, x] + + result = Panel._from_axes(result, new_axes) + + if self.axis == 1: + result = result.swapaxes(0, 1).swapaxes(0, 2) + elif self.axis == 2: + result = result.swapaxes(0, 2) + + return result + + def _aggregate_item_by_item(self, func, *args, **kwargs): + obj = self._obj_with_exclusions + result = {} + + if self.axis > 0: + for item in obj: + try: + itemg = DataFrameGroupBy(obj[item], + axis=self.axis - 1, + grouper=self.grouper) + result[item] = itemg.aggregate(func, *args, **kwargs) + except (ValueError, TypeError): + raise + new_axes = list(obj.axes) + new_axes[self.axis] = self.grouper.result_index + return Panel._from_axes(result, new_axes) + else: + raise ValueError("axis value must be greater than 0") + + def _wrap_aggregated_output(self, output, names=None): + raise com.AbstractMethodError(self) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 5dc1d518d1c2d..ff2ed6970ee76 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1,75 +1,49 @@ +""" +Provide the groupby split-apply-combine paradigm. Define the GroupBy +class providing the base-class of operations. + +The SeriesGroupBy and DataFrameGroupBy sub-class +(defined in pandas.core.groupby.generic) +expose these user-facing objects to provide specific functionailty. +""" + import types from functools import wraps, partial -import numpy as np import datetime import collections import warnings -import copy -from textwrap import dedent from contextlib import contextmanager -from pandas.compat import ( - zip, range, lzip, - callable, map -) +import numpy as np + +from pandas._libs import groupby as libgroupby, Timestamp +from pandas.util._validators import validate_kwargs +from pandas.util._decorators import ( + cache_readonly, Substitution, Appender) from pandas import compat +from pandas.compat import zip, range, callable, set_function_name from pandas.compat.numpy import function as nv -from pandas.compat import set_function_name from pandas.core.dtypes.common import ( is_numeric_dtype, - is_timedelta64_dtype, is_datetime64_dtype, - is_categorical_dtype, - is_interval_dtype, - is_datetimelike, - is_datetime64_any_dtype, - is_bool, is_integer_dtype, - is_complex_dtype, - is_bool_dtype, is_scalar, - is_list_like, - is_hashable, - needs_i8_conversion, - _ensure_float64, - _ensure_platform_int, - _ensure_int64, - _ensure_object, - _ensure_categorical, _ensure_float) from pandas.core.dtypes.cast import maybe_downcast_to_dtype -from pandas.core.dtypes.generic import ABCSeries -from pandas.core.dtypes.missing import isna, isnull, notna, _maybe_fill +from pandas.core.dtypes.missing import isna, notna +from pandas.core.groupby import base from pandas.core.base import (PandasObject, SelectionMixin, GroupByError, DataError, SpecificationError) -from pandas.core.index import (Index, MultiIndex, - CategoricalIndex, _ensure_index) -from pandas.core.arrays import ExtensionArray, Categorical +from pandas.core.index import Index, MultiIndex +from pandas.core.generic import NDFrame from pandas.core.frame import DataFrame -from pandas.core.generic import NDFrame, _shared_docs -from pandas.core.internals import BlockManager, make_block from pandas.core.series import Series -from pandas.core.panel import Panel -from pandas.core.sorting import (get_group_index_sorter, get_group_index, - compress_group_index, get_flattened_iterator, - decons_obs_group_ids, get_indexer_dict) -from pandas.util._decorators import (cache_readonly, Substitution, - Appender, make_signature) -from pandas.io.formats.printing import pprint_thing -from pandas.util._validators import validate_kwargs - +from pandas.core.sorting import get_group_index_sorter import pandas.core.common as com import pandas.core.algorithms as algorithms from pandas.core.config import option_context -from pandas.plotting._core import boxplot_frame_groupby - -from pandas._libs import (lib, reduction, - groupby as libgroupby, - Timestamp, NaT, iNaT) -from pandas._libs.lib import count_level_2d - _doc_template = """ See also @@ -314,220 +288,6 @@ """ -# special case to prevent duplicate plots when catching exceptions when -# forwarding methods from NDFrames -_plotting_methods = frozenset(['plot', 'boxplot', 'hist']) - -_common_apply_whitelist = frozenset([ - 'last', 'first', - 'head', 'tail', 'median', - 'mean', 'sum', 'min', 'max', - 'cumcount', 'ngroup', - 'resample', - 'rank', 'quantile', - 'fillna', - 'mad', - 'any', 'all', - 'take', - 'idxmax', 'idxmin', - 'shift', 'tshift', - 'ffill', 'bfill', - 'pct_change', 'skew', - 'corr', 'cov', 'diff', -]) | _plotting_methods - -_series_apply_whitelist = ((_common_apply_whitelist | - {'nlargest', 'nsmallest', - 'is_monotonic_increasing', - 'is_monotonic_decreasing'}) - - {'boxplot'}) | frozenset(['dtype', 'unique']) - -_dataframe_apply_whitelist = ((_common_apply_whitelist | - frozenset(['dtypes', 'corrwith'])) - - {'boxplot'}) - -_cython_transforms = frozenset(['cumprod', 'cumsum', 'shift', - 'cummin', 'cummax']) - -_cython_cast_blacklist = frozenset(['rank', 'count', 'size']) - - -class Grouper(object): - """ - A Grouper allows the user to specify a groupby instruction for a target - object - - This specification will select a column via the key parameter, or if the - level and/or axis parameters are given, a level of the index of the target - object. - - These are local specifications and will override 'global' settings, - that is the parameters axis and level which are passed to the groupby - itself. - - Parameters - ---------- - key : string, defaults to None - groupby key, which selects the grouping column of the target - level : name/number, defaults to None - the level for the target index - freq : string / frequency object, defaults to None - This will groupby the specified frequency if the target selection - (via key or level) is a datetime-like object. For full specification - of available frequencies, please see `here - <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`_. - axis : number/name of the axis, defaults to 0 - sort : boolean, default to False - whether to sort the resulting labels - - additional kwargs to control time-like groupers (when ``freq`` is passed) - - closed : closed end of interval; 'left' or 'right' - label : interval boundary to use for labeling; 'left' or 'right' - convention : {'start', 'end', 'e', 's'} - If grouper is PeriodIndex - base, loffset - - Returns - ------- - A specification for a groupby instruction - - Examples - -------- - - Syntactic sugar for ``df.groupby('A')`` - - >>> df.groupby(Grouper(key='A')) - - Specify a resample operation on the column 'date' - - >>> df.groupby(Grouper(key='date', freq='60s')) - - Specify a resample operation on the level 'date' on the columns axis - with a frequency of 60s - - >>> df.groupby(Grouper(level='date', freq='60s', axis=1)) - """ - _attributes = ('key', 'level', 'freq', 'axis', 'sort') - - def __new__(cls, *args, **kwargs): - if kwargs.get('freq') is not None: - from pandas.core.resample import TimeGrouper - cls = TimeGrouper - return super(Grouper, cls).__new__(cls) - - def __init__(self, key=None, level=None, freq=None, axis=0, sort=False): - self.key = key - self.level = level - self.freq = freq - self.axis = axis - self.sort = sort - - self.grouper = None - self.obj = None - self.indexer = None - self.binner = None - self._grouper = None - - @property - def ax(self): - return self.grouper - - def _get_grouper(self, obj, validate=True): - """ - Parameters - ---------- - obj : the subject object - validate : boolean, default True - if True, validate the grouper - - Returns - ------- - a tuple of binner, grouper, obj (possibly sorted) - """ - - self._set_grouper(obj) - self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key], - axis=self.axis, - level=self.level, - sort=self.sort, - validate=validate) - return self.binner, self.grouper, self.obj - - def _set_grouper(self, obj, sort=False): - """ - given an object and the specifications, setup the internal grouper - for this particular specification - - Parameters - ---------- - obj : the subject object - sort : bool, default False - whether the resulting grouper should be sorted - """ - - if self.key is not None and self.level is not None: - raise ValueError( - "The Grouper cannot specify both a key and a level!") - - # Keep self.grouper value before overriding - if self._grouper is None: - self._grouper = self.grouper - - # the key must be a valid info item - if self.key is not None: - key = self.key - # The 'on' is already defined - if getattr(self.grouper, 'name', None) == key and \ - isinstance(obj, ABCSeries): - ax = self._grouper.take(obj.index) - else: - if key not in obj._info_axis: - raise KeyError( - "The grouper name {0} is not found".format(key)) - ax = Index(obj[key], name=key) - - else: - ax = obj._get_axis(self.axis) - if self.level is not None: - level = self.level - - # if a level is given it must be a mi level or - # equivalent to the axis name - if isinstance(ax, MultiIndex): - level = ax._get_level_number(level) - ax = Index(ax._get_level_values(level), - name=ax.names[level]) - - else: - if level not in (0, ax.name): - raise ValueError( - "The level {0} is not valid".format(level)) - - # possibly sort - if (self.sort or sort) and not ax.is_monotonic: - # use stable sort to support first, last, nth - indexer = self.indexer = ax.argsort(kind='mergesort') - ax = ax.take(indexer) - obj = obj._take(indexer, axis=self.axis, is_copy=False) - - self.obj = obj - self.grouper = ax - return self.grouper - - @property - def groups(self): - return self.grouper.groups - - def __repr__(self): - attrs_list = ["{}={!r}".format(attr_name, getattr(self, attr_name)) - for attr_name in self._attributes - if getattr(self, attr_name) is not None] - attrs = ", ".join(attrs_list) - cls_name = self.__class__.__name__ - return "{}({})".format(cls_name, attrs) - - class GroupByPlot(PandasObject): """ Class implementing the .plot attribute for groupby objects @@ -591,6 +351,7 @@ def __init__(self, obj, keys=None, axis=0, level=None, self.mutated = kwargs.pop('mutated', False) if grouper is None: + from pandas.core.groupby.grouper import _get_grouper grouper, exclusions, obj = _get_grouper(obj, keys, axis=axis, level=level, @@ -828,7 +589,7 @@ def curried(x): # special case otherwise extra plots are created when catching the # exception below - if name in _plotting_methods: + if name in base.plotting_methods: return self.apply(curried) try: @@ -1010,8 +771,8 @@ def _transform_should_cast(self, func_nm): bool Whether transform should attempt to cast the result of aggregation """ - return (self.size().fillna(0) > 0).any() and (func_nm not in - _cython_cast_blacklist) + return (self.size().fillna(0) > 0).any() and ( + func_nm not in base.cython_cast_blacklist) def _cython_transform(self, how, numeric_only=True, **kwargs): output = collections.OrderedDict() @@ -1235,8 +996,6 @@ class GroupBy(_GroupBy): len(grouped) : int Number of groups """ - _apply_whitelist = _common_apply_whitelist - def _bool_agg(self, val_test, skipna): """Shared func to call any / all Cython GroupBy implementations""" @@ -1768,6 +1527,7 @@ def nth(self, n, dropna=None): # create a grouper with the original parameters, but on the dropped # object + from pandas.core.groupby.grouper import _get_grouper grouper, _, _ = _get_grouper(dropped, key=self.keys, axis=self.axis, level=self.level, sort=self.sort, @@ -2060,7 +1820,7 @@ def _get_cythonized_result(self, how, grouper, aggregate=False, func = partial(func, vals) if needs_mask: - mask = isnull(obj.values).view(np.uint8) + mask = isna(obj.values).view(np.uint8) func = partial(func, mask) if needs_ngroups: @@ -2182,2976 +1942,12 @@ def tail(self, n=5): @Appender(GroupBy.__doc__) def groupby(obj, by, **kwds): if isinstance(obj, Series): + from pandas.core.groupby.generic import SeriesGroupBy klass = SeriesGroupBy elif isinstance(obj, DataFrame): + from pandas.core.groupby.generic import DataFrameGroupBy klass = DataFrameGroupBy else: # pragma: no cover raise TypeError('invalid type: %s' % type(obj)) return klass(obj, by, **kwds) - - -def _get_axes(group): - if isinstance(group, Series): - return [group.index] - else: - return group.axes - - -def _is_indexed_like(obj, axes): - if isinstance(obj, Series): - if len(axes) > 1: - return False - return obj.index.equals(axes[0]) - elif isinstance(obj, DataFrame): - return obj.index.equals(axes[0]) - - return False - - -class BaseGrouper(object): - """ - This is an internal Grouper class, which actually holds - the generated groups - - Parameters - ---------- - axis : int - the axis to group - groupings : array of grouping - all the grouping instances to handle in this grouper - for example for grouper list to groupby, need to pass the list - sort : boolean, default True - whether this grouper will give sorted result or not - group_keys : boolean, default True - mutated : boolean, default False - indexer : intp array, optional - the indexer created by Grouper - some groupers (TimeGrouper) will sort its axis and its - group_info is also sorted, so need the indexer to reorder - - """ - - def __init__(self, axis, groupings, sort=True, group_keys=True, - mutated=False, indexer=None): - self._filter_empty_groups = self.compressed = len(groupings) != 1 - self.axis = axis - self.groupings = groupings - self.sort = sort - self.group_keys = group_keys - self.mutated = mutated - self.indexer = indexer - - @property - def shape(self): - return tuple(ping.ngroups for ping in self.groupings) - - def __iter__(self): - return iter(self.indices) - - @property - def nkeys(self): - return len(self.groupings) - - def get_iterator(self, data, axis=0): - """ - Groupby iterator - - Returns - ------- - Generator yielding sequence of (name, subsetted object) - for each group - """ - splitter = self._get_splitter(data, axis=axis) - keys = self._get_group_keys() - for key, (i, group) in zip(keys, splitter): - yield key, group - - def _get_splitter(self, data, axis=0): - comp_ids, _, ngroups = self.group_info - return get_splitter(data, comp_ids, ngroups, axis=axis) - - def _get_group_keys(self): - if len(self.groupings) == 1: - return self.levels[0] - else: - comp_ids, _, ngroups = self.group_info - - # provide "flattened" iterator for multi-group setting - return get_flattened_iterator(comp_ids, - ngroups, - self.levels, - self.labels) - - def apply(self, f, data, axis=0): - mutated = self.mutated - splitter = self._get_splitter(data, axis=axis) - group_keys = self._get_group_keys() - - # oh boy - f_name = com._get_callable_name(f) - if (f_name not in _plotting_methods and - hasattr(splitter, 'fast_apply') and axis == 0): - try: - values, mutated = splitter.fast_apply(f, group_keys) - return group_keys, values, mutated - except reduction.InvalidApply: - # we detect a mutation of some kind - # so take slow path - pass - except Exception: - # raise this error to the caller - pass - - result_values = [] - for key, (i, group) in zip(group_keys, splitter): - object.__setattr__(group, 'name', key) - - # group might be modified - group_axes = _get_axes(group) - res = f(group) - if not _is_indexed_like(res, group_axes): - mutated = True - result_values.append(res) - - return group_keys, result_values, mutated - - @cache_readonly - def indices(self): - """ dict {group name -> group indices} """ - if len(self.groupings) == 1: - return self.groupings[0].indices - else: - label_list = [ping.labels for ping in self.groupings] - keys = [com._values_from_object(ping.group_index) - for ping in self.groupings] - return get_indexer_dict(label_list, keys) - - @property - def labels(self): - return [ping.labels for ping in self.groupings] - - @property - def levels(self): - return [ping.group_index for ping in self.groupings] - - @property - def names(self): - return [ping.name for ping in self.groupings] - - def size(self): - """ - Compute group sizes - - """ - ids, _, ngroup = self.group_info - ids = _ensure_platform_int(ids) - if ngroup: - out = np.bincount(ids[ids != -1], minlength=ngroup) - else: - out = ids - return Series(out, - index=self.result_index, - dtype='int64') - - @cache_readonly - def groups(self): - """ dict {group name -> group labels} """ - if len(self.groupings) == 1: - return self.groupings[0].groups - else: - to_groupby = lzip(*(ping.grouper for ping in self.groupings)) - to_groupby = Index(to_groupby) - return self.axis.groupby(to_groupby) - - @cache_readonly - def is_monotonic(self): - # return if my group orderings are monotonic - return Index(self.group_info[0]).is_monotonic - - @cache_readonly - def group_info(self): - comp_ids, obs_group_ids = self._get_compressed_labels() - - ngroups = len(obs_group_ids) - comp_ids = _ensure_int64(comp_ids) - return comp_ids, obs_group_ids, ngroups - - @cache_readonly - def label_info(self): - # return the labels of items in original grouped axis - labels, _, _ = self.group_info - if self.indexer is not None: - sorter = np.lexsort((labels, self.indexer)) - labels = labels[sorter] - return labels - - def _get_compressed_labels(self): - all_labels = [ping.labels for ping in self.groupings] - if len(all_labels) > 1: - group_index = get_group_index(all_labels, self.shape, - sort=True, xnull=True) - return compress_group_index(group_index, sort=self.sort) - - ping = self.groupings[0] - return ping.labels, np.arange(len(ping.group_index)) - - @cache_readonly - def ngroups(self): - return len(self.result_index) - - @property - def recons_labels(self): - comp_ids, obs_ids, _ = self.group_info - labels = (ping.labels for ping in self.groupings) - return decons_obs_group_ids( - comp_ids, obs_ids, self.shape, labels, xnull=True) - - @cache_readonly - def result_index(self): - if not self.compressed and len(self.groupings) == 1: - return self.groupings[0].result_index.rename(self.names[0]) - - labels = self.recons_labels - levels = [ping.result_index for ping in self.groupings] - result = MultiIndex(levels=levels, - labels=labels, - verify_integrity=False, - names=self.names) - return result - - def get_group_levels(self): - if not self.compressed and len(self.groupings) == 1: - return [self.groupings[0].result_index] - - name_list = [] - for ping, labels in zip(self.groupings, self.recons_labels): - labels = _ensure_platform_int(labels) - levels = ping.result_index.take(labels) - - name_list.append(levels) - - return name_list - - # ------------------------------------------------------------ - # Aggregation functions - - _cython_functions = { - 'aggregate': { - 'add': 'group_add', - 'prod': 'group_prod', - 'min': 'group_min', - 'max': 'group_max', - 'mean': 'group_mean', - 'median': { - 'name': 'group_median' - }, - 'var': 'group_var', - 'first': { - 'name': 'group_nth', - 'f': lambda func, a, b, c, d, e: func(a, b, c, d, 1, -1) - }, - 'last': 'group_last', - 'ohlc': 'group_ohlc', - }, - - 'transform': { - 'cumprod': 'group_cumprod', - 'cumsum': 'group_cumsum', - 'cummin': 'group_cummin', - 'cummax': 'group_cummax', - 'rank': { - 'name': 'group_rank', - 'f': lambda func, a, b, c, d, **kwargs: func( - a, b, c, d, - kwargs.get('ties_method', 'average'), - kwargs.get('ascending', True), - kwargs.get('pct', False), - kwargs.get('na_option', 'keep') - ) - } - } - } - - _cython_arity = { - 'ohlc': 4, # OHLC - } - - _name_functions = { - 'ohlc': lambda *args: ['open', 'high', 'low', 'close'] - } - - def _is_builtin_func(self, arg): - """ - if we define an builtin function for this argument, return it, - otherwise return the arg - """ - return SelectionMixin._builtin_table.get(arg, arg) - - def _get_cython_function(self, kind, how, values, is_numeric): - - dtype_str = values.dtype.name - - def get_func(fname): - # see if there is a fused-type version of function - # only valid for numeric - f = getattr(libgroupby, fname, None) - if f is not None and is_numeric: - return f - - # otherwise find dtype-specific version, falling back to object - for dt in [dtype_str, 'object']: - f = getattr(libgroupby, "%s_%s" % (fname, dtype_str), None) - if f is not None: - return f - - ftype = self._cython_functions[kind][how] - - if isinstance(ftype, dict): - func = afunc = get_func(ftype['name']) - - # a sub-function - f = ftype.get('f') - if f is not None: - - def wrapper(*args, **kwargs): - return f(afunc, *args, **kwargs) - - # need to curry our sub-function - func = wrapper - - else: - func = get_func(ftype) - - if func is None: - raise NotImplementedError("function is not implemented for this" - "dtype: [how->%s,dtype->%s]" % - (how, dtype_str)) - return func - - def _cython_operation(self, kind, values, how, axis, min_count=-1, - **kwargs): - assert kind in ['transform', 'aggregate'] - - # can we do this operation with our cython functions - # if not raise NotImplementedError - - # we raise NotImplemented if this is an invalid operation - # entirely, e.g. adding datetimes - - # categoricals are only 1d, so we - # are not setup for dim transforming - if is_categorical_dtype(values): - raise NotImplementedError( - "categoricals are not support in cython ops ATM") - elif is_datetime64_any_dtype(values): - if how in ['add', 'prod', 'cumsum', 'cumprod']: - raise NotImplementedError( - "datetime64 type does not support {} " - "operations".format(how)) - elif is_timedelta64_dtype(values): - if how in ['prod', 'cumprod']: - raise NotImplementedError( - "timedelta64 type does not support {} " - "operations".format(how)) - - arity = self._cython_arity.get(how, 1) - - vdim = values.ndim - swapped = False - if vdim == 1: - values = values[:, None] - out_shape = (self.ngroups, arity) - else: - if axis > 0: - swapped = True - values = values.swapaxes(0, axis) - if arity > 1: - raise NotImplementedError("arity of more than 1 is not " - "supported for the 'how' argument") - out_shape = (self.ngroups,) + values.shape[1:] - - is_datetimelike = needs_i8_conversion(values.dtype) - is_numeric = is_numeric_dtype(values.dtype) - - if is_datetimelike: - values = values.view('int64') - is_numeric = True - elif is_bool_dtype(values.dtype): - values = _ensure_float64(values) - elif is_integer_dtype(values): - # we use iNaT for the missing value on ints - # so pre-convert to guard this condition - if (values == iNaT).any(): - values = _ensure_float64(values) - else: - values = values.astype('int64', copy=False) - elif is_numeric and not is_complex_dtype(values): - values = _ensure_float64(values) - else: - values = values.astype(object) - - try: - func = self._get_cython_function( - kind, how, values, is_numeric) - except NotImplementedError: - if is_numeric: - values = _ensure_float64(values) - func = self._get_cython_function( - kind, how, values, is_numeric) - else: - raise - - if how == 'rank': - out_dtype = 'float' - else: - if is_numeric: - out_dtype = '%s%d' % (values.dtype.kind, values.dtype.itemsize) - else: - out_dtype = 'object' - - labels, _, _ = self.group_info - - if kind == 'aggregate': - result = _maybe_fill(np.empty(out_shape, dtype=out_dtype), - fill_value=np.nan) - counts = np.zeros(self.ngroups, dtype=np.int64) - result = self._aggregate( - result, counts, values, labels, func, is_numeric, - is_datetimelike, min_count) - elif kind == 'transform': - result = _maybe_fill(np.empty_like(values, dtype=out_dtype), - fill_value=np.nan) - - # TODO: min_count - result = self._transform( - result, values, labels, func, is_numeric, is_datetimelike, - **kwargs) - - if is_integer_dtype(result) and not is_datetimelike: - mask = result == iNaT - if mask.any(): - result = result.astype('float64') - result[mask] = np.nan - - if kind == 'aggregate' and \ - self._filter_empty_groups and not counts.all(): - if result.ndim == 2: - try: - result = lib.row_bool_subset( - result, (counts > 0).view(np.uint8)) - except ValueError: - result = lib.row_bool_subset_object( - _ensure_object(result), - (counts > 0).view(np.uint8)) - else: - result = result[counts > 0] - - if vdim == 1 and arity == 1: - result = result[:, 0] - - if how in self._name_functions: - # TODO - names = self._name_functions[how]() - else: - names = None - - if swapped: - result = result.swapaxes(0, axis) - - return result, names - - def aggregate(self, values, how, axis=0, min_count=-1): - return self._cython_operation('aggregate', values, how, axis, - min_count=min_count) - - def transform(self, values, how, axis=0, **kwargs): - return self._cython_operation('transform', values, how, axis, **kwargs) - - def _aggregate(self, result, counts, values, comp_ids, agg_func, - is_numeric, is_datetimelike, min_count=-1): - if values.ndim > 3: - # punting for now - raise NotImplementedError("number of dimensions is currently " - "limited to 3") - elif values.ndim > 2: - for i, chunk in enumerate(values.transpose(2, 0, 1)): - - chunk = chunk.squeeze() - agg_func(result[:, :, i], counts, chunk, comp_ids, - min_count) - else: - agg_func(result, counts, values, comp_ids, min_count) - - return result - - def _transform(self, result, values, comp_ids, transform_func, - is_numeric, is_datetimelike, **kwargs): - - comp_ids, _, ngroups = self.group_info - if values.ndim > 3: - # punting for now - raise NotImplementedError("number of dimensions is currently " - "limited to 3") - elif values.ndim > 2: - for i, chunk in enumerate(values.transpose(2, 0, 1)): - - chunk = chunk.squeeze() - transform_func(result[:, :, i], values, - comp_ids, is_datetimelike, **kwargs) - else: - transform_func(result, values, comp_ids, is_datetimelike, **kwargs) - - return result - - def agg_series(self, obj, func): - try: - return self._aggregate_series_fast(obj, func) - except Exception: - return self._aggregate_series_pure_python(obj, func) - - def _aggregate_series_fast(self, obj, func): - func = self._is_builtin_func(func) - - if obj.index._has_complex_internals: - raise TypeError('Incompatible index for Cython grouper') - - group_index, _, ngroups = self.group_info - - # avoids object / Series creation overhead - dummy = obj._get_values(slice(None, 0)).to_dense() - indexer = get_group_index_sorter(group_index, ngroups) - obj = obj._take(indexer).to_dense() - group_index = algorithms.take_nd( - group_index, indexer, allow_fill=False) - grouper = reduction.SeriesGrouper(obj, func, group_index, ngroups, - dummy) - result, counts = grouper.get_result() - return result, counts - - def _aggregate_series_pure_python(self, obj, func): - - group_index, _, ngroups = self.group_info - - counts = np.zeros(ngroups, dtype=int) - result = None - - splitter = get_splitter(obj, group_index, ngroups, axis=self.axis) - - for label, group in splitter: - res = func(group) - if result is None: - if (isinstance(res, (Series, Index, np.ndarray))): - raise ValueError('Function does not reduce') - result = np.empty(ngroups, dtype='O') - - counts[label] = group.shape[0] - result[label] = res - - result = lib.maybe_convert_objects(result, try_float=0) - return result, counts - - -def generate_bins_generic(values, binner, closed): - """ - Generate bin edge offsets and bin labels for one array using another array - which has bin edge values. Both arrays must be sorted. - - Parameters - ---------- - values : array of values - binner : a comparable array of values representing bins into which to bin - the first array. Note, 'values' end-points must fall within 'binner' - end-points. - closed : which end of bin is closed; left (default), right - - Returns - ------- - bins : array of offsets (into 'values' argument) of bins. - Zero and last edge are excluded in result, so for instance the first - bin is values[0:bin[0]] and the last is values[bin[-1]:] - """ - lenidx = len(values) - lenbin = len(binner) - - if lenidx <= 0 or lenbin <= 0: - raise ValueError("Invalid length for values or for binner") - - # check binner fits data - if values[0] < binner[0]: - raise ValueError("Values falls before first bin") - - if values[lenidx - 1] > binner[lenbin - 1]: - raise ValueError("Values falls after last bin") - - bins = np.empty(lenbin - 1, dtype=np.int64) - - j = 0 # index into values - bc = 0 # bin count - - # linear scan, presume nothing about values/binner except that it fits ok - for i in range(0, lenbin - 1): - r_bin = binner[i + 1] - - # count values in current bin, advance to next bin - while j < lenidx and (values[j] < r_bin or - (closed == 'right' and values[j] == r_bin)): - j += 1 - - bins[bc] = j - bc += 1 - - return bins - - -class BinGrouper(BaseGrouper): - - """ - This is an internal Grouper class - - Parameters - ---------- - bins : the split index of binlabels to group the item of axis - binlabels : the label list - filter_empty : boolean, default False - mutated : boolean, default False - indexer : a intp array - - Examples - -------- - bins: [2, 4, 6, 8, 10] - binlabels: DatetimeIndex(['2005-01-01', '2005-01-03', - '2005-01-05', '2005-01-07', '2005-01-09'], - dtype='datetime64[ns]', freq='2D') - - the group_info, which contains the label of each item in grouped - axis, the index of label in label list, group number, is - - (array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]), array([0, 1, 2, 3, 4]), 5) - - means that, the grouped axis has 10 items, can be grouped into 5 - labels, the first and second items belong to the first label, the - third and forth items belong to the second label, and so on - - """ - - def __init__(self, bins, binlabels, filter_empty=False, mutated=False, - indexer=None): - self.bins = _ensure_int64(bins) - self.binlabels = _ensure_index(binlabels) - self._filter_empty_groups = filter_empty - self.mutated = mutated - self.indexer = indexer - - @cache_readonly - def groups(self): - """ dict {group name -> group labels} """ - - # this is mainly for compat - # GH 3881 - result = {} - for key, value in zip(self.binlabels, self.bins): - if key is not NaT: - result[key] = value - return result - - @property - def nkeys(self): - return 1 - - def get_iterator(self, data, axis=0): - """ - Groupby iterator - - Returns - ------- - Generator yielding sequence of (name, subsetted object) - for each group - """ - if isinstance(data, NDFrame): - slicer = lambda start, edge: data._slice( - slice(start, edge), axis=axis) - length = len(data.axes[axis]) - else: - slicer = lambda start, edge: data[slice(start, edge)] - length = len(data) - - start = 0 - for edge, label in zip(self.bins, self.binlabels): - if label is not NaT: - yield label, slicer(start, edge) - start = edge - - if start < length: - yield self.binlabels[-1], slicer(start, None) - - @cache_readonly - def indices(self): - indices = collections.defaultdict(list) - - i = 0 - for label, bin in zip(self.binlabels, self.bins): - if i < bin: - if label is not NaT: - indices[label] = list(range(i, bin)) - i = bin - return indices - - @cache_readonly - def group_info(self): - ngroups = self.ngroups - obs_group_ids = np.arange(ngroups) - rep = np.diff(np.r_[0, self.bins]) - - rep = _ensure_platform_int(rep) - if ngroups == len(self.bins): - comp_ids = np.repeat(np.arange(ngroups), rep) - else: - comp_ids = np.repeat(np.r_[-1, np.arange(ngroups)], rep) - - return comp_ids.astype('int64', copy=False), \ - obs_group_ids.astype('int64', copy=False), ngroups - - @cache_readonly - def ngroups(self): - return len(self.result_index) - - @cache_readonly - def result_index(self): - if len(self.binlabels) != 0 and isna(self.binlabels[0]): - return self.binlabels[1:] - - return self.binlabels - - @property - def levels(self): - return [self.binlabels] - - @property - def names(self): - return [self.binlabels.name] - - @property - def groupings(self): - return [Grouping(lvl, lvl, in_axis=False, level=None, name=name) - for lvl, name in zip(self.levels, self.names)] - - def agg_series(self, obj, func): - dummy = obj[:0] - grouper = reduction.SeriesBinGrouper(obj, func, self.bins, dummy) - return grouper.get_result() - - # ---------------------------------------------------------------------- - # cython aggregation - - _cython_functions = copy.deepcopy(BaseGrouper._cython_functions) - - -class Grouping(object): - - """ - Holds the grouping information for a single key - - Parameters - ---------- - index : Index - grouper : - obj : - name : - level : - observed : boolean, default False - If we are a Categorical, use the observed values - in_axis : if the Grouping is a column in self.obj and hence among - Groupby.exclusions list - - Returns - ------- - **Attributes**: - * indices : dict of {group -> index_list} - * labels : ndarray, group labels - * ids : mapping of label -> group - * counts : array of group counts - * group_index : unique groups - * groups : dict of {group -> label_list} - """ - - def __init__(self, index, grouper=None, obj=None, name=None, level=None, - sort=True, observed=False, in_axis=False): - - self.name = name - self.level = level - self.grouper = _convert_grouper(index, grouper) - self.all_grouper = None - self.index = index - self.sort = sort - self.obj = obj - self.observed = observed - self.in_axis = in_axis - - # right place for this? - if isinstance(grouper, (Series, Index)) and name is None: - self.name = grouper.name - - if isinstance(grouper, MultiIndex): - self.grouper = grouper.values - - # we have a single grouper which may be a myriad of things, - # some of which are dependent on the passing in level - - if level is not None: - if not isinstance(level, int): - if level not in index.names: - raise AssertionError('Level %s not in index' % str(level)) - level = index.names.index(level) - - if self.name is None: - self.name = index.names[level] - - self.grouper, self._labels, self._group_index = \ - index._get_grouper_for_level(self.grouper, level) - - # a passed Grouper like, directly get the grouper in the same way - # as single grouper groupby, use the group_info to get labels - elif isinstance(self.grouper, Grouper): - # get the new grouper; we already have disambiguated - # what key/level refer to exactly, don't need to - # check again as we have by this point converted these - # to an actual value (rather than a pd.Grouper) - _, grouper, _ = self.grouper._get_grouper(self.obj, validate=False) - if self.name is None: - self.name = grouper.result_index.name - self.obj = self.grouper.obj - self.grouper = grouper - - else: - if self.grouper is None and self.name is not None: - self.grouper = self.obj[self.name] - - elif isinstance(self.grouper, (list, tuple)): - self.grouper = com._asarray_tuplesafe(self.grouper) - - # a passed Categorical - elif is_categorical_dtype(self.grouper): - - from pandas.core.groupby.categorical import recode_for_groupby - self.grouper, self.all_grouper = recode_for_groupby( - self.grouper, self.sort, observed) - categories = self.grouper.categories - - # we make a CategoricalIndex out of the cat grouper - # preserving the categories / ordered attributes - self._labels = self.grouper.codes - if observed: - codes = algorithms.unique1d(self.grouper.codes) - else: - codes = np.arange(len(categories)) - - self._group_index = CategoricalIndex( - Categorical.from_codes( - codes=codes, - categories=categories, - ordered=self.grouper.ordered)) - - # we are done - if isinstance(self.grouper, Grouping): - self.grouper = self.grouper.grouper - - # no level passed - elif not isinstance(self.grouper, - (Series, Index, ExtensionArray, np.ndarray)): - if getattr(self.grouper, 'ndim', 1) != 1: - t = self.name or str(type(self.grouper)) - raise ValueError("Grouper for '%s' not 1-dimensional" % t) - self.grouper = self.index.map(self.grouper) - if not (hasattr(self.grouper, "__len__") and - len(self.grouper) == len(self.index)): - errmsg = ('Grouper result violates len(labels) == ' - 'len(data)\nresult: %s' % - pprint_thing(self.grouper)) - self.grouper = None # Try for sanity - raise AssertionError(errmsg) - - # if we have a date/time-like grouper, make sure that we have - # Timestamps like - if getattr(self.grouper, 'dtype', None) is not None: - if is_datetime64_dtype(self.grouper): - from pandas import to_datetime - self.grouper = to_datetime(self.grouper) - elif is_timedelta64_dtype(self.grouper): - from pandas import to_timedelta - self.grouper = to_timedelta(self.grouper) - - def __repr__(self): - return 'Grouping({0})'.format(self.name) - - def __iter__(self): - return iter(self.indices) - - _labels = None - _group_index = None - - @property - def ngroups(self): - return len(self.group_index) - - @cache_readonly - def indices(self): - # we have a list of groupers - if isinstance(self.grouper, BaseGrouper): - return self.grouper.indices - - values = _ensure_categorical(self.grouper) - return values._reverse_indexer() - - @property - def labels(self): - if self._labels is None: - self._make_labels() - return self._labels - - @cache_readonly - def result_index(self): - if self.all_grouper is not None: - from pandas.core.groupby.categorical import recode_from_groupby - return recode_from_groupby(self.all_grouper, - self.sort, self.group_index) - return self.group_index - - @property - def group_index(self): - if self._group_index is None: - self._make_labels() - return self._group_index - - def _make_labels(self): - if self._labels is None or self._group_index is None: - # we have a list of groupers - if isinstance(self.grouper, BaseGrouper): - labels = self.grouper.label_info - uniques = self.grouper.result_index - else: - labels, uniques = algorithms.factorize( - self.grouper, sort=self.sort) - uniques = Index(uniques, name=self.name) - self._labels = labels - self._group_index = uniques - - @cache_readonly - def groups(self): - return self.index.groupby(Categorical.from_codes(self.labels, - self.group_index)) - - -def _get_grouper(obj, key=None, axis=0, level=None, sort=True, - observed=False, mutated=False, validate=True): - """ - create and return a BaseGrouper, which is an internal - mapping of how to create the grouper indexers. - This may be composed of multiple Grouping objects, indicating - multiple groupers - - Groupers are ultimately index mappings. They can originate as: - index mappings, keys to columns, functions, or Groupers - - Groupers enable local references to axis,level,sort, while - the passed in axis, level, and sort are 'global'. - - This routine tries to figure out what the passing in references - are and then creates a Grouping for each one, combined into - a BaseGrouper. - - If observed & we have a categorical grouper, only show the observed - values - - If validate, then check for key/level overlaps - - """ - group_axis = obj._get_axis(axis) - - # validate that the passed single level is compatible with the passed - # axis of the object - if level is not None: - # TODO: These if-block and else-block are almost same. - # MultiIndex instance check is removable, but it seems that there are - # some processes only for non-MultiIndex in else-block, - # eg. `obj.index.name != level`. We have to consider carefully whether - # these are applicable for MultiIndex. Even if these are applicable, - # we need to check if it makes no side effect to subsequent processes - # on the outside of this condition. - # (GH 17621) - if isinstance(group_axis, MultiIndex): - if is_list_like(level) and len(level) == 1: - level = level[0] - - if key is None and is_scalar(level): - # Get the level values from group_axis - key = group_axis.get_level_values(level) - level = None - - else: - # allow level to be a length-one list-like object - # (e.g., level=[0]) - # GH 13901 - if is_list_like(level): - nlevels = len(level) - if nlevels == 1: - level = level[0] - elif nlevels == 0: - raise ValueError('No group keys passed!') - else: - raise ValueError('multiple levels only valid with ' - 'MultiIndex') - - if isinstance(level, compat.string_types): - if obj.index.name != level: - raise ValueError('level name %s is not the name of the ' - 'index' % level) - elif level > 0 or level < -1: - raise ValueError('level > 0 or level < -1 only valid with ' - ' MultiIndex') - - # NOTE: `group_axis` and `group_axis.get_level_values(level)` - # are same in this section. - level = None - key = group_axis - - # a passed-in Grouper, directly convert - if isinstance(key, Grouper): - binner, grouper, obj = key._get_grouper(obj, validate=False) - if key.key is None: - return grouper, [], obj - else: - return grouper, set([key.key]), obj - - # already have a BaseGrouper, just return it - elif isinstance(key, BaseGrouper): - return key, [], obj - - # In the future, a tuple key will always mean an actual key, - # not an iterable of keys. In the meantime, we attempt to provide - # a warning. We can assume that the user wanted a list of keys when - # the key is not in the index. We just have to be careful with - # unhashble elements of `key`. Any unhashable elements implies that - # they wanted a list of keys. - # https://github.com/pandas-dev/pandas/issues/18314 - is_tuple = isinstance(key, tuple) - all_hashable = is_tuple and is_hashable(key) - - if is_tuple: - if ((all_hashable and key not in obj and set(key).issubset(obj)) - or not all_hashable): - # column names ('a', 'b') -> ['a', 'b'] - # arrays like (a, b) -> [a, b] - msg = ("Interpreting tuple 'by' as a list of keys, rather than " - "a single key. Use 'by=[...]' instead of 'by=(...)'. In " - "the future, a tuple will always mean a single key.") - warnings.warn(msg, FutureWarning, stacklevel=5) - key = list(key) - - if not isinstance(key, list): - keys = [key] - match_axis_length = False - else: - keys = key - match_axis_length = len(keys) == len(group_axis) - - # what are we after, exactly? - any_callable = any(callable(g) or isinstance(g, dict) for g in keys) - any_groupers = any(isinstance(g, Grouper) for g in keys) - any_arraylike = any(isinstance(g, (list, tuple, Series, Index, np.ndarray)) - for g in keys) - - try: - if isinstance(obj, DataFrame): - all_in_columns_index = all(g in obj.columns or g in obj.index.names - for g in keys) - else: - all_in_columns_index = False - except Exception: - all_in_columns_index = False - - if not any_callable and not all_in_columns_index and \ - not any_arraylike and not any_groupers and \ - match_axis_length and level is None: - keys = [com._asarray_tuplesafe(keys)] - - if isinstance(level, (tuple, list)): - if key is None: - keys = [None] * len(level) - levels = level - else: - levels = [level] * len(keys) - - groupings = [] - exclusions = [] - - # if the actual grouper should be obj[key] - def is_in_axis(key): - if not _is_label_like(key): - try: - obj._data.items.get_loc(key) - except Exception: - return False - - return True - - # if the grouper is obj[name] - def is_in_obj(gpr): - try: - return id(gpr) == id(obj[gpr.name]) - except Exception: - return False - - for i, (gpr, level) in enumerate(zip(keys, levels)): - - if is_in_obj(gpr): # df.groupby(df['name']) - in_axis, name = True, gpr.name - exclusions.append(name) - - elif is_in_axis(gpr): # df.groupby('name') - if gpr in obj: - if validate: - stacklevel = 5 # Number of stack levels from df.groupby - obj._check_label_or_level_ambiguity( - gpr, stacklevel=stacklevel) - in_axis, name, gpr = True, gpr, obj[gpr] - exclusions.append(name) - elif obj._is_level_reference(gpr): - in_axis, name, level, gpr = False, None, gpr, None - else: - raise KeyError(gpr) - elif isinstance(gpr, Grouper) and gpr.key is not None: - # Add key to exclusions - exclusions.append(gpr.key) - in_axis, name = False, None - else: - in_axis, name = False, None - - if is_categorical_dtype(gpr) and len(gpr) != obj.shape[axis]: - raise ValueError( - ("Length of grouper ({len_gpr}) and axis ({len_axis})" - " must be same length" - .format(len_gpr=len(gpr), len_axis=obj.shape[axis]))) - - # create the Grouping - # allow us to passing the actual Grouping as the gpr - ping = Grouping(group_axis, - gpr, - obj=obj, - name=name, - level=level, - sort=sort, - observed=observed, - in_axis=in_axis) \ - if not isinstance(gpr, Grouping) else gpr - - groupings.append(ping) - - if len(groupings) == 0: - raise ValueError('No group keys passed!') - - # create the internals grouper - grouper = BaseGrouper(group_axis, groupings, sort=sort, mutated=mutated) - return grouper, exclusions, obj - - -def _is_label_like(val): - return (isinstance(val, (compat.string_types, tuple)) or - (val is not None and is_scalar(val))) - - -def _convert_grouper(axis, grouper): - if isinstance(grouper, dict): - return grouper.get - elif isinstance(grouper, Series): - if grouper.index.equals(axis): - return grouper._values - else: - return grouper.reindex(axis)._values - elif isinstance(grouper, (list, Series, Index, np.ndarray)): - if len(grouper) != len(axis): - raise ValueError('Grouper and axis must be same length') - return grouper - else: - return grouper - - -def _whitelist_method_generator(klass, whitelist): - """ - Yields all GroupBy member defs for DataFrame/Series names in _whitelist. - - Parameters - ---------- - klass - class where members are defined. Should be Series or DataFrame - - whitelist - list of names of klass methods to be constructed - - Returns - ------- - The generator yields a sequence of strings, each suitable for exec'ing, - that define implementations of the named methods for DataFrameGroupBy - or SeriesGroupBy. - - Since we don't want to override methods explicitly defined in the - base class, any such name is skipped. - """ - - method_wrapper_template = \ - """def %(name)s(%(sig)s) : - \""" - %(doc)s - \""" - f = %(self)s.__getattr__('%(name)s') - return f(%(args)s)""" - property_wrapper_template = \ - """@property -def %(name)s(self) : - \""" - %(doc)s - \""" - return self.__getattr__('%(name)s')""" - for name in whitelist: - # don't override anything that was explicitly defined - # in the base class - if hasattr(GroupBy, name): - continue - # ugly, but we need the name string itself in the method. - f = getattr(klass, name) - doc = f.__doc__ - doc = doc if type(doc) == str else '' - if isinstance(f, types.MethodType): - wrapper_template = method_wrapper_template - decl, args = make_signature(f) - # pass args by name to f because otherwise - # GroupBy._make_wrapper won't know whether - # we passed in an axis parameter. - args_by_name = ['{0}={0}'.format(arg) for arg in args[1:]] - params = {'name': name, - 'doc': doc, - 'sig': ','.join(decl), - 'self': args[0], - 'args': ','.join(args_by_name)} - else: - wrapper_template = property_wrapper_template - params = {'name': name, 'doc': doc} - yield wrapper_template % params - - -class SeriesGroupBy(GroupBy): - # - # Make class defs of attributes on SeriesGroupBy whitelist - _apply_whitelist = _series_apply_whitelist - for _def_str in _whitelist_method_generator(Series, - _series_apply_whitelist): - exec(_def_str) - - @property - def _selection_name(self): - """ - since we are a series, we by definition only have - a single name, but may be the result of a selection or - the name of our object - """ - if self._selection is None: - return self.obj.name - else: - return self._selection - - _agg_doc = dedent(""" - Examples - -------- - - >>> s = pd.Series([1, 2, 3, 4]) - - >>> s - 0 1 - 1 2 - 2 3 - 3 4 - dtype: int64 - - >>> s.groupby([1, 1, 2, 2]).min() - 1 1 - 2 3 - dtype: int64 - - >>> s.groupby([1, 1, 2, 2]).agg('min') - 1 1 - 2 3 - dtype: int64 - - >>> s.groupby([1, 1, 2, 2]).agg(['min', 'max']) - min max - 1 1 2 - 2 3 4 - - See also - -------- - pandas.Series.groupby.apply - pandas.Series.groupby.transform - pandas.Series.aggregate - - """) - - @Appender(_apply_docs['template'] - .format(input='series', - examples=_apply_docs['series_examples'])) - def apply(self, func, *args, **kwargs): - return super(SeriesGroupBy, self).apply(func, *args, **kwargs) - - @Appender(_agg_doc) - @Appender(_shared_docs['aggregate'] % dict( - klass='Series', - versionadded='', - axis='')) - def aggregate(self, func_or_funcs, *args, **kwargs): - _level = kwargs.pop('_level', None) - if isinstance(func_or_funcs, compat.string_types): - return getattr(self, func_or_funcs)(*args, **kwargs) - - if isinstance(func_or_funcs, collections.Iterable): - # Catch instances of lists / tuples - # but not the class list / tuple itself. - ret = self._aggregate_multiple_funcs(func_or_funcs, - (_level or 0) + 1) - else: - cyfunc = self._is_cython_func(func_or_funcs) - if cyfunc and not args and not kwargs: - return getattr(self, cyfunc)() - - if self.grouper.nkeys > 1: - return self._python_agg_general(func_or_funcs, *args, **kwargs) - - try: - return self._python_agg_general(func_or_funcs, *args, **kwargs) - except Exception: - result = self._aggregate_named(func_or_funcs, *args, **kwargs) - - index = Index(sorted(result), name=self.grouper.names[0]) - ret = Series(result, index=index) - - if not self.as_index: # pragma: no cover - print('Warning, ignoring as_index=True') - - # _level handled at higher - if not _level and isinstance(ret, dict): - from pandas import concat - ret = concat(ret, axis=1) - return ret - - agg = aggregate - - def _aggregate_multiple_funcs(self, arg, _level): - if isinstance(arg, dict): - - # show the deprecation, but only if we - # have not shown a higher level one - # GH 15931 - if isinstance(self._selected_obj, Series) and _level <= 1: - warnings.warn( - ("using a dict on a Series for aggregation\n" - "is deprecated and will be removed in a future " - "version"), - FutureWarning, stacklevel=3) - - columns = list(arg.keys()) - arg = list(arg.items()) - elif any(isinstance(x, (tuple, list)) for x in arg): - arg = [(x, x) if not isinstance(x, (tuple, list)) else x - for x in arg] - - # indicated column order - columns = lzip(*arg)[0] - else: - # list of functions / function names - columns = [] - for f in arg: - if isinstance(f, compat.string_types): - columns.append(f) - else: - # protect against callables without names - columns.append(com._get_callable_name(f)) - arg = lzip(columns, arg) - - results = {} - for name, func in arg: - obj = self - if name in results: - raise SpecificationError('Function names must be unique, ' - 'found multiple named %s' % name) - - # reset the cache so that we - # only include the named selection - if name in self._selected_obj: - obj = copy.copy(obj) - obj._reset_cache() - obj._selection = name - results[name] = obj.aggregate(func) - - if any(isinstance(x, DataFrame) for x in compat.itervalues(results)): - # let higher level handle - if _level: - return results - - return DataFrame(results, columns=columns) - - def _wrap_output(self, output, index, names=None): - """ common agg/transform wrapping logic """ - output = output[self._selection_name] - - if names is not None: - return DataFrame(output, index=index, columns=names) - else: - name = self._selection_name - if name is None: - name = self._selected_obj.name - return Series(output, index=index, name=name) - - def _wrap_aggregated_output(self, output, names=None): - return self._wrap_output(output=output, - index=self.grouper.result_index, - names=names) - - def _wrap_transformed_output(self, output, names=None): - return self._wrap_output(output=output, - index=self.obj.index, - names=names) - - def _wrap_applied_output(self, keys, values, not_indexed_same=False): - if len(keys) == 0: - # GH #6265 - return Series([], name=self._selection_name, index=keys) - - def _get_index(): - if self.grouper.nkeys > 1: - index = MultiIndex.from_tuples(keys, names=self.grouper.names) - else: - index = Index(keys, name=self.grouper.names[0]) - return index - - if isinstance(values[0], dict): - # GH #823 - index = _get_index() - result = DataFrame(values, index=index).stack() - result.name = self._selection_name - return result - - if isinstance(values[0], (Series, dict)): - return self._concat_objects(keys, values, - not_indexed_same=not_indexed_same) - elif isinstance(values[0], DataFrame): - # possible that Series -> DataFrame by applied function - return self._concat_objects(keys, values, - not_indexed_same=not_indexed_same) - else: - # GH #6265 - return Series(values, index=_get_index(), - name=self._selection_name) - - def _aggregate_named(self, func, *args, **kwargs): - result = {} - - for name, group in self: - group.name = name - output = func(group, *args, **kwargs) - if isinstance(output, (Series, Index, np.ndarray)): - raise Exception('Must produce aggregated value') - result[name] = self._try_cast(output, group) - - return result - - @Substitution(klass='Series', selected='A.') - @Appender(_transform_template) - def transform(self, func, *args, **kwargs): - func = self._is_cython_func(func) or func - - # if string function - if isinstance(func, compat.string_types): - if func in _cython_transforms: - # cythonized transform - return getattr(self, func)(*args, **kwargs) - else: - # cythonized aggregation and merge - return self._transform_fast( - lambda: getattr(self, func)(*args, **kwargs), func) - - # reg transform - klass = self._selected_obj.__class__ - results = [] - wrapper = lambda x: func(x, *args, **kwargs) - for name, group in self: - object.__setattr__(group, 'name', name) - res = wrapper(group) - - if hasattr(res, 'values'): - res = res.values - - indexer = self._get_index(name) - s = klass(res, indexer) - results.append(s) - - from pandas.core.reshape.concat import concat - result = concat(results).sort_index() - - # we will only try to coerce the result type if - # we have a numeric dtype, as these are *always* udfs - # the cython take a different path (and casting) - dtype = self._selected_obj.dtype - if is_numeric_dtype(dtype): - result = maybe_downcast_to_dtype(result, dtype) - - result.name = self._selected_obj.name - result.index = self._selected_obj.index - return result - - def _transform_fast(self, func, func_nm): - """ - fast version of transform, only applicable to - builtin/cythonizable functions - """ - if isinstance(func, compat.string_types): - func = getattr(self, func) - - ids, _, ngroup = self.grouper.group_info - cast = self._transform_should_cast(func_nm) - out = algorithms.take_1d(func().values, ids) - if cast: - out = self._try_cast(out, self.obj) - return Series(out, index=self.obj.index, name=self.obj.name) - - def filter(self, func, dropna=True, *args, **kwargs): # noqa - """ - Return a copy of a Series excluding elements from groups that - do not satisfy the boolean criterion specified by func. - - Parameters - ---------- - func : function - To apply to each group. Should return True or False. - dropna : Drop groups that do not pass the filter. True by default; - if False, groups that evaluate False are filled with NaNs. - - Examples - -------- - >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', - ... 'foo', 'bar'], - ... 'B' : [1, 2, 3, 4, 5, 6], - ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) - >>> grouped = df.groupby('A') - >>> df.groupby('A').B.filter(lambda x: x.mean() > 3.) - 1 2 - 3 4 - 5 6 - Name: B, dtype: int64 - - Returns - ------- - filtered : Series - """ - if isinstance(func, compat.string_types): - wrapper = lambda x: getattr(x, func)(*args, **kwargs) - else: - wrapper = lambda x: func(x, *args, **kwargs) - - # Interpret np.nan as False. - def true_and_notna(x, *args, **kwargs): - b = wrapper(x, *args, **kwargs) - return b and notna(b) - - try: - indices = [self._get_index(name) for name, group in self - if true_and_notna(group)] - except ValueError: - raise TypeError("the filter must return a boolean result") - except TypeError: - raise TypeError("the filter must return a boolean result") - - filtered = self._apply_filter(indices, dropna) - return filtered - - def nunique(self, dropna=True): - """ Returns number of unique elements in the group """ - ids, _, _ = self.grouper.group_info - - val = self.obj.get_values() - - try: - sorter = np.lexsort((val, ids)) - except TypeError: # catches object dtypes - assert val.dtype == object, \ - 'val.dtype must be object, got %s' % val.dtype - val, _ = algorithms.factorize(val, sort=False) - sorter = np.lexsort((val, ids)) - _isna = lambda a: a == -1 - else: - _isna = isna - - ids, val = ids[sorter], val[sorter] - - # group boundaries are where group ids change - # unique observations are where sorted values change - idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] - inc = np.r_[1, val[1:] != val[:-1]] - - # 1st item of each group is a new unique observation - mask = _isna(val) - if dropna: - inc[idx] = 1 - inc[mask] = 0 - else: - inc[mask & np.r_[False, mask[:-1]]] = 0 - inc[idx] = 1 - - out = np.add.reduceat(inc, idx).astype('int64', copy=False) - if len(ids): - # NaN/NaT group exists if the head of ids is -1, - # so remove it from res and exclude its index from idx - if ids[0] == -1: - res = out[1:] - idx = idx[np.flatnonzero(idx)] - else: - res = out - else: - res = out[1:] - ri = self.grouper.result_index - - # we might have duplications among the bins - if len(res) != len(ri): - res, out = np.zeros(len(ri), dtype=out.dtype), res - res[ids[idx]] = out - - return Series(res, - index=ri, - name=self._selection_name) - - @Appender(Series.describe.__doc__) - def describe(self, **kwargs): - result = self.apply(lambda x: x.describe(**kwargs)) - if self.axis == 1: - return result.T - return result.unstack() - - def value_counts(self, normalize=False, sort=True, ascending=False, - bins=None, dropna=True): - - from pandas.core.reshape.tile import cut - from pandas.core.reshape.merge import _get_join_indexers - - if bins is not None and not np.iterable(bins): - # scalar bins cannot be done at top level - # in a backward compatible way - return self.apply(Series.value_counts, - normalize=normalize, - sort=sort, - ascending=ascending, - bins=bins) - - ids, _, _ = self.grouper.group_info - val = self.obj.get_values() - - # groupby removes null keys from groupings - mask = ids != -1 - ids, val = ids[mask], val[mask] - - if bins is None: - lab, lev = algorithms.factorize(val, sort=True) - llab = lambda lab, inc: lab[inc] - else: - - # lab is a Categorical with categories an IntervalIndex - lab = cut(Series(val), bins, include_lowest=True) - lev = lab.cat.categories - lab = lev.take(lab.cat.codes) - llab = lambda lab, inc: lab[inc]._multiindex.labels[-1] - - if is_interval_dtype(lab): - # TODO: should we do this inside II? - sorter = np.lexsort((lab.left, lab.right, ids)) - else: - sorter = np.lexsort((lab, ids)) - - ids, lab = ids[sorter], lab[sorter] - - # group boundaries are where group ids change - idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] - - # new values are where sorted labels change - lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1)) - inc = np.r_[True, lchanges] - inc[idx] = True # group boundaries are also new values - out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts - - # num. of times each group should be repeated - rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx)) - - # multi-index components - labels = list(map(rep, self.grouper.recons_labels)) + [llab(lab, inc)] - levels = [ping.group_index for ping in self.grouper.groupings] + [lev] - names = self.grouper.names + [self._selection_name] - - if dropna: - mask = labels[-1] != -1 - if mask.all(): - dropna = False - else: - out, labels = out[mask], [label[mask] for label in labels] - - if normalize: - out = out.astype('float') - d = np.diff(np.r_[idx, len(ids)]) - if dropna: - m = ids[lab == -1] - np.add.at(d, m, -1) - acc = rep(d)[mask] - else: - acc = rep(d) - out /= acc - - if sort and bins is None: - cat = ids[inc][mask] if dropna else ids[inc] - sorter = np.lexsort((out if ascending else -out, cat)) - out, labels[-1] = out[sorter], labels[-1][sorter] - - if bins is None: - mi = MultiIndex(levels=levels, labels=labels, names=names, - verify_integrity=False) - - if is_integer_dtype(out): - out = _ensure_int64(out) - return Series(out, index=mi, name=self._selection_name) - - # for compat. with libgroupby.value_counts need to ensure every - # bin is present at every index level, null filled with zeros - diff = np.zeros(len(out), dtype='bool') - for lab in labels[:-1]: - diff |= np.r_[True, lab[1:] != lab[:-1]] - - ncat, nbin = diff.sum(), len(levels[-1]) - - left = [np.repeat(np.arange(ncat), nbin), - np.tile(np.arange(nbin), ncat)] - - right = [diff.cumsum() - 1, labels[-1]] - - _, idx = _get_join_indexers(left, right, sort=False, how='left') - out = np.where(idx != -1, out[idx], 0) - - if sort: - sorter = np.lexsort((out if ascending else -out, left[0])) - out, left[-1] = out[sorter], left[-1][sorter] - - # build the multi-index w/ full levels - labels = list(map(lambda lab: np.repeat(lab[diff], nbin), labels[:-1])) - labels.append(left[-1]) - - mi = MultiIndex(levels=levels, labels=labels, names=names, - verify_integrity=False) - - if is_integer_dtype(out): - out = _ensure_int64(out) - return Series(out, index=mi, name=self._selection_name) - - def count(self): - """ Compute count of group, excluding missing values """ - ids, _, ngroups = self.grouper.group_info - val = self.obj.get_values() - - mask = (ids != -1) & ~isna(val) - ids = _ensure_platform_int(ids) - out = np.bincount(ids[mask], minlength=ngroups or 0) - - return Series(out, - index=self.grouper.result_index, - name=self._selection_name, - dtype='int64') - - def _apply_to_column_groupbys(self, func): - """ return a pass thru """ - return func(self) - - def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None): - """Calculate percent change of each value to previous entry in group""" - filled = getattr(self, fill_method)(limit=limit) - shifted = filled.shift(periods=periods, freq=freq) - - return (filled / shifted) - 1 - - -class NDFrameGroupBy(GroupBy): - - def _iterate_slices(self): - if self.axis == 0: - # kludge - if self._selection is None: - slice_axis = self.obj.columns - else: - slice_axis = self._selection_list - slicer = lambda x: self.obj[x] - else: - slice_axis = self.obj.index - slicer = self.obj.xs - - for val in slice_axis: - if val in self.exclusions: - continue - yield val, slicer(val) - - def _cython_agg_general(self, how, alt=None, numeric_only=True, - min_count=-1): - new_items, new_blocks = self._cython_agg_blocks( - how, alt=alt, numeric_only=numeric_only, min_count=min_count) - return self._wrap_agged_blocks(new_items, new_blocks) - - def _wrap_agged_blocks(self, items, blocks): - obj = self._obj_with_exclusions - - new_axes = list(obj._data.axes) - - # more kludge - if self.axis == 0: - new_axes[0], new_axes[1] = new_axes[1], self.grouper.result_index - else: - new_axes[self.axis] = self.grouper.result_index - - # Make sure block manager integrity check passes. - assert new_axes[0].equals(items) - new_axes[0] = items - - mgr = BlockManager(blocks, new_axes) - - new_obj = type(obj)(mgr) - - return self._post_process_cython_aggregate(new_obj) - - _block_agg_axis = 0 - - def _cython_agg_blocks(self, how, alt=None, numeric_only=True, - min_count=-1): - # TODO: the actual managing of mgr_locs is a PITA - # here, it should happen via BlockManager.combine - - data, agg_axis = self._get_data_to_aggregate() - - if numeric_only: - data = data.get_numeric_data(copy=False) - - new_blocks = [] - new_items = [] - deleted_items = [] - for block in data.blocks: - - locs = block.mgr_locs.as_array - try: - result, _ = self.grouper.aggregate( - block.values, how, axis=agg_axis, min_count=min_count) - except NotImplementedError: - # generally if we have numeric_only=False - # and non-applicable functions - # try to python agg - - if alt is None: - # we cannot perform the operation - # in an alternate way, exclude the block - deleted_items.append(locs) - continue - - # call our grouper again with only this block - obj = self.obj[data.items[locs]] - s = groupby(obj, self.grouper) - result = s.aggregate(lambda x: alt(x, axis=self.axis)) - newb = result._data.blocks[0] - - finally: - - # see if we can cast the block back to the original dtype - result = block._try_coerce_and_cast_result(result) - newb = block.make_block(result) - - new_items.append(locs) - new_blocks.append(newb) - - if len(new_blocks) == 0: - raise DataError('No numeric types to aggregate') - - # reset the locs in the blocks to correspond to our - # current ordering - indexer = np.concatenate(new_items) - new_items = data.items.take(np.sort(indexer)) - - if len(deleted_items): - - # we need to adjust the indexer to account for the - # items we have removed - # really should be done in internals :< - - deleted = np.concatenate(deleted_items) - ai = np.arange(len(data)) - mask = np.zeros(len(data)) - mask[deleted] = 1 - indexer = (ai - mask.cumsum())[indexer] - - offset = 0 - for b in new_blocks: - loc = len(b.mgr_locs) - b.mgr_locs = indexer[offset:(offset + loc)] - offset += loc - - return new_items, new_blocks - - def _get_data_to_aggregate(self): - obj = self._obj_with_exclusions - if self.axis == 0: - return obj.swapaxes(0, 1)._data, 1 - else: - return obj._data, self.axis - - def _post_process_cython_aggregate(self, obj): - # undoing kludge from below - if self.axis == 0: - obj = obj.swapaxes(0, 1) - return obj - - def aggregate(self, arg, *args, **kwargs): - - _level = kwargs.pop('_level', None) - result, how = self._aggregate(arg, _level=_level, *args, **kwargs) - if how is None: - return result - - if result is None: - - # grouper specific aggregations - if self.grouper.nkeys > 1: - return self._python_agg_general(arg, *args, **kwargs) - else: - - # try to treat as if we are passing a list - try: - assert not args and not kwargs - result = self._aggregate_multiple_funcs( - [arg], _level=_level, _axis=self.axis) - result.columns = Index( - result.columns.levels[0], - name=self._selected_obj.columns.name) - except Exception: - result = self._aggregate_generic(arg, *args, **kwargs) - - if not self.as_index: - self._insert_inaxis_grouper_inplace(result) - result.index = np.arange(len(result)) - - return result._convert(datetime=True) - - agg = aggregate - - def _aggregate_generic(self, func, *args, **kwargs): - if self.grouper.nkeys != 1: - raise AssertionError('Number of keys must be 1') - - axis = self.axis - obj = self._obj_with_exclusions - - result = {} - if axis != obj._info_axis_number: - try: - for name, data in self: - result[name] = self._try_cast(func(data, *args, **kwargs), - data) - except Exception: - return self._aggregate_item_by_item(func, *args, **kwargs) - else: - for name in self.indices: - try: - data = self.get_group(name, obj=obj) - result[name] = self._try_cast(func(data, *args, **kwargs), - data) - except Exception: - wrapper = lambda x: func(x, *args, **kwargs) - result[name] = data.apply(wrapper, axis=axis) - - return self._wrap_generic_output(result, obj) - - def _wrap_aggregated_output(self, output, names=None): - raise com.AbstractMethodError(self) - - def _aggregate_item_by_item(self, func, *args, **kwargs): - # only for axis==0 - - obj = self._obj_with_exclusions - result = {} - cannot_agg = [] - errors = None - for item in obj: - try: - data = obj[item] - colg = SeriesGroupBy(data, selection=item, - grouper=self.grouper) - result[item] = self._try_cast( - colg.aggregate(func, *args, **kwargs), data) - except ValueError: - cannot_agg.append(item) - continue - except TypeError as e: - cannot_agg.append(item) - errors = e - continue - - result_columns = obj.columns - if cannot_agg: - result_columns = result_columns.drop(cannot_agg) - - # GH6337 - if not len(result_columns) and errors is not None: - raise errors - - return DataFrame(result, columns=result_columns) - - def _decide_output_index(self, output, labels): - if len(output) == len(labels): - output_keys = labels - else: - output_keys = sorted(output) - try: - output_keys.sort() - except Exception: # pragma: no cover - pass - - if isinstance(labels, MultiIndex): - output_keys = MultiIndex.from_tuples(output_keys, - names=labels.names) - - return output_keys - - def _wrap_applied_output(self, keys, values, not_indexed_same=False): - from pandas.core.index import _all_indexes_same - from pandas.core.tools.numeric import to_numeric - - if len(keys) == 0: - return DataFrame(index=keys) - - key_names = self.grouper.names - - # GH12824. - def first_not_none(values): - try: - return next(com._not_none(*values)) - except StopIteration: - return None - - v = first_not_none(values) - - if v is None: - # GH9684. If all values are None, then this will throw an error. - # We'd prefer it return an empty dataframe. - return DataFrame() - elif isinstance(v, DataFrame): - return self._concat_objects(keys, values, - not_indexed_same=not_indexed_same) - elif self.grouper.groupings is not None: - if len(self.grouper.groupings) > 1: - key_index = self.grouper.result_index - - else: - ping = self.grouper.groupings[0] - if len(keys) == ping.ngroups: - key_index = ping.group_index - key_index.name = key_names[0] - - key_lookup = Index(keys) - indexer = key_lookup.get_indexer(key_index) - - # reorder the values - values = [values[i] for i in indexer] - else: - - key_index = Index(keys, name=key_names[0]) - - # don't use the key indexer - if not self.as_index: - key_index = None - - # make Nones an empty object - v = first_not_none(values) - if v is None: - return DataFrame() - elif isinstance(v, NDFrame): - values = [ - x if x is not None else - v._constructor(**v._construct_axes_dict()) - for x in values - ] - - v = values[0] - - if isinstance(v, (np.ndarray, Index, Series)): - if isinstance(v, Series): - applied_index = self._selected_obj._get_axis(self.axis) - all_indexed_same = _all_indexes_same([ - x.index for x in values - ]) - singular_series = (len(values) == 1 and - applied_index.nlevels == 1) - - # GH3596 - # provide a reduction (Frame -> Series) if groups are - # unique - if self.squeeze: - - # assign the name to this series - if singular_series: - values[0].name = keys[0] - - # GH2893 - # we have series in the values array, we want to - # produce a series: - # if any of the sub-series are not indexed the same - # OR we don't have a multi-index and we have only a - # single values - return self._concat_objects( - keys, values, not_indexed_same=not_indexed_same - ) - - # still a series - # path added as of GH 5545 - elif all_indexed_same: - from pandas.core.reshape.concat import concat - return concat(values) - - if not all_indexed_same: - # GH 8467 - return self._concat_objects( - keys, values, not_indexed_same=True, - ) - - try: - if self.axis == 0: - # GH6124 if the list of Series have a consistent name, - # then propagate that name to the result. - index = v.index.copy() - if index.name is None: - # Only propagate the series name to the result - # if all series have a consistent name. If the - # series do not have a consistent name, do - # nothing. - names = {v.name for v in values} - if len(names) == 1: - index.name = list(names)[0] - - # normally use vstack as its faster than concat - # and if we have mi-columns - if (isinstance(v.index, MultiIndex) or - key_index is None or - isinstance(key_index, MultiIndex)): - stacked_values = np.vstack(map(np.asarray, values)) - result = DataFrame(stacked_values, index=key_index, - columns=index) - else: - # GH5788 instead of stacking; concat gets the - # dtypes correct - from pandas.core.reshape.concat import concat - result = concat(values, keys=key_index, - names=key_index.names, - axis=self.axis).unstack() - result.columns = index - else: - stacked_values = np.vstack(map(np.asarray, values)) - result = DataFrame(stacked_values.T, index=v.index, - columns=key_index) - - except (ValueError, AttributeError): - # GH1738: values is list of arrays of unequal lengths fall - # through to the outer else caluse - return Series(values, index=key_index, - name=self._selection_name) - - # if we have date/time like in the original, then coerce dates - # as we are stacking can easily have object dtypes here - so = self._selected_obj - if (so.ndim == 2 and so.dtypes.apply(is_datetimelike).any()): - result = result.apply( - lambda x: to_numeric(x, errors='ignore')) - date_cols = self._selected_obj.select_dtypes( - include=['datetime', 'timedelta']).columns - date_cols = date_cols.intersection(result.columns) - result[date_cols] = (result[date_cols] - ._convert(datetime=True, - coerce=True)) - else: - result = result._convert(datetime=True) - - return self._reindex_output(result) - - # values are not series or array-like but scalars - else: - # only coerce dates if we find at least 1 datetime - coerce = any(isinstance(x, Timestamp) for x in values) - # self._selection_name not passed through to Series as the - # result should not take the name of original selection - # of columns - return (Series(values, index=key_index) - ._convert(datetime=True, - coerce=coerce)) - - else: - # Handle cases like BinGrouper - return self._concat_objects(keys, values, - not_indexed_same=not_indexed_same) - - def _transform_general(self, func, *args, **kwargs): - from pandas.core.reshape.concat import concat - - applied = [] - obj = self._obj_with_exclusions - gen = self.grouper.get_iterator(obj, axis=self.axis) - fast_path, slow_path = self._define_paths(func, *args, **kwargs) - - path = None - for name, group in gen: - object.__setattr__(group, 'name', name) - - if path is None: - # Try slow path and fast path. - try: - path, res = self._choose_path(fast_path, slow_path, group) - except TypeError: - return self._transform_item_by_item(obj, fast_path) - except ValueError: - msg = 'transform must return a scalar value for each group' - raise ValueError(msg) - else: - res = path(group) - - if isinstance(res, Series): - - # we need to broadcast across the - # other dimension; this will preserve dtypes - # GH14457 - if not np.prod(group.shape): - continue - elif res.index.is_(obj.index): - r = concat([res] * len(group.columns), axis=1) - r.columns = group.columns - r.index = group.index - else: - r = DataFrame( - np.concatenate([res.values] * len(group.index) - ).reshape(group.shape), - columns=group.columns, index=group.index) - - applied.append(r) - else: - applied.append(res) - - concat_index = obj.columns if self.axis == 0 else obj.index - concatenated = concat(applied, join_axes=[concat_index], - axis=self.axis, verify_integrity=False) - return self._set_result_index_ordered(concatenated) - - @Substitution(klass='DataFrame', selected='') - @Appender(_transform_template) - def transform(self, func, *args, **kwargs): - - # optimized transforms - func = self._is_cython_func(func) or func - if isinstance(func, compat.string_types): - if func in _cython_transforms: - # cythonized transform - return getattr(self, func)(*args, **kwargs) - else: - # cythonized aggregation and merge - result = getattr(self, func)(*args, **kwargs) - else: - return self._transform_general(func, *args, **kwargs) - - # a reduction transform - if not isinstance(result, DataFrame): - return self._transform_general(func, *args, **kwargs) - - obj = self._obj_with_exclusions - - # nuiscance columns - if not result.columns.equals(obj.columns): - return self._transform_general(func, *args, **kwargs) - - return self._transform_fast(result, obj, func) - - def _transform_fast(self, result, obj, func_nm): - """ - Fast transform path for aggregations - """ - # if there were groups with no observations (Categorical only?) - # try casting data to original dtype - cast = self._transform_should_cast(func_nm) - - # for each col, reshape to to size of original frame - # by take operation - ids, _, ngroup = self.grouper.group_info - output = [] - for i, _ in enumerate(result.columns): - res = algorithms.take_1d(result.iloc[:, i].values, ids) - if cast: - res = self._try_cast(res, obj.iloc[:, i]) - output.append(res) - - return DataFrame._from_arrays(output, columns=result.columns, - index=obj.index) - - def _define_paths(self, func, *args, **kwargs): - if isinstance(func, compat.string_types): - fast_path = lambda group: getattr(group, func)(*args, **kwargs) - slow_path = lambda group: group.apply( - lambda x: getattr(x, func)(*args, **kwargs), axis=self.axis) - else: - fast_path = lambda group: func(group, *args, **kwargs) - slow_path = lambda group: group.apply( - lambda x: func(x, *args, **kwargs), axis=self.axis) - return fast_path, slow_path - - def _choose_path(self, fast_path, slow_path, group): - path = slow_path - res = slow_path(group) - - # if we make it here, test if we can use the fast path - try: - res_fast = fast_path(group) - - # compare that we get the same results - if res.shape == res_fast.shape: - res_r = res.values.ravel() - res_fast_r = res_fast.values.ravel() - mask = notna(res_r) - if (res_r[mask] == res_fast_r[mask]).all(): - path = fast_path - - except Exception: - pass - return path, res - - def _transform_item_by_item(self, obj, wrapper): - # iterate through columns - output = {} - inds = [] - for i, col in enumerate(obj): - try: - output[col] = self[col].transform(wrapper) - inds.append(i) - except Exception: - pass - - if len(output) == 0: # pragma: no cover - raise TypeError('Transform function invalid for data types') - - columns = obj.columns - if len(output) < len(obj.columns): - columns = columns.take(inds) - - return DataFrame(output, index=obj.index, columns=columns) - - def filter(self, func, dropna=True, *args, **kwargs): # noqa - """ - Return a copy of a DataFrame excluding elements from groups that - do not satisfy the boolean criterion specified by func. - - Parameters - ---------- - f : function - Function to apply to each subframe. Should return True or False. - dropna : Drop groups that do not pass the filter. True by default; - if False, groups that evaluate False are filled with NaNs. - - Notes - ----- - Each subframe is endowed the attribute 'name' in case you need to know - which group you are working on. - - Examples - -------- - >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', - ... 'foo', 'bar'], - ... 'B' : [1, 2, 3, 4, 5, 6], - ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) - >>> grouped = df.groupby('A') - >>> grouped.filter(lambda x: x['B'].mean() > 3.) - A B C - 1 bar 2 5.0 - 3 bar 4 1.0 - 5 bar 6 9.0 - - Returns - ------- - filtered : DataFrame - """ - - indices = [] - - obj = self._selected_obj - gen = self.grouper.get_iterator(obj, axis=self.axis) - - for name, group in gen: - object.__setattr__(group, 'name', name) - - res = func(group, *args, **kwargs) - - try: - res = res.squeeze() - except AttributeError: # allow e.g., scalars and frames to pass - pass - - # interpret the result of the filter - if is_bool(res) or (is_scalar(res) and isna(res)): - if res and notna(res): - indices.append(self._get_index(name)) - else: - # non scalars aren't allowed - raise TypeError("filter function returned a %s, " - "but expected a scalar bool" % - type(res).__name__) - - return self._apply_filter(indices, dropna) - - -class DataFrameGroupBy(NDFrameGroupBy): - _apply_whitelist = _dataframe_apply_whitelist - # - # Make class defs of attributes on DataFrameGroupBy whitelist. - for _def_str in _whitelist_method_generator(DataFrame, _apply_whitelist): - exec(_def_str) - - _block_agg_axis = 1 - - _agg_doc = dedent(""" - Examples - -------- - - >>> df = pd.DataFrame({'A': [1, 1, 2, 2], - ... 'B': [1, 2, 3, 4], - ... 'C': np.random.randn(4)}) - - >>> df - A B C - 0 1 1 0.362838 - 1 1 2 0.227877 - 2 2 3 1.267767 - 3 2 4 -0.562860 - - The aggregation is for each column. - - >>> df.groupby('A').agg('min') - B C - A - 1 1 0.227877 - 2 3 -0.562860 - - Multiple aggregations - - >>> df.groupby('A').agg(['min', 'max']) - B C - min max min max - A - 1 1 2 0.227877 0.362838 - 2 3 4 -0.562860 1.267767 - - Select a column for aggregation - - >>> df.groupby('A').B.agg(['min', 'max']) - min max - A - 1 1 2 - 2 3 4 - - Different aggregations per column - - >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'}) - B C - min max sum - A - 1 1 2 0.590716 - 2 3 4 0.704907 - - See also - -------- - pandas.DataFrame.groupby.apply - pandas.DataFrame.groupby.transform - pandas.DataFrame.aggregate - - """) - - @Appender(_agg_doc) - @Appender(_shared_docs['aggregate'] % dict( - klass='DataFrame', - versionadded='', - axis='')) - def aggregate(self, arg, *args, **kwargs): - return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs) - - agg = aggregate - - def _gotitem(self, key, ndim, subset=None): - """ - sub-classes to define - return a sliced object - - Parameters - ---------- - key : string / list of selections - ndim : 1,2 - requested ndim of result - subset : object, default None - subset to act on - """ - - if ndim == 2: - if subset is None: - subset = self.obj - return DataFrameGroupBy(subset, self.grouper, selection=key, - grouper=self.grouper, - exclusions=self.exclusions, - as_index=self.as_index) - elif ndim == 1: - if subset is None: - subset = self.obj[key] - return SeriesGroupBy(subset, selection=key, - grouper=self.grouper) - - raise AssertionError("invalid ndim for _gotitem") - - def _wrap_generic_output(self, result, obj): - result_index = self.grouper.levels[0] - - if self.axis == 0: - return DataFrame(result, index=obj.columns, - columns=result_index).T - else: - return DataFrame(result, index=obj.index, - columns=result_index) - - def _get_data_to_aggregate(self): - obj = self._obj_with_exclusions - if self.axis == 1: - return obj.T._data, 1 - else: - return obj._data, 1 - - def _insert_inaxis_grouper_inplace(self, result): - # zip in reverse so we can always insert at loc 0 - izip = zip(* map(reversed, ( - self.grouper.names, - self.grouper.get_group_levels(), - [grp.in_axis for grp in self.grouper.groupings]))) - - for name, lev, in_axis in izip: - if in_axis: - result.insert(0, name, lev) - - def _wrap_aggregated_output(self, output, names=None): - agg_axis = 0 if self.axis == 1 else 1 - agg_labels = self._obj_with_exclusions._get_axis(agg_axis) - - output_keys = self._decide_output_index(output, agg_labels) - - if not self.as_index: - result = DataFrame(output, columns=output_keys) - self._insert_inaxis_grouper_inplace(result) - result = result._consolidate() - else: - index = self.grouper.result_index - result = DataFrame(output, index=index, columns=output_keys) - - if self.axis == 1: - result = result.T - - return self._reindex_output(result)._convert(datetime=True) - - def _wrap_transformed_output(self, output, names=None): - return DataFrame(output, index=self.obj.index) - - def _wrap_agged_blocks(self, items, blocks): - if not self.as_index: - index = np.arange(blocks[0].values.shape[-1]) - mgr = BlockManager(blocks, [items, index]) - result = DataFrame(mgr) - - self._insert_inaxis_grouper_inplace(result) - result = result._consolidate() - else: - index = self.grouper.result_index - mgr = BlockManager(blocks, [items, index]) - result = DataFrame(mgr) - - if self.axis == 1: - result = result.T - - return self._reindex_output(result)._convert(datetime=True) - - def _reindex_output(self, result): - """ - If we have categorical groupers, then we want to make sure that - we have a fully reindex-output to the levels. These may have not - participated in the groupings (e.g. may have all been - nan groups); - - This can re-expand the output space - """ - - # we need to re-expand the output space to accomodate all values - # whether observed or not in the cartesian product of our groupes - groupings = self.grouper.groupings - if groupings is None: - return result - elif len(groupings) == 1: - return result - - # if we only care about the observed values - # we are done - elif self.observed: - return result - - # reindexing only applies to a Categorical grouper - elif not any(isinstance(ping.grouper, (Categorical, CategoricalIndex)) - for ping in groupings): - return result - - levels_list = [ping.group_index for ping in groupings] - index, _ = MultiIndex.from_product( - levels_list, names=self.grouper.names).sortlevel() - - if self.as_index: - d = {self.obj._get_axis_name(self.axis): index, 'copy': False} - return result.reindex(**d) - - # GH 13204 - # Here, the categorical in-axis groupers, which need to be fully - # expanded, are columns in `result`. An idea is to do: - # result = result.set_index(self.grouper.names) - # .reindex(index).reset_index() - # but special care has to be taken because of possible not-in-axis - # groupers. - # So, we manually select and drop the in-axis grouper columns, - # reindex `result`, and then reset the in-axis grouper columns. - - # Select in-axis groupers - in_axis_grps = [(i, ping.name) for (i, ping) - in enumerate(groupings) if ping.in_axis] - g_nums, g_names = zip(*in_axis_grps) - - result = result.drop(labels=list(g_names), axis=1) - - # Set a temp index and reindex (possibly expanding) - result = result.set_index(self.grouper.result_index - ).reindex(index, copy=False) - - # Reset in-axis grouper columns - # (using level numbers `g_nums` because level names may not be unique) - result = result.reset_index(level=g_nums) - - return result.reset_index(drop=True) - - def _iterate_column_groupbys(self): - for i, colname in enumerate(self._selected_obj.columns): - yield colname, SeriesGroupBy(self._selected_obj.iloc[:, i], - selection=colname, - grouper=self.grouper, - exclusions=self.exclusions) - - def _apply_to_column_groupbys(self, func): - from pandas.core.reshape.concat import concat - return concat( - (func(col_groupby) for _, col_groupby - in self._iterate_column_groupbys()), - keys=self._selected_obj.columns, axis=1) - - def _fill(self, direction, limit=None): - """Overridden method to join grouped columns in output""" - res = super(DataFrameGroupBy, self)._fill(direction, limit=limit) - output = collections.OrderedDict( - (grp.name, grp.grouper) for grp in self.grouper.groupings) - - from pandas import concat - return concat((self._wrap_transformed_output(output), res), axis=1) - - def count(self): - """ Compute count of group, excluding missing values """ - from pandas.core.dtypes.missing import _isna_ndarraylike as isna - - data, _ = self._get_data_to_aggregate() - ids, _, ngroups = self.grouper.group_info - mask = ids != -1 - - val = ((mask & ~isna(np.atleast_2d(blk.get_values()))) - for blk in data.blocks) - loc = (blk.mgr_locs for blk in data.blocks) - - counter = partial(count_level_2d, labels=ids, max_bin=ngroups, axis=1) - blk = map(make_block, map(counter, val), loc) - - return self._wrap_agged_blocks(data.items, list(blk)) - - def nunique(self, dropna=True): - """ - Return DataFrame with number of distinct observations per group for - each column. - - .. versionadded:: 0.20.0 - - Parameters - ---------- - dropna : boolean, default True - Don't include NaN in the counts. - - Returns - ------- - nunique: DataFrame - - Examples - -------- - >>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam', - ... 'ham', 'ham'], - ... 'value1': [1, 5, 5, 2, 5, 5], - ... 'value2': list('abbaxy')}) - >>> df - id value1 value2 - 0 spam 1 a - 1 egg 5 b - 2 egg 5 b - 3 spam 2 a - 4 ham 5 x - 5 ham 5 y - - >>> df.groupby('id').nunique() - id value1 value2 - id - egg 1 1 1 - ham 1 1 2 - spam 1 2 1 - - # check for rows with the same id but conflicting values - >>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any()) - id value1 value2 - 0 spam 1 a - 3 spam 2 a - 4 ham 5 x - 5 ham 5 y - """ - - obj = self._selected_obj - - def groupby_series(obj, col=None): - return SeriesGroupBy(obj, - selection=col, - grouper=self.grouper).nunique(dropna=dropna) - - if isinstance(obj, Series): - results = groupby_series(obj) - else: - from pandas.core.reshape.concat import concat - results = [groupby_series(obj[col], col) for col in obj.columns] - results = concat(results, axis=1) - - if not self.as_index: - results.index = com._default_index(len(results)) - return results - - boxplot = boxplot_frame_groupby - - -class PanelGroupBy(NDFrameGroupBy): - - def aggregate(self, arg, *args, **kwargs): - return super(PanelGroupBy, self).aggregate(arg, *args, **kwargs) - - agg = aggregate - - def _iterate_slices(self): - if self.axis == 0: - # kludge - if self._selection is None: - slice_axis = self._selected_obj.items - else: - slice_axis = self._selection_list - slicer = lambda x: self._selected_obj[x] - else: - raise NotImplementedError("axis other than 0 is not supported") - - for val in slice_axis: - if val in self.exclusions: - continue - - yield val, slicer(val) - - def aggregate(self, arg, *args, **kwargs): - """ - Aggregate using input function or dict of {column -> function} - - Parameters - ---------- - arg : function or dict - Function to use for aggregating groups. If a function, must either - work when passed a Panel or when passed to Panel.apply. If - pass a dict, the keys must be DataFrame column names - - Returns - ------- - aggregated : Panel - """ - if isinstance(arg, compat.string_types): - return getattr(self, arg)(*args, **kwargs) - - return self._aggregate_generic(arg, *args, **kwargs) - - def _wrap_generic_output(self, result, obj): - if self.axis == 0: - new_axes = list(obj.axes) - new_axes[0] = self.grouper.result_index - elif self.axis == 1: - x, y, z = obj.axes - new_axes = [self.grouper.result_index, z, x] - else: - x, y, z = obj.axes - new_axes = [self.grouper.result_index, y, x] - - result = Panel._from_axes(result, new_axes) - - if self.axis == 1: - result = result.swapaxes(0, 1).swapaxes(0, 2) - elif self.axis == 2: - result = result.swapaxes(0, 2) - - return result - - def _aggregate_item_by_item(self, func, *args, **kwargs): - obj = self._obj_with_exclusions - result = {} - - if self.axis > 0: - for item in obj: - try: - itemg = DataFrameGroupBy(obj[item], - axis=self.axis - 1, - grouper=self.grouper) - result[item] = itemg.aggregate(func, *args, **kwargs) - except (ValueError, TypeError): - raise - new_axes = list(obj.axes) - new_axes[self.axis] = self.grouper.result_index - return Panel._from_axes(result, new_axes) - else: - raise ValueError("axis value must be greater than 0") - - def _wrap_aggregated_output(self, output, names=None): - raise com.AbstractMethodError(self) - - -# ---------------------------------------------------------------------- -# Splitting / application - - -class DataSplitter(object): - - def __init__(self, data, labels, ngroups, axis=0): - self.data = data - self.labels = _ensure_int64(labels) - self.ngroups = ngroups - - self.axis = axis - - @cache_readonly - def slabels(self): - # Sorted labels - return algorithms.take_nd(self.labels, self.sort_idx, allow_fill=False) - - @cache_readonly - def sort_idx(self): - # Counting sort indexer - return get_group_index_sorter(self.labels, self.ngroups) - - def __iter__(self): - sdata = self._get_sorted_data() - - if self.ngroups == 0: - # we are inside a generator, rather than raise StopIteration - # we merely return signal the end - return - - starts, ends = lib.generate_slices(self.slabels, self.ngroups) - - for i, (start, end) in enumerate(zip(starts, ends)): - # Since I'm now compressing the group ids, it's now not "possible" - # to produce empty slices because such groups would not be observed - # in the data - # if start >= end: - # raise AssertionError('Start %s must be less than end %s' - # % (str(start), str(end))) - yield i, self._chop(sdata, slice(start, end)) - - def _get_sorted_data(self): - return self.data._take(self.sort_idx, axis=self.axis) - - def _chop(self, sdata, slice_obj): - return sdata.iloc[slice_obj] - - def apply(self, f): - raise com.AbstractMethodError(self) - - -class SeriesSplitter(DataSplitter): - - def _chop(self, sdata, slice_obj): - return sdata._get_values(slice_obj).to_dense() - - -class FrameSplitter(DataSplitter): - - def __init__(self, data, labels, ngroups, axis=0): - super(FrameSplitter, self).__init__(data, labels, ngroups, axis=axis) - - def fast_apply(self, f, names): - # must return keys::list, values::list, mutated::bool - try: - starts, ends = lib.generate_slices(self.slabels, self.ngroups) - except Exception: - # fails when all -1 - return [], True - - sdata = self._get_sorted_data() - results, mutated = reduction.apply_frame_axis0(sdata, f, names, - starts, ends) - - return results, mutated - - def _chop(self, sdata, slice_obj): - if self.axis == 0: - return sdata.iloc[slice_obj] - else: - return sdata._slice(slice_obj, axis=1) # .loc[:, slice_obj] - - -class NDFrameSplitter(DataSplitter): - - def __init__(self, data, labels, ngroups, axis=0): - super(NDFrameSplitter, self).__init__(data, labels, ngroups, axis=axis) - - self.factory = data._constructor - - def _get_sorted_data(self): - # this is the BlockManager - data = self.data._data - - # this is sort of wasteful but... - sorted_axis = data.axes[self.axis].take(self.sort_idx) - sorted_data = data.reindex_axis(sorted_axis, axis=self.axis) - - return sorted_data - - def _chop(self, sdata, slice_obj): - return self.factory(sdata.get_slice(slice_obj, axis=self.axis)) - - -def get_splitter(data, *args, **kwargs): - if isinstance(data, Series): - klass = SeriesSplitter - elif isinstance(data, DataFrame): - klass = FrameSplitter - else: - klass = NDFrameSplitter - - return klass(data, *args, **kwargs) diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py new file mode 100644 index 0000000000000..d5c4c2946a632 --- /dev/null +++ b/pandas/core/groupby/grouper.py @@ -0,0 +1,636 @@ +""" +Provide user facing operators for doing the split part of the +split-apply-combine paradigm. +""" + +import warnings +import numpy as np + +from pandas.util._decorators import cache_readonly + +from pandas import compat +from pandas.compat import zip, callable + +from pandas.core.dtypes.generic import ABCSeries +from pandas.core.arrays import ExtensionArray, Categorical +from pandas.core.index import ( + Index, MultiIndex, CategoricalIndex) +from pandas.core.dtypes.common import ( + _ensure_categorical, + is_hashable, + is_list_like, + is_timedelta64_dtype, + is_datetime64_dtype, + is_categorical_dtype, + is_scalar) +from pandas.core.series import Series +from pandas.core.frame import DataFrame +import pandas.core.common as com +from pandas.core.groupby.ops import BaseGrouper +import pandas.core.algorithms as algorithms +from pandas.io.formats.printing import pprint_thing + + +class Grouper(object): + """ + A Grouper allows the user to specify a groupby instruction for a target + object + + This specification will select a column via the key parameter, or if the + level and/or axis parameters are given, a level of the index of the target + object. + + These are local specifications and will override 'global' settings, + that is the parameters axis and level which are passed to the groupby + itself. + + Parameters + ---------- + key : string, defaults to None + groupby key, which selects the grouping column of the target + level : name/number, defaults to None + the level for the target index + freq : string / frequency object, defaults to None + This will groupby the specified frequency if the target selection + (via key or level) is a datetime-like object. For full specification + of available frequencies, please see `here + <http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases>`_. + axis : number/name of the axis, defaults to 0 + sort : boolean, default to False + whether to sort the resulting labels + + additional kwargs to control time-like groupers (when ``freq`` is passed) + + closed : closed end of interval; 'left' or 'right' + label : interval boundary to use for labeling; 'left' or 'right' + convention : {'start', 'end', 'e', 's'} + If grouper is PeriodIndex + base, loffset + + Returns + ------- + A specification for a groupby instruction + + Examples + -------- + + Syntactic sugar for ``df.groupby('A')`` + + >>> df.groupby(Grouper(key='A')) + + Specify a resample operation on the column 'date' + + >>> df.groupby(Grouper(key='date', freq='60s')) + + Specify a resample operation on the level 'date' on the columns axis + with a frequency of 60s + + >>> df.groupby(Grouper(level='date', freq='60s', axis=1)) + """ + _attributes = ('key', 'level', 'freq', 'axis', 'sort') + + def __new__(cls, *args, **kwargs): + if kwargs.get('freq') is not None: + from pandas.core.resample import TimeGrouper + cls = TimeGrouper + return super(Grouper, cls).__new__(cls) + + def __init__(self, key=None, level=None, freq=None, axis=0, sort=False): + self.key = key + self.level = level + self.freq = freq + self.axis = axis + self.sort = sort + + self.grouper = None + self.obj = None + self.indexer = None + self.binner = None + self._grouper = None + + @property + def ax(self): + return self.grouper + + def _get_grouper(self, obj, validate=True): + """ + Parameters + ---------- + obj : the subject object + validate : boolean, default True + if True, validate the grouper + + Returns + ------- + a tuple of binner, grouper, obj (possibly sorted) + """ + + self._set_grouper(obj) + self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key], + axis=self.axis, + level=self.level, + sort=self.sort, + validate=validate) + return self.binner, self.grouper, self.obj + + def _set_grouper(self, obj, sort=False): + """ + given an object and the specifications, setup the internal grouper + for this particular specification + + Parameters + ---------- + obj : the subject object + sort : bool, default False + whether the resulting grouper should be sorted + """ + + if self.key is not None and self.level is not None: + raise ValueError( + "The Grouper cannot specify both a key and a level!") + + # Keep self.grouper value before overriding + if self._grouper is None: + self._grouper = self.grouper + + # the key must be a valid info item + if self.key is not None: + key = self.key + # The 'on' is already defined + if getattr(self.grouper, 'name', None) == key and \ + isinstance(obj, ABCSeries): + ax = self._grouper.take(obj.index) + else: + if key not in obj._info_axis: + raise KeyError( + "The grouper name {0} is not found".format(key)) + ax = Index(obj[key], name=key) + + else: + ax = obj._get_axis(self.axis) + if self.level is not None: + level = self.level + + # if a level is given it must be a mi level or + # equivalent to the axis name + if isinstance(ax, MultiIndex): + level = ax._get_level_number(level) + ax = Index(ax._get_level_values(level), + name=ax.names[level]) + + else: + if level not in (0, ax.name): + raise ValueError( + "The level {0} is not valid".format(level)) + + # possibly sort + if (self.sort or sort) and not ax.is_monotonic: + # use stable sort to support first, last, nth + indexer = self.indexer = ax.argsort(kind='mergesort') + ax = ax.take(indexer) + obj = obj._take(indexer, axis=self.axis, is_copy=False) + + self.obj = obj + self.grouper = ax + return self.grouper + + @property + def groups(self): + return self.grouper.groups + + def __repr__(self): + attrs_list = ["{}={!r}".format(attr_name, getattr(self, attr_name)) + for attr_name in self._attributes + if getattr(self, attr_name) is not None] + attrs = ", ".join(attrs_list) + cls_name = self.__class__.__name__ + return "{}({})".format(cls_name, attrs) + + +class Grouping(object): + + """ + Holds the grouping information for a single key + + Parameters + ---------- + index : Index + grouper : + obj : + name : + level : + observed : boolean, default False + If we are a Categorical, use the observed values + in_axis : if the Grouping is a column in self.obj and hence among + Groupby.exclusions list + + Returns + ------- + **Attributes**: + * indices : dict of {group -> index_list} + * labels : ndarray, group labels + * ids : mapping of label -> group + * counts : array of group counts + * group_index : unique groups + * groups : dict of {group -> label_list} + """ + + def __init__(self, index, grouper=None, obj=None, name=None, level=None, + sort=True, observed=False, in_axis=False): + + self.name = name + self.level = level + self.grouper = _convert_grouper(index, grouper) + self.all_grouper = None + self.index = index + self.sort = sort + self.obj = obj + self.observed = observed + self.in_axis = in_axis + + # right place for this? + if isinstance(grouper, (Series, Index)) and name is None: + self.name = grouper.name + + if isinstance(grouper, MultiIndex): + self.grouper = grouper.values + + # we have a single grouper which may be a myriad of things, + # some of which are dependent on the passing in level + + if level is not None: + if not isinstance(level, int): + if level not in index.names: + raise AssertionError('Level %s not in index' % str(level)) + level = index.names.index(level) + + if self.name is None: + self.name = index.names[level] + + self.grouper, self._labels, self._group_index = \ + index._get_grouper_for_level(self.grouper, level) + + # a passed Grouper like, directly get the grouper in the same way + # as single grouper groupby, use the group_info to get labels + elif isinstance(self.grouper, Grouper): + # get the new grouper; we already have disambiguated + # what key/level refer to exactly, don't need to + # check again as we have by this point converted these + # to an actual value (rather than a pd.Grouper) + _, grouper, _ = self.grouper._get_grouper(self.obj, validate=False) + if self.name is None: + self.name = grouper.result_index.name + self.obj = self.grouper.obj + self.grouper = grouper + + else: + if self.grouper is None and self.name is not None: + self.grouper = self.obj[self.name] + + elif isinstance(self.grouper, (list, tuple)): + self.grouper = com._asarray_tuplesafe(self.grouper) + + # a passed Categorical + elif is_categorical_dtype(self.grouper): + + from pandas.core.groupby.categorical import recode_for_groupby + self.grouper, self.all_grouper = recode_for_groupby( + self.grouper, self.sort, observed) + categories = self.grouper.categories + + # we make a CategoricalIndex out of the cat grouper + # preserving the categories / ordered attributes + self._labels = self.grouper.codes + if observed: + codes = algorithms.unique1d(self.grouper.codes) + else: + codes = np.arange(len(categories)) + + self._group_index = CategoricalIndex( + Categorical.from_codes( + codes=codes, + categories=categories, + ordered=self.grouper.ordered)) + + # we are done + if isinstance(self.grouper, Grouping): + self.grouper = self.grouper.grouper + + # no level passed + elif not isinstance(self.grouper, + (Series, Index, ExtensionArray, np.ndarray)): + if getattr(self.grouper, 'ndim', 1) != 1: + t = self.name or str(type(self.grouper)) + raise ValueError("Grouper for '%s' not 1-dimensional" % t) + self.grouper = self.index.map(self.grouper) + if not (hasattr(self.grouper, "__len__") and + len(self.grouper) == len(self.index)): + errmsg = ('Grouper result violates len(labels) == ' + 'len(data)\nresult: %s' % + pprint_thing(self.grouper)) + self.grouper = None # Try for sanity + raise AssertionError(errmsg) + + # if we have a date/time-like grouper, make sure that we have + # Timestamps like + if getattr(self.grouper, 'dtype', None) is not None: + if is_datetime64_dtype(self.grouper): + from pandas import to_datetime + self.grouper = to_datetime(self.grouper) + elif is_timedelta64_dtype(self.grouper): + from pandas import to_timedelta + self.grouper = to_timedelta(self.grouper) + + def __repr__(self): + return 'Grouping({0})'.format(self.name) + + def __iter__(self): + return iter(self.indices) + + _labels = None + _group_index = None + + @property + def ngroups(self): + return len(self.group_index) + + @cache_readonly + def indices(self): + # we have a list of groupers + if isinstance(self.grouper, BaseGrouper): + return self.grouper.indices + + values = _ensure_categorical(self.grouper) + return values._reverse_indexer() + + @property + def labels(self): + if self._labels is None: + self._make_labels() + return self._labels + + @cache_readonly + def result_index(self): + if self.all_grouper is not None: + from pandas.core.groupby.categorical import recode_from_groupby + return recode_from_groupby(self.all_grouper, + self.sort, self.group_index) + return self.group_index + + @property + def group_index(self): + if self._group_index is None: + self._make_labels() + return self._group_index + + def _make_labels(self): + if self._labels is None or self._group_index is None: + # we have a list of groupers + if isinstance(self.grouper, BaseGrouper): + labels = self.grouper.label_info + uniques = self.grouper.result_index + else: + labels, uniques = algorithms.factorize( + self.grouper, sort=self.sort) + uniques = Index(uniques, name=self.name) + self._labels = labels + self._group_index = uniques + + @cache_readonly + def groups(self): + return self.index.groupby(Categorical.from_codes(self.labels, + self.group_index)) + + +def _get_grouper(obj, key=None, axis=0, level=None, sort=True, + observed=False, mutated=False, validate=True): + """ + create and return a BaseGrouper, which is an internal + mapping of how to create the grouper indexers. + This may be composed of multiple Grouping objects, indicating + multiple groupers + + Groupers are ultimately index mappings. They can originate as: + index mappings, keys to columns, functions, or Groupers + + Groupers enable local references to axis,level,sort, while + the passed in axis, level, and sort are 'global'. + + This routine tries to figure out what the passing in references + are and then creates a Grouping for each one, combined into + a BaseGrouper. + + If observed & we have a categorical grouper, only show the observed + values + + If validate, then check for key/level overlaps + + """ + group_axis = obj._get_axis(axis) + + # validate that the passed single level is compatible with the passed + # axis of the object + if level is not None: + # TODO: These if-block and else-block are almost same. + # MultiIndex instance check is removable, but it seems that there are + # some processes only for non-MultiIndex in else-block, + # eg. `obj.index.name != level`. We have to consider carefully whether + # these are applicable for MultiIndex. Even if these are applicable, + # we need to check if it makes no side effect to subsequent processes + # on the outside of this condition. + # (GH 17621) + if isinstance(group_axis, MultiIndex): + if is_list_like(level) and len(level) == 1: + level = level[0] + + if key is None and is_scalar(level): + # Get the level values from group_axis + key = group_axis.get_level_values(level) + level = None + + else: + # allow level to be a length-one list-like object + # (e.g., level=[0]) + # GH 13901 + if is_list_like(level): + nlevels = len(level) + if nlevels == 1: + level = level[0] + elif nlevels == 0: + raise ValueError('No group keys passed!') + else: + raise ValueError('multiple levels only valid with ' + 'MultiIndex') + + if isinstance(level, compat.string_types): + if obj.index.name != level: + raise ValueError('level name %s is not the name of the ' + 'index' % level) + elif level > 0 or level < -1: + raise ValueError('level > 0 or level < -1 only valid with ' + ' MultiIndex') + + # NOTE: `group_axis` and `group_axis.get_level_values(level)` + # are same in this section. + level = None + key = group_axis + + # a passed-in Grouper, directly convert + if isinstance(key, Grouper): + binner, grouper, obj = key._get_grouper(obj, validate=False) + if key.key is None: + return grouper, [], obj + else: + return grouper, set([key.key]), obj + + # already have a BaseGrouper, just return it + elif isinstance(key, BaseGrouper): + return key, [], obj + + # In the future, a tuple key will always mean an actual key, + # not an iterable of keys. In the meantime, we attempt to provide + # a warning. We can assume that the user wanted a list of keys when + # the key is not in the index. We just have to be careful with + # unhashble elements of `key`. Any unhashable elements implies that + # they wanted a list of keys. + # https://github.com/pandas-dev/pandas/issues/18314 + is_tuple = isinstance(key, tuple) + all_hashable = is_tuple and is_hashable(key) + + if is_tuple: + if ((all_hashable and key not in obj and set(key).issubset(obj)) + or not all_hashable): + # column names ('a', 'b') -> ['a', 'b'] + # arrays like (a, b) -> [a, b] + msg = ("Interpreting tuple 'by' as a list of keys, rather than " + "a single key. Use 'by=[...]' instead of 'by=(...)'. In " + "the future, a tuple will always mean a single key.") + warnings.warn(msg, FutureWarning, stacklevel=5) + key = list(key) + + if not isinstance(key, list): + keys = [key] + match_axis_length = False + else: + keys = key + match_axis_length = len(keys) == len(group_axis) + + # what are we after, exactly? + any_callable = any(callable(g) or isinstance(g, dict) for g in keys) + any_groupers = any(isinstance(g, Grouper) for g in keys) + any_arraylike = any(isinstance(g, (list, tuple, Series, Index, np.ndarray)) + for g in keys) + + try: + if isinstance(obj, DataFrame): + all_in_columns_index = all(g in obj.columns or g in obj.index.names + for g in keys) + else: + all_in_columns_index = False + except Exception: + all_in_columns_index = False + + if not any_callable and not all_in_columns_index and \ + not any_arraylike and not any_groupers and \ + match_axis_length and level is None: + keys = [com._asarray_tuplesafe(keys)] + + if isinstance(level, (tuple, list)): + if key is None: + keys = [None] * len(level) + levels = level + else: + levels = [level] * len(keys) + + groupings = [] + exclusions = [] + + # if the actual grouper should be obj[key] + def is_in_axis(key): + if not _is_label_like(key): + try: + obj._data.items.get_loc(key) + except Exception: + return False + + return True + + # if the grouper is obj[name] + def is_in_obj(gpr): + try: + return id(gpr) == id(obj[gpr.name]) + except Exception: + return False + + for i, (gpr, level) in enumerate(zip(keys, levels)): + + if is_in_obj(gpr): # df.groupby(df['name']) + in_axis, name = True, gpr.name + exclusions.append(name) + + elif is_in_axis(gpr): # df.groupby('name') + if gpr in obj: + if validate: + stacklevel = 5 # Number of stack levels from df.groupby + obj._check_label_or_level_ambiguity( + gpr, stacklevel=stacklevel) + in_axis, name, gpr = True, gpr, obj[gpr] + exclusions.append(name) + elif obj._is_level_reference(gpr): + in_axis, name, level, gpr = False, None, gpr, None + else: + raise KeyError(gpr) + elif isinstance(gpr, Grouper) and gpr.key is not None: + # Add key to exclusions + exclusions.append(gpr.key) + in_axis, name = False, None + else: + in_axis, name = False, None + + if is_categorical_dtype(gpr) and len(gpr) != obj.shape[axis]: + raise ValueError( + ("Length of grouper ({len_gpr}) and axis ({len_axis})" + " must be same length" + .format(len_gpr=len(gpr), len_axis=obj.shape[axis]))) + + # create the Grouping + # allow us to passing the actual Grouping as the gpr + ping = Grouping(group_axis, + gpr, + obj=obj, + name=name, + level=level, + sort=sort, + observed=observed, + in_axis=in_axis) \ + if not isinstance(gpr, Grouping) else gpr + + groupings.append(ping) + + if len(groupings) == 0: + raise ValueError('No group keys passed!') + + # create the internals grouper + grouper = BaseGrouper(group_axis, groupings, sort=sort, mutated=mutated) + return grouper, exclusions, obj + + +def _is_label_like(val): + return (isinstance(val, (compat.string_types, tuple)) or + (val is not None and is_scalar(val))) + + +def _convert_grouper(axis, grouper): + if isinstance(grouper, dict): + return grouper.get + elif isinstance(grouper, Series): + if grouper.index.equals(axis): + return grouper._values + else: + return grouper.reindex(axis)._values + elif isinstance(grouper, (list, Series, Index, np.ndarray)): + if len(grouper) != len(axis): + raise ValueError('Grouper and axis must be same length') + return grouper + else: + return grouper diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py new file mode 100644 index 0000000000000..65b9144c0ddc9 --- /dev/null +++ b/pandas/core/groupby/ops.py @@ -0,0 +1,916 @@ +""" +Provide classes to perform the groupby aggregate operations. + +These are not exposed to the user and provide implementations of the grouping +operations, primarily in cython. These classes (BaseGrouper and BinGrouper) +are contained *in* the SeriesGroupBy and DataFrameGroupBy objects. +""" + +import copy +import collections +import numpy as np + +from pandas._libs import lib, reduction, NaT, iNaT, groupby as libgroupby +from pandas.util._decorators import cache_readonly + +from pandas.compat import zip, range, lzip + +from pandas.core.base import SelectionMixin +from pandas.core.dtypes.missing import isna, _maybe_fill +from pandas.core.index import ( + Index, MultiIndex, _ensure_index) +from pandas.core.dtypes.common import ( + _ensure_float64, + _ensure_platform_int, + _ensure_int64, + _ensure_object, + needs_i8_conversion, + is_integer_dtype, + is_complex_dtype, + is_bool_dtype, + is_numeric_dtype, + is_timedelta64_dtype, + is_datetime64_any_dtype, + is_categorical_dtype) +from pandas.core.series import Series +from pandas.core.frame import DataFrame +from pandas.core.generic import NDFrame +import pandas.core.common as com +from pandas.core.groupby import base +from pandas.core.sorting import (get_group_index_sorter, get_group_index, + compress_group_index, get_flattened_iterator, + decons_obs_group_ids, get_indexer_dict) +import pandas.core.algorithms as algorithms + + +def generate_bins_generic(values, binner, closed): + """ + Generate bin edge offsets and bin labels for one array using another array + which has bin edge values. Both arrays must be sorted. + + Parameters + ---------- + values : array of values + binner : a comparable array of values representing bins into which to bin + the first array. Note, 'values' end-points must fall within 'binner' + end-points. + closed : which end of bin is closed; left (default), right + + Returns + ------- + bins : array of offsets (into 'values' argument) of bins. + Zero and last edge are excluded in result, so for instance the first + bin is values[0:bin[0]] and the last is values[bin[-1]:] + """ + lenidx = len(values) + lenbin = len(binner) + + if lenidx <= 0 or lenbin <= 0: + raise ValueError("Invalid length for values or for binner") + + # check binner fits data + if values[0] < binner[0]: + raise ValueError("Values falls before first bin") + + if values[lenidx - 1] > binner[lenbin - 1]: + raise ValueError("Values falls after last bin") + + bins = np.empty(lenbin - 1, dtype=np.int64) + + j = 0 # index into values + bc = 0 # bin count + + # linear scan, presume nothing about values/binner except that it fits ok + for i in range(0, lenbin - 1): + r_bin = binner[i + 1] + + # count values in current bin, advance to next bin + while j < lenidx and (values[j] < r_bin or + (closed == 'right' and values[j] == r_bin)): + j += 1 + + bins[bc] = j + bc += 1 + + return bins + + +class BaseGrouper(object): + """ + This is an internal Grouper class, which actually holds + the generated groups + + Parameters + ---------- + axis : int + the axis to group + groupings : array of grouping + all the grouping instances to handle in this grouper + for example for grouper list to groupby, need to pass the list + sort : boolean, default True + whether this grouper will give sorted result or not + group_keys : boolean, default True + mutated : boolean, default False + indexer : intp array, optional + the indexer created by Grouper + some groupers (TimeGrouper) will sort its axis and its + group_info is also sorted, so need the indexer to reorder + + """ + + def __init__(self, axis, groupings, sort=True, group_keys=True, + mutated=False, indexer=None): + self._filter_empty_groups = self.compressed = len(groupings) != 1 + self.axis = axis + self.groupings = groupings + self.sort = sort + self.group_keys = group_keys + self.mutated = mutated + self.indexer = indexer + + @property + def shape(self): + return tuple(ping.ngroups for ping in self.groupings) + + def __iter__(self): + return iter(self.indices) + + @property + def nkeys(self): + return len(self.groupings) + + def get_iterator(self, data, axis=0): + """ + Groupby iterator + + Returns + ------- + Generator yielding sequence of (name, subsetted object) + for each group + """ + splitter = self._get_splitter(data, axis=axis) + keys = self._get_group_keys() + for key, (i, group) in zip(keys, splitter): + yield key, group + + def _get_splitter(self, data, axis=0): + comp_ids, _, ngroups = self.group_info + return get_splitter(data, comp_ids, ngroups, axis=axis) + + def _get_group_keys(self): + if len(self.groupings) == 1: + return self.levels[0] + else: + comp_ids, _, ngroups = self.group_info + + # provide "flattened" iterator for multi-group setting + return get_flattened_iterator(comp_ids, + ngroups, + self.levels, + self.labels) + + def apply(self, f, data, axis=0): + mutated = self.mutated + splitter = self._get_splitter(data, axis=axis) + group_keys = self._get_group_keys() + + # oh boy + f_name = com._get_callable_name(f) + if (f_name not in base.plotting_methods and + hasattr(splitter, 'fast_apply') and axis == 0): + try: + values, mutated = splitter.fast_apply(f, group_keys) + return group_keys, values, mutated + except reduction.InvalidApply: + # we detect a mutation of some kind + # so take slow path + pass + except Exception: + # raise this error to the caller + pass + + result_values = [] + for key, (i, group) in zip(group_keys, splitter): + object.__setattr__(group, 'name', key) + + # group might be modified + group_axes = _get_axes(group) + res = f(group) + if not _is_indexed_like(res, group_axes): + mutated = True + result_values.append(res) + + return group_keys, result_values, mutated + + @cache_readonly + def indices(self): + """ dict {group name -> group indices} """ + if len(self.groupings) == 1: + return self.groupings[0].indices + else: + label_list = [ping.labels for ping in self.groupings] + keys = [com._values_from_object(ping.group_index) + for ping in self.groupings] + return get_indexer_dict(label_list, keys) + + @property + def labels(self): + return [ping.labels for ping in self.groupings] + + @property + def levels(self): + return [ping.group_index for ping in self.groupings] + + @property + def names(self): + return [ping.name for ping in self.groupings] + + def size(self): + """ + Compute group sizes + + """ + ids, _, ngroup = self.group_info + ids = _ensure_platform_int(ids) + if ngroup: + out = np.bincount(ids[ids != -1], minlength=ngroup) + else: + out = ids + return Series(out, + index=self.result_index, + dtype='int64') + + @cache_readonly + def groups(self): + """ dict {group name -> group labels} """ + if len(self.groupings) == 1: + return self.groupings[0].groups + else: + to_groupby = lzip(*(ping.grouper for ping in self.groupings)) + to_groupby = Index(to_groupby) + return self.axis.groupby(to_groupby) + + @cache_readonly + def is_monotonic(self): + # return if my group orderings are monotonic + return Index(self.group_info[0]).is_monotonic + + @cache_readonly + def group_info(self): + comp_ids, obs_group_ids = self._get_compressed_labels() + + ngroups = len(obs_group_ids) + comp_ids = _ensure_int64(comp_ids) + return comp_ids, obs_group_ids, ngroups + + @cache_readonly + def label_info(self): + # return the labels of items in original grouped axis + labels, _, _ = self.group_info + if self.indexer is not None: + sorter = np.lexsort((labels, self.indexer)) + labels = labels[sorter] + return labels + + def _get_compressed_labels(self): + all_labels = [ping.labels for ping in self.groupings] + if len(all_labels) > 1: + group_index = get_group_index(all_labels, self.shape, + sort=True, xnull=True) + return compress_group_index(group_index, sort=self.sort) + + ping = self.groupings[0] + return ping.labels, np.arange(len(ping.group_index)) + + @cache_readonly + def ngroups(self): + return len(self.result_index) + + @property + def recons_labels(self): + comp_ids, obs_ids, _ = self.group_info + labels = (ping.labels for ping in self.groupings) + return decons_obs_group_ids( + comp_ids, obs_ids, self.shape, labels, xnull=True) + + @cache_readonly + def result_index(self): + if not self.compressed and len(self.groupings) == 1: + return self.groupings[0].result_index.rename(self.names[0]) + + labels = self.recons_labels + levels = [ping.result_index for ping in self.groupings] + result = MultiIndex(levels=levels, + labels=labels, + verify_integrity=False, + names=self.names) + return result + + def get_group_levels(self): + if not self.compressed and len(self.groupings) == 1: + return [self.groupings[0].result_index] + + name_list = [] + for ping, labels in zip(self.groupings, self.recons_labels): + labels = _ensure_platform_int(labels) + levels = ping.result_index.take(labels) + + name_list.append(levels) + + return name_list + + # ------------------------------------------------------------ + # Aggregation functions + + _cython_functions = { + 'aggregate': { + 'add': 'group_add', + 'prod': 'group_prod', + 'min': 'group_min', + 'max': 'group_max', + 'mean': 'group_mean', + 'median': { + 'name': 'group_median' + }, + 'var': 'group_var', + 'first': { + 'name': 'group_nth', + 'f': lambda func, a, b, c, d, e: func(a, b, c, d, 1, -1) + }, + 'last': 'group_last', + 'ohlc': 'group_ohlc', + }, + + 'transform': { + 'cumprod': 'group_cumprod', + 'cumsum': 'group_cumsum', + 'cummin': 'group_cummin', + 'cummax': 'group_cummax', + 'rank': { + 'name': 'group_rank', + 'f': lambda func, a, b, c, d, **kwargs: func( + a, b, c, d, + kwargs.get('ties_method', 'average'), + kwargs.get('ascending', True), + kwargs.get('pct', False), + kwargs.get('na_option', 'keep') + ) + } + } + } + + _cython_arity = { + 'ohlc': 4, # OHLC + } + + _name_functions = { + 'ohlc': lambda *args: ['open', 'high', 'low', 'close'] + } + + def _is_builtin_func(self, arg): + """ + if we define an builtin function for this argument, return it, + otherwise return the arg + """ + return SelectionMixin._builtin_table.get(arg, arg) + + def _get_cython_function(self, kind, how, values, is_numeric): + + dtype_str = values.dtype.name + + def get_func(fname): + # see if there is a fused-type version of function + # only valid for numeric + f = getattr(libgroupby, fname, None) + if f is not None and is_numeric: + return f + + # otherwise find dtype-specific version, falling back to object + for dt in [dtype_str, 'object']: + f = getattr(libgroupby, "%s_%s" % (fname, dtype_str), None) + if f is not None: + return f + + ftype = self._cython_functions[kind][how] + + if isinstance(ftype, dict): + func = afunc = get_func(ftype['name']) + + # a sub-function + f = ftype.get('f') + if f is not None: + + def wrapper(*args, **kwargs): + return f(afunc, *args, **kwargs) + + # need to curry our sub-function + func = wrapper + + else: + func = get_func(ftype) + + if func is None: + raise NotImplementedError("function is not implemented for this" + "dtype: [how->%s,dtype->%s]" % + (how, dtype_str)) + return func + + def _cython_operation(self, kind, values, how, axis, min_count=-1, + **kwargs): + assert kind in ['transform', 'aggregate'] + + # can we do this operation with our cython functions + # if not raise NotImplementedError + + # we raise NotImplemented if this is an invalid operation + # entirely, e.g. adding datetimes + + # categoricals are only 1d, so we + # are not setup for dim transforming + if is_categorical_dtype(values): + raise NotImplementedError( + "categoricals are not support in cython ops ATM") + elif is_datetime64_any_dtype(values): + if how in ['add', 'prod', 'cumsum', 'cumprod']: + raise NotImplementedError( + "datetime64 type does not support {} " + "operations".format(how)) + elif is_timedelta64_dtype(values): + if how in ['prod', 'cumprod']: + raise NotImplementedError( + "timedelta64 type does not support {} " + "operations".format(how)) + + arity = self._cython_arity.get(how, 1) + + vdim = values.ndim + swapped = False + if vdim == 1: + values = values[:, None] + out_shape = (self.ngroups, arity) + else: + if axis > 0: + swapped = True + values = values.swapaxes(0, axis) + if arity > 1: + raise NotImplementedError("arity of more than 1 is not " + "supported for the 'how' argument") + out_shape = (self.ngroups,) + values.shape[1:] + + is_datetimelike = needs_i8_conversion(values.dtype) + is_numeric = is_numeric_dtype(values.dtype) + + if is_datetimelike: + values = values.view('int64') + is_numeric = True + elif is_bool_dtype(values.dtype): + values = _ensure_float64(values) + elif is_integer_dtype(values): + # we use iNaT for the missing value on ints + # so pre-convert to guard this condition + if (values == iNaT).any(): + values = _ensure_float64(values) + else: + values = values.astype('int64', copy=False) + elif is_numeric and not is_complex_dtype(values): + values = _ensure_float64(values) + else: + values = values.astype(object) + + try: + func = self._get_cython_function( + kind, how, values, is_numeric) + except NotImplementedError: + if is_numeric: + values = _ensure_float64(values) + func = self._get_cython_function( + kind, how, values, is_numeric) + else: + raise + + if how == 'rank': + out_dtype = 'float' + else: + if is_numeric: + out_dtype = '%s%d' % (values.dtype.kind, values.dtype.itemsize) + else: + out_dtype = 'object' + + labels, _, _ = self.group_info + + if kind == 'aggregate': + result = _maybe_fill(np.empty(out_shape, dtype=out_dtype), + fill_value=np.nan) + counts = np.zeros(self.ngroups, dtype=np.int64) + result = self._aggregate( + result, counts, values, labels, func, is_numeric, + is_datetimelike, min_count) + elif kind == 'transform': + result = _maybe_fill(np.empty_like(values, dtype=out_dtype), + fill_value=np.nan) + + # TODO: min_count + result = self._transform( + result, values, labels, func, is_numeric, is_datetimelike, + **kwargs) + + if is_integer_dtype(result) and not is_datetimelike: + mask = result == iNaT + if mask.any(): + result = result.astype('float64') + result[mask] = np.nan + + if kind == 'aggregate' and \ + self._filter_empty_groups and not counts.all(): + if result.ndim == 2: + try: + result = lib.row_bool_subset( + result, (counts > 0).view(np.uint8)) + except ValueError: + result = lib.row_bool_subset_object( + _ensure_object(result), + (counts > 0).view(np.uint8)) + else: + result = result[counts > 0] + + if vdim == 1 and arity == 1: + result = result[:, 0] + + if how in self._name_functions: + # TODO + names = self._name_functions[how]() + else: + names = None + + if swapped: + result = result.swapaxes(0, axis) + + return result, names + + def aggregate(self, values, how, axis=0, min_count=-1): + return self._cython_operation('aggregate', values, how, axis, + min_count=min_count) + + def transform(self, values, how, axis=0, **kwargs): + return self._cython_operation('transform', values, how, axis, **kwargs) + + def _aggregate(self, result, counts, values, comp_ids, agg_func, + is_numeric, is_datetimelike, min_count=-1): + if values.ndim > 3: + # punting for now + raise NotImplementedError("number of dimensions is currently " + "limited to 3") + elif values.ndim > 2: + for i, chunk in enumerate(values.transpose(2, 0, 1)): + + chunk = chunk.squeeze() + agg_func(result[:, :, i], counts, chunk, comp_ids, + min_count) + else: + agg_func(result, counts, values, comp_ids, min_count) + + return result + + def _transform(self, result, values, comp_ids, transform_func, + is_numeric, is_datetimelike, **kwargs): + + comp_ids, _, ngroups = self.group_info + if values.ndim > 3: + # punting for now + raise NotImplementedError("number of dimensions is currently " + "limited to 3") + elif values.ndim > 2: + for i, chunk in enumerate(values.transpose(2, 0, 1)): + + chunk = chunk.squeeze() + transform_func(result[:, :, i], values, + comp_ids, is_datetimelike, **kwargs) + else: + transform_func(result, values, comp_ids, is_datetimelike, **kwargs) + + return result + + def agg_series(self, obj, func): + try: + return self._aggregate_series_fast(obj, func) + except Exception: + return self._aggregate_series_pure_python(obj, func) + + def _aggregate_series_fast(self, obj, func): + func = self._is_builtin_func(func) + + if obj.index._has_complex_internals: + raise TypeError('Incompatible index for Cython grouper') + + group_index, _, ngroups = self.group_info + + # avoids object / Series creation overhead + dummy = obj._get_values(slice(None, 0)).to_dense() + indexer = get_group_index_sorter(group_index, ngroups) + obj = obj._take(indexer).to_dense() + group_index = algorithms.take_nd( + group_index, indexer, allow_fill=False) + grouper = reduction.SeriesGrouper(obj, func, group_index, ngroups, + dummy) + result, counts = grouper.get_result() + return result, counts + + def _aggregate_series_pure_python(self, obj, func): + + group_index, _, ngroups = self.group_info + + counts = np.zeros(ngroups, dtype=int) + result = None + + splitter = get_splitter(obj, group_index, ngroups, axis=self.axis) + + for label, group in splitter: + res = func(group) + if result is None: + if (isinstance(res, (Series, Index, np.ndarray))): + raise ValueError('Function does not reduce') + result = np.empty(ngroups, dtype='O') + + counts[label] = group.shape[0] + result[label] = res + + result = lib.maybe_convert_objects(result, try_float=0) + return result, counts + + +class BinGrouper(BaseGrouper): + + """ + This is an internal Grouper class + + Parameters + ---------- + bins : the split index of binlabels to group the item of axis + binlabels : the label list + filter_empty : boolean, default False + mutated : boolean, default False + indexer : a intp array + + Examples + -------- + bins: [2, 4, 6, 8, 10] + binlabels: DatetimeIndex(['2005-01-01', '2005-01-03', + '2005-01-05', '2005-01-07', '2005-01-09'], + dtype='datetime64[ns]', freq='2D') + + the group_info, which contains the label of each item in grouped + axis, the index of label in label list, group number, is + + (array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]), array([0, 1, 2, 3, 4]), 5) + + means that, the grouped axis has 10 items, can be grouped into 5 + labels, the first and second items belong to the first label, the + third and forth items belong to the second label, and so on + + """ + + def __init__(self, bins, binlabels, filter_empty=False, mutated=False, + indexer=None): + self.bins = _ensure_int64(bins) + self.binlabels = _ensure_index(binlabels) + self._filter_empty_groups = filter_empty + self.mutated = mutated + self.indexer = indexer + + @cache_readonly + def groups(self): + """ dict {group name -> group labels} """ + + # this is mainly for compat + # GH 3881 + result = {} + for key, value in zip(self.binlabels, self.bins): + if key is not NaT: + result[key] = value + return result + + @property + def nkeys(self): + return 1 + + def get_iterator(self, data, axis=0): + """ + Groupby iterator + + Returns + ------- + Generator yielding sequence of (name, subsetted object) + for each group + """ + if isinstance(data, NDFrame): + slicer = lambda start, edge: data._slice( + slice(start, edge), axis=axis) + length = len(data.axes[axis]) + else: + slicer = lambda start, edge: data[slice(start, edge)] + length = len(data) + + start = 0 + for edge, label in zip(self.bins, self.binlabels): + if label is not NaT: + yield label, slicer(start, edge) + start = edge + + if start < length: + yield self.binlabels[-1], slicer(start, None) + + @cache_readonly + def indices(self): + indices = collections.defaultdict(list) + + i = 0 + for label, bin in zip(self.binlabels, self.bins): + if i < bin: + if label is not NaT: + indices[label] = list(range(i, bin)) + i = bin + return indices + + @cache_readonly + def group_info(self): + ngroups = self.ngroups + obs_group_ids = np.arange(ngroups) + rep = np.diff(np.r_[0, self.bins]) + + rep = _ensure_platform_int(rep) + if ngroups == len(self.bins): + comp_ids = np.repeat(np.arange(ngroups), rep) + else: + comp_ids = np.repeat(np.r_[-1, np.arange(ngroups)], rep) + + return comp_ids.astype('int64', copy=False), \ + obs_group_ids.astype('int64', copy=False), ngroups + + @cache_readonly + def ngroups(self): + return len(self.result_index) + + @cache_readonly + def result_index(self): + if len(self.binlabels) != 0 and isna(self.binlabels[0]): + return self.binlabels[1:] + + return self.binlabels + + @property + def levels(self): + return [self.binlabels] + + @property + def names(self): + return [self.binlabels.name] + + @property + def groupings(self): + from pandas.core.groupby.grouper import Grouping + return [Grouping(lvl, lvl, in_axis=False, level=None, name=name) + for lvl, name in zip(self.levels, self.names)] + + def agg_series(self, obj, func): + dummy = obj[:0] + grouper = reduction.SeriesBinGrouper(obj, func, self.bins, dummy) + return grouper.get_result() + + # ---------------------------------------------------------------------- + # cython aggregation + + _cython_functions = copy.deepcopy(BaseGrouper._cython_functions) + + +def _get_axes(group): + if isinstance(group, Series): + return [group.index] + else: + return group.axes + + +def _is_indexed_like(obj, axes): + if isinstance(obj, Series): + if len(axes) > 1: + return False + return obj.index.equals(axes[0]) + elif isinstance(obj, DataFrame): + return obj.index.equals(axes[0]) + + return False + + +# ---------------------------------------------------------------------- +# Splitting / application + + +class DataSplitter(object): + + def __init__(self, data, labels, ngroups, axis=0): + self.data = data + self.labels = _ensure_int64(labels) + self.ngroups = ngroups + + self.axis = axis + + @cache_readonly + def slabels(self): + # Sorted labels + return algorithms.take_nd(self.labels, self.sort_idx, allow_fill=False) + + @cache_readonly + def sort_idx(self): + # Counting sort indexer + return get_group_index_sorter(self.labels, self.ngroups) + + def __iter__(self): + sdata = self._get_sorted_data() + + if self.ngroups == 0: + # we are inside a generator, rather than raise StopIteration + # we merely return signal the end + return + + starts, ends = lib.generate_slices(self.slabels, self.ngroups) + + for i, (start, end) in enumerate(zip(starts, ends)): + # Since I'm now compressing the group ids, it's now not "possible" + # to produce empty slices because such groups would not be observed + # in the data + # if start >= end: + # raise AssertionError('Start %s must be less than end %s' + # % (str(start), str(end))) + yield i, self._chop(sdata, slice(start, end)) + + def _get_sorted_data(self): + return self.data._take(self.sort_idx, axis=self.axis) + + def _chop(self, sdata, slice_obj): + return sdata.iloc[slice_obj] + + def apply(self, f): + raise com.AbstractMethodError(self) + + +class SeriesSplitter(DataSplitter): + + def _chop(self, sdata, slice_obj): + return sdata._get_values(slice_obj).to_dense() + + +class FrameSplitter(DataSplitter): + + def __init__(self, data, labels, ngroups, axis=0): + super(FrameSplitter, self).__init__(data, labels, ngroups, axis=axis) + + def fast_apply(self, f, names): + # must return keys::list, values::list, mutated::bool + try: + starts, ends = lib.generate_slices(self.slabels, self.ngroups) + except Exception: + # fails when all -1 + return [], True + + sdata = self._get_sorted_data() + results, mutated = reduction.apply_frame_axis0(sdata, f, names, + starts, ends) + + return results, mutated + + def _chop(self, sdata, slice_obj): + if self.axis == 0: + return sdata.iloc[slice_obj] + else: + return sdata._slice(slice_obj, axis=1) # .loc[:, slice_obj] + + +class NDFrameSplitter(DataSplitter): + + def __init__(self, data, labels, ngroups, axis=0): + super(NDFrameSplitter, self).__init__(data, labels, ngroups, axis=axis) + + self.factory = data._constructor + + def _get_sorted_data(self): + # this is the BlockManager + data = self.data._data + + # this is sort of wasteful but... + sorted_axis = data.axes[self.axis].take(self.sort_idx) + sorted_data = data.reindex_axis(sorted_axis, axis=self.axis) + + return sorted_data + + def _chop(self, sdata, slice_obj): + return self.factory(sdata.get_slice(slice_obj, axis=self.axis)) + + +def get_splitter(data, *args, **kwargs): + if isinstance(data, Series): + klass = SeriesSplitter + elif isinstance(data, DataFrame): + klass = FrameSplitter + else: + klass = NDFrameSplitter + + return klass(data, *args, **kwargs) diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 9f08fabef8cc7..a1812cb5801b9 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -911,7 +911,7 @@ def groupby(self, function, axis='major'): ------- grouped : PanelGroupBy """ - from pandas.core.groupby.groupby import PanelGroupBy + from pandas.core.groupby import PanelGroupBy axis = self._get_axis_number(axis) return PanelGroupBy(self, function, axis=axis) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 5c3135fe14b51..3f3f74975a29d 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -5,12 +5,13 @@ from textwrap import dedent import pandas as pd -from pandas.core.base import GroupByMixin - +from pandas.core.groupby.base import GroupByMixin +from pandas.core.groupby.ops import BinGrouper from pandas.core.groupby.groupby import ( - BinGrouper, Grouper, _GroupBy, GroupBy, SeriesGroupBy, groupby, - PanelGroupBy, _pipe_template + _GroupBy, GroupBy, groupby, _pipe_template ) +from pandas.core.groupby.grouper import Grouper +from pandas.core.groupby.generic import SeriesGroupBy, PanelGroupBy from pandas.tseries.frequencies import to_offset, is_subperiod, is_superperiod from pandas.core.indexes.datetimes import DatetimeIndex, date_range diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 3390451c60c0f..da5246d389817 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -8,7 +8,7 @@ from pandas.core.reshape.concat import concat from pandas.core.series import Series -from pandas.core.groupby.groupby import Grouper +from pandas.core.groupby import Grouper from pandas.core.reshape.util import cartesian_product from pandas.core.index import Index, _get_objs_combined_axis from pandas.compat import range, lrange, zip diff --git a/pandas/core/window.py b/pandas/core/window.py index 5e7330ed6001c..e20db4df2cb2a 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -30,8 +30,8 @@ _ensure_float64, is_scalar) -from pandas.core.base import (PandasObject, SelectionMixin, - GroupByMixin) +from pandas.core.base import PandasObject, SelectionMixin +from pandas.core.groupby.base import GroupByMixin import pandas.core.common as com import pandas._libs.window as _window diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index b2f18e11de8ee..b0d6a0e83440a 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -10,7 +10,8 @@ import pandas as pd from pandas import concat, DataFrame, Index, MultiIndex, Series -from pandas.core.groupby.groupby import Grouping, SpecificationError +from pandas.core.groupby.grouper import Grouping +from pandas.core.base import SpecificationError from pandas.compat import OrderedDict import pandas.util.testing as tm diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py index c293f49c5bc2a..9a838341c7d8c 100644 --- a/pandas/tests/groupby/test_bin_groupby.py +++ b/pandas/tests/groupby/test_bin_groupby.py @@ -7,6 +7,7 @@ from pandas.core.dtypes.common import _ensure_int64 from pandas import Index, isna +from pandas.core.groupby.ops import generate_bins_generic from pandas.util.testing import assert_almost_equal import pandas.util.testing as tm from pandas._libs import lib, groupby, reduction @@ -54,7 +55,6 @@ def setup_method(self, method): self.bins = np.array([3, 6], dtype=np.int64) def test_generate_bins(self): - from pandas.core.groupby.groupby import generate_bins_generic values = np.array([1, 2, 3, 4, 5, 6], dtype=np.int64) binner = np.array([0, 3, 6, 9], dtype=np.int64) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index c0f5c43b2fd35..58e9797dbeea5 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -9,7 +9,7 @@ Index, MultiIndex, DataFrame, Series, CategoricalIndex) from pandas.util.testing import (assert_panel_equal, assert_frame_equal, assert_series_equal, assert_almost_equal) -from pandas.core.groupby.groupby import Grouping +from pandas.core.groupby.grouper import Grouping from pandas.compat import lrange, long from pandas import compat diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 17ca5d31b6b59..23b51b93d6a72 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -10,6 +10,7 @@ import pandas as pd from pandas import (DataFrame, date_range, Index, Series, MultiIndex, Timestamp, DatetimeIndex) +from pandas.core.groupby.ops import BinGrouper from pandas.compat import StringIO from pandas.util import testing as tm from pandas.util.testing import assert_frame_equal, assert_series_equal @@ -83,8 +84,7 @@ def test_groupby_with_timegrouper_methods(self, should_sort): g = df.groupby(pd.Grouper(freq='6M')) assert g.group_keys - import pandas.core.groupby.groupby - assert isinstance(g.grouper, pandas.core.groupby.groupby.BinGrouper) + assert isinstance(g.grouper, BinGrouper) groups = g.groups assert isinstance(groups, dict) assert len(groups) == 3 diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index f4a58b9cbe61b..3afc278f9bc93 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -13,7 +13,7 @@ 'mad', 'std', 'var', 'sem'] AGG_FUNCTIONS_WITH_SKIPNA = ['skew', 'mad'] -df_whitelist = frozenset([ +df_whitelist = [ 'last', 'first', 'mean', @@ -48,9 +48,15 @@ 'corr', 'cov', 'diff', -]) +] -s_whitelist = frozenset([ + +@pytest.fixture(params=df_whitelist) +def df_whitelist_fixture(request): + return request.param + + +s_whitelist = [ 'last', 'first', 'mean', @@ -89,7 +95,12 @@ 'nsmallest', 'is_monotonic_increasing', 'is_monotonic_decreasing', -]) +] + + +@pytest.fixture(params=s_whitelist) +def s_whitelist_fixture(request): + return request.param @pytest.fixture @@ -127,6 +138,13 @@ def df_letters(): (df_whitelist, s_whitelist))) def test_groupby_whitelist(df_letters, obj, whitelist): df = df_letters + gb = obj.groupby(df.letters) + + assert set(whitelist) == set(gb._apply_whitelist) + + +def check_whitelist(obj, df, m): + # check the obj for a particular whitelist m # these are aliases so ok to have the alias __name__ alias = {'bfill': 'backfill', @@ -135,29 +153,38 @@ def test_groupby_whitelist(df_letters, obj, whitelist): gb = obj.groupby(df.letters) - assert whitelist == gb._apply_whitelist - for m in whitelist: + m = alias.get(m, m) + if m is None: + return - m = alias.get(m, m) - if m is None: - continue + f = getattr(type(gb), m) - f = getattr(type(gb), m) + # name + try: + n = f.__name__ + except AttributeError: + return + assert n == m - # name + # qualname + if compat.PY3: try: - n = f.__name__ + n = f.__qualname__ except AttributeError: - continue - assert n == m - - # qualname - if compat.PY3: - try: - n = f.__qualname__ - except AttributeError: - continue - assert n.endswith(m) + return + assert n.endswith(m) + + +def test_groupby_series_whitelist(df_letters, s_whitelist_fixture): + m = s_whitelist_fixture + df = df_letters + check_whitelist(df.letters, df, m) + + +def test_groupby_frame_whitelist(df_letters, df_whitelist_fixture): + m = df_whitelist_fixture + df = df_letters + check_whitelist(df, df, m) @pytest.fixture diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 60f23309b11d9..d664a9060b684 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -11,27 +11,31 @@ import dateutil import numpy as np -import pandas as pd -import pandas.tseries.offsets as offsets +from pandas._libs.tslibs.period import IncompatibleFrequency +from pandas._libs.tslibs.ccalendar import DAYS, MONTHS + import pandas.util.testing as tm +from pandas.util.testing import (assert_series_equal, assert_almost_equal, + assert_frame_equal, assert_index_equal) + +import pandas as pd + from pandas import (Series, DataFrame, Panel, Index, isna, notna, Timestamp) from pandas.compat import range, lrange, zip, OrderedDict from pandas.errors import UnsupportedFunctionCall +import pandas.tseries.offsets as offsets +from pandas.tseries.frequencies import to_offset +from pandas.tseries.offsets import Minute, BDay + from pandas.core.groupby.groupby import DataError import pandas.core.common as com -from pandas.tseries.frequencies import to_offset from pandas.core.indexes.datetimes import date_range -from pandas.tseries.offsets import Minute, BDay from pandas.core.indexes.period import period_range, PeriodIndex, Period from pandas.core.resample import DatetimeIndex, TimeGrouper from pandas.core.indexes.timedeltas import timedelta_range, TimedeltaIndex -from pandas.util.testing import (assert_series_equal, assert_almost_equal, - assert_frame_equal, assert_index_equal) -from pandas._libs.tslibs.period import IncompatibleFrequency -from pandas._libs.tslibs.ccalendar import DAYS, MONTHS bday = BDay()
makes the impl of groupby a bit easier to grok. cc @WillAyd @TomAugspurger @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/21820
2018-07-08T20:42:37Z
2018-07-11T23:59:28Z
2018-07-11T23:59:28Z
2018-07-11T23:59:54Z
Modernize the fix for #10043
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 034a56b2ac0cb..767c4e8b85c95 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -425,6 +425,7 @@ Other - :meth: `~pandas.io.formats.style.Styler.background_gradient` now takes a ``text_color_threshold`` parameter to automatically lighten the text color based on the luminance of the background color. This improves readability with dark background colors without the need to limit the background colormap range. (:issue:`21258`) - Require at least 0.28.2 version of ``cython`` to support read-only memoryviews (:issue:`21688`) +- Utilize cython version to simplify the treatment of read-only memoryviews in take_nd (:issue:`10043`) - - - diff --git a/pandas/_libs/algos_take_helper.pxi.in b/pandas/_libs/algos_take_helper.pxi.in index 71bb1bb4fe9be..cef4098561eec 100644 --- a/pandas/_libs/algos_take_helper.pxi.in +++ b/pandas/_libs/algos_take_helper.pxi.in @@ -36,87 +36,6 @@ dtypes = [ def get_dispatch(dtypes): - inner_take_1d_template = """ - cdef: - Py_ssize_t i, n, idx - %(c_type_out)s fv - - n = indexer.shape[0] - - fv = fill_value - - %(nogil_str)s - %(tab)sfor i from 0 <= i < n: - %(tab)s idx = indexer[i] - %(tab)s if idx == -1: - %(tab)s out[i] = fv - %(tab)s else: - %(tab)s out[i] = %(preval)svalues[idx]%(postval)s -""" - - inner_take_2d_axis0_template = """\ - cdef: - Py_ssize_t i, j, k, n, idx - %(c_type_out)s fv - - n = len(indexer) - k = values.shape[1] - - fv = fill_value - - IF %(can_copy)s: - cdef: - %(c_type_out)s *v - %(c_type_out)s *o - - #GH3130 - if (values.strides[1] == out.strides[1] and - values.strides[1] == sizeof(%(c_type_out)s) and - sizeof(%(c_type_out)s) * n >= 256): - - for i from 0 <= i < n: - idx = indexer[i] - if idx == -1: - for j from 0 <= j < k: - out[i, j] = fv - else: - v = &values[idx, 0] - o = &out[i, 0] - memmove(o, v, <size_t>(sizeof(%(c_type_out)s) * k)) - return - - for i from 0 <= i < n: - idx = indexer[i] - if idx == -1: - for j from 0 <= j < k: - out[i, j] = fv - else: - for j from 0 <= j < k: - out[i, j] = %(preval)svalues[idx, j]%(postval)s -""" - - inner_take_2d_axis1_template = """\ - cdef: - Py_ssize_t i, j, k, n, idx - %(c_type_out)s fv - - n = len(values) - k = len(indexer) - - if n == 0 or k == 0: - return - - fv = fill_value - - for i from 0 <= i < n: - for j from 0 <= j < k: - idx = indexer[j] - if idx == -1: - out[i, j] = fv - else: - out[i, j] = %(preval)svalues[i, idx]%(postval)s -""" - for (name, dest, c_type_in, c_type_out, preval, postval, can_copy, nogil) in dtypes: if nogil: @@ -126,108 +45,112 @@ def get_dispatch(dtypes): nogil_str = '' tab = '' - args = dict(name=name, dest=dest, c_type_in=c_type_in, - c_type_out=c_type_out, preval=preval, postval=postval, - can_copy=can_copy, nogil_str=nogil_str, tab=tab) - - inner_take_1d = inner_take_1d_template % args - inner_take_2d_axis0 = inner_take_2d_axis0_template % args - inner_take_2d_axis1 = inner_take_2d_axis1_template % args - yield (name, dest, c_type_in, c_type_out, preval, postval, can_copy, - inner_take_1d, inner_take_2d_axis0, inner_take_2d_axis1) + nogil_str, tab) }} {{for name, dest, c_type_in, c_type_out, preval, postval, can_copy, - inner_take_1d, inner_take_2d_axis0, inner_take_2d_axis1 + nogil_str, tab in get_dispatch(dtypes)}} @cython.wraparound(False) @cython.boundscheck(False) -cdef inline take_1d_{{name}}_{{dest}}_memview({{c_type_in}}[:] values, - int64_t[:] indexer, - {{c_type_out}}[:] out, - fill_value=np.nan): - - -{{inner_take_1d}} - - -@cython.wraparound(False) -@cython.boundscheck(False) -def take_1d_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=1] values, - int64_t[:] indexer, +def take_1d_{{name}}_{{dest}}({{if c_type_in != 'object'}}const{{endif}} {{c_type_in}}[:] values, + const int64_t[:] indexer, {{c_type_out}}[:] out, fill_value=np.nan): + cdef: + Py_ssize_t i, n, idx + {{c_type_out}} fv - if values.flags.writeable: - # We can call the memoryview version of the code - take_1d_{{name}}_{{dest}}_memview(values, indexer, out, - fill_value=fill_value) - return - - # We cannot use the memoryview version on readonly-buffers due to - # a limitation of Cython's typed memoryviews. Instead we can use - # the slightly slower Cython ndarray type directly. -{{inner_take_1d}} + n = indexer.shape[0] + fv = fill_value -@cython.wraparound(False) -@cython.boundscheck(False) -cdef inline take_2d_axis0_{{name}}_{{dest}}_memview({{c_type_in}}[:, :] values, - int64_t[:] indexer, - {{c_type_out}}[:, :] out, - fill_value=np.nan): -{{inner_take_2d_axis0}} + {{nogil_str}} + {{tab}}for i from 0 <= i < n: + {{tab}} idx = indexer[i] + {{tab}} if idx == -1: + {{tab}} out[i] = fv + {{tab}} else: + {{tab}} out[i] = {{preval}}values[idx]{{postval}} @cython.wraparound(False) @cython.boundscheck(False) -def take_2d_axis0_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=2] values, - ndarray[int64_t] indexer, +def take_2d_axis0_{{name}}_{{dest}}({{if c_type_in != 'object'}}const{{endif}} {{c_type_in}}[:, :] values, + const int64_t[:] indexer, {{c_type_out}}[:, :] out, fill_value=np.nan): - if values.flags.writeable: - # We can call the memoryview version of the code - take_2d_axis0_{{name}}_{{dest}}_memview(values, indexer, out, - fill_value=fill_value) - return + cdef: + Py_ssize_t i, j, k, n, idx + {{c_type_out}} fv - # We cannot use the memoryview version on readonly-buffers due to - # a limitation of Cython's typed memoryviews. Instead we can use - # the slightly slower Cython ndarray type directly. -{{inner_take_2d_axis0}} + n = len(indexer) + k = values.shape[1] + fv = fill_value -@cython.wraparound(False) -@cython.boundscheck(False) -cdef inline take_2d_axis1_{{name}}_{{dest}}_memview({{c_type_in}}[:, :] values, - int64_t[:] indexer, - {{c_type_out}}[:, :] out, - fill_value=np.nan): -{{inner_take_2d_axis1}} + {{if can_copy}} + cdef: + {{c_type_out}} *v + {{c_type_out}} *o + + #GH3130 + if (values.strides[1] == out.strides[1] and + values.strides[1] == sizeof({{c_type_out}}) and + sizeof({{c_type_out}}) * n >= 256): + + for i from 0 <= i < n: + idx = indexer[i] + if idx == -1: + for j from 0 <= j < k: + out[i, j] = fv + else: + v = &values[idx, 0] + o = &out[i, 0] + memmove(o, v, <size_t>(sizeof({{c_type_out}}) * k)) + return + {{endif}} + + for i from 0 <= i < n: + idx = indexer[i] + if idx == -1: + for j from 0 <= j < k: + out[i, j] = fv + else: + for j from 0 <= j < k: + out[i, j] = {{preval}}values[idx, j]{{postval}} @cython.wraparound(False) @cython.boundscheck(False) -def take_2d_axis1_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=2] values, - ndarray[int64_t] indexer, +def take_2d_axis1_{{name}}_{{dest}}({{if c_type_in != 'object'}}const{{endif}} {{c_type_in}}[:, :] values, + const int64_t[:] indexer, {{c_type_out}}[:, :] out, fill_value=np.nan): + cdef: + Py_ssize_t i, j, k, n, idx + {{c_type_out}} fv - if values.flags.writeable: - # We can call the memoryview version of the code - take_2d_axis1_{{name}}_{{dest}}_memview(values, indexer, out, - fill_value=fill_value) + n = len(values) + k = len(indexer) + + if n == 0 or k == 0: return - # We cannot use the memoryview version on readonly-buffers due to - # a limitation of Cython's typed memoryviews. Instead we can use - # the slightly slower Cython ndarray type directly. -{{inner_take_2d_axis1}} + fv = fill_value + + for i from 0 <= i < n: + for j from 0 <= j < k: + idx = indexer[j] + if idx == -1: + out[i, j] = fv + else: + out[i, j] = {{preval}}values[i, idx]{{postval}} @cython.wraparound(False)
- [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21817
2018-07-08T19:23:33Z
2018-09-25T16:45:56Z
null
2018-09-25T16:45:56Z
update tslibs imports
diff --git a/pandas/_libs/__init__.py b/pandas/_libs/__init__.py index b4c3ff8008015..ad72980105c4f 100644 --- a/pandas/_libs/__init__.py +++ b/pandas/_libs/__init__.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # flake8: noqa -from .tslib import iNaT, NaT, Timestamp, Timedelta, OutOfBoundsDatetime +from .tslibs import iNaT, NaT, Timestamp, Timedelta, OutOfBoundsDatetime # TODO # period is directly dependent on tslib and imports python diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 41047d9c25c22..5b41057c5052f 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -25,8 +25,7 @@ from tslibs.conversion cimport maybe_datetimelike_to_i8 from hashtable cimport HashTable from pandas._libs import algos, hashtable as _hash -from pandas._libs.tslibs import period as periodlib -from pandas._libs.tslib import Timestamp, Timedelta +from pandas._libs.tslibs import Timestamp, Timedelta, period as periodlib from pandas._libs.missing import checknull cdef int64_t iNaT = util.get_nat() diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index fbb7265a17f8b..4129132251682 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -5,7 +5,7 @@ cimport util cimport cython import cython from numpy cimport ndarray -from tslib import Timestamp +from tslibs import Timestamp from tslibs.timezones cimport tz_compare from cpython.object cimport (Py_EQ, Py_NE, Py_GT, Py_LT, Py_GE, Py_LE, diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index ae9d240afcb93..23aebc85e6300 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1,6 +1,5 @@ +# -*- coding: utf-8 -*- # cython: profile=False -import operator - cimport cython from cython cimport Py_ssize_t diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index 79c30ac5f3778..6161a55b22342 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -15,7 +15,6 @@ cimport util from tslibs.np_datetime cimport get_timedelta64_value, get_datetime64_value from tslibs.nattype import NaT -from tslibs.nattype cimport is_null_datetimelike cdef double INF = <double> np.inf cdef double NEGINF = -INF diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx index 1d7893f69c31d..4fd1fd0f37b1d 100644 --- a/pandas/_libs/reshape.pyx +++ b/pandas/_libs/reshape.pyx @@ -4,11 +4,9 @@ cimport cython from cython cimport Py_ssize_t import numpy as np -cimport numpy as cnp from numpy cimport (ndarray, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t, float32_t, float64_t) -cnp.import_array() cdef double NaN = <double> np.NaN diff --git a/pandas/_libs/src/util.pxd b/pandas/_libs/src/util.pxd index 2c1876fad95d2..a8cd78016665f 100644 --- a/pandas/_libs/src/util.pxd +++ b/pandas/_libs/src/util.pxd @@ -100,6 +100,7 @@ cdef extern from "headers/stdint.h": enum: INT64_MAX enum: INT64_MIN + cdef inline object get_value_at(ndarray arr, object loc): cdef: Py_ssize_t i, sz @@ -119,6 +120,7 @@ cdef inline object get_value_at(ndarray arr, object loc): return get_value_1d(arr, i) + cdef inline set_value_at_unsafe(ndarray arr, object loc, object value): """Sets a value into the array without checking the writeable flag. @@ -153,12 +155,14 @@ cdef inline set_value_at(ndarray arr, object loc, object value): cdef inline is_array(object o): return cnp.PyArray_Check(o) + cdef inline bint _checknull(object val): try: return val is None or (cpython.PyFloat_Check(val) and val != val) except ValueError: return False + cdef inline bint is_period_object(object val): return getattr(val, '_typ', '_typ') == 'period' diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index c1a0e58a4fb1a..281e497945c5f 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -38,14 +38,12 @@ import pytz from tslibs.timedeltas cimport cast_from_unit -from tslibs.timedeltas import Timedelta, ints_to_pytimedelta # noqa:F841 from tslibs.timezones cimport (is_utc, is_tzlocal, is_fixed_offset, treat_tz_as_pytz, get_dst_info) from tslibs.conversion cimport (tz_convert_single, _TSObject, convert_datetime_to_tsobject, get_datetime64_nanos, tz_convert_utc_to_tzlocal) -from tslibs.conversion import tz_convert_single, normalize_date # noqa:F841 from tslibs.nattype import NaT, nat_strings, iNaT from tslibs.nattype cimport checknull_with_nat, NPY_NAT diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx index 56dcd5c405c6b..7803595badee1 100644 --- a/pandas/_libs/tslibs/frequencies.pyx +++ b/pandas/_libs/tslibs/frequencies.pyx @@ -5,7 +5,6 @@ import re cimport cython cimport numpy as cnp -from numpy cimport int64_t cnp.import_array() from util cimport is_integer_object, is_string_object diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 1b319e12f06d5..27b7f03358a3a 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -11,7 +11,6 @@ from cpython.datetime cimport (PyDateTime_IMPORT, PyDateTime_CheckExact, PyDateTime_IMPORT from dateutil.relativedelta import relativedelta -from pytz import UTC import numpy as np cimport numpy as cnp @@ -24,7 +23,6 @@ from util cimport is_string_object, is_integer_object from ccalendar import MONTHS, DAYS from ccalendar cimport get_days_in_month, dayofweek from conversion cimport tz_convert_single, pydt_to_i8, localize_pydatetime -from frequencies cimport get_freq_code from nattype cimport NPY_NAT from np_datetime cimport (pandas_datetimestruct, dtstruct_to_dt64, dt64_to_dtstruct) diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 2ecd55ea88170..f5048d32e826b 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -6,10 +6,6 @@ Parsing functions for datetime and datetime-like strings. import sys import re -from cpython cimport PyString_Check, PyUnicode_Check - -from libc.stdlib cimport free - cimport cython from cython cimport Py_ssize_t @@ -34,7 +30,6 @@ else: # dateutil compat from dateutil.tz import (tzoffset, tzlocal as _dateutil_tzlocal, - tzfile as _dateutil_tzfile, tzutc as _dateutil_tzutc, tzstr as _dateutil_tzstr) from dateutil.relativedelta import relativedelta diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index d89c06d43ccb9..d4b7c00d78857 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # cython: profile=False -from datetime import datetime, date, timedelta +from datetime import datetime, date from cpython cimport ( PyUnicode_Check, @@ -37,7 +37,7 @@ cimport util from util cimport is_period_object, is_string_object, INT32_MIN from timestamps import Timestamp -from timezones cimport is_utc, is_tzlocal, get_utcoffset, get_dst_info +from timezones cimport is_utc, is_tzlocal, get_dst_info from timedeltas cimport delta_to_nanoseconds cimport ccalendar diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 8565857fa945f..c10e108081f02 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -15,12 +15,10 @@ from pandas._libs.khash cimport (khiter_t, kh_init_int64, kh_int64_t, kh_resize_int64, kh_get_int64) -from cpython.datetime cimport datetime - from np_datetime cimport pandas_datetimestruct, dt64_to_dtstruct from frequencies cimport get_freq_code from timezones cimport (is_utc, is_tzlocal, - maybe_get_tz, get_dst_info, get_utcoffset) + maybe_get_tz, get_dst_info) from fields import build_field_sarray from conversion import tz_convert from conversion cimport tz_convert_utc_to_tzlocal diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 77ce8e4ed4127..5b3d4399a6e10 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -31,7 +31,6 @@ import numpy as np from numpy cimport ndarray, int64_t from datetime import date as datetime_date -from cpython.datetime cimport datetime from np_datetime cimport (check_dts_bounds, dtstruct_to_dt64, pandas_datetimestruct) diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index 5121d293efcb6..9e704a9bd8d3f 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -20,8 +20,7 @@ cdef extern from "../src/headers/cmath" namespace "std": cimport util from util cimport numeric -from skiplist cimport (IndexableSkiplist, - node_t, skiplist_t, +from skiplist cimport (skiplist_t, skiplist_init, skiplist_destroy, skiplist_get, skiplist_insert, skiplist_remove) diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index af0fa2c3477f4..aaa2f2c9201bc 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -3,8 +3,8 @@ import numpy as np -from pandas._libs import tslib -from pandas._libs.tslib import Timedelta, NaT +from pandas._libs import tslibs +from pandas._libs.tslibs import Timedelta, NaT from pandas._libs.tslibs.fields import get_timedelta_field from pandas._libs.tslibs.timedeltas import array_to_timedelta64 @@ -148,7 +148,7 @@ def to_pytimedelta(self): ------- datetimes : ndarray """ - return tslib.ints_to_pytimedelta(self.asi8) + return tslibs.ints_to_pytimedelta(self.asi8) days = _field_accessor("days", "days", " Number of days for each element. ") diff --git a/pandas/core/common.py b/pandas/core/common.py index 7aa092c2354da..0a33873630d27 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -8,7 +8,7 @@ import collections import numpy as np -from pandas._libs import lib, tslib +from pandas._libs import lib, tslibs from pandas import compat from pandas.compat import long, zip, iteritems, PY36, OrderedDict @@ -87,9 +87,9 @@ def _maybe_box_datetimelike(value): # turn a datetime like into a Timestamp/timedelta as needed if isinstance(value, (np.datetime64, datetime)): - value = tslib.Timestamp(value) + value = tslibs.Timestamp(value) elif isinstance(value, (np.timedelta64, timedelta)): - value = tslib.Timedelta(value) + value = tslibs.Timedelta(value) return value diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 2cd8144e43cea..0bc6ad8499934 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -5,8 +5,8 @@ import numpy as np import warnings -from pandas._libs import tslib, lib -from pandas._libs.tslib import iNaT +from pandas._libs import tslib, lib, tslibs +from pandas._libs.tslibs import iNaT from pandas.compat import string_types, text_type, PY3 from .common import (_ensure_object, is_bool, is_integer, is_float, is_complex, is_datetimetz, is_categorical_dtype, @@ -278,14 +278,14 @@ def maybe_promote(dtype, fill_value=np.nan): else: if issubclass(dtype.type, np.datetime64): try: - fill_value = tslib.Timestamp(fill_value).value + fill_value = tslibs.Timestamp(fill_value).value except Exception: # the proper thing to do here would probably be to upcast # to object (but numpy 1.6.1 doesn't do this properly) fill_value = iNaT elif issubclass(dtype.type, np.timedelta64): try: - fill_value = tslib.Timedelta(fill_value).value + fill_value = tslibs.Timedelta(fill_value).value except Exception: # as for datetimes, cannot upcast to object fill_value = iNaT @@ -393,8 +393,8 @@ def infer_dtype_from_scalar(val, pandas_dtype=False): dtype = np.object_ elif isinstance(val, (np.datetime64, datetime)): - val = tslib.Timestamp(val) - if val is tslib.NaT or val.tz is None: + val = tslibs.Timestamp(val) + if val is tslibs.NaT or val.tz is None: dtype = np.dtype('M8[ns]') else: if pandas_dtype: @@ -405,7 +405,7 @@ def infer_dtype_from_scalar(val, pandas_dtype=False): val = val.value elif isinstance(val, (np.timedelta64, timedelta)): - val = tslib.Timedelta(val).value + val = tslibs.Timedelta(val).value dtype = np.dtype('m8[ns]') elif is_bool(val): @@ -625,7 +625,7 @@ def conv(r, dtype): if isna(r): pass elif dtype == _NS_DTYPE: - r = tslib.Timestamp(r) + r = tslibs.Timestamp(r) elif dtype == _TD_DTYPE: r = _coerce_scalar_to_timedelta_type(r) elif dtype == np.bool_: @@ -679,7 +679,7 @@ def astype_nansafe(arr, dtype, copy=True): elif is_timedelta64_dtype(arr): if is_object_dtype(dtype): - return tslib.ints_to_pytimedelta(arr.view(np.int64)) + return tslibs.ints_to_pytimedelta(arr.view(np.int64)) elif dtype == np.int64: return arr.view(dtype) diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 9f6813bc38464..285e386e25613 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -3,7 +3,7 @@ """ import numpy as np -import pandas._libs.tslib as tslib +from pandas._libs import tslib, tslibs from pandas import compat from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -486,7 +486,7 @@ def _convert_datetimelike_to_object(x): elif x.dtype == _TD_DTYPE: shape = x.shape - x = tslib.ints_to_pytimedelta(x.view(np.int64).ravel(), box=True) + x = tslibs.ints_to_pytimedelta(x.view(np.int64).ravel(), box=True) x = x.reshape(shape) return x diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index ad4588f254174..6683612eb8a3e 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -3,7 +3,7 @@ """ import numpy as np from pandas._libs import lib, missing as libmissing -from pandas._libs.tslib import NaT, iNaT +from pandas._libs.tslibs import NaT, iNaT from .generic import (ABCMultiIndex, ABCSeries, ABCIndexClass, ABCGeneric, ABCExtensionArray) diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 6f4fdfe5bf5cd..2286033e97d85 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -17,8 +17,7 @@ from pandas.core.indexes.datetimes import DatetimeIndex import pandas.core.common as com -from pandas._libs import lib -from pandas._libs.tslib import NaT +from pandas._libs import lib, NaT _sort_msg = textwrap.dedent("""\ Sorting because non-concatenation axis is not aligned. A future version diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index d7dda62ff2ac1..2fbd648096d5c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4,7 +4,7 @@ from textwrap import dedent import numpy as np -from pandas._libs import (lib, index as libindex, tslib as libts, +from pandas._libs import (lib, index as libindex, tslibs, algos as libalgos, join as libjoin, Timedelta) from pandas._libs.lib import is_datetime_array @@ -407,7 +407,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, try: return DatetimeIndex(subarr, copy=copy, name=name, **kwargs) - except libts.OutOfBoundsDatetime: + except tslibs.OutOfBoundsDatetime: pass elif inferred.startswith('timedelta'): diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 53b1186b37a90..2ee91d008dd02 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -53,7 +53,7 @@ import pandas.tseries.offsets as offsets import pandas.core.tools.datetimes as tools -from pandas._libs import (lib, index as libindex, tslib as libts, +from pandas._libs import (lib, index as libindex, tslibs, tslib as libts, join as libjoin, Timestamp) from pandas._libs.tslibs import (timezones, conversion, fields, parsing, ccalendar) @@ -494,14 +494,14 @@ def _generate(cls, start, end, periods, name, freq, if start is not None: if normalize: - start = libts.normalize_date(start) + start = tslibs.normalize_date(start) _normalized = True else: _normalized = _normalized and start.time() == _midnight if end is not None: if normalize: - end = libts.normalize_date(end) + end = tslibs.normalize_date(end) _normalized = True else: _normalized = _normalized and end.time() == _midnight @@ -796,10 +796,10 @@ def _sub_datelike(self, other): .format(cls=type(self).__name__)) result = self._sub_datelike_dti(other) elif isinstance(other, (datetime, np.datetime64)): - assert other is not libts.NaT + assert other is not tslibs.NaT other = Timestamp(other) - if other is libts.NaT: - return self - libts.NaT + if other is tslibs.NaT: + return self - tslibs.NaT # require tz compat elif not self._has_same_tz(other): raise TypeError("Timestamp subtraction must have the same " @@ -809,7 +809,7 @@ def _sub_datelike(self, other): result = checked_add_with_arr(i8, -other.value, arr_mask=self._isnan) result = self._maybe_mask_results(result, - fill_value=libts.iNaT) + fill_value=tslibs.iNaT) else: raise TypeError("cannot subtract {cls} and {typ}" .format(cls=type(self).__name__, diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e42953d618659..208d7b8bcf8a7 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -74,10 +74,9 @@ import pandas.core.missing as missing from pandas.core.sparse.array import _maybe_to_sparse, SparseArray -from pandas._libs import lib, tslib -from pandas._libs.tslib import Timedelta +from pandas._libs import lib, tslib, tslibs +from pandas._libs.tslibs import conversion, Timedelta from pandas._libs.internals import BlockPlacement -from pandas._libs.tslibs import conversion from pandas.util._decorators import cache_readonly from pandas.util._validators import validate_bool_kwarg @@ -2140,11 +2139,11 @@ def _holder(self): @property def _na_value(self): - return tslib.NaT + return tslibs.NaT @property def fill_value(self): - return tslib.iNaT + return tslibs.iNaT def get_values(self, dtype=None): """ @@ -2175,7 +2174,7 @@ def _holder(self): @property def _box_func(self): - return lambda x: tslib.Timedelta(x, unit='ns') + return lambda x: Timedelta(x, unit='ns') def _can_hold_element(self, element): tipo = maybe_infer_dtype_type(element) @@ -2214,7 +2213,7 @@ def _try_coerce_args(self, values, other): if isinstance(other, bool): raise TypeError elif is_null_datelike_scalar(other): - other = tslib.iNaT + other = tslibs.iNaT other_mask = True elif isinstance(other, Timedelta): other_mask = isna(other) @@ -2240,7 +2239,7 @@ def _try_coerce_result(self, result): mask = isna(result) if result.dtype.kind in ['i', 'f', 'O']: result = result.astype('m8[ns]') - result[mask] = tslib.iNaT + result[mask] = tslibs.iNaT elif isinstance(result, (np.integer, np.float)): result = self._box_func(result) return result @@ -2714,7 +2713,7 @@ def _try_coerce_args(self, values, other): if isinstance(other, bool): raise TypeError elif is_null_datelike_scalar(other): - other = tslib.iNaT + other = tslibs.iNaT other_mask = True elif isinstance(other, (datetime, np.datetime64, date)): other = self._box_func(other) @@ -2747,7 +2746,7 @@ def _try_coerce_result(self, result): @property def _box_func(self): - return tslib.Timestamp + return tslibs.Timestamp def to_native_types(self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs): @@ -2892,7 +2891,7 @@ def _try_coerce_args(self, values, other): raise TypeError elif (is_null_datelike_scalar(other) or (is_scalar(other) and isna(other))): - other = tslib.iNaT + other = tslibs.iNaT other_mask = True elif isinstance(other, self._holder): if other.tz != self.values.tz: @@ -2900,7 +2899,7 @@ def _try_coerce_args(self, values, other): other_mask = _block_shape(isna(other), ndim=self.ndim) other = _block_shape(other.asi8, ndim=self.ndim) elif isinstance(other, (np.datetime64, datetime, date)): - other = tslib.Timestamp(other) + other = tslibs.Timestamp(other) tz = getattr(other, 'tz', None) # test we can have an equal time zone @@ -2919,7 +2918,7 @@ def _try_coerce_result(self, result): if result.dtype.kind in ['i', 'f', 'O']: result = result.astype('M8[ns]') elif isinstance(result, (np.integer, np.float, np.datetime64)): - result = tslib.Timestamp(result, tz=self.values.tz) + result = tslibs.Timestamp(result, tz=self.values.tz) if isinstance(result, np.ndarray): # allow passing of > 1dim if its trivial if result.ndim > 1: @@ -2930,7 +2929,7 @@ def _try_coerce_result(self, result): @property def _box_func(self): - return lambda x: tslib.Timestamp(x, tz=self.dtype.tz) + return lambda x: tslibs.Timestamp(x, tz=self.dtype.tz) def shift(self, periods, axis=0, mgr=None): """ shift the block by periods """ @@ -2948,9 +2947,9 @@ def shift(self, periods, axis=0, mgr=None): new_values = self.values.asi8.take(indexer) if periods > 0: - new_values[:periods] = tslib.iNaT + new_values[:periods] = tslibs.iNaT else: - new_values[periods:] = tslib.iNaT + new_values[periods:] = tslibs.iNaT new_values = self.values._shallow_copy(new_values) return [self.make_block_same_class(new_values, @@ -5540,11 +5539,11 @@ def get_empty_dtype_and_na(join_units): return np.dtype(np.object_), np.nan elif 'datetimetz' in upcast_classes: dtype = upcast_classes['datetimetz'] - return dtype[0], tslib.iNaT + return dtype[0], tslibs.iNaT elif 'datetime' in upcast_classes: - return np.dtype('M8[ns]'), tslib.iNaT + return np.dtype('M8[ns]'), tslibs.iNaT elif 'timedelta' in upcast_classes: - return np.dtype('m8[ns]'), tslib.iNaT + return np.dtype('m8[ns]'), tslibs.iNaT else: # pragma g = np.find_common_type(upcast_classes, []) if is_float_dtype(g): diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 90333c23817c5..de31c6ac11c3f 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -6,7 +6,7 @@ import numpy as np from pandas import compat -from pandas._libs import tslib, lib +from pandas._libs import tslibs, lib from pandas.core.dtypes.common import ( _get_dtype, is_float, is_scalar, @@ -190,13 +190,13 @@ def _get_fill_value(dtype, fill_value=None, fill_value_typ=None): return -np.inf else: if fill_value_typ is None: - return tslib.iNaT + return tslibs.iNaT else: if fill_value_typ == '+inf': # need the max int here return _int64_max else: - return tslib.iNaT + return tslibs.iNaT def _get_values(values, skipna, fill_value=None, fill_value_typ=None, @@ -268,7 +268,7 @@ def _wrap_results(result, dtype): if is_datetime64_dtype(dtype): if not isinstance(result, np.ndarray): - result = tslib.Timestamp(result) + result = tslibs.Timestamp(result) else: result = result.view(dtype) elif is_timedelta64_dtype(dtype): @@ -278,7 +278,7 @@ def _wrap_results(result, dtype): if np.fabs(result) > _int64_max: raise ValueError("overflow in timedelta operation") - result = tslib.Timedelta(result, unit='ns') + result = tslibs.Timedelta(result, unit='ns') else: result = result.astype('i8').view(dtype) @@ -722,7 +722,7 @@ def _maybe_null_out(result, axis, mask, min_count=1): else: # GH12941, use None to auto cast null result[null_mask] = None - elif result is not tslib.NaT: + elif result is not tslibs.NaT: null_mask = mask.size - mask.sum() if null_mask < min_count: result = np.nan diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 0b0fcacc1bc48..7b487f37c0f2f 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -24,8 +24,8 @@ import pandas.compat as compat from pandas.compat.numpy import function as nv -from pandas._libs import lib, tslib -from pandas._libs.tslib import Timestamp +from pandas._libs import lib +from pandas._libs.tslibs import Timestamp, NaT from pandas._libs.tslibs.period import IncompatibleFrequency from pandas.util._decorators import Appender, Substitution @@ -1345,8 +1345,8 @@ def _get_time_bins(self, ax): labels = labels[:-1] if ax.hasnans: - binner = binner.insert(0, tslib.NaT) - labels = labels.insert(0, tslib.NaT) + binner = binner.insert(0, NaT) + labels = labels.insert(0, NaT) # if we end up with more labels than bins # adjust the labels @@ -1461,8 +1461,8 @@ def _get_period_bins(self, ax): # shift bins by the number of NaT bins += nat_count bins = np.insert(bins, 0, nat_count) - binner = binner.insert(0, tslib.NaT) - labels = labels.insert(0, tslib.NaT) + binner = binner.insert(0, NaT) + labels = labels.insert(0, NaT) return binner, bins, labels diff --git a/pandas/core/series.py b/pandas/core/series.py index db3d02ad7b3d5..303978c8ed46e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -76,7 +76,7 @@ Appender, deprecate, deprecate_kwarg, Substitution) from pandas.util._validators import validate_bool_kwarg -from pandas._libs import index as libindex, tslib as libts, lib, iNaT +from pandas._libs import index as libindex, tslibs, lib, iNaT from pandas.core.config import get_option from pandas.core.strings import StringMethods from pandas.core.tools.datetimes import to_datetime @@ -380,7 +380,7 @@ def _set_axis(self, axis, labels, fastpath=False): # need to set here because we changed the index if fastpath: self._data.set_axis(axis, labels) - except (libts.OutOfBoundsDatetime, ValueError): + except (tslibs.OutOfBoundsDatetime, ValueError): # labels may exceeds datetime bounds, # or not be a DatetimeIndex pass diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index a99c913f95e82..c8204faa55cf8 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -4,9 +4,9 @@ import numpy as np -from pandas._libs import tslib +from pandas._libs import tslib, tslibs from pandas._libs.tslibs.strptime import array_strptime -from pandas._libs.tslibs import parsing, conversion +from pandas._libs.tslibs import parsing, conversion, Timestamp from pandas._libs.tslibs.parsing import ( # noqa parse_time_string, DateParseError, @@ -131,7 +131,7 @@ def _return_parsed_timezone_results(result, timezones, box, tz): raise ValueError("Cannot pass a tz argument when " "parsing strings with timezone " "information.") - tz_results = np.array([tslib.Timestamp(res).tz_localize(zone) for res, zone + tz_results = np.array([Timestamp(res).tz_localize(zone) for res, zone in zip(result, timezones)]) if box: from pandas import Index @@ -252,7 +252,7 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None, if '%Z' in format or '%z' in format: return _return_parsed_timezone_results( result, timezones, box, tz) - except tslib.OutOfBoundsDatetime: + except tslibs.OutOfBoundsDatetime: if errors == 'raise': raise result = arg @@ -307,7 +307,7 @@ def _adjust_to_origin(arg, origin, unit): """ if origin == 'julian': original = arg - j0 = tslib.Timestamp(0).to_julian_date() + j0 = Timestamp(0).to_julian_date() if unit != 'D': raise ValueError("unit must be 'D' for origin='julian'") try: @@ -317,10 +317,10 @@ def _adjust_to_origin(arg, origin, unit): "'origin'='julian'") # premptively check this for a nice range - j_max = tslib.Timestamp.max.to_julian_date() - j0 - j_min = tslib.Timestamp.min.to_julian_date() - j0 + j_max = Timestamp.max.to_julian_date() - j0 + j_min = Timestamp.min.to_julian_date() - j0 if np.any(arg > j_max) or np.any(arg < j_min): - raise tslib.OutOfBoundsDatetime( + raise tslibs.OutOfBoundsDatetime( "{original} is Out of Bounds for " "origin='julian'".format(original=original)) else: @@ -335,9 +335,9 @@ def _adjust_to_origin(arg, origin, unit): # we are going to offset back to unix / epoch time try: - offset = tslib.Timestamp(origin) - except tslib.OutOfBoundsDatetime: - raise tslib.OutOfBoundsDatetime( + offset = Timestamp(origin) + except tslibs.OutOfBoundsDatetime: + raise tslibs.OutOfBoundsDatetime( "origin {origin} is Out of Bounds".format(origin=origin)) except ValueError: raise ValueError("origin {origin} cannot be converted " @@ -346,11 +346,11 @@ def _adjust_to_origin(arg, origin, unit): if offset.tz is not None: raise ValueError( "origin offset {} must be tz-naive".format(offset)) - offset -= tslib.Timestamp(0) + offset -= Timestamp(0) # convert the offset to the unit of the arg # this should be lossless in terms of precision - offset = offset // tslib.Timedelta(1, unit=unit) + offset = offset // tslibs.Timedelta(1, unit=unit) # scalars & ndarray-like can handle the addition if is_list_like(arg) and not isinstance( @@ -538,7 +538,7 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, errors=errors, exact=exact, infer_datetime_format=infer_datetime_format) - if isinstance(arg, tslib.Timestamp): + if isinstance(arg, Timestamp): result = arg elif isinstance(arg, ABCSeries): cache_array = _maybe_cache(arg, format, cache, convert_listlike) @@ -701,7 +701,7 @@ def calc(carg): def calc_with_mask(carg, mask): result = np.empty(carg.shape, dtype='M8[ns]') iresult = result.view('i8') - iresult[~mask] = tslib.iNaT + iresult[~mask] = tslibs.iNaT result[mask] = calc(carg[mask].astype(np.float64).astype(np.int64)). \ astype('M8[ns]') return result diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 94e2f2342bd51..29618fb4dec52 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -4,7 +4,7 @@ import numpy as np import pandas as pd -import pandas._libs.tslib as tslib +from pandas._libs import tslibs from pandas._libs.tslibs.timedeltas import (convert_to_timedelta64, array_to_timedelta64) @@ -153,7 +153,7 @@ def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'): result = pd.NaT if box: - result = tslib.Timedelta(result) + result = tslibs.Timedelta(result) return result diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index 7edb5b16ce77a..cc3f140d70832 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -4,7 +4,7 @@ import itertools import numpy as np -from pandas._libs import hashing, tslib +from pandas._libs import hashing, tslibs from pandas.core.dtypes.generic import ( ABCMultiIndex, ABCIndexClass, @@ -321,8 +321,8 @@ def _hash_scalar(val, encoding='utf8', hash_key=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, tslib.Timestamp): - val = tslib.Timestamp(val) + if not isinstance(val, tslibs.Timestamp): + val = tslibs.Timestamp(val) val = val.tz_convert(None) dtype, val = infer_dtype_from_scalar(val) diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index f2794574944e7..147c43b30d45f 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -4,7 +4,7 @@ Expose public exceptions & warnings """ -from pandas._libs.tslib import OutOfBoundsDatetime +from pandas._libs.tslibs import OutOfBoundsDatetime class PerformanceWarning(Warning): diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 2133d0c981b71..3ae1d71e36714 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -7,6 +7,17 @@ from __future__ import print_function # pylint: disable=W0141 +from functools import partial + +import numpy as np + +from pandas._libs import lib +from pandas._libs.tslibs import iNaT, Timestamp, Timedelta +from pandas._libs.tslib import format_array_from_datetime + +from pandas import compat +from pandas.compat import StringIO, lzip, map, zip, u + from pandas.core.dtypes.missing import isna, notna from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -26,23 +37,16 @@ from pandas.core.base import PandasObject import pandas.core.common as com from pandas.core.index import Index, MultiIndex, _ensure_index -from pandas import compat -from pandas.compat import (StringIO, lzip, map, zip, u) +from pandas.core.config import get_option, set_option +from pandas.core.indexes.datetimes import DatetimeIndex +from pandas.core.indexes.period import PeriodIndex from pandas.io.formats.terminal import get_terminal_size -from pandas.core.config import get_option, set_option from pandas.io.common import (_expand_user, _stringify_path) from pandas.io.formats.printing import adjoin, justify, pprint_thing -from pandas._libs import lib -from pandas._libs.tslib import (iNaT, Timestamp, Timedelta, - format_array_from_datetime) -from pandas.core.indexes.datetimes import DatetimeIndex -from pandas.core.indexes.period import PeriodIndex import pandas as pd -import numpy as np -from functools import partial common_docstring = """ Parameters diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py index 9992be521d61f..3ec5e8d9be955 100644 --- a/pandas/io/json/json.py +++ b/pandas/io/json/json.py @@ -4,7 +4,7 @@ import numpy as np import pandas._libs.json as json -from pandas._libs.tslib import iNaT +from pandas._libs.tslibs import iNaT from pandas.compat import StringIO, long, u, to_str from pandas import compat, isna from pandas import Series, DataFrame, to_datetime, MultiIndex diff --git a/pandas/io/stata.py b/pandas/io/stata.py index c3af5d214317a..297a24fa3a149 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -18,7 +18,7 @@ import numpy as np from dateutil.relativedelta import relativedelta from pandas._libs.lib import infer_dtype -from pandas._libs.tslib import NaT, Timestamp +from pandas._libs.tslibs import NaT, Timestamp from pandas._libs.writers import max_len_string_array import pandas as pd diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index f413e4177b386..97e0d0b4608ae 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -23,7 +23,7 @@ from pandas.compat import lrange import pandas.compat as compat -from pandas._libs import tslib +from pandas._libs import tslibs import pandas.core.common as com from pandas.core.index import Index @@ -52,7 +52,7 @@ def get_pairs(): pairs = [ - (tslib.Timestamp, DatetimeConverter), + (tslibs.Timestamp, DatetimeConverter), (Period, PeriodConverter), (pydt.datetime, DatetimeConverter), (pydt.date, DatetimeConverter), @@ -312,7 +312,7 @@ def try_parse(values): if isinstance(values, (datetime, pydt.date)): return _dt_to_float_ordinal(values) elif isinstance(values, np.datetime64): - return _dt_to_float_ordinal(tslib.Timestamp(values)) + return _dt_to_float_ordinal(tslibs.Timestamp(values)) elif isinstance(values, pydt.time): return dates.date2num(values) elif (is_integer(values) or is_float(values)): diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 166af4c89877d..a323e2487e356 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -13,7 +13,7 @@ import pandas.util.testing as tm import pandas as pd -from pandas._libs.tslib import Timestamp, Timedelta +from pandas._libs.tslibs import Timestamp, Timedelta from pandas.tests.indexes.common import Base diff --git a/pandas/tests/tslibs/test_tslib.py b/pandas/tests/tslibs/test_tslib.py index 484ec71cdc4c1..0df9328d0db16 100644 --- a/pandas/tests/tslibs/test_tslib.py +++ b/pandas/tests/tslibs/test_tslib.py @@ -3,21 +3,21 @@ from datetime import datetime, date -from pandas._libs import tslib +from pandas._libs import tslibs def test_normalize_date(): value = date(2012, 9, 7) - result = tslib.normalize_date(value) + result = tslibs.normalize_date(value) assert (result == datetime(2012, 9, 7)) value = datetime(2012, 9, 7, 12) - result = tslib.normalize_date(value) + result = tslibs.normalize_date(value) assert (result == datetime(2012, 9, 7)) value = datetime(2007, 10, 1, 1, 12, 5, 10) - actual = tslib.normalize_date(value) + actual = tslibs.normalize_date(value) assert actual == datetime(2007, 10, 1) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index b161e7764b884..d4ad2e4eeb2e6 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -14,7 +14,7 @@ from pandas.tseries.offsets import DateOffset -from pandas._libs.tslib import Timedelta +from pandas._libs.tslibs import Timedelta import pandas._libs.tslibs.frequencies as libfreqs from pandas._libs.tslibs.frequencies import ( # noqa, semi-public API diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index d78d199f1404b..5d076bf33a8ac 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -13,7 +13,7 @@ # import after tools, dateutil check from dateutil.easter import easter -from pandas._libs import tslib, Timestamp, OutOfBoundsDatetime, Timedelta +from pandas._libs import tslibs, Timestamp, OutOfBoundsDatetime, Timedelta from pandas.util._decorators import cache_readonly from pandas._libs.tslibs import ( @@ -60,8 +60,8 @@ def as_timestamp(obj): def apply_wraps(func): @functools.wraps(func) def wrapper(self, other): - if other is tslib.NaT: - return tslib.NaT + if other is tslibs.NaT: + return tslibs.NaT elif isinstance(other, (timedelta, Tick, DateOffset)): # timedelta path return func(self, other) @@ -89,7 +89,7 @@ def wrapper(self, other): if not isinstance(self, Nano) and result.nanosecond != nano: if result.tz is not None: # convert to UTC - value = tslib.tz_convert_single( + value = conversion.tz_convert_single( result.value, 'UTC', result.tz) else: value = result.value @@ -103,7 +103,7 @@ def wrapper(self, other): if self.normalize: # normalize_date returns normal datetime - result = tslib.normalize_date(result) + result = tslibs.normalize_date(result) if tz is not None and result.tzinfo is None: result = conversion.localize_pydatetime(result, tz) diff --git a/pandas/tslib.py b/pandas/tslib.py index c06b34c1b0483..fc4a1ccb5da00 100644 --- a/pandas/tslib.py +++ b/pandas/tslib.py @@ -3,5 +3,5 @@ import warnings warnings.warn("The pandas.tslib module is deprecated and will be " "removed in a future version.", FutureWarning, stacklevel=2) -from pandas._libs.tslib import Timestamp, Timedelta, OutOfBoundsDatetime +from pandas._libs.tslibs import Timestamp, Timedelta, OutOfBoundsDatetime from pandas._libs.tslibs.nattype import NaT, NaTType
Another try at #21802. Removing `Timedelta` from the `tslib` namespace broke a ton of imports, so this goes through and updates all of them.
https://api.github.com/repos/pandas-dev/pandas/pulls/21816
2018-07-08T18:46:31Z
2018-07-09T12:55:39Z
2018-07-09T12:55:39Z
2018-07-11T20:21:24Z
REF: Move most remaining arith helpers to datetimelike mixins
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 118516192e4ed..65f34b847f8d0 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import operator +import warnings import numpy as np @@ -8,12 +9,16 @@ from pandas._libs.tslibs.period import ( DIFFERENT_FREQ_INDEX, IncompatibleFrequency) -from pandas.errors import NullFrequencyError +from pandas.errors import NullFrequencyError, PerformanceWarning from pandas.tseries import frequencies from pandas.tseries.offsets import Tick -from pandas.core.dtypes.common import is_period_dtype, is_timedelta64_dtype +from pandas.core.dtypes.common import ( + is_period_dtype, + is_timedelta64_dtype, + is_object_dtype) + import pandas.core.common as com from pandas.core.algorithms import checked_add_with_arr @@ -108,38 +113,43 @@ def __getitem__(self, key): if is_int: val = getitem(key) return self._box_func(val) + + if com.is_bool_indexer(key): + key = np.asarray(key) + if key.all(): + key = slice(0, None, None) + else: + key = lib.maybe_booleans_to_slice(key.view(np.uint8)) + + attribs = self._get_attributes_dict() + + is_period = is_period_dtype(self) + if is_period: + freq = self.freq else: - if com.is_bool_indexer(key): - key = np.asarray(key) - if key.all(): - key = slice(0, None, None) + freq = None + if isinstance(key, slice): + if self.freq is not None and key.step is not None: + freq = key.step * self.freq else: - key = lib.maybe_booleans_to_slice(key.view(np.uint8)) + freq = self.freq - attribs = self._get_attributes_dict() + attribs['freq'] = freq - is_period = is_period_dtype(self) + result = getitem(key) + if result.ndim > 1: + # To support MPL which performs slicing with 2 dim + # even though it only has 1 dim by definition if is_period: - freq = self.freq - else: - freq = None - if isinstance(key, slice): - if self.freq is not None and key.step is not None: - freq = key.step * self.freq - else: - freq = self.freq - - attribs['freq'] = freq + return self._simple_new(result, **attribs) + return result - result = getitem(key) - if result.ndim > 1: - # To support MPL which performs slicing with 2 dim - # even though it only has 1 dim by definition - if is_period: - return self._simple_new(result, **attribs) - return result + return self._simple_new(result, **attribs) - return self._simple_new(result, **attribs) + def astype(self, dtype, copy=True): + if is_object_dtype(dtype): + return self._box_values(self.asi8) + return super(DatetimeLikeArrayMixin, self).astype(dtype, copy) # ------------------------------------------------------------------ # Null Handling @@ -397,3 +407,31 @@ def _addsub_int_array(self, other, op): # to _addsub_offset_array assert not is_timedelta64_dtype(self) return op(self, np.array(other) * self.freq) + + def _addsub_offset_array(self, other, op): + """ + Add or subtract array-like of DateOffset objects + + Parameters + ---------- + other : Index, np.ndarray + object-dtype containing pd.DateOffset objects + op : {operator.add, operator.sub} + + Returns + ------- + result : same class as self + """ + assert op in [operator.add, operator.sub] + if len(other) == 1: + return op(self, other[0]) + + warnings.warn("Adding/subtracting array of DateOffsets to " + "{cls} not vectorized" + .format(cls=type(self).__name__), PerformanceWarning) + + res_values = op(self.astype('O').values, np.array(other)) + kwargs = {} + if not is_period_dtype(self): + kwargs['freq'] = 'infer' + return type(self)(res_values, **kwargs) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index e6e0544bfa22b..05bc3d23cfb8e 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +from datetime import timedelta import warnings import numpy as np @@ -11,15 +12,18 @@ resolution as libresolution) from pandas.util._decorators import cache_readonly +from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import ( _NS_DTYPE, is_datetime64tz_dtype, is_datetime64_dtype, + is_timedelta64_dtype, _ensure_int64) from pandas.core.dtypes.dtypes import DatetimeTZDtype from pandas.tseries.frequencies import to_offset, DateOffset +from pandas.tseries.offsets import Tick from .datetimelike import DatetimeLikeArrayMixin @@ -104,6 +108,10 @@ def _simple_new(cls, values, freq=None, tz=None, **kwargs): return result def __new__(cls, values, freq=None, tz=None): + if tz is None and hasattr(values, 'tz'): + # e.g. DatetimeIndex + tz = values.tz + if (freq is not None and not isinstance(freq, DateOffset) and freq != 'infer'): freq = to_offset(freq) @@ -131,6 +139,17 @@ def dtype(self): return _NS_DTYPE return DatetimeTZDtype('ns', self.tz) + @property + def tz(self): + # GH 18595 + return self._tz + + @tz.setter + def tz(self, value): + # GH 3746: Prevent localizing or converting the index by setting tz + raise AttributeError("Cannot directly set timezone. Use tz_localize() " + "or tz_convert() as appropriate") + @property def tzinfo(self): """ @@ -244,6 +263,60 @@ def _sub_datelike_dti(self, other): new_values[mask] = iNaT return new_values.view('timedelta64[ns]') + def _add_offset(self, offset): + assert not isinstance(offset, Tick) + try: + if self.tz is not None: + values = self.tz_localize(None) + else: + values = self + result = offset.apply_index(values) + if self.tz is not None: + result = result.tz_localize(self.tz) + + except NotImplementedError: + warnings.warn("Non-vectorized DateOffset being applied to Series " + "or DatetimeIndex", PerformanceWarning) + result = self.astype('O') + offset + + return type(self)(result, freq='infer') + + def _add_delta(self, delta): + """ + Add a timedelta-like, DateOffset, or TimedeltaIndex-like object + to self. + + Parameters + ---------- + delta : {timedelta, np.timedelta64, DateOffset, + TimedelaIndex, ndarray[timedelta64]} + + Returns + ------- + result : same type as self + + Notes + ----- + The result's name is set outside of _add_delta by the calling + method (__add__ or __sub__) + """ + from pandas.core.arrays.timedelta import TimedeltaArrayMixin + + if isinstance(delta, (Tick, timedelta, np.timedelta64)): + new_values = self._add_delta_td(delta) + elif is_timedelta64_dtype(delta): + if not isinstance(delta, TimedeltaArrayMixin): + delta = TimedeltaArrayMixin(delta) + new_values = self._add_delta_tdi(delta) + else: + new_values = self.astype('O') + delta + + tz = 'UTC' if self.tz is not None else None + result = type(self)(new_values, tz=tz, freq='infer') + if self.tz is not None and self.tz is not utc: + result = result.tz_convert(self.tz) + return result + # ----------------------------------------------------------------- # Timezone Conversion and Localization Methods diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index fa416e30493e9..35baa3262d3dd 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -8,14 +8,16 @@ from pandas._libs.tslib import NaT, iNaT from pandas._libs.tslibs.period import ( Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX, - get_period_field_arr) + get_period_field_arr, period_asfreq_arr) +from pandas._libs.tslibs import period as libperiod from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas._libs.tslibs.fields import isleapyear_arr from pandas import compat from pandas.util._decorators import cache_readonly -from pandas.core.dtypes.common import is_integer_dtype, is_float_dtype +from pandas.core.dtypes.common import ( + is_integer_dtype, is_float_dtype, is_period_dtype) from pandas.core.dtypes.dtypes import PeriodDtype from pandas.tseries import frequencies @@ -113,12 +115,23 @@ def freq(self, value): _attributes = ["freq"] + def __new__(cls, values, freq=None, **kwargs): + if is_period_dtype(values): + # PeriodArray, PeriodIndex + if freq is not None and values.freq != freq: + raise IncompatibleFrequency(freq, values.freq) + freq = values.freq + values = values.asi8 + + return cls._simple_new(values, freq, **kwargs) + @classmethod def _simple_new(cls, values, freq=None, **kwargs): """ Values can be any type that can be coerced to Periods. Ordinals in an ndarray are fastpath-ed to `_from_ordinals` """ + if not is_integer_dtype(values): values = np.array(values, copy=False) if len(values) > 0 and is_float_dtype(values): @@ -128,8 +141,6 @@ def _simple_new(cls, values, freq=None, **kwargs): return cls._from_ordinals(values, freq) - __new__ = _simple_new # For now... - @classmethod def _from_ordinals(cls, values, freq=None): """ @@ -173,6 +184,65 @@ def is_leap_year(self): """ Logical indicating if the date belongs to a leap year """ return isleapyear_arr(np.asarray(self.year)) + def asfreq(self, freq=None, how='E'): + """ + Convert the Period Array/Index to the specified frequency `freq`. + + Parameters + ---------- + freq : str + a frequency + how : str {'E', 'S'} + 'E', 'END', or 'FINISH' for end, + 'S', 'START', or 'BEGIN' for start. + Whether the elements should be aligned to the end + or start within pa period. January 31st ('END') vs. + January 1st ('START') for example. + + Returns + ------- + new : Period Array/Index with the new frequency + + Examples + -------- + >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A') + >>> pidx + <class 'pandas.core.indexes.period.PeriodIndex'> + [2010, ..., 2015] + Length: 6, Freq: A-DEC + + >>> pidx.asfreq('M') + <class 'pandas.core.indexes.period.PeriodIndex'> + [2010-12, ..., 2015-12] + Length: 6, Freq: M + + >>> pidx.asfreq('M', how='S') + <class 'pandas.core.indexes.period.PeriodIndex'> + [2010-01, ..., 2015-01] + Length: 6, Freq: M + """ + how = libperiod._validate_end_alias(how) + + freq = Period._maybe_convert_freq(freq) + + base1, mult1 = frequencies.get_freq_code(self.freq) + base2, mult2 = frequencies.get_freq_code(freq) + + asi8 = self.asi8 + # mult1 can't be negative or 0 + end = how == 'E' + if end: + ordinal = asi8 + mult1 - 1 + else: + ordinal = asi8 + + new_data = period_asfreq_arr(ordinal, base1, base2, end) + + if self.hasnans: + new_data[self._isnan] = iNaT + + return self._simple_new(new_data, self.name, freq=freq) + # ------------------------------------------------------------------ # Arithmetic Methods diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index af0fa2c3477f4..20a9f263bf5e1 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -10,7 +10,8 @@ from pandas import compat -from pandas.core.dtypes.common import _TD_DTYPE, _ensure_int64 +from pandas.core.dtypes.common import ( + _TD_DTYPE, _ensure_int64, is_timedelta64_dtype) from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.missing import isna @@ -58,7 +59,11 @@ def _simple_new(cls, values, freq=None, **kwargs): if values.dtype == np.object_: values = array_to_timedelta64(values) if values.dtype != _TD_DTYPE: - values = _ensure_int64(values).view(_TD_DTYPE) + if is_timedelta64_dtype(values): + # non-nano unit + values = values.astype(_TD_DTYPE) + else: + values = _ensure_int64(values).view(_TD_DTYPE) result = object.__new__(cls) result._data = values @@ -92,6 +97,38 @@ def _sub_datelike(self, other): raise TypeError("cannot subtract a datelike from a {cls}" .format(cls=type(self).__name__)) + def _add_delta(self, delta): + """ + Add a timedelta-like, Tick, or TimedeltaIndex-like object + to self. + + Parameters + ---------- + delta : timedelta, np.timedelta64, Tick, TimedeltaArray, TimedeltaIndex + + Returns + ------- + result : same type as self + + Notes + ----- + The result's name is set outside of _add_delta by the calling + method (__add__ or __sub__) + """ + if isinstance(delta, (Tick, timedelta, np.timedelta64)): + new_values = self._add_delta_td(delta) + elif isinstance(delta, TimedeltaArrayMixin): + new_values = self._add_delta_tdi(delta) + elif is_timedelta64_dtype(delta): + # ndarray[timedelta64] --> wrap in TimedeltaArray/Index + delta = type(self)(delta) + new_values = self._add_delta_tdi(delta) + else: + raise TypeError("cannot add the type {0} to a TimedeltaIndex" + .format(type(delta))) + + return type(self)(new_values, freq='infer') + def _evaluate_with_timedelta_like(self, other, op): if isinstance(other, ABCSeries): # GH#19042 diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index daaa40addf6c0..37e20496aafce 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -41,7 +41,7 @@ from pandas.core.dtypes.missing import isna from pandas.core import common as com, algorithms, ops -from pandas.errors import NullFrequencyError, PerformanceWarning +from pandas.errors import NullFrequencyError import pandas.io.formats.printing as printing from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin @@ -599,34 +599,6 @@ def _convert_scalar_indexer(self, key, kind=None): return (super(DatetimeIndexOpsMixin, self) ._convert_scalar_indexer(key, kind=kind)) - def _addsub_offset_array(self, other, op): - """ - Add or subtract array-like of DateOffset objects - - Parameters - ---------- - other : Index, np.ndarray - object-dtype containing pd.DateOffset objects - op : {operator.add, operator.sub} - - Returns - ------- - result : same class as self - """ - assert op in [operator.add, operator.sub] - if len(other) == 1: - return op(self, other[0]) - - warnings.warn("Adding/subtracting array of DateOffsets to " - "{cls} not vectorized" - .format(cls=type(self).__name__), PerformanceWarning) - - res_values = op(self.astype('O').values, np.array(other)) - kwargs = {} - if not is_period_dtype(self): - kwargs['freq'] = 'infer' - return type(self)(res_values, **kwargs) - @classmethod def _add_datetimelike_methods(cls): """ diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 53b1186b37a90..13344a77d8cc6 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -2,7 +2,7 @@ from __future__ import division import operator import warnings -from datetime import time, datetime, timedelta +from datetime import time, datetime import numpy as np from pytz import utc @@ -16,7 +16,6 @@ is_datetime64_dtype, is_datetimetz, is_dtype_equal, - is_timedelta64_dtype, is_integer, is_float, is_integer_dtype, @@ -33,7 +32,6 @@ from pandas.core.dtypes.missing import isna import pandas.core.dtypes.concat as _concat -from pandas.errors import PerformanceWarning from pandas.core.algorithms import checked_add_with_arr from pandas.core.arrays.datetimes import DatetimeArrayMixin @@ -824,60 +822,6 @@ def _maybe_update_attributes(self, attrs): attrs['freq'] = 'infer' return attrs - def _add_delta(self, delta): - """ - Add a timedelta-like, DateOffset, or TimedeltaIndex-like object - to self. - - Parameters - ---------- - delta : {timedelta, np.timedelta64, DateOffset, - TimedelaIndex, ndarray[timedelta64]} - - Returns - ------- - result : DatetimeIndex - - Notes - ----- - The result's name is set outside of _add_delta by the calling - method (__add__ or __sub__) - """ - from pandas import TimedeltaIndex - - if isinstance(delta, (Tick, timedelta, np.timedelta64)): - new_values = self._add_delta_td(delta) - elif is_timedelta64_dtype(delta): - if not isinstance(delta, TimedeltaIndex): - delta = TimedeltaIndex(delta) - new_values = self._add_delta_tdi(delta) - else: - new_values = self.astype('O') + delta - - tz = 'UTC' if self.tz is not None else None - result = DatetimeIndex(new_values, tz=tz, freq='infer') - if self.tz is not None and self.tz is not utc: - result = result.tz_convert(self.tz) - return result - - def _add_offset(self, offset): - assert not isinstance(offset, Tick) - try: - if self.tz is not None: - values = self.tz_localize(None) - else: - values = self - result = offset.apply_index(values) - if self.tz is not None: - result = result.tz_localize(self.tz) - - except NotImplementedError: - warnings.warn("Non-vectorized DateOffset being applied to Series " - "or DatetimeIndex", PerformanceWarning) - result = self.astype('O') + offset - - return DatetimeIndex(result, freq='infer') - def _format_native_types(self, na_rep='NaT', date_format=None, **kwargs): from pandas.io.formats.format import _get_format_datetime64_from_values format = _get_format_datetime64_from_values(self, date_format) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 3fa525b8617c5..4ded4527e0a36 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -480,66 +480,6 @@ def is_full(self): values = self.asi8 return ((values[1:] - values[:-1]) < 2).all() - def asfreq(self, freq=None, how='E'): - """ - Convert the PeriodIndex to the specified frequency `freq`. - - Parameters - ---------- - - freq : str - a frequency - how : str {'E', 'S'} - 'E', 'END', or 'FINISH' for end, - 'S', 'START', or 'BEGIN' for start. - Whether the elements should be aligned to the end - or start within pa period. January 31st ('END') vs. - January 1st ('START') for example. - - Returns - ------- - new : PeriodIndex with the new frequency - - Examples - -------- - >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A') - >>> pidx - <class 'pandas.core.indexes.period.PeriodIndex'> - [2010, ..., 2015] - Length: 6, Freq: A-DEC - - >>> pidx.asfreq('M') - <class 'pandas.core.indexes.period.PeriodIndex'> - [2010-12, ..., 2015-12] - Length: 6, Freq: M - - >>> pidx.asfreq('M', how='S') - <class 'pandas.core.indexes.period.PeriodIndex'> - [2010-01, ..., 2015-01] - Length: 6, Freq: M - """ - how = _validate_end_alias(how) - - freq = Period._maybe_convert_freq(freq) - - base1, mult1 = _gfc(self.freq) - base2, mult2 = _gfc(freq) - - asi8 = self.asi8 - # mult1 can't be negative or 0 - end = how == 'E' - if end: - ordinal = asi8 + mult1 - 1 - else: - ordinal = asi8 - - new_data = period.period_asfreq_arr(ordinal, base1, base2, end) - - if self.hasnans: - new_data[self._isnan] = tslib.iNaT - - return self._simple_new(new_data, self.name, freq=freq) - year = _wrap_field_accessor('year') month = _wrap_field_accessor('month') day = _wrap_field_accessor('day') diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index b1dc6e6286b98..3af825455caac 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -337,38 +337,6 @@ def _maybe_update_attributes(self, attrs): attrs['freq'] = 'infer' return attrs - def _add_delta(self, delta): - """ - Add a timedelta-like, Tick, or TimedeltaIndex-like object - to self. - - Parameters - ---------- - delta : {timedelta, np.timedelta64, Tick, TimedeltaIndex} - - Returns - ------- - result : TimedeltaIndex - - Notes - ----- - The result's name is set outside of _add_delta by the calling - method (__add__ or __sub__) - """ - if isinstance(delta, (Tick, timedelta, np.timedelta64)): - new_values = self._add_delta_td(delta) - elif isinstance(delta, TimedeltaIndex): - new_values = self._add_delta_tdi(delta) - elif is_timedelta64_dtype(delta): - # ndarray[timedelta64] --> wrap in TimedeltaIndex - delta = TimedeltaIndex(delta) - new_values = self._add_delta_tdi(delta) - else: - raise TypeError("cannot add the type {0} to a TimedeltaIndex" - .format(type(delta))) - - return TimedeltaIndex(new_values, freq='infer') - def _evaluate_with_timedelta_like(self, other, op): result = TimedeltaArrayMixin._evaluate_with_timedelta_like(self, other, op) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py new file mode 100644 index 0000000000000..d116b3bcff86a --- /dev/null +++ b/pandas/tests/arrays/test_datetimelike.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +import numpy as np + +import pandas as pd + +from pandas.core.arrays.datetimes import DatetimeArrayMixin +from pandas.core.arrays.timedelta import TimedeltaArrayMixin +from pandas.core.arrays.period import PeriodArrayMixin + + +class TestDatetimeArray(object): + + def test_from_dti(self, tz_naive_fixture): + tz = tz_naive_fixture + dti = pd.date_range('2016-01-01', periods=3, tz=tz) + arr = DatetimeArrayMixin(dti) + assert list(dti) == list(arr) + + def test_astype_object(self, tz_naive_fixture): + tz = tz_naive_fixture + dti = pd.date_range('2016-01-01', periods=3, tz=tz) + arr = DatetimeArrayMixin(dti) + asobj = arr.astype('O') + assert isinstance(asobj, np.ndarray) + assert asobj.dtype == 'O' + assert list(asobj) == list(dti) + + +class TestTimedeltaArray(object): + def test_from_tdi(self): + tdi = pd.TimedeltaIndex(['1 Day', '3 Hours']) + arr = TimedeltaArrayMixin(tdi) + assert list(arr) == list(tdi) + + def test_astype_object(self): + tdi = pd.TimedeltaIndex(['1 Day', '3 Hours']) + arr = TimedeltaArrayMixin(tdi) + asobj = arr.astype('O') + assert isinstance(asobj, np.ndarray) + assert asobj.dtype == 'O' + assert list(asobj) == list(tdi) + + +class TestPeriodArray(object): + + def test_from_pi(self): + pi = pd.period_range('2016', freq='Q', periods=3) + arr = PeriodArrayMixin(pi) + assert list(arr) == list(pi) + + def test_astype_object(self): + pi = pd.period_range('2016', freq='Q', periods=3) + arr = PeriodArrayMixin(pi) + asobj = arr.astype('O') + assert isinstance(asobj, np.ndarray) + assert asobj.dtype == 'O' + assert list(asobj) == list(pi)
Before we can finally move over `_add_datetimelike_methods` and be done with this, some more work needs to go into the `__new__` methods. This gets another big chunk through, starts implementing tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/21815
2018-07-08T17:13:24Z
2018-07-09T12:56:56Z
2018-07-09T12:56:56Z
2018-07-10T13:52:36Z
CI: Migrate to circleci 2.0
diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000000000..e947f30d285cd --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,147 @@ +version: 2 +jobs: + + # -------------------------------------------------------------------------- + # 0. py27_compat + # -------------------------------------------------------------------------- + py27_compat: + docker: + - image: continuumio/miniconda:latest + # databases configuration + - image: circleci/postgres:9.6.5-alpine-ram + environment: + POSTGRES_USER: postgres + POSTGRES_DB: pandas_nosetest + - image: circleci/mysql:8-ram + environment: + MYSQL_USER: "root" + MYSQL_HOST: "localhost" + MYSQL_ALLOW_EMPTY_PASSWORD: "true" + MYSQL_DATABASE: "pandas_nosetest" + environment: + JOB: "2.7_COMPAT" + ENV_FILE: "ci/circle-27-compat.yaml" + LOCALE_OVERRIDE: "it_IT.UTF-8" + MINICONDA_DIR: /home/ubuntu/miniconda3 + steps: + - checkout + - run: + name: build + command: | + ./ci/install_circle.sh + ./ci/show_circle.sh + - run: + name: test + command: ./ci/run_circle.sh --skip-slow --skip-network + + # -------------------------------------------------------------------------- + # 1. py36_locale + # -------------------------------------------------------------------------- + py36_locale: + docker: + - image: continuumio/miniconda:latest + # databases configuration + - image: circleci/postgres:9.6.5-alpine-ram + environment: + POSTGRES_USER: postgres + POSTGRES_DB: pandas_nosetest + - image: circleci/mysql:8-ram + environment: + MYSQL_USER: "root" + MYSQL_HOST: "localhost" + MYSQL_ALLOW_EMPTY_PASSWORD: "true" + MYSQL_DATABASE: "pandas_nosetest" + + environment: + JOB: "3.6_LOCALE" + ENV_FILE: "ci/circle-36-locale.yaml" + LOCALE_OVERRIDE: "zh_CN.UTF-8" + MINICONDA_DIR: /home/ubuntu/miniconda3 + steps: + - checkout + - run: + name: build + command: | + ./ci/install_circle.sh + ./ci/show_circle.sh + - run: + name: test + command: ./ci/run_circle.sh --skip-slow --skip-network + + # -------------------------------------------------------------------------- + # 2. py36_locale_slow + # -------------------------------------------------------------------------- + py36_locale_slow: + docker: + - image: continuumio/miniconda:latest + # databases configuration + - image: circleci/postgres:9.6.5-alpine-ram + environment: + POSTGRES_USER: postgres + POSTGRES_DB: pandas_nosetest + - image: circleci/mysql:8-ram + environment: + MYSQL_USER: "root" + MYSQL_HOST: "localhost" + MYSQL_ALLOW_EMPTY_PASSWORD: "true" + MYSQL_DATABASE: "pandas_nosetest" + + environment: + JOB: "3.6_LOCALE_SLOW" + ENV_FILE: "ci/circle-36-locale_slow.yaml" + LOCALE_OVERRIDE: "zh_CN.UTF-8" + MINICONDA_DIR: /home/ubuntu/miniconda3 + steps: + - checkout + - run: + name: build + command: | + ./ci/install_circle.sh + ./ci/show_circle.sh + - run: + name: test + command: ./ci/run_circle.sh --only-slow --skip-network + + # -------------------------------------------------------------------------- + # 3. py35_ascii + # -------------------------------------------------------------------------- + py35_ascii: + docker: + - image: continuumio/miniconda:latest + # databases configuration + - image: circleci/postgres:9.6.5-alpine-ram + environment: + POSTGRES_USER: postgres + POSTGRES_DB: pandas_nosetest + - image: circleci/mysql:8-ram + environment: + MYSQL_USER: "root" + MYSQL_HOST: "localhost" + MYSQL_ALLOW_EMPTY_PASSWORD: "true" + MYSQL_DATABASE: "pandas_nosetest" + + environment: + JOB: "3.5_ASCII" + ENV_FILE: "ci/circle-35-ascii.yaml" + LOCALE_OVERRIDE: "C" + MINICONDA_DIR: /home/ubuntu/miniconda3 + steps: + - checkout + - run: + name: build + command: | + ./ci/install_circle.sh + ./ci/show_circle.sh + - run: + name: test + command: ./ci/run_circle.sh --skip-slow --skip-network + + +workflows: + version: 2 + build_and_test: + jobs: + - py27_compat + - py36_locale + - py36_locale_slow + - py35_ascii diff --git a/ci/install_circle.sh b/ci/install_circle.sh index 5ffff84c88488..f8bcf6bcffc99 100755 --- a/ci/install_circle.sh +++ b/ci/install_circle.sh @@ -6,14 +6,7 @@ echo "[home_dir: $home_dir]" echo "[ls -ltr]" ls -ltr -echo "[Using clean Miniconda install]" -rm -rf "$MINICONDA_DIR" - -# install miniconda -wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -q -O miniconda.sh || exit 1 -bash miniconda.sh -b -p "$MINICONDA_DIR" || exit 1 - -export PATH="$MINICONDA_DIR/bin:$PATH" +apt-get update -y && apt-get install -y build-essential postgresql-client-9.6 echo "[update conda]" conda config --set ssl_verify false || exit 1 @@ -48,9 +41,17 @@ source $ENVS_FILE # edit the locale override if needed if [ -n "$LOCALE_OVERRIDE" ]; then + + apt-get update && apt-get -y install locales locales-all + + export LANG=$LOCALE_OVERRIDE + export LC_ALL=$LOCALE_OVERRIDE + + python -c "import locale; locale.setlocale(locale.LC_ALL, \"$LOCALE_OVERRIDE\")" || exit 1; + echo "[Adding locale to the first line of pandas/__init__.py]" rm -f pandas/__init__.pyc - sedc="3iimport locale\nlocale.setlocale(locale.LC_ALL, '$LOCALE_OVERRIDE')\n" + sedc="3iimport locale\nlocale.setlocale(locale.LC_ALL, \"$LOCALE_OVERRIDE\")\n" sed -i "$sedc" pandas/__init__.py echo "[head -4 pandas/__init__.py]" head -4 pandas/__init__.py diff --git a/ci/install_db_circle.sh b/ci/install_db_circle.sh deleted file mode 100755 index a00f74f009f54..0000000000000 --- a/ci/install_db_circle.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash - -echo "installing dbs" -mysql -e 'create database pandas_nosetest;' -psql -c 'create database pandas_nosetest;' -U postgres - -echo "done" -exit 0 diff --git a/ci/run_circle.sh b/ci/run_circle.sh index 435985bd42148..fc2a8b849a354 100755 --- a/ci/run_circle.sh +++ b/ci/run_circle.sh @@ -6,4 +6,4 @@ export PATH="$MINICONDA_DIR/bin:$PATH" source activate pandas echo "pytest --strict --junitxml=$CIRCLE_TEST_REPORTS/reports/junit.xml $@ pandas" -pytest --strict --junitxml=$CIRCLE_TEST_REPORTS/reports/junit.xml $@ pandas +pytest --strict --color=no --junitxml=$CIRCLE_TEST_REPORTS/reports/junit.xml $@ pandas diff --git a/circle.yml b/circle.yml deleted file mode 100644 index 66415defba6fe..0000000000000 --- a/circle.yml +++ /dev/null @@ -1,38 +0,0 @@ -machine: - environment: - # these are globally set - MINICONDA_DIR: /home/ubuntu/miniconda3 - - -database: - override: - - ./ci/install_db_circle.sh - - -checkout: - post: - # since circleci does a shallow fetch - # we need to populate our tags - - git fetch --depth=1000 - - -dependencies: - override: - - > - case $CIRCLE_NODE_INDEX in - 0) - sudo apt-get install language-pack-it && ./ci/install_circle.sh JOB="2.7_COMPAT" ENV_FILE="ci/circle-27-compat.yaml" LOCALE_OVERRIDE="it_IT.UTF-8" ;; - 1) - sudo apt-get install language-pack-zh-hans && ./ci/install_circle.sh JOB="3.6_LOCALE" ENV_FILE="ci/circle-36-locale.yaml" LOCALE_OVERRIDE="zh_CN.UTF-8" ;; - 2) - sudo apt-get install language-pack-zh-hans && ./ci/install_circle.sh JOB="3.6_LOCALE_SLOW" ENV_FILE="ci/circle-36-locale_slow.yaml" LOCALE_OVERRIDE="zh_CN.UTF-8" ;; - 3) - ./ci/install_circle.sh JOB="3.5_ASCII" ENV_FILE="ci/circle-35-ascii.yaml" LOCALE_OVERRIDE="C" ;; - esac - - ./ci/show_circle.sh - - -test: - override: - - case $CIRCLE_NODE_INDEX in 0) ./ci/run_circle.sh --skip-slow --skip-network ;; 1) ./ci/run_circle.sh --only-slow --skip-network ;; 2) ./ci/run_circle.sh --skip-slow --skip-network ;; 3) ./ci/run_circle.sh --skip-slow --skip-network ;; esac: - parallel: true diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index 056924f2c6663..743cbc107cce5 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -1,5 +1,6 @@ import locale import calendar +import unicodedata import pytest @@ -7,7 +8,7 @@ import pandas as pd import pandas.util.testing as tm from pandas import (Index, DatetimeIndex, datetime, offsets, - date_range, Timestamp) + date_range, Timestamp, compat) class TestTimeSeries(object): @@ -284,10 +285,24 @@ def test_datetime_name_accessors(self, time_locale): dti = DatetimeIndex(freq='M', start='2012', end='2013') result = dti.month_name(locale=time_locale) expected = Index([month.capitalize() for month in expected_months]) + + # work around different normalization schemes + # https://github.com/pandas-dev/pandas/issues/22342 + if not compat.PY2: + result = result.str.normalize("NFD") + expected = expected.str.normalize("NFD") + tm.assert_index_equal(result, expected) + for date, expected in zip(dti, expected_months): result = date.month_name(locale=time_locale) - assert result == expected.capitalize() + expected = expected.capitalize() + + if not compat.PY2: + result = unicodedata.normalize("NFD", result) + expected = unicodedata.normalize("NFD", result) + + assert result == expected dti = dti.append(DatetimeIndex([pd.NaT])) assert np.isnan(dti.month_name(locale=time_locale)[-1]) diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index f2e72e5fe00e1..b411744f7bac2 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -2,6 +2,7 @@ import pandas as pd import pandas.util.testing as tm +import pandas.util._test_decorators as td from pandas.util.testing import assert_frame_equal, assert_raises_regex @@ -31,6 +32,7 @@ def test_read_zipped_json(datapath): assert_frame_equal(uncompressed_df, compressed_df) +@td.skip_if_not_us_locale def test_with_s3_url(compression): boto3 = pytest.importorskip('boto3') pytest.importorskip('s3fs') diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 0715521a74819..04f0220839523 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -15,6 +15,7 @@ assert_series_equal, network, ensure_clean, assert_index_equal) import pandas.util.testing as tm +import pandas.util._test_decorators as td _seriesd = tm.getSeriesData() _tsd = tm.getTimeSeriesData() @@ -1047,6 +1048,7 @@ def test_read_inline_jsonl(self): expected = DataFrame([[1, 2], [1, 2]], columns=['a', 'b']) assert_frame_equal(result, expected) + @td.skip_if_not_us_locale def test_read_s3_jsonl(self, s3_resource): # GH17200 diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index a7cc3ad989ea1..bfe33980ac617 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -55,10 +55,12 @@ def tips_df(datapath): @pytest.mark.usefixtures("s3_resource") +@td.skip_if_not_us_locale() class TestS3(object): def test_parse_public_s3_bucket(self, tips_df): pytest.importorskip('s3fs') + # more of an integration test due to the not-public contents portion # can probably mock this though. for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index fa5a8f6a1900c..5f27ff719fda1 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -586,6 +586,7 @@ def test_read_from_http_url(self, ext): tm.assert_frame_equal(url_table, local_table) @td.skip_if_no('s3fs') + @td.skip_if_not_us_locale def test_read_from_s3_url(self, ext): boto3 = pytest.importorskip('boto3') moto = pytest.importorskip('moto') diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 4172bfd41b9db..58146cae587fe 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -5,6 +5,7 @@ import dateutil import calendar import locale +import unicodedata import numpy as np from dateutil.tz import tzutc @@ -20,7 +21,7 @@ from pandas._libs.tslibs.timezones import get_timezone, dateutil_gettz as gettz from pandas.errors import OutOfBoundsDatetime -from pandas.compat import long, PY3 +from pandas.compat import long, PY3, PY2 from pandas.compat.numpy import np_datetime64_compat from pandas import Timestamp, Period, Timedelta, NaT @@ -116,8 +117,21 @@ def test_names(self, data, time_locale): expected_day = calendar.day_name[0].capitalize() expected_month = calendar.month_name[8].capitalize() - assert data.day_name(time_locale) == expected_day - assert data.month_name(time_locale) == expected_month + result_day = data.day_name(time_locale) + result_month = data.month_name(time_locale) + + # Work around https://github.com/pandas-dev/pandas/issues/22342 + # different normalizations + + if not PY2: + expected_day = unicodedata.normalize("NFD", expected_day) + expected_month = unicodedata.normalize("NFD", expected_month) + + result_day = unicodedata.normalize("NFD", result_day,) + result_month = unicodedata.normalize("NFD", result_month) + + assert result_day == expected_day + assert result_month == expected_month # Test NaT nan_ts = Timestamp(NaT) diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index 06eb525bbac56..e2dcbfae78b16 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -3,6 +3,7 @@ import locale import calendar +import unicodedata import pytest from datetime import datetime, time, date @@ -13,7 +14,8 @@ from pandas.core.dtypes.common import is_integer_dtype, is_list_like from pandas import (Index, Series, DataFrame, bdate_range, date_range, period_range, timedelta_range, - PeriodIndex, DatetimeIndex, TimedeltaIndex) + PeriodIndex, DatetimeIndex, TimedeltaIndex, + compat) import pandas.core.common as com import dateutil @@ -308,10 +310,24 @@ def test_dt_accessor_datetime_name_accessors(self, time_locale): s = Series(DatetimeIndex(freq='M', start='2012', end='2013')) result = s.dt.month_name(locale=time_locale) expected = Series([month.capitalize() for month in expected_months]) + + # work around https://github.com/pandas-dev/pandas/issues/22342 + if not compat.PY2: + result = result.str.normalize("NFD") + expected = expected.str.normalize("NFD") + tm.assert_series_equal(result, expected) + for s_date, expected in zip(s, expected_months): result = s_date.month_name(locale=time_locale) - assert result == expected.capitalize() + expected = expected.capitalize() + + if not compat.PY2: + result = unicodedata.normalize("NFD", result) + expected = unicodedata.normalize("NFD", expected) + + assert result == expected + s = s.append(Series([pd.NaT])) assert np.isnan(s.dt.month_name(locale=time_locale).iloc[-1])
closes https://github.com/pandas-dev/pandas/issues/19929
https://api.github.com/repos/pandas-dev/pandas/pulls/21814
2018-07-08T16:44:06Z
2018-08-17T11:20:51Z
2018-08-17T11:20:51Z
2018-08-17T11:45:33Z
BUG: rolling with MSVC 2017 build
diff --git a/appveyor.yml b/appveyor.yml index f70fc829ec971..c6199c1493f22 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -20,12 +20,14 @@ environment: matrix: - CONDA_ROOT: "C:\\Miniconda3_64" + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 PYTHON_VERSION: "3.6" PYTHON_ARCH: "64" CONDA_PY: "36" CONDA_NPY: "113" - CONDA_ROOT: "C:\\Miniconda3_64" + APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 PYTHON_VERSION: "2.7" PYTHON_ARCH: "64" CONDA_PY: "27" diff --git a/doc/source/whatsnew/v0.23.4.txt b/doc/source/whatsnew/v0.23.4.txt index 69525aaea1d62..c17f4ffdd6b8e 100644 --- a/doc/source/whatsnew/v0.23.4.txt +++ b/doc/source/whatsnew/v0.23.4.txt @@ -20,7 +20,7 @@ and bug fixes. We recommend that all users upgrade to this version. Fixed Regressions ~~~~~~~~~~~~~~~~~ -- +- Python 3.7 with Windows gave all missing values for rolling variance calculations (:issue:`21813`) - .. _whatsnew_0234.bug_fixes: diff --git a/pandas/_libs/src/headers/cmath b/pandas/_libs/src/headers/cmath index d8e2239406cae..2bccf9bb13d77 100644 --- a/pandas/_libs/src/headers/cmath +++ b/pandas/_libs/src/headers/cmath @@ -6,6 +6,7 @@ #if defined(_MSC_VER) && (_MSC_VER < 1800) #include <cmath> namespace std { + __inline int isnan(double x) { return _isnan(x); } __inline int signbit(double num) { return _copysign(1.0, num) < 0; } } #else diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index c52bd99c37e31..6453b5ed2ab3a 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -14,6 +14,7 @@ cnp.import_array() cdef extern from "src/headers/cmath" namespace "std": + bint isnan(double) nogil int signbit(double) nogil double sqrt(double x) nogil @@ -653,16 +654,16 @@ cdef inline void add_var(double val, double *nobs, double *mean_x, double *ssqdm_x) nogil: """ add a value from the var calc """ cdef double delta - - # Not NaN - if val == val: - nobs[0] = nobs[0] + 1 - - # a part of Welford's method for the online variance-calculation - # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance - delta = val - mean_x[0] - mean_x[0] = mean_x[0] + delta / nobs[0] - ssqdm_x[0] = ssqdm_x[0] + ((nobs[0] - 1) * delta ** 2) / nobs[0] + # `isnan` instead of equality as fix for GH-21813, msvc 2017 bug + if isnan(val): + return + + nobs[0] = nobs[0] + 1 + # a part of Welford's method for the online variance-calculation + # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + delta = val - mean_x[0] + mean_x[0] = mean_x[0] + delta / nobs[0] + ssqdm_x[0] = ssqdm_x[0] + ((nobs[0] - 1) * delta ** 2) / nobs[0] cdef inline void remove_var(double val, double *nobs, double *mean_x,
- [x] closes #21786 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry For now just trying 3.7 on appveyor, not sure if all necessary conda packages are there
https://api.github.com/repos/pandas-dev/pandas/pulls/21813
2018-07-08T16:02:42Z
2018-07-26T17:32:30Z
2018-07-26T17:32:30Z
2019-03-11T19:15:32Z
DOC: consolidate clip_upper and clip_lower docstrings
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 605db412e5a5f..48366a286ac05 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6547,32 +6547,46 @@ def clip(self, lower=None, upper=None, axis=None, inplace=False, def clip_upper(self, threshold, axis=None, inplace=False): """ - Return copy of the input with values above given value(s) truncated. + Trim values above a given threshold. - It truncates values above a certain threshold. Threshold can be a - single value or an array, in the latter case it performs the truncation - element-wise. + Elements above the `threshold` will be changed to match the + `threshold` value(s). Threshold can be a single value or an array, + in the latter case it performs the truncation element-wise. Parameters ---------- - threshold : float or array-like + threshold : numeric or array-like Maximum value allowed. All values above threshold will be set to this value. - axis : int or string axis name, optional - Align object with threshold along the given axis. + + * float : every value is compared to `threshold`. + * array-like : The shape of `threshold` should match the object + it's compared to. When `self` is a Series, `threshold` should be + the length. When `self` is a DataFrame, `threshold` should 2-D + and the same shape as `self` for ``axis=None``, or 1-D and the + same length as the axis being compared. + + axis : {0 or 'index', 1 or 'columns'}, default 0 + Align object with `threshold` along the given axis. inplace : boolean, default False Whether to perform the operation in place on the data. .. versionadded:: 0.21.0 - See Also - -------- - clip : Return input copy with values below/above thresholds truncated. - clip_lower : Method to truncate values below given thresholds. - Returns ------- - clipped : same type as input + clipped + Original data with values trimmed. + + See Also + -------- + DataFrame.clip : General purpose method to trim DataFrame values to + given threshold(s) + DataFrame.clip_lower : Trim DataFrame values below given + threshold(s) + Series.clip : General purpose method to trim Series values to given + threshold(s) + Series.clip_lower : Trim Series values below given threshold(s) Examples -------- @@ -6613,7 +6627,8 @@ def clip_lower(self, threshold, axis=None, inplace=False): Trim values below a given threshold. Elements below the `threshold` will be changed to match the - `threshold` value(s). + `threshold` value(s). Threshold can be a single value or an array, + in the latter case it performs the truncation element-wise. Parameters ---------- @@ -6636,20 +6651,20 @@ def clip_lower(self, threshold, axis=None, inplace=False): .. versionadded:: 0.21.0 + Returns + ------- + clipped + Original data with values trimmed. + See Also -------- - DataFrame.clip : General purpose method to trim `DataFrame` values to + DataFrame.clip : General purpose method to trim DataFrame values to given threshold(s) - DataFrame.clip_upper : Trim `DataFrame` values above given + DataFrame.clip_upper : Trim DataFrame values above given threshold(s) - Series.clip : General purpose method to trim `Series` values to given + Series.clip : General purpose method to trim Series values to given threshold(s) - Series.clip_upper : Trim `Series` values above given threshold(s) - - Returns - ------- - clipped - Original data with values trimmed. + Series.clip_upper : Trim Series values above given threshold(s) Examples -------- @@ -6716,7 +6731,6 @@ def clip_lower(self, threshold, axis=None, inplace=False): 0 4 5 1 4 5 2 5 6 - """ return self._clip_with_one_bound(threshold, method=self.ge, axis=axis, inplace=inplace)
Follow-up on merging https://github.com/pandas-dev/pandas/pull/20135 and https://github.com/pandas-dev/pandas/pull/20289
https://api.github.com/repos/pandas-dev/pandas/pulls/21812
2018-07-08T14:57:45Z
2018-07-08T14:58:14Z
2018-07-08T14:58:14Z
2018-07-08T14:58:17Z
Add unit test for #12813
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 29c1a68053aef..be5b8f9ba93ac 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -331,6 +331,7 @@ Numeric ^^^^^^^ - Bug in :class:`Series` ``__rmatmul__`` doesn't support matrix vector multiplication (:issue:`21530`) +- Bug in :func:`factorize` fails with read-only array (:issue:`12813`) - - diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index de3c9574a4471..25e64aa82cc36 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -231,8 +231,9 @@ def test_complex_sorting(self): pytest.raises(TypeError, algos.factorize, x17[::-1], sort=True) - def test_uint64_factorize(self): + def test_uint64_factorize(self, writable): data = np.array([2**63, 1, 2**63], dtype=np.uint64) + data.setflags(write=writable) exp_labels = np.array([0, 1, 0], dtype=np.intp) exp_uniques = np.array([2**63, 1], dtype=np.uint64)
- [x] closes #12813 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry The bug was already fixed with my previous PR but this adds a fixture to a unit test to also test read-only arrays as factorize input.
https://api.github.com/repos/pandas-dev/pandas/pulls/21811
2018-07-08T13:48:15Z
2018-07-08T14:14:25Z
2018-07-08T14:14:24Z
2018-07-08T17:47:13Z
More doc warnings
diff --git a/doc/source/merging.rst b/doc/source/merging.rst index eb71722dd563a..d78e476dd7837 100644 --- a/doc/source/merging.rst +++ b/doc/source/merging.rst @@ -245,7 +245,7 @@ need to be: .. ipython:: python - result = df1.append(df4) + result = df1.append(df4, sort=False) .. ipython:: python :suppress: @@ -285,7 +285,7 @@ do this, use the ``ignore_index`` argument: .. ipython:: python - result = pd.concat([df1, df4], ignore_index=True) + result = pd.concat([df1, df4], ignore_index=True, sort=False) .. ipython:: python :suppress: @@ -299,7 +299,7 @@ This is also a valid argument to :meth:`DataFrame.append`: .. ipython:: python - result = df1.append(df4, ignore_index=True) + result = df1.append(df4, ignore_index=True, sort=False) .. ipython:: python :suppress: diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1c3d80bdc3abd..812ea366b704a 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -100,27 +100,33 @@ Creating a ``Tick`` object (:class:`Day`, :class:`Hour`, :class:`Minute`, `normalize=True` is no longer supported. This prevents unexpected behavior where addition could fail to be monotone or associative. (:issue:`21427`) -.. ipython:: python +*Previous Behavior*: - ts = pd.Timestamp('2018-06-11 18:01:14') - ts - tic = pd.offsets.Hour(n=2, normalize=True) - tic +.. code-block:: ipython -Previous Behavior: -.. code-block:: ipython + In [2]: ts = pd.Timestamp('2018-06-11 18:01:14') - In [4]: ts + tic - Out [4]: Timestamp('2018-06-11 00:00:00') + In [3]: ts + Out[3]: Timestamp('2018-06-11 18:01:14') - In [5]: ts + tic + tic + tic == ts + (tic + tic + tic) - Out [5]: False + In [4]: tic = pd.offsets.Hour(n=2, normalize=True) + ...: -Current Behavior: + In [5]: tic + Out[5]: <2 * Hours> + + In [6]: ts + tic + Out[6]: Timestamp('2018-06-11 00:00:00') + + In [7]: ts + tic + tic + tic == ts + (tic + tic + tic) + Out[7]: False + +*Current Behavior*: .. ipython:: python + ts = pd.Timestamp('2018-06-11 18:01:14') tic = pd.offsets.Hour(n=2) ts + tic + tic + tic == ts + (tic + tic + tic) diff --git a/pandas/core/strings.py b/pandas/core/strings.py index e422027b9b500..669b19fc35430 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2556,7 +2556,7 @@ def encode(self, encoding, errors="strict"): result = str_encode(self._data, encoding, errors) return self._wrap_result(result) - _shared_docs['str_strip'] = (""" + _shared_docs['str_strip'] = (r""" Remove leading and trailing characters. Strip whitespaces (including newlines) or a set of specified characters
https://api.github.com/repos/pandas-dev/pandas/pulls/21808
2018-07-08T02:33:32Z
2018-07-08T13:01:26Z
2018-07-08T13:01:26Z
2018-07-08T14:05:26Z
BENCH: asv csv reading benchmarks now rewind StringIO objects
diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py index 0f5d07f9fac55..2d4bdc7ae812a 100644 --- a/asv_bench/benchmarks/io/csv.py +++ b/asv_bench/benchmarks/io/csv.py @@ -54,7 +54,14 @@ def time_frame_date_formatting(self): self.data.to_csv(self.fname, date_format='%Y%m%d') -class ReadCSVDInferDatetimeFormat(object): +class StringIORewind(object): + + def data(self, stringio_object): + stringio_object.seek(0) + return stringio_object + + +class ReadCSVDInferDatetimeFormat(StringIORewind): goal_time = 0.2 params = ([True, False], ['custom', 'iso8601', 'ymd']) @@ -66,10 +73,12 @@ def setup(self, infer_datetime_format, format): 'iso8601': '%Y-%m-%d %H:%M:%S', 'ymd': '%Y%m%d'} dt_format = formats[format] - self.data = StringIO('\n'.join(rng.strftime(dt_format).tolist())) + self.StringIO_input = StringIO('\n'.join( + rng.strftime(dt_format).tolist())) def time_read_csv(self, infer_datetime_format, format): - read_csv(self.data, header=None, names=['foo'], parse_dates=['foo'], + read_csv(self.data(self.StringIO_input), + header=None, names=['foo'], parse_dates=['foo'], infer_datetime_format=infer_datetime_format) @@ -95,7 +104,7 @@ def time_skipprows(self, skiprows): read_csv(self.fname, skiprows=skiprows) -class ReadUint64Integers(object): +class ReadUint64Integers(StringIORewind): goal_time = 0.2 @@ -108,13 +117,13 @@ def setup(self): self.data2 = StringIO('\n'.join(arr.astype(str).tolist())) def time_read_uint64(self): - read_csv(self.data1, header=None, names=['foo']) + read_csv(self.data(self.data1), header=None, names=['foo']) def time_read_uint64_neg_values(self): - read_csv(self.data2, header=None, names=['foo']) + read_csv(self.data(self.data2), header=None, names=['foo']) def time_read_uint64_na_values(self): - read_csv(self.data1, header=None, names=['foo'], + read_csv(self.data(self.data1), header=None, names=['foo'], na_values=self.na_values) @@ -140,19 +149,20 @@ def time_thousands(self, sep, thousands): read_csv(self.fname, sep=sep, thousands=thousands) -class ReadCSVComment(object): +class ReadCSVComment(StringIORewind): goal_time = 0.2 def setup(self): data = ['A,B,C'] + (['1,2,3 # comment'] * 100000) - self.s_data = StringIO('\n'.join(data)) + self.StringIO_input = StringIO('\n'.join(data)) def time_comment(self): - read_csv(self.s_data, comment='#', header=None, names=list('abc')) + read_csv(self.data(self.StringIO_input), comment='#', + header=None, names=list('abc')) -class ReadCSVFloatPrecision(object): +class ReadCSVFloatPrecision(StringIORewind): goal_time = 0.2 params = ([',', ';'], ['.', '_'], [None, 'high', 'round_trip']) @@ -164,14 +174,14 @@ def setup(self, sep, decimal, float_precision): rows = sep.join(['0{}'.format(decimal) + '{}'] * 3) + '\n' data = rows * 5 data = data.format(*floats) * 200 # 1000 x 3 strings csv - self.s_data = StringIO(data) + self.StringIO_input = StringIO(data) def time_read_csv(self, sep, decimal, float_precision): - read_csv(self.s_data, sep=sep, header=None, names=list('abc'), - float_precision=float_precision) + read_csv(self.data(self.StringIO_input), sep=sep, header=None, + names=list('abc'), float_precision=float_precision) def time_read_csv_python_engine(self, sep, decimal, float_precision): - read_csv(self.s_data, sep=sep, header=None, engine='python', + read_csv(self.data(self.StringIO_input), sep=sep, header=None, engine='python', float_precision=None, names=list('abc')) @@ -193,7 +203,7 @@ def time_convert_direct(self): read_csv(self.fname, dtype='category') -class ReadCSVParseDates(object): +class ReadCSVParseDates(StringIORewind): goal_time = 0.2 @@ -206,12 +216,14 @@ def setup(self): """ two_cols = ['KORD,19990127'] * 5 data = data.format(*two_cols) - self.s_data = StringIO(data) + self.StringIO_input = StringIO(data) def time_multiple_date(self): - read_csv(self.s_data, sep=',', header=None, - names=list(string.digits[:9]), parse_dates=[[1, 2], [1, 3]]) + read_csv(self.data(self.StringIO_input), sep=',', header=None, + names=list(string.digits[:9]), + parse_dates=[[1, 2], [1, 3]]) def time_baseline(self): - read_csv(self.s_data, sep=',', header=None, parse_dates=[1], + read_csv(self.data(self.StringIO_input), sep=',', header=None, + parse_dates=[1], names=list(string.digits[:9]))
In short, the `asv` benchmarks used for timing `read_csv` are actually reading in empty file-like objects most of the time at the moment. This is because the `setup()` method of the benchmarks is only called between **repeats** and not between **iterations** of repeats--see [writing benchmarks docs](http://asv.readthedocs.io/en/latest/writing_benchmarks.html#timing). You can confirm this by simply printing the `size` of the dataframes you get from `read_csv` in any StringIO-dependent benchmarks--the **first** iteration of a repeat should have the correct size, but the rest will all be 0. You could also just print the memory address (StringIO object)--they'll all be the same after the first iteration of a repeat. I did this with @stefanv and @mattip in the NumPy context. This can be quite confusing--a bit different than the paradigm you might expect in i.e, a unit test context--for more gory details see [my related comment in NumPy loadtxt() asv benchmarks](https://github.com/numpy/numpy/pull/11422#issuecomment-403247951). As noted there, one could probably avoid this by using an actual file object instead / if preferred, but realistically this just boils down to [how timeit works](https://stackoverflow.com/questions/8220801/how-to-use-timeit-module#comment11535453_8220943). Confounding the results with the seek is unfortunate, so working with file objects may be preferred if dumping files in the bench env is acceptable.
https://api.github.com/repos/pandas-dev/pandas/pulls/21807
2018-07-07T23:55:10Z
2018-07-28T14:29:32Z
2018-07-28T14:29:32Z
2018-07-28T14:29:35Z
Consistent Naming Standard When Using Dict in GroupBy .agg
diff --git a/pandas/core/base.py b/pandas/core/base.py index 4ea8c43b640fb..adab991821838 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -364,52 +364,46 @@ def nested_renaming_depr(level=4): "version"), FutureWarning, stacklevel=level) - # if we have a dict of any non-scalars - # eg. {'A' : ['mean']}, normalize all to - # be list-likes - if any(is_aggregator(x) for x in compat.itervalues(arg)): - new_arg = compat.OrderedDict() - for k, v in compat.iteritems(arg): - if not isinstance(v, (tuple, list, dict)): - new_arg[k] = [v] - else: - new_arg[k] = v - - # the keys must be in the columns - # for ndim=2, or renamers for ndim=1 - - # ok for now, but deprecated - # {'A': { 'ra': 'mean' }} - # {'A': { 'ra': ['mean'] }} - # {'ra': ['mean']} - - # not ok - # {'ra' : { 'A' : 'mean' }} - if isinstance(v, dict): - is_nested_renamer = True - - if k not in obj.columns: - msg = ('cannot perform renaming for {key} with a ' - 'nested dictionary').format(key=k) - raise SpecificationError(msg) - nested_renaming_depr(4 + (_level or 0)) - - elif isinstance(obj, ABCSeries): - nested_renaming_depr() - elif isinstance(obj, ABCDataFrame) and \ - k not in obj.columns: - raise KeyError( - "Column '{col}' does not exist!".format(col=k)) - - arg = new_arg - - else: + if any(issubclass(type(x), dict) for x in compat.itervalues(arg)): # deprecation of renaming keys # GH 15931 - keys = list(compat.iterkeys(arg)) - if (isinstance(obj, ABCDataFrame) and - len(obj.columns.intersection(keys)) != len(keys)): + nested_renaming_depr() + + # normalize all non-scalars be list-likes + new_arg = compat.OrderedDict() + for k, v in compat.iteritems(arg): + if not isinstance(v, (tuple, list, dict)): + new_arg[k] = [v] + else: + new_arg[k] = v + + # the keys must be in the columns + # for ndim=2, or renamers for ndim=1 + + # ok for now, but deprecated + # {'A': { 'ra': 'mean' }} + # {'A': { 'ra': ['mean'] }} + # {'ra': ['mean']} + + # not ok + # {'ra' : { 'A' : 'mean' }} + if isinstance(v, dict): + is_nested_renamer = True + + if k not in obj.columns: + msg = ('cannot perform renaming for {key} with a ' + 'nested dictionary').format(key=k) + raise SpecificationError(msg) + nested_renaming_depr(4 + (_level or 0)) + + elif isinstance(obj, ABCSeries): nested_renaming_depr() + elif isinstance(obj, ABCDataFrame) and \ + k not in obj.columns: + raise KeyError( + "Column '{col}' does not exist!".format(col=k)) + + arg = new_arg from pandas.core.reshape.concat import concat @@ -456,11 +450,6 @@ def _agg(arg, func): result.update(r) keys = list(compat.iterkeys(result)) - else: - - if self._selection is not None: - keys = None - # some selection on the object elif self._selection is not None: diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index b2f18e11de8ee..6af5dbcc09dc2 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -117,11 +117,11 @@ def test_agg_python_multiindex(mframe): tm.assert_frame_equal(result, expected) -@pytest.mark.parametrize('groupbyfunc', [ - lambda x: x.weekday(), - [lambda x: x.month, lambda x: x.weekday()], +@pytest.mark.parametrize('groupbyfunc,multiple', [ + (lambda x: x.weekday(), False), + ([lambda x: x.month, lambda x: x.weekday()], True), ]) -def test_aggregate_str_func(tsframe, groupbyfunc): +def test_aggregate_str_func(tsframe, groupbyfunc, multiple): grouped = tsframe.groupby(groupbyfunc) # single series @@ -139,10 +139,19 @@ def test_aggregate_str_func(tsframe, groupbyfunc): ['B', 'std'], ['C', 'mean'], ['D', 'sem']])) - expected = DataFrame(OrderedDict([['A', grouped['A'].var()], - ['B', grouped['B'].std()], - ['C', grouped['C'].mean()], - ['D', grouped['D'].sem()]])) + + columns = pd.MultiIndex.from_arrays([ + list('ABCD'), ['var', 'std', 'mean', 'sem']]) + expected = DataFrame(list(zip(grouped['A'].var(), + grouped['B'].std(), + grouped['C'].mean(), + grouped['D'].sem())), columns=columns) + + if multiple: + mi = pd.MultiIndex.from_product([ + range(1, len(groupbyfunc) + 1, 1), range(5)]) + expected = expected.set_index(mi) + tm.assert_frame_equal(result, expected) @@ -225,13 +234,11 @@ def test_more_flexible_frame_multi_function(df): exmean = grouped.agg(OrderedDict([['C', np.mean], ['D', np.mean]])) exstd = grouped.agg(OrderedDict([['C', np.std], ['D', np.std]])) - - expected = concat([exmean, exstd], keys=['mean', 'std'], axis=1) - expected = expected.swaplevel(0, 1, axis=1).sort_index(level=0, axis=1) + expected = concat([exmean, exstd], axis=1) + expected = expected.sort_index(axis=1) d = OrderedDict([['C', [np.mean, np.std]], ['D', [np.mean, np.std]]]) result = grouped.aggregate(d) - tm.assert_frame_equal(result, expected) # be careful @@ -239,13 +246,12 @@ def test_more_flexible_frame_multi_function(df): ['D', [np.mean, np.std]]])) expected = grouped.aggregate(OrderedDict([['C', np.mean], ['D', [np.mean, np.std]]])) + tm.assert_frame_equal(result, expected) - def foo(x): - return np.mean(x) - def bar(x): - return np.std(x, ddof=1) +def test_more_flexible_frame_mult_function_warns(df): + grouped = df.groupby('A') # this uses column selection & renaming with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): @@ -254,6 +260,12 @@ def bar(x): ['bar', np.std]])]]) result = grouped.aggregate(d) + def foo(x): + return np.mean(x) + + def bar(x): + return np.std(x, ddof=1) + d = OrderedDict([['C', [np.mean]], ['D', [foo, bar]]]) expected = grouped.aggregate(d) @@ -271,18 +283,18 @@ def test_multi_function_flexible_mix(df): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): expected = grouped.aggregate(d) - # Test 1 d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])], - ['D', 'sum']]) + ['D', ['sum']]]) # this uses column selection & renaming with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = grouped.aggregate(d) tm.assert_frame_equal(result, expected) - # Test 2 d = OrderedDict([['C', OrderedDict([['foo', 'mean'], ['bar', 'std']])], - ['D', ['sum']]]) + ['D', 'sum']]) + # this uses column selection & renaming with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = grouped.aggregate(d) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index 34489051efc18..a9ed4b7dbb54e 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -99,19 +99,23 @@ def test_agg_dict_parameter_cast_result_dtypes(): grouped = df.groupby('class') tm.assert_frame_equal(grouped.first(), exp) tm.assert_frame_equal(grouped.agg('first'), exp) - tm.assert_frame_equal(grouped.agg({'time': 'first'}), exp) tm.assert_series_equal(grouped.time.first(), exp['time']) tm.assert_series_equal(grouped.time.agg('first'), exp['time']) + exp.columns = pd.MultiIndex.from_tuples([('time', 'first')]) + tm.assert_frame_equal(grouped.agg({'time': 'first'}), exp) + # test for `last` function exp = df.loc[[0, 3, 4, 7]].set_index('class') grouped = df.groupby('class') tm.assert_frame_equal(grouped.last(), exp) tm.assert_frame_equal(grouped.agg('last'), exp) - tm.assert_frame_equal(grouped.agg({'time': 'last'}), exp) tm.assert_series_equal(grouped.time.last(), exp['time']) tm.assert_series_equal(grouped.time.agg('last'), exp['time']) + exp.columns = pd.MultiIndex.from_tuples([('time', 'last')]) + tm.assert_frame_equal(grouped.agg({'time': 'last'}), exp) + # count exp = pd.Series([2, 2, 2, 2], index=Index(list('ABCD'), name='class'), @@ -192,7 +196,9 @@ def test_aggregate_api_consistency(): tm.assert_frame_equal(result, expected, check_like=True) result = grouped.agg({'C': 'mean', 'D': 'sum'}) - expected = pd.concat([d_sum, c_mean], axis=1) + expected = pd.concat([c_mean, d_sum], axis=1) + expected.columns = MultiIndex.from_arrays([['C', 'D'], + ['mean', 'sum']]) tm.assert_frame_equal(result, expected, check_like=True) result = grouped.agg({'C': ['mean', 'sum'], @@ -201,13 +207,19 @@ def test_aggregate_api_consistency(): expected.columns = MultiIndex.from_product([['C', 'D'], ['mean', 'sum']]) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): +def test_aggregate_api_raises(): + df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar', + 'foo', 'bar', 'foo', 'foo'], + 'B': ['one', 'one', 'two', 'two', + 'two', 'two', 'one', 'two'], + 'C': np.random.randn(8) + 1.0, + 'D': np.arange(8)}) + + grouped = df.groupby(['A', 'B']) + + with pytest.raises(KeyError): result = grouped[['D', 'C']].agg({'r': np.sum, 'r2': np.mean}) - expected = pd.concat([d_sum, c_sum, d_mean, c_mean], axis=1) - expected.columns = MultiIndex.from_product([['r', 'r2'], - ['D', 'C']]) - tm.assert_frame_equal(result, expected, check_like=True) def test_agg_dict_renaming_deprecation(): @@ -222,14 +234,21 @@ def test_agg_dict_renaming_deprecation(): 'C': {'bar': ['count', 'min']}}) assert "using a dict with renaming" in str(w[0].message) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - df.groupby('A')[['B', 'C']].agg({'ma': 'max'}) - + # TODO: Shouldn't the below fail as well? with tm.assert_produces_warning(FutureWarning) as w: df.groupby('A').B.agg({'foo': 'count'}) assert "using a dict on a Series for aggregation" in str(w[0].message) +def test_agg_dict_renaming_deprecation_raises(): + df = pd.DataFrame({'A': [1, 1, 1, 2, 2], + 'B': range(5), + 'C': range(5)}) + + with pytest.raises(KeyError): + df.groupby('A')[['B', 'C']].agg({'ma': 'max'}) + + def test_agg_compat(): # GH 12334 df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar', @@ -267,11 +286,6 @@ def test_agg_nested_dicts(): g = df.groupby(['A', 'B']) - msg = r'cannot perform renaming for r[1-2] with a nested dictionary' - with tm.assert_raises_regex(SpecificationError, msg): - g.aggregate({'r1': {'C': ['mean', 'sum']}, - 'r2': {'D': ['mean', 'sum']}}) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = g.agg({'C': {'ra': ['mean', 'std']}, 'D': {'rb': ['mean', 'std']}}) @@ -283,6 +297,23 @@ def test_agg_nested_dicts(): ('rb', 'mean'), ('rb', 'std')]) tm.assert_frame_equal(result, expected, check_like=True) + +def test_agg_nested_dicts_raises(): + # API change for disallowing these types of nested dicts + df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar', + 'foo', 'bar', 'foo', 'foo'], + 'B': ['one', 'one', 'two', 'two', + 'two', 'two', 'one', 'two'], + 'C': np.random.randn(8) + 1.0, + 'D': np.arange(8)}) + + g = df.groupby(['A', 'B']) + + msg = r'cannot perform renaming for r[1-2] with a nested dictionary' + with tm.assert_raises_regex(SpecificationError, msg): + g.aggregate({'r1': {'C': ['mean', 'sum']}, + 'r2': {'D': ['mean', 'sum']}}) + # same name as the original column # GH9052 with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 66577d738dd28..ec4f06fa0d4d8 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -552,6 +552,8 @@ def test_groupby_as_index_agg(df): result2 = grouped.agg(OrderedDict([['C', np.mean], ['D', np.sum]])) expected2 = grouped.mean() expected2['D'] = grouped.sum()['D'] + expected2.columns = pd.MultiIndex.from_arrays([ + expected2.columns, ['', 'mean', 'sum']]) assert_frame_equal(result2, expected2) grouped = df.groupby('A', as_index=True) @@ -561,6 +563,7 @@ def test_groupby_as_index_agg(df): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result3 = grouped['C'].agg({'Q': np.sum}) + assert_frame_equal(result3, expected3) # multi-key @@ -574,10 +577,14 @@ def test_groupby_as_index_agg(df): result2 = grouped.agg(OrderedDict([['C', np.mean], ['D', np.sum]])) expected2 = grouped.mean() expected2['D'] = grouped.sum()['D'] + expected2.columns = pd.MultiIndex.from_arrays([ + expected2.columns, ['', '', 'mean', 'sum']]) assert_frame_equal(result2, expected2) expected3 = grouped['C'].sum() expected3 = DataFrame(expected3).rename(columns={'C': 'Q'}) + expected3.columns = pd.MultiIndex.from_arrays([ + expected3.columns, ['', '', 'sum']]) result3 = grouped['C'].agg({'Q': np.sum}) assert_frame_equal(result3, expected3) @@ -1340,6 +1347,7 @@ def test_multifunc_sum_bug(): grouped = x.groupby('test') result = grouped.agg({'fl': 'sum', 2: 'size'}) + result.columns = result.columns.droplevel(-1) assert result['fl'].dtype == np.float64 @@ -1693,3 +1701,25 @@ def test_groupby_agg_ohlc_non_first(): result = df.groupby(pd.Grouper(freq='D')).agg(['sum', 'ohlc']) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("select_columns", [True, False]) +@pytest.mark.parametrize("agg_argument", [ + {'B': 'sum', 'C': 'min'}, # Scalar result + {'B': 'sum', 'C': ['min']}, # Scalar and list + {'B': ['sum'], 'C': ['min']}, # Lists + {'B': {'sum': 'sum'}, 'C': {'min': 'min'}} # deprecated call +]) +def test_agg_dict_naming_consistency(select_columns, agg_argument): + df = pd.DataFrame([['foo', 1, 1], ['bar', 1, 1]], columns=['A', 'B', 'C']) + expected = pd.DataFrame([[1, 1], [1, 1]], index=pd.Index( + ['bar', 'foo'], name='A'), columns=pd.MultiIndex.from_tuples( + (('B', 'sum'), ('C', 'min')))) + + with catch_warnings(record=True): + if select_columns: + result = df.groupby('A')[['B', 'C']].agg(agg_argument) + else: + result = df.groupby('A').agg(agg_argument) + + tm.assert_frame_equal(result, expected)
- [X] closes #21790 - [] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This is a WIP as all of the tests in the groupby directory pass, but there are some outside of that which need touch ups. This is a relatively aggressive change so I figured I'd get buy in before going outside of that to modify tests. This not only addresses the referenced issue but provides consistent expectations around columns returned when using a `dict` argument in a `DataFrameGroupBy`, namely that the returned object will have a `MultiIndex` where the top level is the column name and the subsequent level is the aggregation performed. To play devil's advocate, this may be considered undesirable as it now returns a MultiIndex in *some* cases where that was flat before. However, I'd counter that this: - Behavior is more consistent and easier to communicate - Provides a return value whose column labeling is less ambiguous AND - Simplifies the code base, providing us a clear path forward for whatever the renaming solution actually SHOULD be Curious to hear other's feedback @jreback @TomAugspurger @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/21806
2018-07-07T23:03:05Z
2018-08-17T17:17:10Z
null
2019-02-28T07:23:19Z
DOC: Bunch o warnings
diff --git a/doc/source/extending.rst b/doc/source/extending.rst index dcabfed2b6021..9422434a1d998 100644 --- a/doc/source/extending.rst +++ b/doc/source/extending.rst @@ -80,7 +80,7 @@ on :ref:`ecosystem.extensions`. The interface consists of two classes. :class:`~pandas.api.extensions.ExtensionDtype` -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A :class:`pandas.api.extensions.ExtensionDtype` is similar to a ``numpy.dtype`` object. It describes the data type. Implementors are responsible for a few unique items like the name. @@ -124,7 +124,7 @@ and comments contain guidance for properly implementing the interface. .. _extending.extension.operator: :class:`~pandas.api.extensions.ExtensionArray` Operator Support -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. versionadded:: 0.24.0 diff --git a/doc/source/text.rst b/doc/source/text.rst index dde82e3c19f82..0081b592f91bf 100644 --- a/doc/source/text.rst +++ b/doc/source/text.rst @@ -312,7 +312,7 @@ All one-dimensional list-likes can be arbitrarily combined in a list-like contai s u - s.str.cat([u, u.values, ['A', 'B', 'C', 'D'], map(str, u.index)], na_rep='-') + s.str.cat([u.values, ['A', 'B', 'C', 'D'], map(str, u.index)], na_rep='-') All elements must match in length to the calling ``Series`` (or ``Index``), except those having an index if ``join`` is not None: diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 2430b6ac2bbd4..7509c502f27ed 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -202,7 +202,7 @@ for storing ip addresses. ...: ``IPArray`` isn't a normal 1-D NumPy array, but because it's a pandas -:class:`~pandas.api.extension.ExtensionArray`, it can be stored properly inside pandas' containers. +:class:`~pandas.api.extensions.ExtensionArray`, it can be stored properly inside pandas' containers. .. code-block:: ipython diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index a2210c39bb6a6..1c3d80bdc3abd 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -81,7 +81,7 @@ Other Enhancements (:issue:`21627`) - New method :meth:`HDFStore.walk` will recursively walk the group hierarchy of an HDF5 file (:issue:`10932`) - :func:`read_html` copies cell data across ``colspan``s and ``rowspan``s, and it treats all-``th`` table rows as headers if ``header`` kwarg is not given and there is no ``thead`` (:issue:`17054`) -- :meth:`Series.nlargest`, :meth:`Series.nsmallest`, :meth:`DataFrame.nlargest`, and :meth:`DataFrame.nsmallest` now accept the value ``"all"`` for the ``keep` argument. This keeps all ties for the nth largest/smallest value (:issue:`16818`) +- :meth:`Series.nlargest`, :meth:`Series.nsmallest`, :meth:`DataFrame.nlargest`, and :meth:`DataFrame.nsmallest` now accept the value ``"all"`` for the ``keep`` argument. This keeps all ties for the nth largest/smallest value (:issue:`16818`) - :class:`IntervalIndex` has gained the :meth:`~IntervalIndex.set_closed` method to change the existing ``closed`` value (:issue:`21670`) - @@ -183,15 +183,8 @@ ExtensionType Changes - :meth:`Series.combine()` with scalar argument now works for any function type (:issue:`21248`) - -.. _whatsnew_0240.api.other: - -Other API Changes -^^^^^^^^^^^^^^^^^ - .. _whatsnew_0240.api.incompatibilities: -- Trying to reindex a ``DataFrame`` with a non unique ``MultiIndex`` now raises a ``ValueError`` instead of an ``Exception`` (:issue:`21770`) - Series and Index Data-Dtype Incompatibilities ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -231,7 +224,7 @@ Other API Changes - :class:`DatetimeIndex` now accepts :class:`Int64Index` arguments as epoch timestamps (:issue:`20997`) - Invalid construction of ``IntervalDtype`` will now always raise a ``TypeError`` rather than a ``ValueError`` if the subdtype is invalid (:issue:`21185`) -- +- Trying to reindex a ``DataFrame`` with a non unique ``MultiIndex`` now raises a ``ValueError`` instead of an ``Exception`` (:issue:`21770`) - .. _whatsnew_0240.deprecations: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 97592ab75845a..7e8fef9644d8c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4199,8 +4199,9 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None, * 1, or 'columns' : Drop columns which contain missing value. .. deprecated:: 0.23.0 - Pass tuple or list to drop on multiple axes. - Only a single axis is allowed. + + Pass tuple or list to drop on multiple axes. + Only a single axis is allowed. how : {'any', 'all'}, default 'any' Determine if row or column is removed from DataFrame, when we have @@ -4208,6 +4209,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None, * 'any' : If any NA values are present, drop that row or column. * 'all' : If all values are NA, drop that row or column. + thresh : int, optional Require that many non-NA values. subset : array-like, optional @@ -4676,10 +4678,11 @@ def nsmallest(self, n, columns, keep='first'): Column name or names to order by keep : {'first', 'last', 'all'}, default 'first' Where there are duplicate values: + - ``first`` : take the first occurrence. - ``last`` : take the last occurrence. - ``all`` : do not drop any duplicates, even it means - selecting more than `n` items. + selecting more than `n` items. .. versionadded:: 0.24.0 diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 353a92e25d3cf..a1e9a9a6e561d 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1879,6 +1879,7 @@ def tz_localize(self, tz, ambiguous='raise', errors='raise'): remove the time zone information preserving local time. ambiguous : str {'infer', 'NaT', 'raise'} or bool array, default 'raise' + - 'infer' will attempt to infer fall dst-transition hours based on order - bool-ndarray where True signifies a DST time, False signifies a @@ -1887,10 +1888,12 @@ def tz_localize(self, tz, ambiguous='raise', errors='raise'): - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times + errors : {'raise', 'coerce'}, default 'raise' + - 'raise' will raise a NonExistentTimeError if a timestamp is not - valid in the specified time zone (e.g. due to a transition from - or to DST time) + valid in the specified time zone (e.g. due to a transition from + or to DST time) - 'coerce' will return NaT if the timestamp can not be converted to the specified time zone
https://api.github.com/repos/pandas-dev/pandas/pulls/21805
2018-07-07T22:55:10Z
2018-07-07T22:58:07Z
2018-07-07T22:58:07Z
2018-07-07T23:04:25Z
implement constructors for TimedeltaArray, DatetimeArray
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index a9cf0301747b0..118516192e4ed 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -18,7 +18,37 @@ from pandas.core.algorithms import checked_add_with_arr -class DatetimeLikeArrayMixin(object): +class AttributesMixin(object): + + @property + def _attributes(self): + # Inheriting subclass should implement _attributes as a list of strings + from pandas.errors import AbstractMethodError + raise AbstractMethodError(self) + + @classmethod + def _simple_new(cls, values, **kwargs): + from pandas.errors import AbstractMethodError + raise AbstractMethodError(cls) + + def _get_attributes_dict(self): + """return an attributes dict for my class""" + return {k: getattr(self, k, None) for k in self._attributes} + + def _shallow_copy(self, values=None, **kwargs): + if values is None: + # Note: slightly different from Index implementation which defaults + # to self.values + values = self._ndarray_values + + attributes = self._get_attributes_dict() + attributes.update(kwargs) + if not len(values) and 'dtype' not in kwargs: + attributes['dtype'] = self.dtype + return self._simple_new(values, **attributes) + + +class DatetimeLikeArrayMixin(AttributesMixin): """ Shared Base/Mixin class for DatetimeArray, TimedeltaArray, PeriodArray @@ -56,9 +86,61 @@ def asi8(self): # do not cache or you'll create a memory leak return self.values.view('i8') + # ------------------------------------------------------------------ + # Array-like Methods + def __len__(self): return len(self._data) + def __getitem__(self, key): + """ + This getitem defers to the underlying array, which by-definition can + only handle list-likes, slices, and integer scalars + """ + + is_int = lib.is_integer(key) + if lib.is_scalar(key) and not is_int: + raise IndexError("only integers, slices (`:`), ellipsis (`...`), " + "numpy.newaxis (`None`) and integer or boolean " + "arrays are valid indices") + + getitem = self._data.__getitem__ + if is_int: + val = getitem(key) + return self._box_func(val) + else: + if com.is_bool_indexer(key): + key = np.asarray(key) + if key.all(): + key = slice(0, None, None) + else: + key = lib.maybe_booleans_to_slice(key.view(np.uint8)) + + attribs = self._get_attributes_dict() + + is_period = is_period_dtype(self) + if is_period: + freq = self.freq + else: + freq = None + if isinstance(key, slice): + if self.freq is not None and key.step is not None: + freq = key.step * self.freq + else: + freq = self.freq + + attribs['freq'] = freq + + result = getitem(key) + if result.ndim > 1: + # To support MPL which performs slicing with 2 dim + # even though it only has 1 dim by definition + if is_period: + return self._simple_new(result, **attribs) + return result + + return self._simple_new(result, **attribs) + # ------------------------------------------------------------------ # Null Handling @@ -97,6 +179,27 @@ def _maybe_mask_results(self, result, fill_value=None, convert=None): result[self._isnan] = fill_value return result + def _nat_new(self, box=True): + """ + Return Array/Index or ndarray filled with NaT which has the same + length as the caller. + + Parameters + ---------- + box : boolean, default True + - If True returns a Array/Index as the same as caller. + - If False returns ndarray of np.int64. + """ + result = np.zeros(len(self), dtype=np.int64) + result.fill(iNaT) + if not box: + return result + + attribs = self._get_attributes_dict() + if not is_period_dtype(self): + attribs['freq'] = None + return self._simple_new(result, **attribs) + # ------------------------------------------------------------------ # Frequency Properties/Methods @@ -195,6 +298,17 @@ def _add_delta_tdi(self, other): new_values[mask] = iNaT return new_values.view('i8') + def _add_nat(self): + """Add pd.NaT to self""" + if is_period_dtype(self): + raise TypeError('Cannot add {cls} and {typ}' + .format(cls=type(self).__name__, + typ=type(NaT).__name__)) + + # GH#19124 pd.NaT is treated like a timedelta for both timedelta + # and datetime dtypes + return self._nat_new(box=True) + def _sub_nat(self): """Subtract pd.NaT from self""" # GH#19124 Timedelta - datetime is not in general well-defined. diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index cbdbc021cfd72..e6e0544bfa22b 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -6,13 +6,21 @@ from pandas._libs import tslib from pandas._libs.tslib import Timestamp, NaT, iNaT -from pandas._libs.tslibs import conversion, fields, timezones +from pandas._libs.tslibs import ( + conversion, fields, timezones, + resolution as libresolution) from pandas.util._decorators import cache_readonly -from pandas.core.dtypes.common import _NS_DTYPE, is_datetime64tz_dtype +from pandas.core.dtypes.common import ( + _NS_DTYPE, + is_datetime64tz_dtype, + is_datetime64_dtype, + _ensure_int64) from pandas.core.dtypes.dtypes import DatetimeTZDtype +from pandas.tseries.frequencies import to_offset, DateOffset + from .datetimelike import DatetimeLikeArrayMixin @@ -66,6 +74,50 @@ class DatetimeArrayMixin(DatetimeLikeArrayMixin): 'is_year_end', 'is_leap_year'] _object_ops = ['weekday_name', 'freq', 'tz'] + # ----------------------------------------------------------------- + # Constructors + + _attributes = ["freq", "tz"] + + @classmethod + def _simple_new(cls, values, freq=None, tz=None, **kwargs): + """ + we require the we have a dtype compat for the values + if we are passed a non-dtype compat, then coerce using the constructor + """ + + if getattr(values, 'dtype', None) is None: + # empty, but with dtype compat + if values is None: + values = np.empty(0, dtype=_NS_DTYPE) + return cls(values, freq=freq, tz=tz, **kwargs) + values = np.array(values, copy=False) + + if not is_datetime64_dtype(values): + values = _ensure_int64(values).view(_NS_DTYPE) + + result = object.__new__(cls) + result._data = values + result._freq = freq + tz = timezones.maybe_get_tz(tz) + result._tz = timezones.tz_standardize(tz) + return result + + def __new__(cls, values, freq=None, tz=None): + if (freq is not None and not isinstance(freq, DateOffset) and + freq != 'infer'): + freq = to_offset(freq) + + result = cls._simple_new(values, freq=freq, tz=tz) + if freq == 'infer': + inferred = result.inferred_freq + if inferred: + result.freq = to_offset(inferred) + + # NB: Among other things not yet ported from the DatetimeIndex + # constructor, this does not call _deepcopy_if_needed + return result + # ----------------------------------------------------------------- # Descriptive Properties @@ -116,6 +168,10 @@ def is_normalized(self): """ return conversion.is_date_array_normalized(self.asi8, self.tz) + @property # NB: override with cache_readonly in immutable subclasses + def _resolution(self): + return libresolution.resolution(self.asi8, self.tz) + # ---------------------------------------------------------------- # Array-like Methods @@ -207,6 +263,173 @@ def _local_timestamps(self): reverse.put(indexer, np.arange(n)) return result.take(reverse) + def tz_convert(self, tz): + """ + Convert tz-aware Datetime Array/Index from one time zone to another. + + Parameters + ---------- + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time. Corresponding timestamps would be converted + to this time zone of the Datetime Array/Index. A `tz` of None will + convert to UTC and remove the timezone information. + + Returns + ------- + normalized : same type as self + + Raises + ------ + TypeError + If Datetime Array/Index is tz-naive. + + See Also + -------- + DatetimeIndex.tz : A timezone that has a variable offset from UTC + DatetimeIndex.tz_localize : Localize tz-naive DatetimeIndex to a + given time zone, or remove timezone from a tz-aware DatetimeIndex. + + Examples + -------- + With the `tz` parameter, we can change the DatetimeIndex + to other time zones: + + >>> dti = pd.DatetimeIndex(start='2014-08-01 09:00', + ... freq='H', periods=3, tz='Europe/Berlin') + + >>> dti + DatetimeIndex(['2014-08-01 09:00:00+02:00', + '2014-08-01 10:00:00+02:00', + '2014-08-01 11:00:00+02:00'], + dtype='datetime64[ns, Europe/Berlin]', freq='H') + + >>> dti.tz_convert('US/Central') + DatetimeIndex(['2014-08-01 02:00:00-05:00', + '2014-08-01 03:00:00-05:00', + '2014-08-01 04:00:00-05:00'], + dtype='datetime64[ns, US/Central]', freq='H') + + With the ``tz=None``, we can remove the timezone (after converting + to UTC if necessary): + + >>> dti = pd.DatetimeIndex(start='2014-08-01 09:00',freq='H', + ... periods=3, tz='Europe/Berlin') + + >>> dti + DatetimeIndex(['2014-08-01 09:00:00+02:00', + '2014-08-01 10:00:00+02:00', + '2014-08-01 11:00:00+02:00'], + dtype='datetime64[ns, Europe/Berlin]', freq='H') + + >>> dti.tz_convert(None) + DatetimeIndex(['2014-08-01 07:00:00', + '2014-08-01 08:00:00', + '2014-08-01 09:00:00'], + dtype='datetime64[ns]', freq='H') + """ + tz = timezones.maybe_get_tz(tz) + + if self.tz is None: + # tz naive, use tz_localize + raise TypeError('Cannot convert tz-naive timestamps, use ' + 'tz_localize to localize') + + # No conversion since timestamps are all UTC to begin with + return self._shallow_copy(tz=tz) + + def tz_localize(self, tz, ambiguous='raise', errors='raise'): + """ + Localize tz-naive Datetime Array/Index to tz-aware + Datetime Array/Index. + + This method takes a time zone (tz) naive Datetime Array/Index object + and makes this time zone aware. It does not move the time to another + time zone. + Time zone localization helps to switch from time zone aware to time + zone unaware objects. + + Parameters + ---------- + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone to convert timestamps to. Passing ``None`` will + remove the time zone information preserving local time. + ambiguous : str {'infer', 'NaT', 'raise'} or bool array, + default 'raise' + + - 'infer' will attempt to infer fall dst-transition hours based on + order + - bool-ndarray where True signifies a DST time, False signifies a + non-DST time (note that this flag is only applicable for + ambiguous times) + - 'NaT' will return NaT where there are ambiguous times + - 'raise' will raise an AmbiguousTimeError if there are ambiguous + times + + errors : {'raise', 'coerce'}, default 'raise' + + - 'raise' will raise a NonExistentTimeError if a timestamp is not + valid in the specified time zone (e.g. due to a transition from + or to DST time) + - 'coerce' will return NaT if the timestamp can not be converted + to the specified time zone + + .. versionadded:: 0.19.0 + + Returns + ------- + result : same type as self + Array/Index converted to the specified time zone. + + Raises + ------ + TypeError + If the Datetime Array/Index is tz-aware and tz is not None. + + See Also + -------- + DatetimeIndex.tz_convert : Convert tz-aware DatetimeIndex from + one time zone to another. + + Examples + -------- + >>> tz_naive = pd.date_range('2018-03-01 09:00', periods=3) + >>> tz_naive + DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', + '2018-03-03 09:00:00'], + dtype='datetime64[ns]', freq='D') + + Localize DatetimeIndex in US/Eastern time zone: + + >>> tz_aware = tz_naive.tz_localize(tz='US/Eastern') + >>> tz_aware + DatetimeIndex(['2018-03-01 09:00:00-05:00', + '2018-03-02 09:00:00-05:00', + '2018-03-03 09:00:00-05:00'], + dtype='datetime64[ns, US/Eastern]', freq='D') + + With the ``tz=None``, we can remove the time zone information + while keeping the local time (not converted to UTC): + + >>> tz_aware.tz_localize(None) + DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', + '2018-03-03 09:00:00'], + dtype='datetime64[ns]', freq='D') + """ + if self.tz is not None: + if tz is None: + new_dates = conversion.tz_convert(self.asi8, 'UTC', self.tz) + else: + raise TypeError("Already tz-aware, use tz_convert to convert.") + else: + tz = timezones.maybe_get_tz(tz) + # Convert to UTC + + new_dates = conversion.tz_localize_to_utc(self.asi8, tz, + ambiguous=ambiguous, + errors=errors) + new_dates = new_dates.view(_NS_DTYPE) + return self._shallow_copy(new_dates, tz=tz) + # ---------------------------------------------------------------- # Conversion Methods - Vectorized analogues of Timestamp methods diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 08e894ce6c31c..fa416e30493e9 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -113,20 +113,8 @@ def freq(self, value): _attributes = ["freq"] - def _get_attributes_dict(self): - """return an attributes dict for my class""" - return {k: getattr(self, k, None) for k in self._attributes} - - # TODO: share docstring? - def _shallow_copy(self, values=None, **kwargs): - if values is None: - values = self._ndarray_values - attributes = self._get_attributes_dict() - attributes.update(kwargs) - return self._simple_new(values, **attributes) - @classmethod - def _simple_new(cls, values, freq=None): + def _simple_new(cls, values, freq=None, **kwargs): """ Values can be any type that can be coerced to Periods. Ordinals in an ndarray are fastpath-ed to `_from_ordinals` diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index 4258679e1ddc5..af0fa2c3477f4 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -6,14 +6,16 @@ from pandas._libs import tslib from pandas._libs.tslib import Timedelta, NaT from pandas._libs.tslibs.fields import get_timedelta_field +from pandas._libs.tslibs.timedeltas import array_to_timedelta64 from pandas import compat -from pandas.core.dtypes.common import _TD_DTYPE +from pandas.core.dtypes.common import _TD_DTYPE, _ensure_int64 from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.missing import isna -from pandas.tseries.offsets import Tick +from pandas.tseries.offsets import Tick, DateOffset +from pandas.tseries.frequencies import to_offset from .datetimelike import DatetimeLikeArrayMixin @@ -46,6 +48,36 @@ def _box_func(self): def dtype(self): return _TD_DTYPE + # ---------------------------------------------------------------- + # Constructors + _attributes = ["freq"] + + @classmethod + def _simple_new(cls, values, freq=None, **kwargs): + values = np.array(values, copy=False) + if values.dtype == np.object_: + values = array_to_timedelta64(values) + if values.dtype != _TD_DTYPE: + values = _ensure_int64(values).view(_TD_DTYPE) + + result = object.__new__(cls) + result._data = values + result._freq = freq + return result + + def __new__(cls, values, freq=None): + if (freq is not None and not isinstance(freq, DateOffset) and + freq != 'infer'): + freq = to_offset(freq) + + result = cls._simple_new(values, freq=freq) + if freq == 'infer': + inferred = result.inferred_freq + if inferred: + result._freq = to_offset(inferred) + + return result + # ---------------------------------------------------------------- # Arithmetic Methods diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 5d0cc27979ee5..daaa40addf6c0 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -367,76 +367,6 @@ def __contains__(self, key): contains = __contains__ - def __getitem__(self, key): - """ - This getitem defers to the underlying array, which by-definition can - only handle list-likes, slices, and integer scalars - """ - - is_int = is_integer(key) - if is_scalar(key) and not is_int: - raise IndexError("only integers, slices (`:`), ellipsis (`...`), " - "numpy.newaxis (`None`) and integer or boolean " - "arrays are valid indices") - - getitem = self._data.__getitem__ - if is_int: - val = getitem(key) - return self._box_func(val) - else: - if com.is_bool_indexer(key): - key = np.asarray(key) - if key.all(): - key = slice(0, None, None) - else: - key = lib.maybe_booleans_to_slice(key.view(np.uint8)) - - attribs = self._get_attributes_dict() - - is_period = isinstance(self, ABCPeriodIndex) - if is_period: - freq = self.freq - else: - freq = None - if isinstance(key, slice): - if self.freq is not None and key.step is not None: - freq = key.step * self.freq - else: - freq = self.freq - - attribs['freq'] = freq - - result = getitem(key) - if result.ndim > 1: - # To support MPL which performs slicing with 2 dim - # even though it only has 1 dim by definition - if is_period: - return self._simple_new(result, **attribs) - return result - - return self._simple_new(result, **attribs) - - def _nat_new(self, box=True): - """ - Return Index or ndarray filled with NaT which has the same - length as the caller. - - Parameters - ---------- - box : boolean, default True - - If True returns a Index as the same as caller. - - If False returns ndarray of np.int64. - """ - result = np.zeros(len(self), dtype=np.int64) - result.fill(iNaT) - if not box: - return result - - attribs = self._get_attributes_dict() - if not is_period_dtype(self): - attribs['freq'] = None - return self._simple_new(result, **attribs) - # Try to run function on index first, and then on elements of index # Especially important for group-by functionality def map(self, f): @@ -669,17 +599,6 @@ def _convert_scalar_indexer(self, key, kind=None): return (super(DatetimeIndexOpsMixin, self) ._convert_scalar_indexer(key, kind=kind)) - def _add_nat(self): - """Add pd.NaT to self""" - if is_period_dtype(self): - raise TypeError('Cannot add {cls} and {typ}' - .format(cls=type(self).__name__, - typ=type(NaT).__name__)) - - # GH#19124 pd.NaT is treated like a timedelta for both timedelta - # and datetime dtypes - return self._nat_new(box=True) - def _addsub_offset_array(self, other, op): """ Add or subtract array-like of DateOffset objects @@ -706,7 +625,7 @@ def _addsub_offset_array(self, other, op): kwargs = {} if not is_period_dtype(self): kwargs['freq'] = 'infer' - return self._constructor(res_values, **kwargs) + return type(self)(res_values, **kwargs) @classmethod def _add_datetimelike_methods(cls): diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index a1e9a9a6e561d..53b1186b37a90 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -56,8 +56,7 @@ from pandas._libs import (lib, index as libindex, tslib as libts, join as libjoin, Timestamp) from pandas._libs.tslibs import (timezones, conversion, fields, parsing, - ccalendar, - resolution as libresolution) + ccalendar) # -------- some conversion wrapper functions @@ -266,6 +265,7 @@ class DatetimeIndex(DatetimeArrayMixin, DatelikeOps, TimelikeOps, PeriodIndex : Index of Period data pandas.to_datetime : Convert argument to datetime """ + _resolution = cache_readonly(DatetimeArrayMixin._resolution.fget) _typ = 'datetimeindex' _join_precedence = 10 @@ -614,12 +614,9 @@ def _simple_new(cls, values, name=None, freq=None, tz=None, elif not is_datetime64_dtype(values): values = _ensure_int64(values).view(_NS_DTYPE) - result = object.__new__(cls) - result._data = values + result = super(DatetimeIndex, cls)._simple_new(values, freq, tz, + **kwargs) result.name = name - result._freq = freq - result._tz = timezones.maybe_get_tz(tz) - result._tz = timezones.tz_standardize(result._tz) result._reset_identity() return result @@ -1707,10 +1704,6 @@ def inferred_type(self): def is_all_dates(self): return True - @cache_readonly - def _resolution(self): - return libresolution.resolution(self.asi8, self.tz) - def insert(self, loc, item): """ Make new Index inserting new item at location @@ -1788,172 +1781,6 @@ def delete(self, loc): return DatetimeIndex(new_dates, name=self.name, freq=freq, tz=self.tz) - def tz_convert(self, tz): - """ - Convert tz-aware DatetimeIndex from one time zone to another. - - Parameters - ---------- - tz : string, pytz.timezone, dateutil.tz.tzfile or None - Time zone for time. Corresponding timestamps would be converted - to this time zone of the DatetimeIndex. A `tz` of None will - convert to UTC and remove the timezone information. - - Returns - ------- - normalized : DatetimeIndex - - Raises - ------ - TypeError - If DatetimeIndex is tz-naive. - - See Also - -------- - DatetimeIndex.tz : A timezone that has a variable offset from UTC - DatetimeIndex.tz_localize : Localize tz-naive DatetimeIndex to a - given time zone, or remove timezone from a tz-aware DatetimeIndex. - - Examples - -------- - With the `tz` parameter, we can change the DatetimeIndex - to other time zones: - - >>> dti = pd.DatetimeIndex(start='2014-08-01 09:00', - ... freq='H', periods=3, tz='Europe/Berlin') - - >>> dti - DatetimeIndex(['2014-08-01 09:00:00+02:00', - '2014-08-01 10:00:00+02:00', - '2014-08-01 11:00:00+02:00'], - dtype='datetime64[ns, Europe/Berlin]', freq='H') - - >>> dti.tz_convert('US/Central') - DatetimeIndex(['2014-08-01 02:00:00-05:00', - '2014-08-01 03:00:00-05:00', - '2014-08-01 04:00:00-05:00'], - dtype='datetime64[ns, US/Central]', freq='H') - - With the ``tz=None``, we can remove the timezone (after converting - to UTC if necessary): - - >>> dti = pd.DatetimeIndex(start='2014-08-01 09:00',freq='H', - ... periods=3, tz='Europe/Berlin') - - >>> dti - DatetimeIndex(['2014-08-01 09:00:00+02:00', - '2014-08-01 10:00:00+02:00', - '2014-08-01 11:00:00+02:00'], - dtype='datetime64[ns, Europe/Berlin]', freq='H') - - >>> dti.tz_convert(None) - DatetimeIndex(['2014-08-01 07:00:00', - '2014-08-01 08:00:00', - '2014-08-01 09:00:00'], - dtype='datetime64[ns]', freq='H') - """ - tz = timezones.maybe_get_tz(tz) - - if self.tz is None: - # tz naive, use tz_localize - raise TypeError('Cannot convert tz-naive timestamps, use ' - 'tz_localize to localize') - - # No conversion since timestamps are all UTC to begin with - return self._shallow_copy(tz=tz) - - def tz_localize(self, tz, ambiguous='raise', errors='raise'): - """ - Localize tz-naive DatetimeIndex to tz-aware DatetimeIndex. - - This method takes a time zone (tz) naive DatetimeIndex object and - makes this time zone aware. It does not move the time to another - time zone. - Time zone localization helps to switch from time zone aware to time - zone unaware objects. - - Parameters - ---------- - tz : string, pytz.timezone, dateutil.tz.tzfile or None - Time zone to convert timestamps to. Passing ``None`` will - remove the time zone information preserving local time. - ambiguous : str {'infer', 'NaT', 'raise'} or bool array, - default 'raise' - - - 'infer' will attempt to infer fall dst-transition hours based on - order - - bool-ndarray where True signifies a DST time, False signifies a - non-DST time (note that this flag is only applicable for - ambiguous times) - - 'NaT' will return NaT where there are ambiguous times - - 'raise' will raise an AmbiguousTimeError if there are ambiguous - times - - errors : {'raise', 'coerce'}, default 'raise' - - - 'raise' will raise a NonExistentTimeError if a timestamp is not - valid in the specified time zone (e.g. due to a transition from - or to DST time) - - 'coerce' will return NaT if the timestamp can not be converted - to the specified time zone - - .. versionadded:: 0.19.0 - - Returns - ------- - DatetimeIndex - Index converted to the specified time zone. - - Raises - ------ - TypeError - If the DatetimeIndex is tz-aware and tz is not None. - - See Also - -------- - DatetimeIndex.tz_convert : Convert tz-aware DatetimeIndex from - one time zone to another. - - Examples - -------- - >>> tz_naive = pd.date_range('2018-03-01 09:00', periods=3) - >>> tz_naive - DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', - '2018-03-03 09:00:00'], - dtype='datetime64[ns]', freq='D') - - Localize DatetimeIndex in US/Eastern time zone: - - >>> tz_aware = tz_naive.tz_localize(tz='US/Eastern') - >>> tz_aware - DatetimeIndex(['2018-03-01 09:00:00-05:00', - '2018-03-02 09:00:00-05:00', - '2018-03-03 09:00:00-05:00'], - dtype='datetime64[ns, US/Eastern]', freq='D') - - With the ``tz=None``, we can remove the time zone information - while keeping the local time (not converted to UTC): - - >>> tz_aware.tz_localize(None) - DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', - '2018-03-03 09:00:00'], - dtype='datetime64[ns]', freq='D') - """ - if self.tz is not None: - if tz is None: - new_dates = conversion.tz_convert(self.asi8, 'UTC', self.tz) - else: - raise TypeError("Already tz-aware, use tz_convert to convert.") - else: - tz = timezones.maybe_get_tz(tz) - # Convert to UTC - - new_dates = conversion.tz_localize_to_utc(self.asi8, tz, - ambiguous=ambiguous, - errors=errors) - new_dates = new_dates.view(_NS_DTYPE) - return self._shallow_copy(new_dates, tz=tz) - def indexer_at_time(self, time, asof=False): """ Returns index locations of index values at particular time of day diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index e6c2094defb2d..3fa525b8617c5 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -597,14 +597,6 @@ def to_timestamp(self, freq=None, how='start'): new_data = period.periodarr_to_dt64arr(new_data._ndarray_values, base) return DatetimeIndex(new_data, freq='infer', name=self.name) - def _sub_period(self, other): - # If the operation is well-defined, we return an object-Index - # of DateOffsets. Null entries are filled with pd.NaT - new_data = PeriodArrayMixin._sub_period(self, other) - - # TODO: Should name=self.name be passed here? - return Index(new_data) - @property def inferred_type(self): # b/c data is represented as ints make sure we can't have ambiguous diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 25f72d38eeb9b..b1dc6e6286b98 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -36,7 +36,6 @@ from pandas.tseries.offsets import Tick, DateOffset from pandas._libs import (lib, index as libindex, join as libjoin, Timedelta, NaT, iNaT) -from pandas._libs.tslibs.timedeltas import array_to_timedelta64 def _wrap_field_accessor(name): @@ -312,16 +311,8 @@ def _generate(cls, start, end, periods, name, freq, closed=None): @classmethod def _simple_new(cls, values, name=None, freq=None, **kwargs): - values = np.array(values, copy=False) - if values.dtype == np.object_: - values = array_to_timedelta64(values) - if values.dtype != _TD_DTYPE: - values = _ensure_int64(values).view(_TD_DTYPE) - - result = object.__new__(cls) - result._data = values + result = super(TimedeltaIndex, cls)._simple_new(values, freq, **kwargs) result.name = name - result._freq = freq result._reset_identity() return result
Implements AttributesMixin since this is a pattern we might want to formalize. The `_simple_new` that this implements for TimedeltaArray and DatetimeArray are pretty close to the "full" versions in the Index classes. The `__new__` methods though are very much stripped down for the now. With these in place we get to move `tz_convert` and `tz_localize`. Could do a bunch more if I wasn't too much of a wuss to do it all in one go.
https://api.github.com/repos/pandas-dev/pandas/pulls/21803
2018-07-07T22:29:31Z
2018-07-08T12:57:11Z
2018-07-08T12:57:11Z
2018-07-11T20:23:47Z
CLN: Remove unused imports in pyx files
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index ae9d240afcb93..45ec0f0429e92 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1,6 +1,4 @@ # cython: profile=False -import operator - cimport cython from cython cimport Py_ssize_t @@ -29,7 +27,7 @@ from cpython.datetime cimport (PyDateTime_Check, PyDate_Check, PyDateTime_IMPORT) PyDateTime_IMPORT -from tslib import NaT, array_to_datetime +from tslib import array_to_datetime from missing cimport checknull diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index 79c30ac5f3778..6161a55b22342 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -15,7 +15,6 @@ cimport util from tslibs.np_datetime cimport get_timedelta64_value, get_datetime64_value from tslibs.nattype import NaT -from tslibs.nattype cimport is_null_datetimelike cdef double INF = <double> np.inf cdef double NEGINF = -INF diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index c1a0e58a4fb1a..31be057b1a57d 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -38,14 +38,13 @@ import pytz from tslibs.timedeltas cimport cast_from_unit -from tslibs.timedeltas import Timedelta, ints_to_pytimedelta # noqa:F841 from tslibs.timezones cimport (is_utc, is_tzlocal, is_fixed_offset, treat_tz_as_pytz, get_dst_info) from tslibs.conversion cimport (tz_convert_single, _TSObject, convert_datetime_to_tsobject, get_datetime64_nanos, tz_convert_utc_to_tzlocal) -from tslibs.conversion import tz_convert_single, normalize_date # noqa:F841 +from tslibs.conversion import tz_convert_single from tslibs.nattype import NaT, nat_strings, iNaT from tslibs.nattype cimport checknull_with_nat, NPY_NAT diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx index 56dcd5c405c6b..7803595badee1 100644 --- a/pandas/_libs/tslibs/frequencies.pyx +++ b/pandas/_libs/tslibs/frequencies.pyx @@ -5,7 +5,6 @@ import re cimport cython cimport numpy as cnp -from numpy cimport int64_t cnp.import_array() from util cimport is_integer_object, is_string_object diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 1b319e12f06d5..27b7f03358a3a 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -11,7 +11,6 @@ from cpython.datetime cimport (PyDateTime_IMPORT, PyDateTime_CheckExact, PyDateTime_IMPORT from dateutil.relativedelta import relativedelta -from pytz import UTC import numpy as np cimport numpy as cnp @@ -24,7 +23,6 @@ from util cimport is_string_object, is_integer_object from ccalendar import MONTHS, DAYS from ccalendar cimport get_days_in_month, dayofweek from conversion cimport tz_convert_single, pydt_to_i8, localize_pydatetime -from frequencies cimport get_freq_code from nattype cimport NPY_NAT from np_datetime cimport (pandas_datetimestruct, dtstruct_to_dt64, dt64_to_dtstruct) diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 2ecd55ea88170..f5048d32e826b 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -6,10 +6,6 @@ Parsing functions for datetime and datetime-like strings. import sys import re -from cpython cimport PyString_Check, PyUnicode_Check - -from libc.stdlib cimport free - cimport cython from cython cimport Py_ssize_t @@ -34,7 +30,6 @@ else: # dateutil compat from dateutil.tz import (tzoffset, tzlocal as _dateutil_tzlocal, - tzfile as _dateutil_tzfile, tzutc as _dateutil_tzutc, tzstr as _dateutil_tzstr) from dateutil.relativedelta import relativedelta diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index d89c06d43ccb9..d4b7c00d78857 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # cython: profile=False -from datetime import datetime, date, timedelta +from datetime import datetime, date from cpython cimport ( PyUnicode_Check, @@ -37,7 +37,7 @@ cimport util from util cimport is_period_object, is_string_object, INT32_MIN from timestamps import Timestamp -from timezones cimport is_utc, is_tzlocal, get_utcoffset, get_dst_info +from timezones cimport is_utc, is_tzlocal, get_dst_info from timedeltas cimport delta_to_nanoseconds cimport ccalendar diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 8565857fa945f..c10e108081f02 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -15,12 +15,10 @@ from pandas._libs.khash cimport (khiter_t, kh_init_int64, kh_int64_t, kh_resize_int64, kh_get_int64) -from cpython.datetime cimport datetime - from np_datetime cimport pandas_datetimestruct, dt64_to_dtstruct from frequencies cimport get_freq_code from timezones cimport (is_utc, is_tzlocal, - maybe_get_tz, get_dst_info, get_utcoffset) + maybe_get_tz, get_dst_info) from fields import build_field_sarray from conversion import tz_convert from conversion cimport tz_convert_utc_to_tzlocal diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 77ce8e4ed4127..5b3d4399a6e10 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -31,7 +31,6 @@ import numpy as np from numpy cimport ndarray, int64_t from datetime import date as datetime_date -from cpython.datetime cimport datetime from np_datetime cimport (check_dts_bounds, dtstruct_to_dt64, pandas_datetimestruct) diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index 5121d293efcb6..9e704a9bd8d3f 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -20,8 +20,7 @@ cdef extern from "../src/headers/cmath" namespace "std": cimport util from util cimport numeric -from skiplist cimport (IndexableSkiplist, - node_t, skiplist_t, +from skiplist cimport (skiplist_t, skiplist_init, skiplist_destroy, skiplist_get, skiplist_insert, skiplist_remove)
cc @jbrockmendel Removed unused imports flagged by PyCharm. Compiled fine locally, waiting for CI to pass.
https://api.github.com/repos/pandas-dev/pandas/pulls/21802
2018-07-07T22:10:48Z
2018-07-08T18:51:22Z
null
2018-07-08T18:51:51Z
Use CB3 syntax for compiler
diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml index 86bed996c8aab..2bc42c1bd2dec 100644 --- a/conda.recipe/meta.yaml +++ b/conda.recipe/meta.yaml @@ -12,16 +12,19 @@ source: requirements: build: + - {{ compiler('c') }} + - {{ compiler('cxx') }} + host: - python + - pip - cython - - numpy 1.11.* + - numpy - setuptools >=3.3 - python-dateutil >=2.5.0 - pytz - run: - - python - - numpy >=1.11.* + - python {{ python }} + - {{ pin_compatible('numpy') }} - python-dateutil >=2.5.0 - pytz
This fixes the `headerpad_max_install_names` I was seeing.
https://api.github.com/repos/pandas-dev/pandas/pulls/21800
2018-07-07T21:07:18Z
2018-07-07T22:42:56Z
2018-07-07T22:42:56Z
2018-07-07T22:42:56Z
ENH: between_time, at_time accept axis parameter
diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 69232fa836102..51db86cc82be7 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -291,6 +291,7 @@ Other Enhancements - :meth:`read_excel()` now accepts ``usecols`` as a list of column names or callable (:issue:`18273`) - :meth:`MultiIndex.to_flat_index` has been added to flatten multiple levels into a single-level :class:`Index` object. - :meth:`DataFrame.to_stata` and :class:` pandas.io.stata.StataWriter117` can write mixed sting columns to Stata strl format (:issue:`23633`) +- :meth:`DataFrame.between_time` and :meth:`DataFrame.at_time` have gained the an ``axis`` parameter (:issue: `8839`) .. _whatsnew_0240.api_breaking: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7d8873fe6a642..dde671993a56b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7381,7 +7381,7 @@ def asfreq(self, freq, method=None, how=None, normalize=False, return asfreq(self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value) - def at_time(self, time, asof=False): + def at_time(self, time, asof=False, axis=None): """ Select values at particular time of day (e.g. 9:30AM). @@ -7393,6 +7393,10 @@ def at_time(self, time, asof=False): Parameters ---------- time : datetime.time or string + axis : {0 or 'index', 1 or 'columns'}, default 0 + + .. versionadded:: 0.24.0 + Returns ------- @@ -7422,14 +7426,20 @@ def at_time(self, time, asof=False): DatetimeIndex.indexer_at_time : Get just the index locations for values at particular time of the day. """ + if axis is None: + axis = self._stat_axis_number + axis = self._get_axis_number(axis) + + index = self._get_axis(axis) try: - indexer = self.index.indexer_at_time(time, asof=asof) - return self._take(indexer) + indexer = index.indexer_at_time(time, asof=asof) except AttributeError: raise TypeError('Index must be DatetimeIndex') + return self._take(indexer, axis=axis) + def between_time(self, start_time, end_time, include_start=True, - include_end=True): + include_end=True, axis=None): """ Select values between particular times of the day (e.g., 9:00-9:30 AM). @@ -7447,6 +7457,9 @@ def between_time(self, start_time, end_time, include_start=True, end_time : datetime.time or string include_start : boolean, default True include_end : boolean, default True + axis : {0 or 'index', 1 or 'columns'}, default 0 + + .. versionadded:: 0.24.0 Returns ------- @@ -7484,14 +7497,20 @@ def between_time(self, start_time, end_time, include_start=True, DatetimeIndex.indexer_between_time : Get just the index locations for values between particular times of the day. """ + if axis is None: + axis = self._stat_axis_number + axis = self._get_axis_number(axis) + + index = self._get_axis(axis) try: - indexer = self.index.indexer_between_time( + indexer = index.indexer_between_time( start_time, end_time, include_start=include_start, include_end=include_end) - return self._take(indexer) except AttributeError: raise TypeError('Index must be DatetimeIndex') + return self._take(indexer, axis=axis) + def resample(self, rule, how=None, axis=0, fill_method=None, closed=None, label=None, convention='start', kind=None, loffset=None, limit=None, base=0, on=None, level=None): diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 4f04169d08206..52f0b30bf0f0c 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -25,6 +25,11 @@ from pandas.tests.frame.common import TestData +@pytest.fixture(params=product([True, False], [True, False])) +def close_open_fixture(request): + return request.param + + class TestDataFrameTimeSeriesMethods(TestData): def test_diff(self): @@ -638,33 +643,49 @@ def test_at_time_raises(self): with pytest.raises(TypeError): # index is not a DatetimeIndex df.at_time('00:00') - def test_between_time(self): + @pytest.mark.parametrize('axis', ['index', 'columns', 0, 1]) + def test_at_time_axis(self, axis): + # issue 8839 + rng = date_range('1/1/2000', '1/5/2000', freq='5min') + ts = DataFrame(np.random.randn(len(rng), len(rng))) + ts.index, ts.columns = rng, rng + + indices = rng[(rng.hour == 9) & (rng.minute == 30) & (rng.second == 0)] + + if axis in ['index', 0]: + expected = ts.loc[indices, :] + elif axis in ['columns', 1]: + expected = ts.loc[:, indices] + + result = ts.at_time('9:30', axis=axis) + assert_frame_equal(result, expected) + + def test_between_time(self, close_open_fixture): rng = date_range('1/1/2000', '1/5/2000', freq='5min') ts = DataFrame(np.random.randn(len(rng), 2), index=rng) stime = time(0, 0) etime = time(1, 0) - - close_open = product([True, False], [True, False]) - for inc_start, inc_end in close_open: - filtered = ts.between_time(stime, etime, inc_start, inc_end) - exp_len = 13 * 4 + 1 - if not inc_start: - exp_len -= 5 - if not inc_end: - exp_len -= 4 - - assert len(filtered) == exp_len - for rs in filtered.index: - t = rs.time() - if inc_start: - assert t >= stime - else: - assert t > stime - - if inc_end: - assert t <= etime - else: - assert t < etime + inc_start, inc_end = close_open_fixture + + filtered = ts.between_time(stime, etime, inc_start, inc_end) + exp_len = 13 * 4 + 1 + if not inc_start: + exp_len -= 5 + if not inc_end: + exp_len -= 4 + + assert len(filtered) == exp_len + for rs in filtered.index: + t = rs.time() + if inc_start: + assert t >= stime + else: + assert t > stime + + if inc_end: + assert t <= etime + else: + assert t < etime result = ts.between_time('00:00', '01:00') expected = ts.between_time(stime, etime) @@ -676,27 +697,25 @@ def test_between_time(self): stime = time(22, 0) etime = time(9, 0) - close_open = product([True, False], [True, False]) - for inc_start, inc_end in close_open: - filtered = ts.between_time(stime, etime, inc_start, inc_end) - exp_len = (12 * 11 + 1) * 4 + 1 - if not inc_start: - exp_len -= 4 - if not inc_end: - exp_len -= 4 - - assert len(filtered) == exp_len - for rs in filtered.index: - t = rs.time() - if inc_start: - assert (t >= stime) or (t <= etime) - else: - assert (t > stime) or (t <= etime) - - if inc_end: - assert (t <= etime) or (t >= stime) - else: - assert (t < etime) or (t >= stime) + filtered = ts.between_time(stime, etime, inc_start, inc_end) + exp_len = (12 * 11 + 1) * 4 + 1 + if not inc_start: + exp_len -= 4 + if not inc_end: + exp_len -= 4 + + assert len(filtered) == exp_len + for rs in filtered.index: + t = rs.time() + if inc_start: + assert (t >= stime) or (t <= etime) + else: + assert (t > stime) or (t <= etime) + + if inc_end: + assert (t <= etime) or (t >= stime) + else: + assert (t < etime) or (t >= stime) def test_between_time_raises(self): # GH20725 @@ -704,6 +723,40 @@ def test_between_time_raises(self): with pytest.raises(TypeError): # index is not a DatetimeIndex df.between_time(start_time='00:00', end_time='12:00') + def test_between_time_axis(self, axis): + # issue 8839 + rng = date_range('1/1/2000', periods=100, freq='10min') + ts = DataFrame(np.random.randn(len(rng), len(rng))) + stime, etime = ('08:00:00', '09:00:00') + exp_len = 7 + + if axis in ['index', 0]: + ts.index = rng + assert len(ts.between_time(stime, etime)) == exp_len + assert len(ts.between_time(stime, etime, axis=0)) == exp_len + + if axis in ['columns', 1]: + ts.columns = rng + selected = ts.between_time(stime, etime, axis=1).columns + assert len(selected) == exp_len + + def test_between_time_axis_raises(self, axis): + # issue 8839 + rng = date_range('1/1/2000', periods=100, freq='10min') + mask = np.arange(0, len(rng)) + rand_data = np.random.randn(len(rng), len(rng)) + ts = DataFrame(rand_data, index=rng, columns=rng) + stime, etime = ('08:00:00', '09:00:00') + + if axis in ['columns', 1]: + ts.index = mask + pytest.raises(TypeError, ts.between_time, stime, etime) + pytest.raises(TypeError, ts.between_time, stime, etime, axis=0) + + if axis in ['index', 0]: + ts.columns = mask + pytest.raises(TypeError, ts.between_time, stime, etime, axis=1) + def test_operation_on_NaT(self): # Both NaT and Timestamp are in DataFrame. df = pd.DataFrame({'foo': [pd.NaT, pd.NaT, diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 1681255f7e6bd..969c20601c7c8 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -817,6 +817,17 @@ def test_between_time_formats(self): for time_string in strings: assert len(ts.between_time(*time_string)) == expected_length + def test_between_time_axis(self): + # issue 8839 + rng = date_range('1/1/2000', periods=100, freq='10min') + ts = Series(np.random.randn(len(rng)), index=rng) + stime, etime = ('08:00:00', '09:00:00') + expected_length = 7 + + assert len(ts.between_time(stime, etime)) == expected_length + assert len(ts.between_time(stime, etime, axis=0)) == expected_length + pytest.raises(ValueError, ts.between_time, stime, etime, axis=1) + def test_to_period(self): from pandas.core.indexes.period import period_range
xref #2141 - [x] closes #8839 - [x] tests added / passed Axis parameter added to between_time and at_time, defaults to index for DataFrame
https://api.github.com/repos/pandas-dev/pandas/pulls/21799
2018-07-07T20:13:04Z
2018-11-19T01:21:33Z
2018-11-19T01:21:33Z
2018-11-19T01:21:36Z
move PeriodIndex comparisons, implement PeriodArray constructor
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 74bf90eb94065..a9cf0301747b0 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1,15 +1,19 @@ # -*- coding: utf-8 -*- +import operator import numpy as np from pandas._libs import lib, iNaT, NaT -from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds +from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds, Timedelta from pandas._libs.tslibs.period import ( DIFFERENT_FREQ_INDEX, IncompatibleFrequency) +from pandas.errors import NullFrequencyError + from pandas.tseries import frequencies +from pandas.tseries.offsets import Tick -from pandas.core.dtypes.common import is_period_dtype +from pandas.core.dtypes.common import is_period_dtype, is_timedelta64_dtype import pandas.core.common as com from pandas.core.algorithms import checked_add_with_arr @@ -130,6 +134,17 @@ def inferred_freq(self): except ValueError: return None + @property # NB: override with cache_readonly in immutable subclasses + def _resolution(self): + return frequencies.Resolution.get_reso_from_freq(self.freqstr) + + @property # NB: override with cache_readonly in immutable subclasses + def resolution(self): + """ + Returns day, hour, minute, second, millisecond or microsecond + """ + return frequencies.Resolution.get_str(self._resolution) + # ------------------------------------------------------------------ # Arithmetic Methods @@ -228,3 +243,43 @@ def _sub_period_array(self, other): mask = (self._isnan) | (other._isnan) new_values[mask] = NaT return new_values + + def _addsub_int_array(self, other, op): + """ + Add or subtract array-like of integers equivalent to applying + `shift` pointwise. + + Parameters + ---------- + other : Index, ExtensionArray, np.ndarray + integer-dtype + op : {operator.add, operator.sub} + + Returns + ------- + result : same class as self + """ + assert op in [operator.add, operator.sub] + if is_period_dtype(self): + # easy case for PeriodIndex + if op is operator.sub: + other = -other + res_values = checked_add_with_arr(self.asi8, other, + arr_mask=self._isnan) + res_values = res_values.view('i8') + res_values[self._isnan] = iNaT + return self._from_ordinals(res_values, freq=self.freq) + + elif self.freq is None: + # GH#19123 + raise NullFrequencyError("Cannot shift with no freq") + + elif isinstance(self.freq, Tick): + # easy case where we can convert to timedelta64 operation + td = Timedelta(self.freq) + return op(self, td * other) + + # We should only get here with DatetimeIndex; dispatch + # to _addsub_offset_array + assert not is_timedelta64_dtype(self) + return op(self, np.array(other) * self.freq) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 34749f3631fca..cbdbc021cfd72 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -94,19 +94,28 @@ def _timezone(self): @property def offset(self): """get/set the frequency of the instance""" - msg = ('DatetimeIndex.offset has been deprecated and will be removed ' - 'in a future version; use DatetimeIndex.freq instead.') + msg = ('{cls}.offset has been deprecated and will be removed ' + 'in a future version; use {cls}.freq instead.' + .format(cls=type(self).__name__)) warnings.warn(msg, FutureWarning, stacklevel=2) return self.freq @offset.setter def offset(self, value): """get/set the frequency of the instance""" - msg = ('DatetimeIndex.offset has been deprecated and will be removed ' - 'in a future version; use DatetimeIndex.freq instead.') + msg = ('{cls}.offset has been deprecated and will be removed ' + 'in a future version; use {cls}.freq instead.' + .format(cls=type(self).__name__)) warnings.warn(msg, FutureWarning, stacklevel=2) self.freq = value + @property # NB: override with cache_readonly in immutable subclasses + def is_normalized(self): + """ + Returns True if all of the dates are at midnight ("no time") + """ + return conversion.is_date_array_normalized(self.asi8, self.tz) + # ---------------------------------------------------------------- # Array-like Methods @@ -582,7 +591,7 @@ def date(self): def to_julian_date(self): """ - Convert DatetimeIndex to float64 ndarray of Julian Dates. + Convert Datetime Array to float64 ndarray of Julian Dates. 0 Julian date is noon January 1, 4713 BC. http://en.wikipedia.org/wiki/Julian_day """ diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 697c2ffc88050..08e894ce6c31c 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -5,15 +5,17 @@ import numpy as np from pandas._libs import lib -from pandas._libs.tslib import NaT +from pandas._libs.tslib import NaT, iNaT from pandas._libs.tslibs.period import ( Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX, get_period_field_arr) from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas._libs.tslibs.fields import isleapyear_arr +from pandas import compat from pandas.util._decorators import cache_readonly +from pandas.core.dtypes.common import is_integer_dtype, is_float_dtype from pandas.core.dtypes.dtypes import PeriodDtype from pandas.tseries import frequencies @@ -33,6 +35,47 @@ def f(self): return property(f) +def _period_array_cmp(opname, cls): + """ + Wrap comparison operations to convert Period-like to PeriodDtype + """ + nat_result = True if opname == '__ne__' else False + + def wrapper(self, other): + op = getattr(self._ndarray_values, opname) + if isinstance(other, Period): + if other.freq != self.freq: + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + + result = op(other.ordinal) + elif isinstance(other, PeriodArrayMixin): + if other.freq != self.freq: + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + + result = op(other._ndarray_values) + + mask = self._isnan | other._isnan + if mask.any(): + result[mask] = nat_result + + return result + elif other is NaT: + result = np.empty(len(self._ndarray_values), dtype=bool) + result.fill(nat_result) + else: + other = Period(other, freq=self.freq) + result = op(other.ordinal) + + if self.hasnans: + result[self._isnan] = nat_result + + return result + + return compat.set_function_name(wrapper, opname, cls) + + class PeriodArrayMixin(DatetimeLikeArrayMixin): @property def _box_func(self): @@ -59,12 +102,62 @@ def freq(self): @freq.setter def freq(self, value): msg = ('Setting {cls}.freq has been deprecated and will be ' - 'removed in a future version; use PeriodIndex.asfreq instead. ' + 'removed in a future version; use {cls}.asfreq instead. ' 'The {cls}.freq setter is not guaranteed to work.') warnings.warn(msg.format(cls=type(self).__name__), FutureWarning, stacklevel=2) self._freq = value + # -------------------------------------------------------------------- + # Constructors + + _attributes = ["freq"] + + def _get_attributes_dict(self): + """return an attributes dict for my class""" + return {k: getattr(self, k, None) for k in self._attributes} + + # TODO: share docstring? + def _shallow_copy(self, values=None, **kwargs): + if values is None: + values = self._ndarray_values + attributes = self._get_attributes_dict() + attributes.update(kwargs) + return self._simple_new(values, **attributes) + + @classmethod + def _simple_new(cls, values, freq=None): + """ + Values can be any type that can be coerced to Periods. + Ordinals in an ndarray are fastpath-ed to `_from_ordinals` + """ + if not is_integer_dtype(values): + values = np.array(values, copy=False) + if len(values) > 0 and is_float_dtype(values): + raise TypeError("{cls} can't take floats" + .format(cls=cls.__name__)) + return cls(values, freq=freq) + + return cls._from_ordinals(values, freq) + + __new__ = _simple_new # For now... + + @classmethod + def _from_ordinals(cls, values, freq=None): + """ + Values should be int ordinals + `__new__` & `_simple_new` cooerce to ordinals and call this method + """ + + values = np.array(values, dtype='int64', copy=False) + + result = object.__new__(cls) + result._data = values + if freq is None: + raise ValueError('freq is not specified and cannot be inferred') + result._freq = Period._maybe_convert_freq(freq) + return result + # -------------------------------------------------------------------- # Vectorized analogues of Period properties @@ -115,6 +208,52 @@ def _sub_period(self, other): return new_data + def _add_offset(self, other): + assert not isinstance(other, Tick) + base = frequencies.get_base_alias(other.rule_code) + if base != self.freq.rule_code: + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + return self.shift(other.n) + + def _add_delta_td(self, other): + assert isinstance(other, (timedelta, np.timedelta64, Tick)) + nanos = delta_to_nanoseconds(other) + own_offset = frequencies.to_offset(self.freq.rule_code) + + if isinstance(own_offset, Tick): + offset_nanos = delta_to_nanoseconds(own_offset) + if np.all(nanos % offset_nanos == 0): + return self.shift(nanos // offset_nanos) + + # raise when input doesn't have freq + raise IncompatibleFrequency("Input has different freq from " + "{cls}(freq={freqstr})" + .format(cls=type(self).__name__, + freqstr=self.freqstr)) + + def _add_delta(self, other): + ordinal_delta = self._maybe_convert_timedelta(other) + return self.shift(ordinal_delta) + + def shift(self, n): + """ + Specialized shift which produces an Period Array/Index + + Parameters + ---------- + n : int + Periods to shift by + + Returns + ------- + shifted : Period Array/Index + """ + values = self._ndarray_values + n * self.freq.n + if self.hasnans: + values[self._isnan] = iNaT + return self._shallow_copy(values=values) + def _maybe_convert_timedelta(self, other): """ Convert timedelta-like input to an integer multiple of self.freq @@ -161,3 +300,16 @@ def _maybe_convert_timedelta(self, other): msg = "Input has different freq from {cls}(freq={freqstr})" raise IncompatibleFrequency(msg.format(cls=type(self).__name__, freqstr=self.freqstr)) + + @classmethod + def _add_comparison_methods(cls): + """ add in comparison methods """ + cls.__eq__ = _period_array_cmp('__eq__', cls) + cls.__ne__ = _period_array_cmp('__ne__', cls) + cls.__lt__ = _period_array_cmp('__lt__', cls) + cls.__gt__ = _period_array_cmp('__gt__', cls) + cls.__le__ = _period_array_cmp('__le__', cls) + cls.__ge__ = _period_array_cmp('__ge__', cls) + + +PeriodArrayMixin._add_comparison_methods() diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index b93cff51bbde9..4258679e1ddc5 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -98,7 +98,7 @@ def total_seconds(self): Returns ------- - seconds : ndarray, Float64Index, or Series + seconds : [ndarray, Float64Index, Series] When the calling object is a TimedeltaArray, the return type is ndarray. When the calling object is a TimedeltaIndex, the return type is a Float64Index. When the calling object diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index cc9b09654289d..5d0cc27979ee5 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -12,7 +12,7 @@ import numpy as np -from pandas._libs import lib, iNaT, NaT, Timedelta +from pandas._libs import lib, iNaT, NaT from pandas._libs.tslibs.period import Period from pandas._libs.tslibs.timestamps import round_ns @@ -40,7 +40,7 @@ ABCIndex, ABCSeries, ABCDataFrame, ABCPeriodIndex, ABCIndexClass) from pandas.core.dtypes.missing import isna from pandas.core import common as com, algorithms, ops -from pandas.core.algorithms import checked_add_with_arr + from pandas.errors import NullFrequencyError, PerformanceWarning import pandas.io.formats.printing as printing @@ -240,6 +240,8 @@ class DatetimeIndexOpsMixin(DatetimeLikeArrayMixin): inferred_freq = cache_readonly(DatetimeLikeArrayMixin.inferred_freq.fget) _isnan = cache_readonly(DatetimeLikeArrayMixin._isnan.fget) hasnans = cache_readonly(DatetimeLikeArrayMixin.hasnans.fget) + _resolution = cache_readonly(DatetimeLikeArrayMixin._resolution.fget) + resolution = cache_readonly(DatetimeLikeArrayMixin.resolution.fget) def equals(self, other): """ @@ -641,17 +643,6 @@ def _format_attrs(self): attrs.append(('freq', freq)) return attrs - @cache_readonly - def _resolution(self): - return frequencies.Resolution.get_reso_from_freq(self.freqstr) - - @cache_readonly - def resolution(self): - """ - Returns day, hour, minute, second, millisecond or microsecond - """ - return frequencies.Resolution.get_str(self._resolution) - def _convert_scalar_indexer(self, key, kind=None): """ we don't allow integer or float indexing on datetime-like when using @@ -717,46 +708,6 @@ def _addsub_offset_array(self, other, op): kwargs['freq'] = 'infer' return self._constructor(res_values, **kwargs) - def _addsub_int_array(self, other, op): - """ - Add or subtract array-like of integers equivalent to applying - `shift` pointwise. - - Parameters - ---------- - other : Index, np.ndarray - integer-dtype - op : {operator.add, operator.sub} - - Returns - ------- - result : same class as self - """ - assert op in [operator.add, operator.sub] - if is_period_dtype(self): - # easy case for PeriodIndex - if op is operator.sub: - other = -other - res_values = checked_add_with_arr(self.asi8, other, - arr_mask=self._isnan) - res_values = res_values.view('i8') - res_values[self._isnan] = iNaT - return self._from_ordinals(res_values, freq=self.freq) - - elif self.freq is None: - # GH#19123 - raise NullFrequencyError("Cannot shift with no freq") - - elif isinstance(self.freq, Tick): - # easy case where we can convert to timedelta64 operation - td = Timedelta(self.freq) - return op(self, td * other) - - # We should only get here with DatetimeIndex; dispatch - # to _addsub_offset_array - assert not is_timedelta64_dtype(self) - return op(self, np.array(other) * self.freq) - @classmethod def _add_datetimelike_methods(cls): """ diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 1d6dc14593e3b..353a92e25d3cf 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -317,6 +317,7 @@ def _add_comparison_methods(cls): _is_numeric_dtype = False _infer_as_myclass = True _timezone = cache_readonly(DatetimeArrayMixin._timezone.fget) + is_normalized = cache_readonly(DatetimeArrayMixin.is_normalized.fget) def __new__(cls, data=None, freq=None, start=None, end=None, periods=None, tz=None, @@ -1706,13 +1707,6 @@ def inferred_type(self): def is_all_dates(self): return True - @cache_readonly - def is_normalized(self): - """ - Returns True if all of the dates are at midnight ("no time") - """ - return conversion.is_date_array_normalized(self.asi8, self.tz) - @cache_readonly def _resolution(self): return libresolution.resolution(self.asi8, self.tz) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 892ef611a34f3..e6c2094defb2d 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,5 +1,5 @@ # pylint: disable=E1101,E1103,W0232 -from datetime import datetime, timedelta +from datetime import datetime import numpy as np import warnings @@ -20,7 +20,6 @@ import pandas.tseries.frequencies as frequencies from pandas.tseries.frequencies import get_freq_code as _gfc -from pandas.tseries.offsets import Tick from pandas.core.indexes.datetimes import DatetimeIndex, Int64Index, Index from pandas.core.indexes.datetimelike import DatelikeOps, DatetimeIndexOpsMixin @@ -32,7 +31,6 @@ DIFFERENT_FREQ_INDEX, _validate_end_alias, _quarter_to_myear) from pandas._libs.tslibs import resolution, period -from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas.core.arrays.period import PeriodArrayMixin from pandas.core.base import _shared_docs @@ -41,7 +39,7 @@ from pandas import compat from pandas.util._decorators import (Appender, Substitution, cache_readonly, deprecate_kwarg) -from pandas.compat import zip, u +from pandas.compat import zip import pandas.core.indexes.base as ibase _index_doc_kwargs = dict(ibase._index_doc_kwargs) @@ -72,47 +70,6 @@ def dt64arr_to_periodarr(data, freq, tz): # --- Period index sketch -def _period_index_cmp(opname, cls): - """ - Wrap comparison operations to convert Period-like to PeriodDtype - """ - nat_result = True if opname == '__ne__' else False - - def wrapper(self, other): - op = getattr(self._ndarray_values, opname) - if isinstance(other, Period): - if other.freq != self.freq: - msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) - raise IncompatibleFrequency(msg) - - result = op(other.ordinal) - elif isinstance(other, PeriodIndex): - if other.freq != self.freq: - msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) - raise IncompatibleFrequency(msg) - - result = op(other._ndarray_values) - - mask = self._isnan | other._isnan - if mask.any(): - result[mask] = nat_result - - return result - elif other is tslib.NaT: - result = np.empty(len(self._ndarray_values), dtype=bool) - result.fill(nat_result) - else: - other = Period(other, freq=self.freq) - result = op(other.ordinal) - - if self.hasnans: - result[self._isnan] = nat_result - - return result - - return compat.set_function_name(wrapper, opname, cls) - - def _new_PeriodIndex(cls, **d): # GH13277 for unpickling if d['data'].dtype == 'int64': @@ -222,16 +179,6 @@ class PeriodIndex(PeriodArrayMixin, DatelikeOps, DatetimeIndexOpsMixin, _engine_type = libindex.PeriodEngine - @classmethod - def _add_comparison_methods(cls): - """ add in comparison methods """ - cls.__eq__ = _period_index_cmp('__eq__', cls) - cls.__ne__ = _period_index_cmp('__ne__', cls) - cls.__lt__ = _period_index_cmp('__lt__', cls) - cls.__gt__ = _period_index_cmp('__gt__', cls) - cls.__le__ = _period_index_cmp('__le__', cls) - cls.__ge__ = _period_index_cmp('__ge__', cls) - def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None, periods=None, tz=None, dtype=None, copy=False, name=None, **fields): @@ -358,15 +305,9 @@ def _from_ordinals(cls, values, name=None, freq=None, **kwargs): Values should be int ordinals `__new__` & `_simple_new` cooerce to ordinals and call this method """ + result = super(PeriodIndex, cls)._from_ordinals(values, freq) - values = np.array(values, dtype='int64', copy=False) - - result = object.__new__(cls) - result._data = values result.name = name - if freq is None: - raise ValueError('freq is not specified and cannot be inferred') - result._freq = Period._maybe_convert_freq(freq) result._reset_identity() return result @@ -374,14 +315,6 @@ def _shallow_copy_with_infer(self, values=None, **kwargs): """ we always want to return a PeriodIndex """ return self._shallow_copy(values=values, **kwargs) - def _shallow_copy(self, values=None, freq=None, **kwargs): - if freq is None: - freq = self.freq - if values is None: - values = self._ndarray_values - return super(PeriodIndex, self)._shallow_copy(values=values, - freq=freq, **kwargs) - def _coerce_scalar_to_index(self, item): """ we need to coerce a scalar to a compat for our index type @@ -565,7 +498,6 @@ def asfreq(self, freq=None, how='E'): Returns ------- - new : PeriodIndex with the new frequency Examples @@ -665,34 +597,6 @@ def to_timestamp(self, freq=None, how='start'): new_data = period.periodarr_to_dt64arr(new_data._ndarray_values, base) return DatetimeIndex(new_data, freq='infer', name=self.name) - def _add_offset(self, other): - assert not isinstance(other, Tick) - base = frequencies.get_base_alias(other.rule_code) - if base != self.freq.rule_code: - msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) - raise IncompatibleFrequency(msg) - return self.shift(other.n) - - def _add_delta_td(self, other): - assert isinstance(other, (timedelta, np.timedelta64, Tick)) - nanos = delta_to_nanoseconds(other) - own_offset = frequencies.to_offset(self.freq.rule_code) - - if isinstance(own_offset, Tick): - offset_nanos = delta_to_nanoseconds(own_offset) - if np.all(nanos % offset_nanos == 0): - return self.shift(nanos // offset_nanos) - - # raise when input doesn't have freq - raise IncompatibleFrequency("Input has different freq from " - "{cls}(freq={freqstr})" - .format(cls=type(self).__name__, - freqstr=self.freqstr)) - - def _add_delta(self, other): - ordinal_delta = self._maybe_convert_timedelta(other) - return self.shift(ordinal_delta) - def _sub_period(self, other): # If the operation is well-defined, we return an object-Index # of DateOffsets. Null entries are filled with pd.NaT @@ -701,24 +605,6 @@ def _sub_period(self, other): # TODO: Should name=self.name be passed here? return Index(new_data) - def shift(self, n): - """ - Specialized shift which produces an PeriodIndex - - Parameters - ---------- - n : int - Periods to shift by - - Returns - ------- - shifted : PeriodIndex - """ - values = self._ndarray_values + n * self.freq.n - if self.hasnans: - values[self._isnan] = tslib.iNaT - return self._shallow_copy(values=values) - @property def inferred_type(self): # b/c data is represented as ints make sure we can't have ambiguous @@ -961,15 +847,14 @@ def _apply_meta(self, rawarr): name=self.name) return rawarr - def _format_native_types(self, na_rep=u('NaT'), date_format=None, - **kwargs): + def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs): values = self.astype(object).values if date_format: formatter = lambda dt: dt.strftime(date_format) else: - formatter = lambda dt: u('%s') % dt + formatter = lambda dt: u'%s' % dt if self.hasnans: mask = self._isnan diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index e9b9fb63811d5..25f72d38eeb9b 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -21,7 +21,7 @@ from pandas.core.indexes.base import Index from pandas.core.indexes.numeric import Int64Index import pandas.compat as compat -from pandas.compat import u + from pandas.tseries.frequencies import to_offset from pandas.core.algorithms import checked_add_with_arr from pandas.core.base import _shared_docs @@ -413,8 +413,7 @@ def _addsub_offset_array(self, other, op): raise TypeError("Cannot add/subtract non-tick DateOffset to {cls}" .format(cls=type(self).__name__)) - def _format_native_types(self, na_rep=u('NaT'), - date_format=None, **kwargs): + def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs): from pandas.io.formats.format import Timedelta64Formatter return Timedelta64Formatter(values=self, nat_rep=na_rep,
PeriodIndex comparisons turn out to be easier to move than the others (though partly because ATM they are broken: #21793), so this moves them over first. Following that, most of the remaining PeriodArray arithmetic methods require `shift`, which in turns requires the constructors, so I went ahead and implemented those in PeriodArrayMixin. Still holding off on TimedeltaArray and DatetimeArray constructors. Found a few more things that could be harmlessly moved and some docstring fixups. CC: @jorisvandenbossche @TomAugspurger @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/21798
2018-07-07T19:57:08Z
2018-07-07T21:21:38Z
2018-07-07T21:21:38Z
2018-07-07T21:24:28Z
DOC: remove imports and use pd in docstrings
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index c4e4f5471c4be..6e49e8044ff25 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -306,8 +306,8 @@ def unique(values): >>> pd.unique(pd.Series([2] + [1] * 5)) array([2, 1]) - >>> pd.unique(Series([pd.Timestamp('20160101'), - ... pd.Timestamp('20160101')])) + >>> pd.unique(pd.Series([pd.Timestamp('20160101'), + ... pd.Timestamp('20160101')])) array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]') >>> pd.unique(pd.Series([pd.Timestamp('20160101', tz='US/Eastern'), @@ -326,20 +326,20 @@ def unique(values): An unordered Categorical will return categories in the order of appearance. - >>> pd.unique(Series(pd.Categorical(list('baabc')))) + >>> pd.unique(pd.Series(pd.Categorical(list('baabc')))) [b, a, c] Categories (3, object): [b, a, c] - >>> pd.unique(Series(pd.Categorical(list('baabc'), - ... categories=list('abc')))) + >>> pd.unique(pd.Series(pd.Categorical(list('baabc'), + ... categories=list('abc')))) [b, a, c] Categories (3, object): [b, a, c] An ordered Categorical preserves the category ordering. - >>> pd.unique(Series(pd.Categorical(list('baabc'), - ... categories=list('abc'), - ... ordered=True))) + >>> pd.unique(pd.Series(pd.Categorical(list('baabc'), + ... categories=list('abc'), + ... ordered=True))) [b, a, c] Categories (3, object): [a < b < c] diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 375db28a4ee5a..83fd0ab499283 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -675,7 +675,7 @@ def _set_categories(self, categories, fastpath=False): Examples -------- - >>> c = Categorical(['a', 'b']) + >>> c = pd.Categorical(['a', 'b']) >>> c [a, b] Categories (2, object): [a, b] @@ -883,7 +883,7 @@ def rename_categories(self, new_categories, inplace=False): Examples -------- - >>> c = Categorical(['a', 'a', 'b']) + >>> c = pd.Categorical(['a', 'a', 'b']) >>> c.rename_categories([0, 1]) [0, 0, 1] Categories (2, int64): [0, 1] diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index de837efc235a0..4f7e9136022a5 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -171,7 +171,7 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): Examples -------- - >>> t = CategoricalDtype(categories=['b', 'a'], ordered=True) + >>> t = pd.CategoricalDtype(categories=['b', 'a'], ordered=True) >>> pd.Series(['a', 'b', 'a', 'c'], dtype=t) 0 a 1 b diff --git a/pandas/core/frame.py b/pandas/core/frame.py index fa720bb38213f..1c8b1ccd0fe8d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2864,8 +2864,6 @@ def query(self, expr, inplace=False, **kwargs): Examples -------- - >>> import numpy as np - >>> import pandas as pd >>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('ab')) >>> df.query('a > b') >>> df[df.a > df.b] # same result as the previous expression diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index aa4c7452bcea9..5dc1d518d1c2d 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1863,7 +1863,7 @@ def cumcount(self, ascending=True): Essentially this is equivalent to - >>> self.apply(lambda x: Series(np.arange(len(x)), x.index)) + >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index)) Parameters ---------- @@ -2133,8 +2133,8 @@ def head(self, n=5): Examples -------- - >>> df = DataFrame([[1, 2], [1, 4], [5, 6]], - columns=['A', 'B']) + >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], + columns=['A', 'B']) >>> df.groupby('A', as_index=False).head(1) A B 0 1 2 @@ -2160,8 +2160,8 @@ def tail(self, n=5): Examples -------- - >>> df = DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]], - columns=['A', 'B']) + >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]], + columns=['A', 'B']) >>> df.groupby('A').tail(1) A B 1 a 2 @@ -3461,7 +3461,7 @@ def _selection_name(self): Examples -------- - >>> s = Series([1, 2, 3, 4]) + >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 904aa3d4bcb03..9458f9667b551 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1272,13 +1272,13 @@ def set_names(self, names, level=None, inplace=False): Examples -------- - >>> Index([1, 2, 3, 4]).set_names('foo') + >>> pd.Index([1, 2, 3, 4]).set_names('foo') Int64Index([1, 2, 3, 4], dtype='int64', name='foo') - >>> Index([1, 2, 3, 4]).set_names(['foo']) + >>> pd.Index([1, 2, 3, 4]).set_names(['foo']) Int64Index([1, 2, 3, 4], dtype='int64', name='foo') - >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), - (2, u'one'), (2, u'two')], - names=['foo', 'bar']) + >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) >>> idx.set_names(['baz', 'quz']) MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], @@ -2891,8 +2891,8 @@ def symmetric_difference(self, other, result_name=None): Examples -------- - >>> idx1 = Index([1, 2, 3, 4]) - >>> idx2 = Index([2, 3, 4, 5]) + >>> idx1 = pd.Index([1, 2, 3, 4]) + >>> idx2 = pd.Index([2, 3, 4, 5]) >>> idx1.symmetric_difference(idx2) Int64Index([1, 5], dtype='int64') diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 8472d5fd49bd9..7c63b3c667c01 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -425,7 +425,7 @@ def get_loc(self, key, method=None): >>> monotonic_index.get_loc('b') slice(1, 3, None) - >>> non_monotonic_index = p.dCategoricalIndex(list('abcb')) + >>> non_monotonic_index = pd.CategoricalIndex(list('abcb')) >>> non_monotonic_index.get_loc('b') array([False, True, False, True], dtype=bool) """ diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index b3bf7abe97279..a791ce1d87264 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -346,9 +346,9 @@ def set_levels(self, levels, level=None, inplace=False, Examples -------- - >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), - (2, u'one'), (2, u'two')], - names=['foo', 'bar']) + >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) >>> idx.set_levels([['a','b'], [1,2]]) MultiIndex(levels=[[u'a', u'b'], [1, 2]], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], @@ -442,9 +442,9 @@ def set_labels(self, labels, level=None, inplace=False, Examples -------- - >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), - (2, u'one'), (2, u'two')], - names=['foo', 'bar']) + >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')], + names=['foo', 'bar']) >>> idx.set_labels([[1,0,1,0], [0,0,1,1]]) MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[1, 0, 1, 0], [0, 0, 1, 1]], @@ -1192,8 +1192,8 @@ def to_hierarchical(self, n_repeat, n_shuffle=1): Examples -------- - >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), - (2, u'one'), (2, u'two')]) + >>> idx = pd.MultiIndex.from_tuples([(1, u'one'), (1, u'two'), + (2, u'one'), (2, u'two')]) >>> idx.to_hierarchical(3) MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], @@ -1255,7 +1255,7 @@ def from_arrays(cls, arrays, sortorder=None, names=None): Examples -------- >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] - >>> MultiIndex.from_arrays(arrays, names=('number', 'color')) + >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) See Also -------- @@ -1304,7 +1304,7 @@ def from_tuples(cls, tuples, sortorder=None, names=None): -------- >>> tuples = [(1, u'red'), (1, u'blue'), (2, u'red'), (2, u'blue')] - >>> MultiIndex.from_tuples(tuples, names=('number', 'color')) + >>> pd.MultiIndex.from_tuples(tuples, names=('number', 'color')) See Also -------- @@ -1357,8 +1357,8 @@ def from_product(cls, iterables, sortorder=None, names=None): -------- >>> numbers = [0, 1, 2] >>> colors = [u'green', u'purple'] - >>> MultiIndex.from_product([numbers, colors], - names=['number', 'color']) + >>> pd.MultiIndex.from_product([numbers, colors], + names=['number', 'color']) MultiIndex(levels=[[0, 1, 2], [u'green', u'purple']], labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], names=[u'number', u'color']) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 3fa525b8617c5..a0b9b25874623 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -147,9 +147,9 @@ class PeriodIndex(PeriodArrayMixin, DatelikeOps, DatetimeIndexOpsMixin, Examples -------- - >>> idx = PeriodIndex(year=year_arr, quarter=q_arr) + >>> idx = pd.PeriodIndex(year=year_arr, quarter=q_arr) - >>> idx2 = PeriodIndex(start='2000', end='2010', freq='A') + >>> idx2 = pd.PeriodIndex(start='2000', end='2010', freq='A') See Also --------- diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 0b0fcacc1bc48..5c3135fe14b51 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -188,9 +188,8 @@ def pipe(self, func, *args, **kwargs): Examples -------- - >>> s = Series([1,2,3,4,5], - index=pd.date_range('20130101', - periods=5,freq='s')) + >>> s = pd.Series([1,2,3,4,5], + index=pd.date_range('20130101', periods=5,freq='s')) 2013-01-01 00:00:00 1 2013-01-01 00:00:01 2 2013-01-01 00:00:02 3 diff --git a/pandas/core/series.py b/pandas/core/series.py index db3d02ad7b3d5..96f9f6c87f969 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1868,7 +1868,7 @@ def quantile(self, q=0.5, interpolation='linear'): Examples -------- - >>> s = Series([1, 2, 3, 4]) + >>> s = pd.Series([1, 2, 3, 4]) >>> s.quantile(.5) 2.5 >>> s.quantile([.25, .5, .75]) @@ -2229,8 +2229,8 @@ def combine(self, other, func, fill_value=None): Examples -------- - >>> s1 = Series([1, 2]) - >>> s2 = Series([0, 3]) + >>> s1 = pd.Series([1, 2]) + >>> s2 = pd.Series([0, 3]) >>> s1.combine(s2, lambda x1, x2: x1 if x1 < x2 else x2) 0 0 1 2 diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index f6428568a6383..fb337d71fcf8d 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -795,7 +795,7 @@ def from_coo(cls, A, dense_index=False): matrix([[ 0., 0., 1., 2.], [ 3., 0., 0., 0.], [ 0., 0., 0., 0.]]) - >>> ss = SparseSeries.from_coo(A) + >>> ss = pd.SparseSeries.from_coo(A) >>> ss 0 2 1 3 2 diff --git a/pandas/core/strings.py b/pandas/core/strings.py index ecc8c266b136d..e4765c00f80fd 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -961,7 +961,7 @@ def str_extractall(arr, pat, flags=0): A pattern with one group will return a DataFrame with one column. Indices with no matches will not appear in the result. - >>> s = Series(["a1a2", "b1", "c1"], index=["A", "B", "C"]) + >>> s = pd.Series(["a1a2", "b1", "c1"], index=["A", "B", "C"]) >>> s.str.extractall(r"[ab](\d)") 0 match @@ -1053,13 +1053,13 @@ def str_get_dummies(arr, sep='|'): Examples -------- - >>> Series(['a|b', 'a', 'a|c']).str.get_dummies() + >>> pd.Series(['a|b', 'a', 'a|c']).str.get_dummies() a b c 0 1 1 0 1 1 0 0 2 1 0 1 - >>> Series(['a|b', np.nan, 'a|c']).str.get_dummies() + >>> pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies() a b c 0 1 1 0 1 0 0 0 @@ -2368,6 +2368,7 @@ def rsplit(self, pat=None, n=-1, expand=False): Examples -------- + >>> s = pd.Series(['Linda van der Berg', 'George Pitt-Rivers']) >>> s 0 Linda van der Berg diff --git a/pandas/core/window.py b/pandas/core/window.py index 1029b96c58475..5e7330ed6001c 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -1825,7 +1825,7 @@ class Expanding(_Rolling_and_Expanding): Examples -------- - >>> df = DataFrame({'B': [0, 1, 2, np.nan, 4]}) + >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) B 0 0.0 1 1.0 @@ -2109,7 +2109,7 @@ class EWM(_Rolling): Examples -------- - >>> df = DataFrame({'B': [0, 1, 2, np.nan, 4]}) + >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) B 0 0.0 1 1.0 diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 374114d2b014b..6b5714bcadba1 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -455,7 +455,7 @@ class HDFStore(StringMixin): Examples -------- >>> bar = pd.DataFrame(np.random.randn(10, 4)) - >>> store = HDFStore('test.h5') + >>> store = pd.HDFStore('test.h5') >>> store['foo'] = bar # write to HDF5 >>> bar = store['foo'] # retrieve >>> store.close() diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index a8ae9b7edd628..be6ff898ec2b7 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -49,7 +49,7 @@ def scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False, Examples -------- - >>> df = DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D']) + >>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D']) >>> scatter_matrix(df, alpha=0.2) """
null
https://api.github.com/repos/pandas-dev/pandas/pulls/21797
2018-07-07T19:56:20Z
2018-07-08T18:45:53Z
2018-07-08T18:45:53Z
2018-07-08T18:45:59Z
TST: create pandas/tests/arrays to consolidate pandas-extension array testing
diff --git a/pandas/tests/categorical/__init__.py b/pandas/tests/arrays/__init__.py similarity index 100% rename from pandas/tests/categorical/__init__.py rename to pandas/tests/arrays/__init__.py diff --git a/pandas/tests/arrays/categorical/__init__.py b/pandas/tests/arrays/categorical/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/categorical/common.py b/pandas/tests/arrays/categorical/common.py similarity index 100% rename from pandas/tests/categorical/common.py rename to pandas/tests/arrays/categorical/common.py diff --git a/pandas/tests/categorical/conftest.py b/pandas/tests/arrays/categorical/conftest.py similarity index 100% rename from pandas/tests/categorical/conftest.py rename to pandas/tests/arrays/categorical/conftest.py diff --git a/pandas/tests/categorical/test_algos.py b/pandas/tests/arrays/categorical/test_algos.py similarity index 100% rename from pandas/tests/categorical/test_algos.py rename to pandas/tests/arrays/categorical/test_algos.py diff --git a/pandas/tests/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py similarity index 100% rename from pandas/tests/categorical/test_analytics.py rename to pandas/tests/arrays/categorical/test_analytics.py diff --git a/pandas/tests/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py similarity index 99% rename from pandas/tests/categorical/test_api.py rename to pandas/tests/arrays/categorical/test_api.py index ad5b78b36438b..037f01733b51c 100644 --- a/pandas/tests/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -8,7 +8,7 @@ from pandas import Categorical, CategoricalIndex, Index, Series, DataFrame from pandas.core.arrays.categorical import _recode_for_categories -from pandas.tests.categorical.common import TestCategorical +from pandas.tests.arrays.categorical.common import TestCategorical class TestCategoricalAPI(object): diff --git a/pandas/tests/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py similarity index 100% rename from pandas/tests/categorical/test_constructors.py rename to pandas/tests/arrays/categorical/test_constructors.py diff --git a/pandas/tests/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py similarity index 100% rename from pandas/tests/categorical/test_dtypes.py rename to pandas/tests/arrays/categorical/test_dtypes.py diff --git a/pandas/tests/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py similarity index 98% rename from pandas/tests/categorical/test_indexing.py rename to pandas/tests/arrays/categorical/test_indexing.py index cf7b5cfa55882..b54ac2835bee3 100644 --- a/pandas/tests/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -6,7 +6,7 @@ import pandas.util.testing as tm from pandas import Categorical, Index, CategoricalIndex, PeriodIndex -from pandas.tests.categorical.common import TestCategorical +from pandas.tests.arrays.categorical.common import TestCategorical class TestCategoricalIndexingWithFactor(TestCategorical): diff --git a/pandas/tests/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py similarity index 100% rename from pandas/tests/categorical/test_missing.py rename to pandas/tests/arrays/categorical/test_missing.py diff --git a/pandas/tests/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py similarity index 99% rename from pandas/tests/categorical/test_operators.py rename to pandas/tests/arrays/categorical/test_operators.py index a26de32d7446c..6d7a98f146679 100644 --- a/pandas/tests/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -7,7 +7,7 @@ import pandas.util.testing as tm from pandas import Categorical, Series, DataFrame, date_range -from pandas.tests.categorical.common import TestCategorical +from pandas.tests.arrays.categorical.common import TestCategorical class TestCategoricalOpsWithFactor(TestCategorical): diff --git a/pandas/tests/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py similarity index 99% rename from pandas/tests/categorical/test_repr.py rename to pandas/tests/arrays/categorical/test_repr.py index 0cadf66b24d46..520d6637c0310 100644 --- a/pandas/tests/categorical/test_repr.py +++ b/pandas/tests/arrays/categorical/test_repr.py @@ -6,7 +6,7 @@ period_range, timedelta_range) from pandas.compat import u, PY3 from pandas.core.config import option_context -from pandas.tests.categorical.common import TestCategorical +from pandas.tests.arrays.categorical.common import TestCategorical class TestCategoricalReprWithFactor(TestCategorical): diff --git a/pandas/tests/categorical/test_sorting.py b/pandas/tests/arrays/categorical/test_sorting.py similarity index 100% rename from pandas/tests/categorical/test_sorting.py rename to pandas/tests/arrays/categorical/test_sorting.py diff --git a/pandas/tests/categorical/test_subclass.py b/pandas/tests/arrays/categorical/test_subclass.py similarity index 100% rename from pandas/tests/categorical/test_subclass.py rename to pandas/tests/arrays/categorical/test_subclass.py diff --git a/pandas/tests/categorical/test_warnings.py b/pandas/tests/arrays/categorical/test_warnings.py similarity index 100% rename from pandas/tests/categorical/test_warnings.py rename to pandas/tests/arrays/categorical/test_warnings.py
https://api.github.com/repos/pandas-dev/pandas/pulls/21795
2018-07-07T19:34:30Z
2018-07-07T22:10:50Z
2018-07-07T22:10:50Z
2018-07-07T22:10:51Z
Removed Need for OHLC As First Element if Used in .agg (#21769)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index df7a5dc9dc173..9d227ef37595f 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3557,13 +3557,11 @@ def _aggregate_multiple_funcs(self, arg, _level): obj._selection = name results[name] = obj.aggregate(func) - if isinstance(list(compat.itervalues(results))[0], - DataFrame): - + if any(isinstance(x, DataFrame) for x in compat.itervalues(results)): # let higher level handle if _level: return results - return list(compat.itervalues(results))[0] + return DataFrame(results, columns=columns) def _wrap_output(self, output, index, names=None): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index e05f9de5ea7f4..66577d738dd28 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1674,3 +1674,22 @@ def test_tuple_correct_keyerror(): [3, 4]])) with tm.assert_raises_regex(KeyError, "(7, 8)"): df.groupby((7, 8)).mean() + + +def test_groupby_agg_ohlc_non_first(): + # GH 21716 + df = pd.DataFrame([[1], [1]], columns=['foo'], + index=pd.date_range('2018-01-01', periods=2, freq='D')) + + expected = pd.DataFrame([ + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1] + ], columns=pd.MultiIndex.from_tuples(( + ('foo', 'ohlc', 'open'), ('foo', 'ohlc', 'high'), + ('foo', 'ohlc', 'low'), ('foo', 'ohlc', 'close'), + ('foo', 'sum', 'foo'))), index=pd.date_range( + '2018-01-01', periods=2, freq='D')) + + result = df.groupby(pd.Grouper(freq='D')).agg(['sum', 'ohlc']) + + tm.assert_frame_equal(result, expected)
closes #21787
https://api.github.com/repos/pandas-dev/pandas/pulls/21794
2018-07-07T16:49:35Z
2018-07-07T18:57:43Z
2018-07-07T18:57:43Z
2018-07-08T03:28:25Z
0.23.3 fixup
diff --git a/doc/source/whatsnew/v0.23.3.txt b/doc/source/whatsnew/v0.23.3.txt index 266d2ce448fb0..b8adce27d2523 100644 --- a/doc/source/whatsnew/v0.23.3.txt +++ b/doc/source/whatsnew/v0.23.3.txt @@ -1,60 +1,7 @@ .. _whatsnew_0233: -v0.23.3 -------- +v0.23.3 (July 7, 2018) +---------------------- -This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes -and bug fixes. We recommend that all users upgrade to this version. - - -.. contents:: What's new in v0.23.3 - :local: - :backlinks: none - -.. _whatsnew_0233.fixed_regressions: - -Fixed Regressions -~~~~~~~~~~~~~~~~~ - -- -- - -.. _whatsnew_0233.bug_fixes: - -Bug Fixes -~~~~~~~~~ - -**Groupby/Resample/Rolling** - -- Bug where calling :func:`DataFrameGroupBy.agg` with a list of functions including ``ohlc`` as the non-initial element would raise a ``ValueError`` (:issue:`21716`) -- - -**Conversion** - -- -- - -**Indexing** - -- -- - -**I/O** - -- -- - -**Categorical** - -- -- - -**Timezones** - -- -- - -**Timedelta** - -- -- +This release fixes a build issue with the sdist for Python 3.7 (:issue:`21785`) +There are no other changes. diff --git a/doc/source/whatsnew/v0.23.4.txt b/doc/source/whatsnew/v0.23.4.txt new file mode 100644 index 0000000000000..a88c22e3d01f7 --- /dev/null +++ b/doc/source/whatsnew/v0.23.4.txt @@ -0,0 +1,60 @@ +.. _whatsnew_0234: + +v0.23.4 +------- + +This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes +and bug fixes. We recommend that all users upgrade to this version. + + +.. contents:: What's new in v0.23.4 + :local: + :backlinks: none + +.. _whatsnew_0234.fixed_regressions: + +Fixed Regressions +~~~~~~~~~~~~~~~~~ + +- +- + +.. _whatsnew_0234.bug_fixes: + +Bug Fixes +~~~~~~~~~ + +**Groupby/Resample/Rolling** + +- Bug where calling :func:`DataFrameGroupBy.agg` with a list of functions including ``ohlc`` as the non-initial element would raise a ``ValueError`` (:issue:`21716`) +- + +**Conversion** + +- +- + +**Indexing** + +- +- + +**I/O** + +- +- + +**Categorical** + +- +- + +**Timezones** + +- +- + +**Timedelta** + +- +-
https://api.github.com/repos/pandas-dev/pandas/pulls/21788
2018-07-07T14:29:41Z
2018-07-07T14:31:26Z
2018-07-07T14:31:26Z
2018-07-07T14:31:34Z
Backport PR #21769 on branch 0.23.x
diff --git a/doc/source/whatsnew/v0.23.3.txt b/doc/source/whatsnew/v0.23.3.txt index d308cf7a3cfac..266d2ce448fb0 100644 --- a/doc/source/whatsnew/v0.23.3.txt +++ b/doc/source/whatsnew/v0.23.3.txt @@ -24,6 +24,11 @@ Fixed Regressions Bug Fixes ~~~~~~~~~ +**Groupby/Resample/Rolling** + +- Bug where calling :func:`DataFrameGroupBy.agg` with a list of functions including ``ohlc`` as the non-initial element would raise a ``ValueError`` (:issue:`21716`) +- + **Conversion** - diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index df7a5dc9dc173..9d227ef37595f 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3557,13 +3557,11 @@ def _aggregate_multiple_funcs(self, arg, _level): obj._selection = name results[name] = obj.aggregate(func) - if isinstance(list(compat.itervalues(results))[0], - DataFrame): - + if any(isinstance(x, DataFrame) for x in compat.itervalues(results)): # let higher level handle if _level: return results - return list(compat.itervalues(results))[0] + return DataFrame(results, columns=columns) def _wrap_output(self, output, index, names=None): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index e05f9de5ea7f4..66577d738dd28 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1674,3 +1674,22 @@ def test_tuple_correct_keyerror(): [3, 4]])) with tm.assert_raises_regex(KeyError, "(7, 8)"): df.groupby((7, 8)).mean() + + +def test_groupby_agg_ohlc_non_first(): + # GH 21716 + df = pd.DataFrame([[1], [1]], columns=['foo'], + index=pd.date_range('2018-01-01', periods=2, freq='D')) + + expected = pd.DataFrame([ + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1] + ], columns=pd.MultiIndex.from_tuples(( + ('foo', 'ohlc', 'open'), ('foo', 'ohlc', 'high'), + ('foo', 'ohlc', 'low'), ('foo', 'ohlc', 'close'), + ('foo', 'sum', 'foo'))), index=pd.date_range( + '2018-01-01', periods=2, freq='D')) + + result = df.groupby(pd.Grouper(freq='D')).agg(['sum', 'ohlc']) + + tm.assert_frame_equal(result, expected)
Backport PR #21769: Removed Need for OHLC As First Element if Used in .agg
https://api.github.com/repos/pandas-dev/pandas/pulls/21787
2018-07-07T13:44:19Z
2018-07-07T16:50:10Z
null
2018-07-08T03:29:10Z
REF: move more methods to EAMixins
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 54e1f0726d772..74bf90eb94065 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -2,7 +2,7 @@ import numpy as np -from pandas._libs import iNaT, NaT +from pandas._libs import lib, iNaT, NaT from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas._libs.tslibs.period import ( DIFFERENT_FREQ_INDEX, IncompatibleFrequency) @@ -33,6 +33,12 @@ def _box_func(self): """ raise com.AbstractMethodError(self) + def _box_values(self, values): + """ + apply box func to passed values + """ + return lib.map_infer(values, self._box_func) + def __iter__(self): return (self._box_func(v) for v in self.asi8) @@ -46,6 +52,9 @@ def asi8(self): # do not cache or you'll create a memory leak return self.values.view('i8') + def __len__(self): + return len(self._data) + # ------------------------------------------------------------------ # Null Handling diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 0e3e50278bbec..34749f3631fca 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -107,6 +107,32 @@ def offset(self, value): warnings.warn(msg, FutureWarning, stacklevel=2) self.freq = value + # ---------------------------------------------------------------- + # Array-like Methods + + def __iter__(self): + """ + Return an iterator over the boxed values + + Yields + ------- + tstamp : Timestamp + """ + + # convert in chunks of 10k for efficiency + data = self.asi8 + length = len(self) + chunksize = 10000 + chunks = int(length / chunksize) + 1 + for i in range(chunks): + start_i = i * chunksize + end_i = min((i + 1) * chunksize, length) + converted = tslib.ints_to_pydatetime(data[start_i:end_i], + tz=self.tz, freq=self.freq, + box="timestamp") + for v in converted: + yield v + # ----------------------------------------------------------------- # Comparison Methods diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 78012688673cf..697c2ffc88050 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -10,6 +10,7 @@ Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX, get_period_field_arr) from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds +from pandas._libs.tslibs.fields import isleapyear_arr from pandas.util._decorators import cache_readonly @@ -86,6 +87,11 @@ def freq(self, value): "The number of days in the month") daysinmonth = days_in_month + @property + def is_leap_year(self): + """ Logical indicating if the date belongs to a leap year """ + return isleapyear_arr(np.asarray(self.year)) + # ------------------------------------------------------------------ # Arithmetic Methods @@ -93,6 +99,22 @@ def _sub_datelike(self, other): assert other is not NaT return NotImplemented + def _sub_period(self, other): + # If the operation is well-defined, we return an object-Index + # of DateOffsets. Null entries are filled with pd.NaT + if self.freq != other.freq: + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + + asi8 = self.asi8 + new_data = asi8 - other.ordinal + new_data = np.array([self.freq * x for x in new_data]) + + if self.hasnans: + new_data[self._isnan] = NaT + + return new_data + def _maybe_convert_timedelta(self, other): """ Convert timedelta-like input to an integer multiple of self.freq diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index 3bd2a0f0281e0..b93cff51bbde9 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -1,16 +1,28 @@ # -*- coding: utf-8 -*- +from datetime import timedelta + +import numpy as np from pandas._libs import tslib from pandas._libs.tslib import Timedelta, NaT from pandas._libs.tslibs.fields import get_timedelta_field +from pandas import compat + from pandas.core.dtypes.common import _TD_DTYPE +from pandas.core.dtypes.generic import ABCSeries +from pandas.core.dtypes.missing import isna from pandas.tseries.offsets import Tick from .datetimelike import DatetimeLikeArrayMixin +def _is_convertible_to_td(key): + return isinstance(key, (Tick, timedelta, + np.timedelta64, compat.string_types)) + + def _field_accessor(name, alias, docstring=None): def f(self): values = self.asi8 @@ -48,9 +60,53 @@ def _sub_datelike(self, other): raise TypeError("cannot subtract a datelike from a {cls}" .format(cls=type(self).__name__)) + def _evaluate_with_timedelta_like(self, other, op): + if isinstance(other, ABCSeries): + # GH#19042 + return NotImplemented + + opstr = '__{opname}__'.format(opname=op.__name__).replace('__r', '__') + # allow division by a timedelta + if opstr in ['__div__', '__truediv__', '__floordiv__']: + if _is_convertible_to_td(other): + other = Timedelta(other) + if isna(other): + raise NotImplementedError( + "division by pd.NaT not implemented") + + i8 = self.asi8 + left, right = i8, other.value + + if opstr in ['__floordiv__']: + result = op(left, right) + else: + result = op(left, np.float64(right)) + result = self._maybe_mask_results(result, convert='float64') + return result + + return NotImplemented + # ---------------------------------------------------------------- # Conversion Methods - Vectorized analogues of Timedelta methods + def total_seconds(self): + """ + Return total duration of each element expressed in seconds. + + This method is available directly on TimedeltaArray, TimedeltaIndex + and on Series containing timedelta values under the ``.dt`` namespace. + + Returns + ------- + seconds : ndarray, Float64Index, or Series + When the calling object is a TimedeltaArray, the return type + is ndarray. When the calling object is a TimedeltaIndex, + the return type is a Float64Index. When the calling object + is a Series, the return type is Series of type `float64` whose + index is the same as the original. + """ + return self._maybe_mask_results(1e-9 * self.asi8) + def to_pytimedelta(self): """ Return Timedelta Array/Index as object ndarray of datetime.timedelta diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 41046e361ac90..cc9b09654289d 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -344,12 +344,6 @@ def _ensure_localized(self, result): result = result.tz_localize(self.tz) return result - def _box_values(self, values): - """ - apply box func to passed values - """ - return lib.map_infer(values, self._box_func) - def _box_values_as_index(self): """ return object Index which contains boxed values diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 8e66381298e57..1d6dc14593e3b 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1251,29 +1251,6 @@ def _fast_union(self, other): end=max(left_end, right_end), freq=left.freq) - def __iter__(self): - """ - Return an iterator over the boxed values - - Returns - ------- - Timestamps : ndarray - """ - - # convert in chunks of 10k for efficiency - data = self.asi8 - length = len(self) - chunksize = 10000 - chunks = int(length / chunksize) + 1 - for i in range(chunks): - start_i = i * chunksize - end_i = min((i + 1) * chunksize, length) - converted = libts.ints_to_pydatetime(data[start_i:end_i], - tz=self.tz, freq=self.freq, - box="timestamp") - for v in converted: - yield v - def _wrap_union_result(self, other, result): name = self.name if self.name == other.name else None if not timezones.tz_compare(self.tz, other.tz): @@ -1906,8 +1883,8 @@ def tz_localize(self, tz, ambiguous='raise', errors='raise'): tz : string, pytz.timezone, dateutil.tz.tzfile or None Time zone to convert timestamps to. Passing ``None`` will remove the time zone information preserving local time. - ambiguous : str {'infer', 'NaT', 'raise'} or bool array, \ -default 'raise' + ambiguous : str {'infer', 'NaT', 'raise'} or bool array, + default 'raise' - 'infer' will attempt to infer fall dst-transition hours based on order - bool-ndarray where True signifies a DST time, False signifies a diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 16d003812f097..892ef611a34f3 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -31,7 +31,6 @@ from pandas._libs.tslibs.period import (Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX, _validate_end_alias, _quarter_to_myear) -from pandas._libs.tslibs.fields import isleapyear_arr from pandas._libs.tslibs import resolution, period from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds @@ -625,11 +624,6 @@ def asfreq(self, freq=None, how='E'): days_in_month = _wrap_field_accessor('days_in_month') daysinmonth = days_in_month - @property - def is_leap_year(self): - """ Logical indicating if the date belongs to a leap year """ - return isleapyear_arr(np.asarray(self.year)) - @property def start_time(self): return self.to_timestamp(how='start') @@ -702,16 +696,7 @@ def _add_delta(self, other): def _sub_period(self, other): # If the operation is well-defined, we return an object-Index # of DateOffsets. Null entries are filled with pd.NaT - if self.freq != other.freq: - msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) - raise IncompatibleFrequency(msg) - - asi8 = self.asi8 - new_data = asi8 - other.ordinal - new_data = np.array([self.freq * x for x in new_data]) - - if self.hasnans: - new_data[self._isnan] = tslib.NaT + new_data = PeriodArrayMixin._sub_period(self, other) # TODO: Should name=self.name be passed here? return Index(new_data) diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index cd819191ef26e..e9b9fb63811d5 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -379,30 +379,11 @@ def _add_delta(self, delta): return TimedeltaIndex(new_values, freq='infer') def _evaluate_with_timedelta_like(self, other, op): - if isinstance(other, ABCSeries): - # GH#19042 + result = TimedeltaArrayMixin._evaluate_with_timedelta_like(self, other, + op) + if result is NotImplemented: return NotImplemented - - opstr = '__{opname}__'.format(opname=op.__name__).replace('__r', '__') - # allow division by a timedelta - if opstr in ['__div__', '__truediv__', '__floordiv__']: - if _is_convertible_to_td(other): - other = Timedelta(other) - if isna(other): - raise NotImplementedError( - "division by pd.NaT not implemented") - - i8 = self.asi8 - left, right = i8, other.value - - if opstr in ['__floordiv__']: - result = op(left, right) - else: - result = op(left, np.float64(right)) - result = self._maybe_mask_results(result, convert='float64') - return Index(result, name=self.name, copy=False) - - return NotImplemented + return Index(result, name=self.name, copy=False) def _add_datelike(self, other): # adding a timedeltaindex to a datetimelike @@ -528,8 +509,8 @@ def total_seconds(self): Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0], dtype='float64') """ - return Index(self._maybe_mask_results(1e-9 * self.asi8), - name=self.name) + result = TimedeltaArrayMixin.total_seconds(self) + return Index(result, name=self.name) @Appender(_index_shared_docs['astype']) def astype(self, dtype, copy=True):
With the exception of the comparison ops, this is the last stuff that can be moved before I have to implement the constructors (and hence a buttload of tests). Let's get this out of the way first. (For the comparison ops there is some super jujitsu that needs to be un-wound, so will do that separately)
https://api.github.com/repos/pandas-dev/pandas/pulls/21782
2018-07-07T01:54:55Z
2018-07-07T14:56:16Z
2018-07-07T14:56:16Z
2018-07-07T14:56:38Z
Replaces Exceptions with ValueError in MultiIndex, closes #21770
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 481749fbbcb96..79e075d8a89c2 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -190,6 +190,8 @@ Other API Changes .. _whatsnew_0240.api.incompatibilities: +- Trying to reindex a ``DataFrame`` with a non unique ``MultiIndex`` now raises a ``ValueError`` instead of an ``Exception`` (:issue:`21770`) + Series and Index Data-Dtype Incompatibilities ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index ab1a5783a4045..e143e5fdebfb1 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1958,8 +1958,8 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): tolerance=tolerance) if not self.is_unique: - raise Exception('Reindexing only valid with uniquely valued Index ' - 'objects') + raise ValueError('Reindexing only valid with uniquely valued ' + 'Index objects') if method == 'pad' or method == 'backfill': if tolerance is not None: @@ -2023,7 +2023,7 @@ def reindex(self, target, method=None, level=None, limit=None, limit=limit, tolerance=tolerance) else: - raise Exception("cannot handle a non-unique multi-index!") + raise ValueError("cannot handle a non-unique multi-index!") if not isinstance(target, MultiIndex): if indexer is None: diff --git a/pandas/tests/indexes/multi/test_reindex.py b/pandas/tests/indexes/multi/test_reindex.py index 346b23fed7075..be1f430140a09 100644 --- a/pandas/tests/indexes/multi/test_reindex.py +++ b/pandas/tests/indexes/multi/test_reindex.py @@ -97,3 +97,12 @@ def test_reindex_base(idx): with tm.assert_raises_regex(ValueError, 'Invalid fill method'): idx.get_indexer(idx, method='invalid') + + +def test_reindex_non_unique(): + idx = pd.MultiIndex.from_tuples([(0, 0), (1, 1), (1, 1), (2, 2)]) + a = pd.Series(np.arange(4), index=idx) + new_idx = pd.MultiIndex.from_tuples([(0, 0), (1, 1), (2, 2)]) + with tm.assert_raises_regex(ValueError, + 'cannot handle a non-unique multi-index!'): + a.reindex(new_idx)
- [X] closes #21770 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21780
2018-07-06T21:09:49Z
2018-07-07T14:16:29Z
2018-07-07T14:16:29Z
2018-07-07T14:16:29Z
TST: Add more information for unexpected warnings
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 7574c17308dd5..54ae8cfb3d39e 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2523,7 +2523,10 @@ class for all warnings. To check that no warning is returned, message=actual_warning.message) assert actual_warning.filename == caller.filename, msg else: - extra_warnings.append(actual_warning.category.__name__) + extra_warnings.append((actual_warning.category.__name__, + actual_warning.message, + actual_warning.filename, + actual_warning.lineno)) if expected_warning: msg = "Did not see expected warning of class {name!r}.".format( name=expected_warning.__name__)
Title is self-explanatory. This will be useful for uncovering the problematic files (hopefully) if / when #21763 rears its head.
https://api.github.com/repos/pandas-dev/pandas/pulls/21779
2018-07-06T19:28:03Z
2018-07-07T14:22:59Z
2018-07-07T14:22:59Z
2018-07-07T18:10:35Z
Move methods and properties to EA Mixin classes
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index e5159141d4b59..0e3e50278bbec 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -6,7 +6,7 @@ from pandas._libs import tslib from pandas._libs.tslib import Timestamp, NaT, iNaT -from pandas._libs.tslibs import conversion, timezones +from pandas._libs.tslibs import conversion, fields, timezones from pandas.util._decorators import cache_readonly @@ -16,6 +16,44 @@ from .datetimelike import DatetimeLikeArrayMixin +def _field_accessor(name, field, docstring=None): + def f(self): + values = self.asi8 + if self.tz is not None: + if self.tz is not utc: + values = self._local_timestamps() + + if field in self._bool_ops: + if field.endswith(('start', 'end')): + freq = self.freq + month_kw = 12 + if freq: + kwds = freq.kwds + month_kw = kwds.get('startingMonth', kwds.get('month', 12)) + + result = fields.get_start_end_field(values, field, + self.freqstr, month_kw) + else: + result = fields.get_date_field(values, field) + + # these return a boolean by-definition + return result + + if field in self._object_ops: + result = fields.get_date_name_field(values, field) + result = self._maybe_mask_results(result) + + else: + result = fields.get_date_field(values, field) + result = self._maybe_mask_results(result, convert='float64') + + return result + + f.__name__ = name + f.__doc__ = docstring + return property(f) + + class DatetimeArrayMixin(DatetimeLikeArrayMixin): """ Assumes that subclass __new__/__init__ defines: @@ -23,6 +61,10 @@ class DatetimeArrayMixin(DatetimeLikeArrayMixin): _freq _data """ + _bool_ops = ['is_month_start', 'is_month_end', + 'is_quarter_start', 'is_quarter_end', 'is_year_start', + 'is_year_end', 'is_leap_year'] + _object_ops = ['weekday_name', 'freq', 'tz'] # ----------------------------------------------------------------- # Descriptive Properties @@ -131,7 +173,7 @@ def _local_timestamps(self): return result.take(reverse) # ---------------------------------------------------------------- - # Conversion Methods - Vectorized analogues of Timedelta methods + # Conversion Methods - Vectorized analogues of Timestamp methods def to_pydatetime(self): """ @@ -143,3 +185,399 @@ def to_pydatetime(self): datetimes : ndarray """ return tslib.ints_to_pydatetime(self.asi8, tz=self.tz) + + # ----------------------------------------------------------------- + # Properties - Vectorized Timestamp Properties/Methods + + def month_name(self, locale=None): + """ + Return the month names of the DateTimeIndex with specified locale. + + Parameters + ---------- + locale : string, default None (English locale) + locale determining the language in which to return the month name + + Returns + ------- + month_names : Index + Index of month names + + .. versionadded:: 0.23.0 + """ + if self.tz is not None and self.tz is not utc: + values = self._local_timestamps() + else: + values = self.asi8 + + result = fields.get_date_name_field(values, 'month_name', + locale=locale) + result = self._maybe_mask_results(result) + return result + + def day_name(self, locale=None): + """ + Return the day names of the DateTimeIndex with specified locale. + + Parameters + ---------- + locale : string, default None (English locale) + locale determining the language in which to return the day name + + Returns + ------- + month_names : Index + Index of day names + + .. versionadded:: 0.23.0 + """ + if self.tz is not None and self.tz is not utc: + values = self._local_timestamps() + else: + values = self.asi8 + + result = fields.get_date_name_field(values, 'day_name', + locale=locale) + result = self._maybe_mask_results(result) + return result + + @property + def time(self): + """ + Returns numpy array of datetime.time. The time part of the Timestamps. + """ + # If the Timestamps have a timezone that is not UTC, + # convert them into their i8 representation while + # keeping their timezone and not using UTC + if self.tz is not None and self.tz is not utc: + timestamps = self._local_timestamps() + else: + timestamps = self.asi8 + + return tslib.ints_to_pydatetime(timestamps, box="time") + + @property + def date(self): + """ + Returns numpy array of python datetime.date objects (namely, the date + part of Timestamps without timezone information). + """ + # If the Timestamps have a timezone that is not UTC, + # convert them into their i8 representation while + # keeping their timezone and not using UTC + if self.tz is not None and self.tz is not utc: + timestamps = self._local_timestamps() + else: + timestamps = self.asi8 + + return tslib.ints_to_pydatetime(timestamps, box="date") + + year = _field_accessor('year', 'Y', "The year of the datetime") + month = _field_accessor('month', 'M', + "The month as January=1, December=12") + day = _field_accessor('day', 'D', "The days of the datetime") + hour = _field_accessor('hour', 'h', "The hours of the datetime") + minute = _field_accessor('minute', 'm', "The minutes of the datetime") + second = _field_accessor('second', 's', "The seconds of the datetime") + microsecond = _field_accessor('microsecond', 'us', + "The microseconds of the datetime") + nanosecond = _field_accessor('nanosecond', 'ns', + "The nanoseconds of the datetime") + weekofyear = _field_accessor('weekofyear', 'woy', + "The week ordinal of the year") + week = weekofyear + dayofweek = _field_accessor('dayofweek', 'dow', + "The day of the week with Monday=0, Sunday=6") + weekday = dayofweek + + weekday_name = _field_accessor( + 'weekday_name', + 'weekday_name', + "The name of day in a week (ex: Friday)\n\n.. deprecated:: 0.23.0") + + dayofyear = _field_accessor('dayofyear', 'doy', + "The ordinal day of the year") + quarter = _field_accessor('quarter', 'q', "The quarter of the date") + days_in_month = _field_accessor( + 'days_in_month', + 'dim', + "The number of days in the month") + daysinmonth = days_in_month + is_month_start = _field_accessor( + 'is_month_start', + 'is_month_start', + "Logical indicating if first day of month (defined by frequency)") + is_month_end = _field_accessor( + 'is_month_end', + 'is_month_end', + """ + Indicator for whether the date is the last day of the month. + + Returns + ------- + Series or array + For Series, returns a Series with boolean values. For + DatetimeIndex, returns a boolean array. + + See Also + -------- + is_month_start : Indicator for whether the date is the first day + of the month. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> dates = pd.Series(pd.date_range("2018-02-27", periods=3)) + >>> dates + 0 2018-02-27 + 1 2018-02-28 + 2 2018-03-01 + dtype: datetime64[ns] + >>> dates.dt.is_month_end + 0 False + 1 True + 2 False + dtype: bool + + >>> idx = pd.date_range("2018-02-27", periods=3) + >>> idx.is_month_end + array([False, True, False], dtype=bool) + """) + is_quarter_start = _field_accessor( + 'is_quarter_start', + 'is_quarter_start', + """ + Indicator for whether the date is the first day of a quarter. + + Returns + ------- + is_quarter_start : Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + quarter : Return the quarter of the date. + is_quarter_end : Similar property for indicating the quarter start. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", + ... periods=4)}) + >>> df.assign(quarter=df.dates.dt.quarter, + ... is_quarter_start=df.dates.dt.is_quarter_start) + dates quarter is_quarter_start + 0 2017-03-30 1 False + 1 2017-03-31 1 False + 2 2017-04-01 2 True + 3 2017-04-02 2 False + + >>> idx = pd.date_range('2017-03-30', periods=4) + >>> idx + DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_quarter_start + array([False, False, True, False]) + """) + is_quarter_end = _field_accessor( + 'is_quarter_end', + 'is_quarter_end', + """ + Indicator for whether the date is the last day of a quarter. + + Returns + ------- + is_quarter_end : Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + quarter : Return the quarter of the date. + is_quarter_start : Similar property indicating the quarter start. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", + ... periods=4)}) + >>> df.assign(quarter=df.dates.dt.quarter, + ... is_quarter_end=df.dates.dt.is_quarter_end) + dates quarter is_quarter_end + 0 2017-03-30 1 False + 1 2017-03-31 1 True + 2 2017-04-01 2 False + 3 2017-04-02 2 False + + >>> idx = pd.date_range('2017-03-30', periods=4) + >>> idx + DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_quarter_end + array([False, True, False, False]) + """) + is_year_start = _field_accessor( + 'is_year_start', + 'is_year_start', + """ + Indicate whether the date is the first day of a year. + + Returns + ------- + Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + is_year_end : Similar property indicating the last day of the year. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) + >>> dates + 0 2017-12-30 + 1 2017-12-31 + 2 2018-01-01 + dtype: datetime64[ns] + + >>> dates.dt.is_year_start + 0 False + 1 False + 2 True + dtype: bool + + >>> idx = pd.date_range("2017-12-30", periods=3) + >>> idx + DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_year_start + array([False, False, True]) + """) + is_year_end = _field_accessor( + 'is_year_end', + 'is_year_end', + """ + Indicate whether the date is the last day of the year. + + Returns + ------- + Series or DatetimeIndex + The same type as the original data with boolean values. Series will + have the same name and index. DatetimeIndex will have the same + name. + + See Also + -------- + is_year_start : Similar property indicating the start of the year. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) + >>> dates + 0 2017-12-30 + 1 2017-12-31 + 2 2018-01-01 + dtype: datetime64[ns] + + >>> dates.dt.is_year_end + 0 False + 1 True + 2 False + dtype: bool + + >>> idx = pd.date_range("2017-12-30", periods=3) + >>> idx + DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], + dtype='datetime64[ns]', freq='D') + + >>> idx.is_year_end + array([False, True, False]) + """) + is_leap_year = _field_accessor( + 'is_leap_year', + 'is_leap_year', + """ + Boolean indicator if the date belongs to a leap year. + + A leap year is a year, which has 366 days (instead of 365) including + 29th of February as an intercalary day. + Leap years are years which are multiples of four with the exception + of years divisible by 100 but not by 400. + + Returns + ------- + Series or ndarray + Booleans indicating if dates belong to a leap year. + + Examples + -------- + This method is available on Series with datetime values under + the ``.dt`` accessor, and directly on DatetimeIndex. + + >>> idx = pd.date_range("2012-01-01", "2015-01-01", freq="Y") + >>> idx + DatetimeIndex(['2012-12-31', '2013-12-31', '2014-12-31'], + dtype='datetime64[ns]', freq='A-DEC') + >>> idx.is_leap_year + array([ True, False, False], dtype=bool) + + >>> dates = pd.Series(idx) + >>> dates_series + 0 2012-12-31 + 1 2013-12-31 + 2 2014-12-31 + dtype: datetime64[ns] + >>> dates_series.dt.is_leap_year + 0 True + 1 False + 2 False + dtype: bool + """) + + def to_julian_date(self): + """ + Convert DatetimeIndex to float64 ndarray of Julian Dates. + 0 Julian date is noon January 1, 4713 BC. + http://en.wikipedia.org/wiki/Julian_day + """ + + # http://mysite.verizon.net/aesir_research/date/jdalg2.htm + year = np.asarray(self.year) + month = np.asarray(self.month) + day = np.asarray(self.day) + testarr = month < 3 + year[testarr] -= 1 + month[testarr] += 12 + return (day + + np.fix((153 * month - 457) / 5) + + 365 * year + + np.floor(year / 4) - + np.floor(year / 100) + + np.floor(year / 400) + + 1721118.5 + + (self.hour + + self.minute / 60.0 + + self.second / 3600.0 + + self.microsecond / 3600.0 / 1e+6 + + self.nanosecond / 3600.0 / 1e+9 + ) / 24.0) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 01acaad228067..78012688673cf 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -7,7 +7,8 @@ from pandas._libs import lib from pandas._libs.tslib import NaT from pandas._libs.tslibs.period import ( - Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX) + Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX, + get_period_field_arr) from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas.util._decorators import cache_readonly @@ -20,6 +21,17 @@ from .datetimelike import DatetimeLikeArrayMixin +def _field_accessor(name, alias, docstring=None): + def f(self): + base, mult = frequencies.get_freq_code(self.freq) + result = get_period_field_arr(alias, self._ndarray_values, base) + return result + + f.__name__ = name + f.__doc__ = docstring + return property(f) + + class PeriodArrayMixin(DatetimeLikeArrayMixin): @property def _box_func(self): @@ -52,6 +64,28 @@ def freq(self, value): FutureWarning, stacklevel=2) self._freq = value + # -------------------------------------------------------------------- + # Vectorized analogues of Period properties + + year = _field_accessor('year', 0, "The year of the period") + month = _field_accessor('month', 3, "The month as January=1, December=12") + day = _field_accessor('day', 4, "The days of the period") + hour = _field_accessor('hour', 5, "The hour of the period") + minute = _field_accessor('minute', 6, "The minute of the period") + second = _field_accessor('second', 7, "The second of the period") + weekofyear = _field_accessor('week', 8, "The week ordinal of the year") + week = weekofyear + dayofweek = _field_accessor('dayofweek', 10, + "The day of the week with Monday=0, Sunday=6") + weekday = dayofweek + dayofyear = day_of_year = _field_accessor('dayofyear', 9, + "The ordinal day of the year") + quarter = _field_accessor('quarter', 2, "The quarter of the date") + qyear = _field_accessor('qyear', 1) + days_in_month = _field_accessor('days_in_month', 11, + "The number of days in the month") + daysinmonth = days_in_month + # ------------------------------------------------------------------ # Arithmetic Methods diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index cc3478e504efb..3bd2a0f0281e0 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -2,6 +2,7 @@ from pandas._libs import tslib from pandas._libs.tslib import Timedelta, NaT +from pandas._libs.tslibs.fields import get_timedelta_field from pandas.core.dtypes.common import _TD_DTYPE @@ -10,6 +11,20 @@ from .datetimelike import DatetimeLikeArrayMixin +def _field_accessor(name, alias, docstring=None): + def f(self): + values = self.asi8 + result = get_timedelta_field(values, alias) + if self.hasnans: + result = self._maybe_mask_results(result, convert='float64') + + return result + + f.__name__ = name + f.__doc__ = docstring + return property(f) + + class TimedeltaArrayMixin(DatetimeLikeArrayMixin): @property def _box_func(self): @@ -46,3 +61,15 @@ def to_pytimedelta(self): datetimes : ndarray """ return tslib.ints_to_pytimedelta(self.asi8) + + days = _field_accessor("days", "days", + " Number of days for each element. ") + seconds = _field_accessor("seconds", "seconds", + " Number of seconds (>= 0 and less than 1 day) " + "for each element. ") + microseconds = _field_accessor("microseconds", "microseconds", + "\nNumber of microseconds (>= 0 and less " + "than 1 second) for each\nelement. ") + nanoseconds = _field_accessor("nanoseconds", "nanoseconds", + "\nNumber of nanoseconds (>= 0 and less " + "than 1 microsecond) for each\nelement.\n") diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 05f7af6383211..1195bece809f3 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -62,44 +62,30 @@ # -------- some conversion wrapper functions -def _field_accessor(name, field, docstring=None): - def f(self): - values = self.asi8 - if self.tz is not None: - if self.tz is not utc: - values = self._local_timestamps() - - if field in self._bool_ops: - if field in ['is_month_start', 'is_month_end', - 'is_quarter_start', 'is_quarter_end', - 'is_year_start', 'is_year_end']: - freq = self.freq - month_kw = 12 - if freq: - kwds = freq.kwds - month_kw = kwds.get('startingMonth', kwds.get('month', 12)) +def _wrap_field_accessor(name): + fget = getattr(DatetimeArrayMixin, name).fget - result = fields.get_start_end_field(values, field, - self.freqstr, month_kw) - else: - result = fields.get_date_field(values, field) - - # these return a boolean by-definition + def f(self): + result = fget(self) + if is_bool_dtype(result): return result + return Index(result, name=self.name) - if field in self._object_ops: - result = fields.get_date_name_field(values, field) - result = self._maybe_mask_results(result) + f.__name__ = name + f.__doc__ = fget.__doc__ + return property(f) - else: - result = fields.get_date_field(values, field) - result = self._maybe_mask_results(result, convert='float64') +def _wrap_in_index(name): + meth = getattr(DatetimeArrayMixin, name) + + def func(self, *args, **kwargs): + result = meth(self, *args, **kwargs) return Index(result, name=self.name) - f.__name__ = name - f.__doc__ = docstring - return property(f) + func.__doc__ = meth.__doc__ + func.__name__ = name + return func def _dt_index_cmp(opname, cls): @@ -1649,320 +1635,32 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None): else: raise - year = _field_accessor('year', 'Y', "The year of the datetime") - month = _field_accessor('month', 'M', - "The month as January=1, December=12") - day = _field_accessor('day', 'D', "The days of the datetime") - hour = _field_accessor('hour', 'h', "The hours of the datetime") - minute = _field_accessor('minute', 'm', "The minutes of the datetime") - second = _field_accessor('second', 's', "The seconds of the datetime") - microsecond = _field_accessor('microsecond', 'us', - "The microseconds of the datetime") - nanosecond = _field_accessor('nanosecond', 'ns', - "The nanoseconds of the datetime") - weekofyear = _field_accessor('weekofyear', 'woy', - "The week ordinal of the year") + year = _wrap_field_accessor('year') + month = _wrap_field_accessor('month') + day = _wrap_field_accessor('day') + hour = _wrap_field_accessor('hour') + minute = _wrap_field_accessor('minute') + second = _wrap_field_accessor('second') + microsecond = _wrap_field_accessor('microsecond') + nanosecond = _wrap_field_accessor('nanosecond') + weekofyear = _wrap_field_accessor('weekofyear') week = weekofyear - dayofweek = _field_accessor('dayofweek', 'dow', - "The day of the week with Monday=0, Sunday=6") + dayofweek = _wrap_field_accessor('dayofweek') weekday = dayofweek - weekday_name = _field_accessor( - 'weekday_name', - 'weekday_name', - "The name of day in a week (ex: Friday)\n\n.. deprecated:: 0.23.0") - - dayofyear = _field_accessor('dayofyear', 'doy', - "The ordinal day of the year") - quarter = _field_accessor('quarter', 'q', "The quarter of the date") - days_in_month = _field_accessor( - 'days_in_month', - 'dim', - "The number of days in the month") - daysinmonth = days_in_month - is_month_start = _field_accessor( - 'is_month_start', - 'is_month_start', - "Logical indicating if first day of month (defined by frequency)") - is_month_end = _field_accessor( - 'is_month_end', - 'is_month_end', - """ - Indicator for whether the date is the last day of the month. - - Returns - ------- - Series or array - For Series, returns a Series with boolean values. For - DatetimeIndex, returns a boolean array. - - See Also - -------- - is_month_start : Indicator for whether the date is the first day - of the month. - - Examples - -------- - This method is available on Series with datetime values under - the ``.dt`` accessor, and directly on DatetimeIndex. - - >>> dates = pd.Series(pd.date_range("2018-02-27", periods=3)) - >>> dates - 0 2018-02-27 - 1 2018-02-28 - 2 2018-03-01 - dtype: datetime64[ns] - >>> dates.dt.is_month_end - 0 False - 1 True - 2 False - dtype: bool - - >>> idx = pd.date_range("2018-02-27", periods=3) - >>> idx.is_month_end - array([False, True, False], dtype=bool) - """) - is_quarter_start = _field_accessor( - 'is_quarter_start', - 'is_quarter_start', - """ - Indicator for whether the date is the first day of a quarter. - - Returns - ------- - is_quarter_start : Series or DatetimeIndex - The same type as the original data with boolean values. Series will - have the same name and index. DatetimeIndex will have the same - name. - - See Also - -------- - quarter : Return the quarter of the date. - is_quarter_end : Similar property for indicating the quarter start. - - Examples - -------- - This method is available on Series with datetime values under - the ``.dt`` accessor, and directly on DatetimeIndex. - - >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", - ... periods=4)}) - >>> df.assign(quarter=df.dates.dt.quarter, - ... is_quarter_start=df.dates.dt.is_quarter_start) - dates quarter is_quarter_start - 0 2017-03-30 1 False - 1 2017-03-31 1 False - 2 2017-04-01 2 True - 3 2017-04-02 2 False - - >>> idx = pd.date_range('2017-03-30', periods=4) - >>> idx - DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], - dtype='datetime64[ns]', freq='D') - - >>> idx.is_quarter_start - array([False, False, True, False]) - """) - is_quarter_end = _field_accessor( - 'is_quarter_end', - 'is_quarter_end', - """ - Indicator for whether the date is the last day of a quarter. - - Returns - ------- - is_quarter_end : Series or DatetimeIndex - The same type as the original data with boolean values. Series will - have the same name and index. DatetimeIndex will have the same - name. - - See Also - -------- - quarter : Return the quarter of the date. - is_quarter_start : Similar property indicating the quarter start. - - Examples - -------- - This method is available on Series with datetime values under - the ``.dt`` accessor, and directly on DatetimeIndex. - - >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", - ... periods=4)}) - >>> df.assign(quarter=df.dates.dt.quarter, - ... is_quarter_end=df.dates.dt.is_quarter_end) - dates quarter is_quarter_end - 0 2017-03-30 1 False - 1 2017-03-31 1 True - 2 2017-04-01 2 False - 3 2017-04-02 2 False - - >>> idx = pd.date_range('2017-03-30', periods=4) - >>> idx - DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], - dtype='datetime64[ns]', freq='D') - - >>> idx.is_quarter_end - array([False, True, False, False]) - """) - is_year_start = _field_accessor( - 'is_year_start', - 'is_year_start', - """ - Indicate whether the date is the first day of a year. - - Returns - ------- - Series or DatetimeIndex - The same type as the original data with boolean values. Series will - have the same name and index. DatetimeIndex will have the same - name. - - See Also - -------- - is_year_end : Similar property indicating the last day of the year. - - Examples - -------- - This method is available on Series with datetime values under - the ``.dt`` accessor, and directly on DatetimeIndex. - - >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) - >>> dates - 0 2017-12-30 - 1 2017-12-31 - 2 2018-01-01 - dtype: datetime64[ns] - - >>> dates.dt.is_year_start - 0 False - 1 False - 2 True - dtype: bool + weekday_name = _wrap_field_accessor('weekday_name') - >>> idx = pd.date_range("2017-12-30", periods=3) - >>> idx - DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], - dtype='datetime64[ns]', freq='D') - - >>> idx.is_year_start - array([False, False, True]) - """) - is_year_end = _field_accessor( - 'is_year_end', - 'is_year_end', - """ - Indicate whether the date is the last day of the year. - - Returns - ------- - Series or DatetimeIndex - The same type as the original data with boolean values. Series will - have the same name and index. DatetimeIndex will have the same - name. - - See Also - -------- - is_year_start : Similar property indicating the start of the year. - - Examples - -------- - This method is available on Series with datetime values under - the ``.dt`` accessor, and directly on DatetimeIndex. - - >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) - >>> dates - 0 2017-12-30 - 1 2017-12-31 - 2 2018-01-01 - dtype: datetime64[ns] - - >>> dates.dt.is_year_end - 0 False - 1 True - 2 False - dtype: bool - - >>> idx = pd.date_range("2017-12-30", periods=3) - >>> idx - DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], - dtype='datetime64[ns]', freq='D') - - >>> idx.is_year_end - array([False, True, False]) - """) - is_leap_year = _field_accessor( - 'is_leap_year', - 'is_leap_year', - """ - Boolean indicator if the date belongs to a leap year. - - A leap year is a year, which has 366 days (instead of 365) including - 29th of February as an intercalary day. - Leap years are years which are multiples of four with the exception - of years divisible by 100 but not by 400. - - Returns - ------- - Series or ndarray - Booleans indicating if dates belong to a leap year. - - Examples - -------- - This method is available on Series with datetime values under - the ``.dt`` accessor, and directly on DatetimeIndex. - - >>> idx = pd.date_range("2012-01-01", "2015-01-01", freq="Y") - >>> idx - DatetimeIndex(['2012-12-31', '2013-12-31', '2014-12-31'], - dtype='datetime64[ns]', freq='A-DEC') - >>> idx.is_leap_year - array([ True, False, False], dtype=bool) - - >>> dates = pd.Series(idx) - >>> dates_series - 0 2012-12-31 - 1 2013-12-31 - 2 2014-12-31 - dtype: datetime64[ns] - >>> dates_series.dt.is_leap_year - 0 True - 1 False - 2 False - dtype: bool - """) - - @property - def time(self): - """ - Returns numpy array of datetime.time. The time part of the Timestamps. - """ - - # If the Timestamps have a timezone that is not UTC, - # convert them into their i8 representation while - # keeping their timezone and not using UTC - if (self.tz is not None and self.tz is not utc): - timestamps = self._local_timestamps() - else: - timestamps = self.asi8 - - return libts.ints_to_pydatetime(timestamps, box="time") - - @property - def date(self): - """ - Returns numpy array of python datetime.date objects (namely, the date - part of Timestamps without timezone information). - """ - - # If the Timestamps have a timezone that is not UTC, - # convert them into their i8 representation while - # keeping their timezone and not using UTC - if (self.tz is not None and self.tz is not utc): - timestamps = self._local_timestamps() - else: - timestamps = self.asi8 - - return libts.ints_to_pydatetime(timestamps, box="date") + dayofyear = _wrap_field_accessor('dayofyear') + quarter = _wrap_field_accessor('quarter') + days_in_month = _wrap_field_accessor('days_in_month') + daysinmonth = days_in_month + is_month_start = _wrap_field_accessor('is_month_start') + is_month_end = _wrap_field_accessor('is_month_end') + is_quarter_start = _wrap_field_accessor('is_quarter_start') + is_quarter_end = _wrap_field_accessor('is_quarter_end') + is_year_start = _wrap_field_accessor('is_year_start') + is_year_end = _wrap_field_accessor('is_year_end') + is_leap_year = _wrap_field_accessor('is_leap_year') def normalize(self): """ @@ -2375,79 +2073,11 @@ def to_julian_date(self): 0 Julian date is noon January 1, 4713 BC. http://en.wikipedia.org/wiki/Julian_day """ + result = DatetimeArrayMixin.to_julian_date(self) + return Float64Index(result) - # http://mysite.verizon.net/aesir_research/date/jdalg2.htm - year = np.asarray(self.year) - month = np.asarray(self.month) - day = np.asarray(self.day) - testarr = month < 3 - year[testarr] -= 1 - month[testarr] += 12 - return Float64Index(day + - np.fix((153 * month - 457) / 5) + - 365 * year + - np.floor(year / 4) - - np.floor(year / 100) + - np.floor(year / 400) + - 1721118.5 + - (self.hour + - self.minute / 60.0 + - self.second / 3600.0 + - self.microsecond / 3600.0 / 1e+6 + - self.nanosecond / 3600.0 / 1e+9 - ) / 24.0) - - def month_name(self, locale=None): - """ - Return the month names of the DateTimeIndex with specified locale. - - Parameters - ---------- - locale : string, default None (English locale) - locale determining the language in which to return the month name - - Returns - ------- - month_names : Index - Index of month names - - .. versionadded:: 0.23.0 - """ - values = self.asi8 - if self.tz is not None: - if self.tz is not utc: - values = self._local_timestamps() - - result = fields.get_date_name_field(values, 'month_name', - locale=locale) - result = self._maybe_mask_results(result) - return Index(result, name=self.name) - - def day_name(self, locale=None): - """ - Return the day names of the DateTimeIndex with specified locale. - - Parameters - ---------- - locale : string, default None (English locale) - locale determining the language in which to return the day name - - Returns - ------- - month_names : Index - Index of day names - - .. versionadded:: 0.23.0 - """ - values = self.asi8 - if self.tz is not None: - if self.tz is not utc: - values = self._local_timestamps() - - result = fields.get_date_name_field(values, 'day_name', - locale=locale) - result = self._maybe_mask_results(result) - return Index(result, name=self.name) + month_name = _wrap_in_index("month_name") + day_name = _wrap_in_index("day_name") DatetimeIndex._add_comparison_methods() diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 143cb8cd3ff6e..16d003812f097 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -29,7 +29,6 @@ from pandas._libs.lib import infer_dtype from pandas._libs import tslib, index as libindex from pandas._libs.tslibs.period import (Period, IncompatibleFrequency, - get_period_field_arr, DIFFERENT_FREQ_INDEX, _validate_end_alias, _quarter_to_myear) from pandas._libs.tslibs.fields import isleapyear_arr @@ -51,13 +50,15 @@ dict(target_klass='PeriodIndex or list of Periods')) -def _field_accessor(name, alias, docstring=None): +def _wrap_field_accessor(name): + fget = getattr(PeriodArrayMixin, name).fget + def f(self): - base, mult = _gfc(self.freq) - result = get_period_field_arr(alias, self._ndarray_values, base) + result = fget(self) return Index(result, name=self.name) + f.__name__ = name - f.__doc__ = docstring + f.__doc__ = fget.__doc__ return property(f) @@ -608,23 +609,20 @@ def asfreq(self, freq=None, how='E'): return self._simple_new(new_data, self.name, freq=freq) - year = _field_accessor('year', 0, "The year of the period") - month = _field_accessor('month', 3, "The month as January=1, December=12") - day = _field_accessor('day', 4, "The days of the period") - hour = _field_accessor('hour', 5, "The hour of the period") - minute = _field_accessor('minute', 6, "The minute of the period") - second = _field_accessor('second', 7, "The second of the period") - weekofyear = _field_accessor('week', 8, "The week ordinal of the year") + year = _wrap_field_accessor('year') + month = _wrap_field_accessor('month') + day = _wrap_field_accessor('day') + hour = _wrap_field_accessor('hour') + minute = _wrap_field_accessor('minute') + second = _wrap_field_accessor('second') + weekofyear = _wrap_field_accessor('week') week = weekofyear - dayofweek = _field_accessor('dayofweek', 10, - "The day of the week with Monday=0, Sunday=6") + dayofweek = _wrap_field_accessor('dayofweek') weekday = dayofweek - dayofyear = day_of_year = _field_accessor('dayofyear', 9, - "The ordinal day of the year") - quarter = _field_accessor('quarter', 2, "The quarter of the date") - qyear = _field_accessor('qyear', 1) - days_in_month = _field_accessor('days_in_month', 11, - "The number of days in the month") + dayofyear = day_of_year = _wrap_field_accessor('dayofyear') + quarter = _wrap_field_accessor('quarter') + qyear = _wrap_field_accessor('qyear') + days_in_month = _wrap_field_accessor('days_in_month') daysinmonth = days_in_month @property diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 520504affaa02..cd819191ef26e 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -37,20 +37,17 @@ from pandas._libs import (lib, index as libindex, join as libjoin, Timedelta, NaT, iNaT) from pandas._libs.tslibs.timedeltas import array_to_timedelta64 -from pandas._libs.tslibs.fields import get_timedelta_field -def _field_accessor(name, alias, docstring=None): - def f(self): - values = self.asi8 - result = get_timedelta_field(values, alias) - if self.hasnans: - result = self._maybe_mask_results(result, convert='float64') +def _wrap_field_accessor(name): + fget = getattr(TimedeltaArrayMixin, name).fget + def f(self): + result = fget(self) return Index(result, name=self.name) f.__name__ = name - f.__doc__ = docstring + f.__doc__ = fget.__doc__ return property(f) @@ -442,17 +439,10 @@ def _format_native_types(self, na_rep=u('NaT'), nat_rep=na_rep, justify='all').get_result() - days = _field_accessor("days", "days", - " Number of days for each element. ") - seconds = _field_accessor("seconds", "seconds", - " Number of seconds (>= 0 and less than 1 day) " - "for each element. ") - microseconds = _field_accessor("microseconds", "microseconds", - "\nNumber of microseconds (>= 0 and less " - "than 1 second) for each\nelement. ") - nanoseconds = _field_accessor("nanoseconds", "nanoseconds", - "\nNumber of nanoseconds (>= 0 and less " - "than 1 microsecond) for each\nelement.\n") + days = _wrap_field_accessor("days") + seconds = _wrap_field_accessor("seconds") + microseconds = _wrap_field_accessor("microseconds") + nanoseconds = _wrap_field_accessor("nanoseconds") @property def components(self):
Not the all-at-once that @jorisvandenbossche asked for, but it's a much bigger chunk than the last few.
https://api.github.com/repos/pandas-dev/pandas/pulls/21776
2018-07-06T17:12:03Z
2018-07-06T18:38:29Z
2018-07-06T18:38:29Z
2018-07-06T18:56:35Z
Fix categorical from codes nan 21767
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index d2d5d40393b62..c4a3847f38758 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -439,6 +439,7 @@ Deprecations - :meth:`MultiIndex.to_hierarchical` is deprecated and will be removed in a future version (:issue:`21613`) - :meth:`Series.ptp` is deprecated. Use ``numpy.ptp`` instead (:issue:`21614`) - :meth:`Series.compress` is deprecated. Use ``Series[condition]`` instead (:issue:`18262`) +- :meth:`Categorical.from_codes` has deprecated providing float values for the ``codes`` argument. (:issue:`21767`) .. _whatsnew_0240.prior_deprecations: @@ -486,9 +487,7 @@ Bug Fixes Categorical ^^^^^^^^^^^ -- -- -- +- Bug in :meth:`Categorical.from_codes` where ``NaN`` values in `codes` were silently converted to ``0`` (:issue:`21767`). In the future this will raise a ``ValueError``. Also changes the behavior of `.from_codes([1.1, 2.0])`. Datetimelike ^^^^^^^^^^^^ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 204e800b932a9..7c793cb1d6488 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -27,6 +27,8 @@ is_timedelta64_dtype, is_categorical, is_categorical_dtype, + is_float_dtype, + is_integer_dtype, is_list_like, is_sequence, is_scalar, is_iterator, is_dict_like) @@ -629,8 +631,21 @@ def from_codes(cls, codes, categories, ordered=False): categorical. If not given, the resulting categorical will be unordered. """ + codes = np.asarray(codes) # #21767 + if not is_integer_dtype(codes): + msg = "codes need to be array-like integers" + if is_float_dtype(codes): + icodes = codes.astype('i8') + if (icodes == codes).all(): + msg = None + codes = icodes + warn(("float codes will be disallowed in the future and " + "raise a ValueError"), FutureWarning, stacklevel=2) + if msg: + raise ValueError(msg) + try: - codes = coerce_indexer_dtype(np.asarray(codes), categories) + codes = coerce_indexer_dtype(codes, categories) except (ValueError, TypeError): raise ValueError( "codes need to be convertible to an arrays of integers") diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index e082629a5433d..c903a8c09195e 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -468,6 +468,26 @@ def test_from_codes_with_categorical_categories(self): with pytest.raises(ValueError): Categorical.from_codes([0, 1], Categorical(['a', 'b', 'a'])) + def test_from_codes_with_nan_code(self): + # GH21767 + codes = [1, 2, np.nan] + categories = ['a', 'b', 'c'] + with pytest.raises(ValueError): + Categorical.from_codes(codes, categories) + + def test_from_codes_with_float(self): + # GH21767 + codes = [1.0, 2.0, 0] # integer, but in float dtype + categories = ['a', 'b', 'c'] + + with tm.assert_produces_warning(FutureWarning): + cat = Categorical.from_codes(codes, categories) + tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype='i1')) + + codes = [1.1, 2.0, 0] # non-integer + with pytest.raises(ValueError): + Categorical.from_codes(codes, categories) + @pytest.mark.parametrize('dtype', [None, 'category']) def test_from_inferred_categories(self, dtype): cats = ['a', 'b']
- [x] closes #21767 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21775
2018-07-06T17:07:45Z
2018-08-01T22:12:54Z
2018-08-01T22:12:54Z
2018-08-01T22:13:07Z
Changed import statements in examples in DOCs
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7b5f310315485..d192b32b26bdb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5643,7 +5643,6 @@ def unstack(self, level=-1, fill_value=None): Examples -------- - >>> import pandas as pd >>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'}, ... 'B': {0: 1, 1: 3, 2: 5}, ... 'C': {0: 2, 1: 4, 2: 6}}) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 818dd1b408518..251bdcf76355a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4824,7 +4824,6 @@ def ftypes(self): Examples -------- - >>> import numpy as np >>> arr = np.random.RandomState(0).randn(100, 4) >>> arr[arr < .8] = np.nan >>> pd.DataFrame(arr).ftypes diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c69d7f43de8ea..e973608507a29 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3704,7 +3704,6 @@ def filter(self, func, dropna=True, *args, **kwargs): # noqa Examples -------- - >>> import pandas as pd >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ... 'foo', 'bar'], ... 'B' : [1, 2, 3, 4, 5, 6], @@ -4538,7 +4537,6 @@ def filter(self, func, dropna=True, *args, **kwargs): # noqa Examples -------- - >>> import pandas as pd >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ... 'foo', 'bar'], ... 'B' : [1, 2, 3, 4, 5, 6], diff --git a/pandas/core/panel.py b/pandas/core/panel.py index e012819812f6b..9f08fabef8cc7 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -89,7 +89,6 @@ def panel_index(time, panels, names=None): or - >>> import numpy as np >>> years = np.repeat(range(1960,1963), 3) >>> panels = np.tile(['A', 'B', 'C'], 3) >>> panel_idx = panel_index(years, panels) diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index b3e3c52f6e363..f4b96c8f1ca49 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -103,7 +103,6 @@ def lreshape(data, groups, dropna=True, label=None): Examples -------- - >>> import pandas as pd >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... 'team': ['Red Sox', 'Yankees'], ... 'year1': [2007, 2007], 'year2': [2008, 2008]}) @@ -217,8 +216,6 @@ def wide_to_long(df, stubnames, i, j, sep="", suffix=r'\d+'): Examples -------- - >>> import pandas as pd - >>> import numpy as np >>> np.random.seed(123) >>> df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, ... "A1980" : {0 : "d", 1 : "e", 2 : "f"}, diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 3d9e84954a63b..089634fb8e315 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -58,7 +58,6 @@ class _Unstacker(object): Examples -------- - >>> import pandas as pd >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), ... ('two', 'a'), ('two', 'b')]) >>> s = pd.Series(np.arange(1, 5, dtype=np.int64), index=index) @@ -771,7 +770,6 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, Examples -------- - >>> import pandas as pd >>> s = pd.Series(list('abca')) >>> pd.get_dummies(s) diff --git a/pandas/core/series.py b/pandas/core/series.py index 93c1f866cad17..10a08dc5e0cde 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2749,8 +2749,6 @@ def nlargest(self, n=5, keep='first'): Examples -------- - >>> import pandas as pd - >>> import numpy as np >>> s = pd.Series(np.random.randn(10**6)) >>> s.nlargest(10) # only sorts up to the N requested 219921 4.644710 @@ -2796,8 +2794,6 @@ def nsmallest(self, n=5, keep='first'): Examples -------- - >>> import pandas as pd - >>> import numpy as np >>> s = pd.Series(np.random.randn(10**6)) >>> s.nsmallest(10) # only sorts up to the N requested 288532 -4.954580 @@ -3048,7 +3044,7 @@ def _gotitem(self, key, ndim, subset=None): Examples -------- - >>> s = Series(np.random.randn(10)) + >>> s = pd.Series(np.random.randn(10)) >>> s.agg('min') -1.3018049988556679 @@ -3127,8 +3123,6 @@ def apply(self, func, convert_dtype=True, args=(), **kwds): Create a series with typical summer temperatures for each city. - >>> import pandas as pd - >>> import numpy as np >>> series = pd.Series([20, 21, 12], index=['London', ... 'New York','Helsinki']) >>> series diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index 09d958059d355..f6428568a6383 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -736,15 +736,14 @@ def to_coo(self, row_levels=(0, ), column_levels=(1, ), sort_labels=False): Examples -------- - >>> from numpy import nan - >>> s = Series([3.0, nan, 1.0, 3.0, nan, nan]) - >>> s.index = MultiIndex.from_tuples([(1, 2, 'a', 0), - (1, 2, 'a', 1), - (1, 1, 'b', 0), - (1, 1, 'b', 1), - (2, 1, 'b', 0), - (2, 1, 'b', 1)], - names=['A', 'B', 'C', 'D']) + >>> s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan]) + >>> s.index = pd.MultiIndex.from_tuples([(1, 2, 'a', 0), + (1, 2, 'a', 1), + (1, 1, 'b', 0), + (1, 1, 'b', 1), + (2, 1, 'b', 0), + (2, 1, 'b', 1)], + names=['A', 'B', 'C', 'D']) >>> ss = s.to_sparse() >>> A, rows, columns = ss.to_coo(row_levels=['A', 'B'], column_levels=['C', 'D'], diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py index ebe135dfb184c..f1d13ccf36cf6 100644 --- a/pandas/core/tools/numeric.py +++ b/pandas/core/tools/numeric.py @@ -58,7 +58,6 @@ def to_numeric(arg, errors='raise', downcast=None): -------- Take separate series and convert to numeric, coercing when told to - >>> import pandas as pd >>> s = pd.Series(['1.0', '2', -3]) >>> pd.to_numeric(s) 0 1.0 diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index f93ad425b2c6a..374114d2b014b 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -454,9 +454,7 @@ class HDFStore(StringMixin): Examples -------- - >>> from pandas import DataFrame - >>> from numpy.random import randn - >>> bar = DataFrame(randn(10, 4)) + >>> bar = pd.DataFrame(np.random.randn(10, 4)) >>> store = HDFStore('test.h5') >>> store['foo'] = bar # write to HDF5 >>> bar = store['foo'] # retrieve diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py index 7994517b9f303..cb01b7a652157 100644 --- a/pandas/io/sas/sas_xport.py +++ b/pandas/io/sas/sas_xport.py @@ -68,11 +68,11 @@ -------- Read a SAS Xport file: ->>> df = pandas.read_sas('filename.XPT') +>>> df = pd.read_sas('filename.XPT') Read a Xport file in 10,000 line chunks: ->>> itr = pandas.read_sas('filename.XPT', chunksize=10000) +>>> itr = pd.read_sas('filename.XPT', chunksize=10000) >>> for chunk in itr: >>> do_something(chunk) diff --git a/pandas/io/stata.py b/pandas/io/stata.py index b2a5bec2a4837..c3af5d214317a 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -102,7 +102,6 @@ -------- Read a Stata dta file: ->>> import pandas as pd >>> df = pd.read_stata('filename.dta') Read a Stata dta file in 10,000 line chunks: @@ -216,7 +215,6 @@ def _stata_elapsed_date_to_datetime_vec(dates, fmt): Examples -------- - >>> import pandas as pd >>> dates = pd.Series([52]) >>> _stata_elapsed_date_to_datetime_vec(dates , "%tw") 0 1961-01-01 @@ -1946,7 +1944,6 @@ class StataWriter(StataParser): Examples -------- - >>> import pandas as pd >>> data = pd.DataFrame([[1.0, 1]], columns=['a', 'b']) >>> writer = StataWriter('./data_file.dta', data) >>> writer.write_file() @@ -2709,7 +2706,6 @@ class StataWriter117(StataWriter): Examples -------- - >>> import pandas as pd >>> from pandas.io.stata import StataWriter117 >>> data = pd.DataFrame([[1.0, 1, 'a']], columns=['a', 'b', 'c']) >>> writer = StataWriter117('./data_file.dta', data) diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 0fb1f2b23faac..842da838b4b83 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -2609,14 +2609,11 @@ def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, Examples -------- - >>> import pandas - >>> import numpy as np >>> import itertools - >>> >>> tuples = [t for t in itertools.product(range(1000), range(4))] - >>> index = pandas.MultiIndex.from_tuples(tuples, names=['lvl0', 'lvl1']) + >>> index = pd.MultiIndex.from_tuples(tuples, names=['lvl0', 'lvl1']) >>> data = np.random.randn(len(index),4) - >>> df = pandas.DataFrame(data, columns=list('ABCD'), index=index) + >>> df = pd.DataFrame(data, columns=list('ABCD'), index=index) >>> >>> grouped = df.groupby(level='lvl1') >>> boxplot_frame_groupby(grouped) diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 150c9274d4e5c..84e545a3ca2f2 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -406,7 +406,6 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): .. plot:: :context: close-figs - >>> import numpy as np >>> s = pd.Series(np.random.uniform(size=100)) >>> fig = pd.plotting.bootstrap_plot(s) """ @@ -498,13 +497,11 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None, Examples -------- - >>> from pandas import read_csv - >>> from pandas.tools.plotting import parallel_coordinates >>> from matplotlib import pyplot as plt - >>> df = read_csv('https://raw.github.com/pandas-dev/pandas/master' - '/pandas/tests/data/iris.csv') - >>> parallel_coordinates(df, 'Name', color=('#556270', - '#4ECDC4', '#C7F464')) + >>> df = pd.read_csv('https://raw.github.com/pandas-dev/pandas/master' + '/pandas/tests/data/iris.csv') + >>> pd.plotting.parallel_coordinates(df, 'Name', + color=('#556270', '#4ECDC4', '#C7F464')) >>> plt.show() """ if axvlines_kwds is None: diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index 4e874eac9e6c6..33dcf6d64b302 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -143,12 +143,11 @@ class from pandas.tseries.offsets Examples -------- >>> from pandas.tseries.holiday import Holiday, nearest_workday - >>> from pandas import DateOffset >>> from dateutil.relativedelta import MO >>> USMemorialDay = Holiday('MemorialDay', month=5, day=24, - offset=DateOffset(weekday=MO(1))) + offset=pd.DateOffset(weekday=MO(1))) >>> USLaborDay = Holiday('Labor Day', month=9, day=1, - offset=DateOffset(weekday=MO(1))) + offset=pd.DateOffset(weekday=MO(1))) >>> July3rd = Holiday('July 3rd', month=7, day=3,) >>> NewYears = Holiday('New Years Day', month=1, day=1, observance=nearest_workday),
This is regarding Issue #21749 - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21774
2018-07-06T16:55:07Z
2018-07-07T19:33:57Z
2018-07-07T19:33:57Z
2018-07-07T23:52:32Z
Interpolation nonnumeric error handling
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3a8c81b5e9281..100d2a406c577 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -243,6 +243,10 @@ Documentation Changes Bug Fixes ~~~~~~~~~ +**Data-type specific** + +- Bug in :meth:`Series.interpolate()` where appropiate error was not raised when interpolating with a non-numeric index column (:issue:`21662`) + Categorical ^^^^^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 26c23b84a9c04..80fffd259c6ab 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6024,6 +6024,13 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False, raise NotImplementedError("Interpolation with NaNs in the index " "has not been implemented. Try filling " "those NaNs before interpolating.") + + if not is_numeric_dtype(index): + raise ValueError("Index column must be numeric when using any " + "interpolation method other than linear. Try " + "setting a numeric index column before " + "interpolating.") + data = _maybe_transposed_self._data new_data = data.interpolate(method=method, axis=ax, index=index, values=_maybe_transposed_self, limit=limit, diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 533bff0384ad9..a41b680f8648a 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -1008,3 +1008,20 @@ def test_pipe_panel(self): with pytest.raises(ValueError): result = wp.pipe((f, 'y'), x=1, y=1) + + def test_interpolate(self): + # GH 21662 + # Using a numeric index column + df = DataFrame([0, 1, np.nan, 3], index=[1, 2, 3, 4]) + series = Series(df[0]) + assert series.interpolate( + method="quadratic").equals(series.interpolate(method="linear")) + + # Using a non-numeric index column + df = DataFrame([0, 1, np.nan, 3], index=["A", "B", "C", "D"]) + series = Series(df[0]) + with pytest.raises(ValueError, match="Index column must be numeric " + "when using any interpolation method other than linear. Try " + "setting a numeric index column before interpolating."): + + result = series.interpolate(method="quadratic")
- [x] closes #21662 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21773
2018-07-06T16:53:42Z
2018-10-11T01:54:08Z
null
2018-10-11T01:54:08Z
Backport PR #21771 on branch 0.23.x
diff --git a/doc/source/whatsnew/v0.23.3.txt b/doc/source/whatsnew/v0.23.3.txt new file mode 100644 index 0000000000000..d308cf7a3cfac --- /dev/null +++ b/doc/source/whatsnew/v0.23.3.txt @@ -0,0 +1,55 @@ +.. _whatsnew_0233: + +v0.23.3 +------- + +This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes +and bug fixes. We recommend that all users upgrade to this version. + + +.. contents:: What's new in v0.23.3 + :local: + :backlinks: none + +.. _whatsnew_0233.fixed_regressions: + +Fixed Regressions +~~~~~~~~~~~~~~~~~ + +- +- + +.. _whatsnew_0233.bug_fixes: + +Bug Fixes +~~~~~~~~~ + +**Conversion** + +- +- + +**Indexing** + +- +- + +**I/O** + +- +- + +**Categorical** + +- +- + +**Timezones** + +- +- + +**Timedelta** + +- +-
Backport PR #21771: Whatsnew note for v0.23.3
https://api.github.com/repos/pandas-dev/pandas/pulls/21772
2018-07-06T16:30:54Z
2018-07-06T16:32:06Z
2018-07-06T16:32:06Z
2018-07-06T20:33:23Z
Whatsnew note for v0.23.3
diff --git a/doc/source/whatsnew/v0.23.3.txt b/doc/source/whatsnew/v0.23.3.txt new file mode 100644 index 0000000000000..d308cf7a3cfac --- /dev/null +++ b/doc/source/whatsnew/v0.23.3.txt @@ -0,0 +1,55 @@ +.. _whatsnew_0233: + +v0.23.3 +------- + +This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes +and bug fixes. We recommend that all users upgrade to this version. + + +.. contents:: What's new in v0.23.3 + :local: + :backlinks: none + +.. _whatsnew_0233.fixed_regressions: + +Fixed Regressions +~~~~~~~~~~~~~~~~~ + +- +- + +.. _whatsnew_0233.bug_fixes: + +Bug Fixes +~~~~~~~~~ + +**Conversion** + +- +- + +**Indexing** + +- +- + +**I/O** + +- +- + +**Categorical** + +- +- + +**Timezones** + +- +- + +**Timedelta** + +- +-
https://api.github.com/repos/pandas-dev/pandas/pulls/21771
2018-07-06T16:28:33Z
2018-07-06T16:30:05Z
2018-07-06T16:30:05Z
2019-02-28T07:23:17Z
Removed Need for OHLC As First Element if Used in .agg
diff --git a/doc/source/whatsnew/v0.23.3.txt b/doc/source/whatsnew/v0.23.3.txt index d308cf7a3cfac..266d2ce448fb0 100644 --- a/doc/source/whatsnew/v0.23.3.txt +++ b/doc/source/whatsnew/v0.23.3.txt @@ -24,6 +24,11 @@ Fixed Regressions Bug Fixes ~~~~~~~~~ +**Groupby/Resample/Rolling** + +- Bug where calling :func:`DataFrameGroupBy.agg` with a list of functions including ``ohlc`` as the non-initial element would raise a ``ValueError`` (:issue:`21716`) +- + **Conversion** - diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 08acdcf94094a..a496394547339 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3549,13 +3549,11 @@ def _aggregate_multiple_funcs(self, arg, _level): obj._selection = name results[name] = obj.aggregate(func) - if isinstance(list(compat.itervalues(results))[0], - DataFrame): - + if any(isinstance(x, DataFrame) for x in compat.itervalues(results)): # let higher level handle if _level: return results - return list(compat.itervalues(results))[0] + return DataFrame(results, columns=columns) def _wrap_output(self, output, index, names=None): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index e05f9de5ea7f4..66577d738dd28 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1674,3 +1674,22 @@ def test_tuple_correct_keyerror(): [3, 4]])) with tm.assert_raises_regex(KeyError, "(7, 8)"): df.groupby((7, 8)).mean() + + +def test_groupby_agg_ohlc_non_first(): + # GH 21716 + df = pd.DataFrame([[1], [1]], columns=['foo'], + index=pd.date_range('2018-01-01', periods=2, freq='D')) + + expected = pd.DataFrame([ + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1] + ], columns=pd.MultiIndex.from_tuples(( + ('foo', 'ohlc', 'open'), ('foo', 'ohlc', 'high'), + ('foo', 'ohlc', 'low'), ('foo', 'ohlc', 'close'), + ('foo', 'sum', 'foo'))), index=pd.date_range( + '2018-01-01', periods=2, freq='D')) + + result = df.groupby(pd.Grouper(freq='D')).agg(['sum', 'ohlc']) + + tm.assert_frame_equal(result, expected)
- [X] closes #21716 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21769
2018-07-06T16:13:38Z
2018-07-07T13:44:04Z
2018-07-07T13:44:04Z
2018-07-07T13:44:10Z
Followup to #21738
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 0076ec74ea9e1..9964ca0847ce7 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -1045,6 +1045,10 @@ def normalize_date(object dt): Returns ------- normalized : datetime.datetime or Timestamp + + Raises + ------ + TypeError : if input is not datetime.date, datetime.datetime, or Timestamp """ if PyDateTime_Check(dt): if not PyDateTime_CheckExact(dt): @@ -1063,7 +1067,7 @@ def normalize_date(object dt): @cython.wraparound(False) @cython.boundscheck(False) -def date_normalize(ndarray[int64_t] stamps, tz=None): +def normalize_i8_timestamps(ndarray[int64_t] stamps, tz=None): """ Normalize each of the (nanosecond) timestamps in the given array by rounding down to the beginning of the day (i.e. midnight). If `tz` diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 401ba76e341b2..711db7cc8fbe2 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -21,7 +21,7 @@ from util cimport (is_datetime64_object, is_timedelta64_object, INT64_MAX) cimport ccalendar -from conversion import tz_localize_to_utc, date_normalize +from conversion import tz_localize_to_utc, normalize_i8_timestamps from conversion cimport (tz_convert_single, _TSObject, convert_to_tsobject, convert_datetime_to_tsobject) from fields import get_start_end_field, get_date_name_field @@ -1083,7 +1083,7 @@ class Timestamp(_Timestamp): Normalize Timestamp to midnight, preserving tz information. """ - normalized_value = date_normalize( + normalized_value = normalize_i8_timestamps( np.array([self.value], dtype='i8'), tz=self.tz)[0] return Timestamp(normalized_value).tz_localize(self.tz) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 05f7af6383211..966eff58262e8 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -2002,7 +2002,7 @@ def normalize(self): '2014-08-01 00:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq=None) """ - new_values = conversion.date_normalize(self.asi8, self.tz) + new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz) return DatetimeIndex(new_values, freq='infer', name=self.name).tz_localize(self.tz) diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py new file mode 100644 index 0000000000000..387a63f61179d --- /dev/null +++ b/pandas/tests/tslibs/test_api.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +"""Tests that the tslibs API is locked down""" + +from pandas._libs import tslibs + + +def test_namespace(): + + submodules = ['ccalendar', + 'conversion', + 'fields', + 'frequencies', + 'nattype', + 'np_datetime', + 'offsets', + 'parsing', + 'period', + 'resolution', + 'strptime', + 'timedeltas', + 'timestamps', + 'timezones'] + + api = ['NaT', + 'iNaT', + 'OutOfBoundsDatetime', + 'Timedelta', + 'Timestamp', + 'delta_to_nanoseconds', + 'ints_to_pytimedelta', + 'localize_pydatetime', + 'normalize_date', + 'tz_convert_single'] + + expected = set(submodules + api) + names = [x for x in dir(tslibs) if not x.startswith('__')] + assert set(names) == expected
Addresses comments/requests from #21738.
https://api.github.com/repos/pandas-dev/pandas/pulls/21764
2018-07-06T14:25:22Z
2018-07-06T16:18:47Z
2018-07-06T16:18:47Z
2018-07-06T17:26:39Z
Fix whatsnew dates
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index af4eeffd87d01..cf60e86553fe3 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -1,7 +1,7 @@ .. _whatsnew_0231: -v0.23.1 -------- +v0.23.1 (June 12, 2018) +----------------------- This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes and bug fixes. We recommend that all users upgrade to this version. diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index bd86576ad8586..3f68eabdca4c2 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -1,7 +1,7 @@ .. _whatsnew_0232: -v0.23.2 -------- +v0.23.2 (July 5, 2018) +---------------------- This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes and bug fixes. We recommend that all users upgrade to this version. diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 691345ad26e58..5b7381d84283e 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -1,7 +1,7 @@ .. _whatsnew_0240: -v0.24.0 -------- +v0.24.0 (Month XX, 2018) +------------------------ .. _whatsnew_0240.enhancements:
Up to v0.23.0, there's always a date in the whatsnew-entries. This adds them back to v0.23.1 & v0.23.2, as well as a blank template for v0.24.0.
https://api.github.com/repos/pandas-dev/pandas/pulls/21759
2018-07-06T09:19:38Z
2018-07-06T13:57:33Z
2018-07-06T13:57:33Z
2018-07-09T08:22:08Z
DOC: Fix typos in Series.idxmin/idxmax docs
diff --git a/pandas/core/series.py b/pandas/core/series.py index 93c1f866cad17..a711f69028917 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1657,7 +1657,7 @@ def duplicated(self, keep='first'): """ return super(Series, self).duplicated(keep=keep) - def idxmin(self, axis=None, skipna=True, *args, **kwargs): + def idxmin(self, axis=0, skipna=True, *args, **kwargs): """ Return the row label of the minimum value. @@ -1673,7 +1673,7 @@ def idxmin(self, axis=None, skipna=True, *args, **kwargs): For compatibility with DataFrame.idxmin. Redundant for application on Series. *args, **kwargs - Additional keywors have no effect but might be accepted + Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns @@ -1742,7 +1742,7 @@ def idxmax(self, axis=0, skipna=True, *args, **kwargs): For compatibility with DataFrame.idxmax. Redundant for application on Series. *args, **kwargs - Additional keywors have no effect but might be accepted + Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns @@ -1802,14 +1802,14 @@ def idxmax(self, axis=0, skipna=True, *args, **kwargs): msg=dedent("""\ 'argmin' is deprecated, use 'idxmin' instead. The behavior of 'argmin' will be corrected to return the positional minimum in the future. - Use 'series.values.argmin' to get the position of the minimum now.""") + Use 'series.values.argmin' to get the position of the minimum row.""") ) argmax = deprecate( 'argmax', idxmax, '0.21.0', msg=dedent("""\ 'argmax' is deprecated, use 'idxmax' instead. The behavior of 'argmax' will be corrected to return the positional maximum in the future. - Use 'series.values.argmax' to get the position of the maximum now.""") + Use 'series.values.argmax' to get the position of the maximum row.""") ) def round(self, decimals=0, *args, **kwargs):
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/21757
2018-07-06T07:41:22Z
2018-07-06T14:27:32Z
2018-07-06T14:27:32Z
2018-07-06T14:27:35Z
TST: Remove check_exact from assert_almost_equal
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 34354e4db601e..14f910051d6c3 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -209,26 +209,26 @@ def decompress_file(path, compression): f.close() -def assert_almost_equal(left, right, check_exact=False, - check_dtype='equiv', check_less_precise=False, - **kwargs): +def assert_almost_equal(left, right, check_dtype="equiv", + check_less_precise=False, **kwargs): """ Check that the left and right objects are approximately equal. + By approximately equal, we refer to objects that are numbers or that + contain numbers which may be equivalent to specific levels of precision. + Parameters ---------- left : object right : object - check_exact : bool, default False - Whether to compare number exactly. check_dtype : bool / string {'equiv'}, default False Check dtype if both a and b are the same type. If 'equiv' is passed in, then `RangeIndex` and `Int64Index` are also considered equivalent when doing type checking. check_less_precise : bool or int, default False - Specify comparison precision. Only used when `check_exact` is False. - 5 digits (False) or 3 digits (True) after decimal points are compared. - If int, then specify the digits to compare. + Specify comparison precision. 5 digits (False) or 3 digits (True) + after decimal points are compared. If int, then specify the number + of digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether @@ -236,42 +236,43 @@ def assert_almost_equal(left, right, check_exact=False, compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. """ + if isinstance(left, pd.Index): return assert_index_equal(left, right, - check_exact=check_exact, + check_exact=False, exact=check_dtype, check_less_precise=check_less_precise, **kwargs) elif isinstance(left, pd.Series): return assert_series_equal(left, right, - check_exact=check_exact, + check_exact=False, check_dtype=check_dtype, check_less_precise=check_less_precise, **kwargs) elif isinstance(left, pd.DataFrame): return assert_frame_equal(left, right, - check_exact=check_exact, + check_exact=False, check_dtype=check_dtype, check_less_precise=check_less_precise, **kwargs) else: - # other sequences + # Other sequences. if check_dtype: if is_number(left) and is_number(right): - # do not compare numeric classes, like np.float64 and float + # Do not compare numeric classes, like np.float64 and float. pass elif is_bool(left) and is_bool(right): - # do not compare bool classes, like np.bool_ and bool + # Do not compare bool classes, like np.bool_ and bool. pass else: if (isinstance(left, np.ndarray) or isinstance(right, np.ndarray)): - obj = 'numpy array' + obj = "numpy array" else: - obj = 'Input' + obj = "Input" assert_class_equal(left, right, obj=obj) return _testing.assert_almost_equal( left, right,
From a semantic point of view, if you're checking for approximate equality, there shouldn't be a parameter that allows you to disable the whole purpose of the function.
https://api.github.com/repos/pandas-dev/pandas/pulls/21756
2018-07-06T06:01:21Z
2018-07-06T14:07:27Z
2018-07-06T14:07:27Z
2018-07-06T22:55:24Z
DOC: Correct docstring for check_dtype in assert_almost_equal
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 09f5e59535adf..34354e4db601e 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -221,8 +221,10 @@ def assert_almost_equal(left, right, check_exact=False, right : object check_exact : bool, default False Whether to compare number exactly. - check_dtype: bool, default True - check dtype if both a and b are the same type + check_dtype : bool / string {'equiv'}, default False + Check dtype if both a and b are the same type. If 'equiv' is passed in, + then `RangeIndex` and `Int64Index` are also considered equivalent + when doing type checking. check_less_precise : bool or int, default False Specify comparison precision. Only used when `check_exact` is False. 5 digits (False) or 3 digits (True) after decimal points are compared. @@ -235,19 +237,22 @@ def assert_almost_equal(left, right, check_exact=False, check whether it is equivalent to 1 within the specified precision. """ if isinstance(left, pd.Index): - return assert_index_equal(left, right, check_exact=check_exact, + return assert_index_equal(left, right, + check_exact=check_exact, exact=check_dtype, check_less_precise=check_less_precise, **kwargs) elif isinstance(left, pd.Series): - return assert_series_equal(left, right, check_exact=check_exact, + return assert_series_equal(left, right, + check_exact=check_exact, check_dtype=check_dtype, check_less_precise=check_less_precise, **kwargs) elif isinstance(left, pd.DataFrame): - return assert_frame_equal(left, right, check_exact=check_exact, + return assert_frame_equal(left, right, + check_exact=check_exact, check_dtype=check_dtype, check_less_precise=check_less_precise, **kwargs)
Title is self-explanatory.
https://api.github.com/repos/pandas-dev/pandas/pulls/21754
2018-07-05T23:00:21Z
2018-07-06T02:34:55Z
2018-07-06T02:34:55Z
2018-07-06T03:19:30Z
CLN: clean up groupby / categorical
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 0252b5b52ae94..375db28a4ee5a 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -698,73 +698,6 @@ def _set_categories(self, categories, fastpath=False): self._dtype = new_dtype - def _codes_for_groupby(self, sort, observed): - """ - Code the categories to ensure we can groupby for categoricals. - - If observed=True, we return a new Categorical with the observed - categories only. - - If sort=False, return a copy of self, coded with categories as - returned by .unique(), followed by any categories not appearing in - the data. If sort=True, return self. - - This method is needed solely to ensure the categorical index of the - GroupBy result has categories in the order of appearance in the data - (GH-8868). - - Parameters - ---------- - sort : boolean - The value of the sort parameter groupby was called with. - observed : boolean - Account only for the observed values - - Returns - ------- - Categorical - If sort=False, the new categories are set to the order of - appearance in codes (unless ordered=True, in which case the - original order is preserved), followed by any unrepresented - categories in the original order. - """ - - # we only care about observed values - if observed: - unique_codes = unique1d(self.codes) - cat = self.copy() - - take_codes = unique_codes[unique_codes != -1] - if self.ordered: - take_codes = np.sort(take_codes) - - # we recode according to the uniques - categories = self.categories.take(take_codes) - codes = _recode_for_categories(self.codes, - self.categories, - categories) - - # return a new categorical that maps our new codes - # and categories - dtype = CategoricalDtype(categories, ordered=self.ordered) - return type(self)(codes, dtype=dtype, fastpath=True) - - # Already sorted according to self.categories; all is fine - if sort: - return self - - # sort=False should order groups in as-encountered order (GH-8868) - cat = self.unique() - - # But for groupby to work, all categories should be present, - # including those missing from the data (GH-13179), which .unique() - # above dropped - cat.add_categories( - self.categories[~self.categories.isin(cat.categories)], - inplace=True) - - return self.reorder_categories(cat.categories) - def _set_dtype(self, dtype): """Internal method for directly updating the CategoricalDtype diff --git a/pandas/core/groupby/categorical.py b/pandas/core/groupby/categorical.py new file mode 100644 index 0000000000000..e54045884ea93 --- /dev/null +++ b/pandas/core/groupby/categorical.py @@ -0,0 +1,99 @@ +import numpy as np +from pandas.core.algorithms import unique1d +from pandas.core.arrays.categorical import ( + _recode_for_categories, CategoricalDtype, Categorical) + + +def recode_for_groupby(c, sort, observed): + """ + Code the categories to ensure we can groupby for categoricals. + + If observed=True, we return a new Categorical with the observed + categories only. + + If sort=False, return a copy of self, coded with categories as + returned by .unique(), followed by any categories not appearing in + the data. If sort=True, return self. + + This method is needed solely to ensure the categorical index of the + GroupBy result has categories in the order of appearance in the data + (GH-8868). + + Parameters + ---------- + c : Categorical + sort : boolean + The value of the sort parameter groupby was called with. + observed : boolean + Account only for the observed values + + Returns + ------- + New Categorical + If sort=False, the new categories are set to the order of + appearance in codes (unless ordered=True, in which case the + original order is preserved), followed by any unrepresented + categories in the original order. + Categorical or None + If we are observed, return the original categorical, otherwise None + """ + + # we only care about observed values + if observed: + unique_codes = unique1d(c.codes) + + take_codes = unique_codes[unique_codes != -1] + if c.ordered: + take_codes = np.sort(take_codes) + + # we recode according to the uniques + categories = c.categories.take(take_codes) + codes = _recode_for_categories(c.codes, + c.categories, + categories) + + # return a new categorical that maps our new codes + # and categories + dtype = CategoricalDtype(categories, ordered=c.ordered) + return Categorical(codes, dtype=dtype, fastpath=True), c + + # Already sorted according to c.categories; all is fine + if sort: + return c, None + + # sort=False should order groups in as-encountered order (GH-8868) + cat = c.unique() + + # But for groupby to work, all categories should be present, + # including those missing from the data (GH-13179), which .unique() + # above dropped + cat = cat.add_categories( + c.categories[~c.categories.isin(cat.categories)]) + + return c.reorder_categories(cat.categories), None + + +def recode_from_groupby(c, sort, ci): + """ + Reverse the codes_to_groupby to account for sort / observed. + + Parameters + ---------- + c : Categorical + sort : boolean + The value of the sort parameter groupby was called with. + ci : CategoricalIndex + The codes / categories to recode + + Returns + ------- + CategoricalIndex + """ + + # we re-order to the original category orderings + if sort: + return ci.set_categories(c.categories) + + # we are not sorting, so add unobserved to the end + return ci.add_categories( + c.categories[~c.categories.isin(ci.categories)]) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c69d7f43de8ea..08acdcf94094a 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2994,9 +2994,9 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None, # a passed Categorical elif is_categorical_dtype(self.grouper): - self.all_grouper = self.grouper - self.grouper = self.grouper._codes_for_groupby( - self.sort, observed) + from pandas.core.groupby.categorical import recode_for_groupby + self.grouper, self.all_grouper = recode_for_groupby( + self.grouper, self.sort, observed) categories = self.grouper.categories # we make a CategoricalIndex out of the cat grouper @@ -3073,17 +3073,9 @@ def labels(self): @cache_readonly def result_index(self): if self.all_grouper is not None: - all_categories = self.all_grouper.categories - - # we re-order to the original category orderings - if self.sort: - return self.group_index.set_categories(all_categories) - - # we are not sorting, so add unobserved to the end - categories = self.group_index.categories - return self.group_index.add_categories( - all_categories[~all_categories.isin(categories)]) - + from pandas.core.groupby.categorical import recode_from_groupby + return recode_from_groupby(self.all_grouper, + self.sort, self.group_index) return self.group_index @property
xref #21151
https://api.github.com/repos/pandas-dev/pandas/pulls/21753
2018-07-05T22:39:16Z
2018-07-06T14:03:13Z
2018-07-06T14:03:13Z
2018-07-06T14:03:13Z
RLS: release notes for 0.23.2
diff --git a/doc/source/release.rst b/doc/source/release.rst index 16fe896d9f58f..cd04288dce2c2 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -37,6 +37,40 @@ analysis / manipulation tool available in any language. * Binary installers on PyPI: https://pypi.org/project/pandas * Documentation: http://pandas.pydata.org +pandas 0.23.2 +------------- + +**Release date**: July 5, 2018 + +This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes +and bug fixes. + +See the :ref:`full whatsnew <whatsnew_0232>` for a list of all the changes. + +Thanks +~~~~~~ + +A total of 17 people contributed to this release. People with a "+" by their +names contributed a patch for the first time. + +* David Krych +* Jacopo Rota + +* Jeff Reback +* Jeremy Schendel +* Joris Van den Bossche +* Kalyan Gokhale +* Matthew Roeschke +* Michael Odintsov + +* Ming Li +* Pietro Battiston +* Tom Augspurger +* Uddeshya Singh +* Vu Le + +* alimcmaster1 + +* david-liu-brattle-1 + +* gfyoung +* jbrockmendel + pandas 0.23.1 ------------- diff --git a/doc/source/whatsnew.rst b/doc/source/whatsnew.rst index c744e44b4c17c..3ec812654ee4a 100644 --- a/doc/source/whatsnew.rst +++ b/doc/source/whatsnew.rst @@ -20,6 +20,8 @@ These are new features and improvements of note in each release. .. include:: whatsnew/v0.24.0.txt +.. include:: whatsnew/v0.23.2.txt + .. include:: whatsnew/v0.23.1.txt .. include:: whatsnew/v0.23.0.txt diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index 2d7808363648b..bd86576ad8586 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -64,7 +64,7 @@ Fixed Regressions Build Changes -------------- +~~~~~~~~~~~~~ - The source and binary distributions no longer include test data files, resulting in smaller download sizes. Tests relying on these data files will be skipped when using ``pandas.test()``. (:issue:`19320`)
https://api.github.com/repos/pandas-dev/pandas/pulls/21752
2018-07-05T20:36:18Z
2018-07-05T20:49:25Z
2018-07-05T20:49:25Z
2018-07-05T21:25:42Z
DOC: clean-up 0.23.2 whatsnew file
diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index b690de40aee06..2d7808363648b 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -63,12 +63,6 @@ Fixed Regressions - Fixed regression in :func:`to_clipboard` that defaulted to copying dataframes with space delimited instead of tab delimited (:issue:`21104`) -Documentation Changes -~~~~~~~~~~~~~~~~~~~~~ - -- -- - Build Changes ------------- @@ -79,56 +73,32 @@ Build Changes Bug Fixes ~~~~~~~~~ -**Groupby/Resample/Rolling** - -- -- - -**Timedelta** - -- Bug in :class:`Timedelta` where non-zero timedeltas shorter than 1 microsecond were considered False (:issue:`21484`) - **Conversion** - Bug in constructing :class:`Index` with an iterator or generator (:issue:`21470`) - Bug in :meth:`Series.nlargest` for signed and unsigned integer dtypes when the minimum value is present (:issue:`21426`) - **Indexing** - Bug in :meth:`Index.get_indexer_non_unique` with categorical key (:issue:`21448`) - Bug in comparison operations for :class:`MultiIndex` where error was raised on equality / inequality comparison involving a MultiIndex with ``nlevels == 1`` (:issue:`21149`) - Bug in :meth:`DataFrame.drop` behaviour is not consistent for unique and non-unique indexes (:issue:`21494`) - Bug in :func:`DataFrame.duplicated` with a large number of columns causing a 'maximum recursion depth exceeded' (:issue:`21524`). -- **I/O** - Bug in :func:`read_csv` that caused it to incorrectly raise an error when ``nrows=0``, ``low_memory=True``, and ``index_col`` was not ``None`` (:issue:`21141`) - Bug in :func:`json_normalize` when formatting the ``record_prefix`` with integer columns (:issue:`21536`) -- - -**Plotting** - -- -- - -**Reshaping** - -- -- **Categorical** - Bug in rendering :class:`Series` with ``Categorical`` dtype in rare conditions under Python 2.7 (:issue:`21002`) -- **Timezones** - Bug in :class:`Timestamp` and :class:`DatetimeIndex` where passing a :class:`Timestamp` localized after a DST transition would return a datetime before the DST transition (:issue:`20854`) - Bug in comparing :class:`DataFrame`s with tz-aware :class:`DatetimeIndex` columns with a DST transition that raised a ``KeyError`` (:issue:`19970`) +**Timedelta** -**Other** - -- +- Bug in :class:`Timedelta` where non-zero timedeltas shorter than 1 microsecond were considered False (:issue:`21484`)
https://api.github.com/repos/pandas-dev/pandas/pulls/21750
2018-07-05T19:04:32Z
2018-07-05T19:05:13Z
2018-07-05T19:05:13Z
2018-07-05T19:09:41Z
DOC: Update documentation with correct link
diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index 2146b7b99a5a7..3c0818343208a 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -1528,7 +1528,7 @@ Removal of prior version deprecations/changes - The ``pandas.io.ga`` module with a ``google-analytics`` interface is removed (:issue:`11308`). Similar functionality can be found in the `Google2Pandas <https://github.com/panalysis/Google2Pandas>`__ package. - ``pd.to_datetime`` and ``pd.to_timedelta`` have dropped the ``coerce`` parameter in favor of ``errors`` (:issue:`13602`) -- ``pandas.stats.fama_macbeth``, ``pandas.stats.ols``, ``pandas.stats.plm`` and ``pandas.stats.var``, as well as the top-level ``pandas.fama_macbeth`` and ``pandas.ols`` routines are removed. Similar functionality can be found in the `statsmodels <shttp://www.statsmodels.org/dev/>`__ package. (:issue:`11898`) +- ``pandas.stats.fama_macbeth``, ``pandas.stats.ols``, ``pandas.stats.plm`` and ``pandas.stats.var``, as well as the top-level ``pandas.fama_macbeth`` and ``pandas.ols`` routines are removed. Similar functionality can be found in the `statsmodels <https://www.statsmodels.org/dev/>`__ package. (:issue:`11898`) - The ``TimeSeries`` and ``SparseTimeSeries`` classes, aliases of ``Series`` and ``SparseSeries``, are removed (:issue:`10890`, :issue:`15098`). - ``Series.is_time_series`` is dropped in favor of ``Series.index.is_all_dates`` (:issue:`15098`)
Fixed from shttp to https in docs link
https://api.github.com/repos/pandas-dev/pandas/pulls/21745
2018-07-05T13:59:49Z
2018-07-05T22:42:51Z
2018-07-05T22:42:51Z
2018-07-06T09:51:43Z
TST: catch warnings for to_hierarchical deprecation
diff --git a/pandas/tests/indexes/multi/test_conversion.py b/pandas/tests/indexes/multi/test_conversion.py index ff99941ba9948..ab99679af0f1a 100644 --- a/pandas/tests/indexes/multi/test_conversion.py +++ b/pandas/tests/indexes/multi/test_conversion.py @@ -57,7 +57,9 @@ def test_to_frame(): def test_to_hierarchical(): index = MultiIndex.from_tuples([(1, 'one'), (1, 'two'), (2, 'one'), ( 2, 'two')]) - result = index.to_hierarchical(3) + with tm.assert_produces_warning(FutureWarning, + check_stacklevel=False): + result = index.to_hierarchical(3) expected = MultiIndex(levels=[[1, 2], ['one', 'two']], labels=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]]) @@ -65,7 +67,9 @@ def test_to_hierarchical(): assert result.names == index.names # K > 1 - result = index.to_hierarchical(3, 2) + with tm.assert_produces_warning(FutureWarning, + check_stacklevel=False): + result = index.to_hierarchical(3, 2) expected = MultiIndex(levels=[[1, 2], ['one', 'two']], labels=[[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]]) @@ -77,7 +81,9 @@ def test_to_hierarchical(): (2, 'a'), (2, 'b')], names=['N1', 'N2']) - result = index.to_hierarchical(2) + with tm.assert_produces_warning(FutureWarning, + check_stacklevel=False): + result = index.to_hierarchical(2) expected = MultiIndex.from_tuples([(2, 'c'), (2, 'c'), (1, 'b'), (1, 'b'), (2, 'a'), (2, 'a'),
https://api.github.com/repos/pandas-dev/pandas/pulls/21744
2018-07-05T11:24:19Z
2018-07-05T16:12:34Z
2018-07-05T16:12:34Z
2018-07-05T16:13:10Z
CLN: Remove Legacy MultiIndex Index Compatibility
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 8cb384f50d371..efd4028f2eada 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -513,7 +513,7 @@ Missing MultiIndex ^^^^^^^^^^ -- +- Removed compatibility for MultiIndex pickles prior to version 0.8.0; compatibility with MultiIndex pickles from version 0.13 forward is maintained (:issue:`21654`) - - diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7d24a901382bb..4912014b43773 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -824,15 +824,6 @@ def values(self): self._tuples = lib.fast_zip(values) return self._tuples - # fml - @property - def _is_v1(self): - return False - - @property - def _is_v2(self): - return False - @property def _has_complex_internals(self): # to disable groupby tricks @@ -2843,22 +2834,6 @@ def delete(self, loc): return MultiIndex(levels=self.levels, labels=new_labels, names=self.names, verify_integrity=False) - get_major_bounds = slice_locs - - __bounds = None - - @property - def _bounds(self): - """ - Return or compute and return slice points for level 0, assuming - sortedness - """ - if self.__bounds is None: - inds = np.arange(len(self.levels[0])) - self.__bounds = self.labels[0].searchsorted(inds) - - return self.__bounds - def _wrap_joined_index(self, joined, other): names = self.names if self.names == other.names else None return MultiIndex.from_tuples(joined, names=names) diff --git a/pandas/tests/indexes/multi/data/mindex_073.pickle b/pandas/tests/indexes/multi/data/mindex_073.pickle deleted file mode 100644 index c99f51fa289ac..0000000000000 Binary files a/pandas/tests/indexes/multi/data/mindex_073.pickle and /dev/null differ diff --git a/pandas/tests/indexes/multi/data/multiindex_v1.pickle b/pandas/tests/indexes/multi/data/multiindex_v1.pickle deleted file mode 100644 index d404a78f9e397..0000000000000 --- a/pandas/tests/indexes/multi/data/multiindex_v1.pickle +++ /dev/null @@ -1,149 +0,0 @@ -cnumpy.core.multiarray -_reconstruct -p0 -(cpandas.core.index -MultiIndex -p1 -(I0 -tp2 -S'b' -p3 -tp4 -Rp5 -((I1 -(I10 -tp6 -cnumpy -dtype -p7 -(S'O8' -p8 -I0 -I1 -tp9 -Rp10 -(I3 -S'|' -p11 -NNNI-1 -I-1 -I63 -tp12 -bI00 -(lp13 -I0 -aI1 -aI2 -aI3 -aI4 -aI5 -aI6 -aI7 -aI8 -aI9 -atp14 -((lp15 -g0 -(cpandas.core.index -Index -p16 -(I0 -tp17 -g3 -tp18 -Rp19 -((I1 -(I4 -tp20 -g10 -I00 -(lp21 -S'foo' -p22 -aS'bar' -p23 -aS'baz' -p24 -aS'qux' -p25 -atp26 -(S'first' -p27 -tp28 -tp29 -bag0 -(g16 -(I0 -tp30 -g3 -tp31 -Rp32 -((I1 -(I3 -tp33 -g10 -I00 -(lp34 -S'one' -p35 -aS'two' -p36 -aS'three' -p37 -atp38 -(S'second' -p39 -tp40 -tp41 -ba(lp42 -g0 -(cnumpy -ndarray -p43 -(I0 -tp44 -g3 -tp45 -Rp46 -(I1 -(I10 -tp47 -g7 -(S'i4' -p48 -I0 -I1 -tp49 -Rp50 -(I3 -S'<' -p51 -NNNI-1 -I-1 -I0 -tp52 -bI00 -S'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00' -p53 -tp54 -bag0 -(g43 -(I0 -tp55 -g3 -tp56 -Rp57 -(I1 -(I10 -tp58 -g50 -I00 -S'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00' -p59 -tp60 -baN(lp61 -g27 -ag39 -atp62 -tp63 -b. \ No newline at end of file diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py index 4cc0504417801..9f6a72f803f9d 100644 --- a/pandas/tests/indexes/multi/test_analytics.py +++ b/pandas/tests/indexes/multi/test_analytics.py @@ -15,10 +15,6 @@ def test_shift(idx): pytest.raises(NotImplementedError, idx.shift, 1, 2) -def test_bounds(idx): - idx._bounds - - def test_groupby(idx): groups = idx.groupby(np.array([1, 1, 1, 2, 2, 2])) labels = idx.get_values().tolist() diff --git a/pandas/tests/indexes/multi/test_conversion.py b/pandas/tests/indexes/multi/test_conversion.py index ab99679af0f1a..fcc22390e17a1 100644 --- a/pandas/tests/indexes/multi/test_conversion.py +++ b/pandas/tests/indexes/multi/test_conversion.py @@ -4,10 +4,8 @@ import numpy as np import pandas as pd import pandas.util.testing as tm -import pytest from pandas import DataFrame, MultiIndex, date_range -from pandas.compat import PY3, range -from pandas.util.testing import assert_almost_equal +from pandas.compat import range def test_tolist(idx): @@ -93,46 +91,6 @@ def test_to_hierarchical(): assert result.names == index.names -@pytest.mark.skipif(PY3, reason="testing legacy pickles not support on py3") -def test_legacy_pickle(datapath): - - path = datapath('indexes', 'multi', 'data', 'multiindex_v1.pickle') - obj = pd.read_pickle(path) - - obj2 = MultiIndex.from_tuples(obj.values) - assert obj.equals(obj2) - - res = obj.get_indexer(obj) - exp = np.arange(len(obj), dtype=np.intp) - assert_almost_equal(res, exp) - - res = obj.get_indexer(obj2[::-1]) - exp = obj.get_indexer(obj[::-1]) - exp2 = obj2.get_indexer(obj2[::-1]) - assert_almost_equal(res, exp) - assert_almost_equal(exp, exp2) - - -def test_legacy_v2_unpickle(datapath): - - # 0.7.3 -> 0.8.0 format manage - path = datapath('indexes', 'multi', 'data', 'mindex_073.pickle') - obj = pd.read_pickle(path) - - obj2 = MultiIndex.from_tuples(obj.values) - assert obj.equals(obj2) - - res = obj.get_indexer(obj) - exp = np.arange(len(obj), dtype=np.intp) - assert_almost_equal(res, exp) - - res = obj.get_indexer(obj2[::-1]) - exp = obj.get_indexer(obj[::-1]) - exp2 = obj2.get_indexer(obj2[::-1]) - assert_almost_equal(res, exp) - assert_almost_equal(exp, exp2) - - def test_roundtrip_pickle_with_tz(): # GH 8367 @@ -146,6 +104,7 @@ def test_roundtrip_pickle_with_tz(): def test_pickle(indices): + unpickled = tm.round_trip_pickle(indices) assert indices.equals(unpickled) original_name, indices.name = indices.name, 'foo'
- [x] closes #21654 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] what's new - removing legacy MultiIndex internal formats
https://api.github.com/repos/pandas-dev/pandas/pulls/21740
2018-07-05T01:06:55Z
2018-07-27T11:33:16Z
2018-07-27T11:33:15Z
2018-07-27T12:18:00Z
CLN/TST: Cleanup tests in test_ujson.py
diff --git a/pandas/conftest.py b/pandas/conftest.py index 8ca90722d17f7..255e0e165041b 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -250,7 +250,7 @@ def string_dtype(request): return request.param -@pytest.fixture(params=["float32", "float64"]) +@pytest.fixture(params=[float, "float32", "float64"]) def float_dtype(request): """ Parameterized fixture for float dtypes. @@ -262,7 +262,7 @@ def float_dtype(request): return request.param -@pytest.fixture(params=["complex64", "complex128"]) +@pytest.fixture(params=[complex, "complex64", "complex128"]) def complex_dtype(request): """ Parameterized fixture for complex dtypes. @@ -275,7 +275,7 @@ def complex_dtype(request): UNSIGNED_INT_DTYPES = ["uint8", "uint16", "uint32", "uint64"] -SIGNED_INT_DTYPES = ["int8", "int16", "int32", "int64"] +SIGNED_INT_DTYPES = [int, "int8", "int16", "int32", "int64"] ALL_INT_DTYPES = UNSIGNED_INT_DTYPES + SIGNED_INT_DTYPES diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 89acbfdc9a746..6706a29e78ae8 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -6,6 +6,7 @@ import simplejson as json import math import pytz +import locale import pytest import time import datetime @@ -14,12 +15,13 @@ import decimal import dateutil from functools import partial -from pandas.compat import range, zip, StringIO, u +from pandas.compat import range, StringIO, u +from pandas._libs.tslib import Timestamp import pandas._libs.json as ujson import pandas.compat as compat import numpy as np -from pandas import DataFrame, Series, Index, NaT, DatetimeIndex +from pandas import DataFrame, Series, Index, NaT, DatetimeIndex, date_range import pandas.util.testing as tm @@ -27,11 +29,43 @@ else partial(json.dumps, encoding="utf-8")) +def _clean_dict(d): + """ + Sanitize dictionary for JSON by converting all keys to strings. + + Parameters + ---------- + d : dict + The dictionary to convert. + + Returns + ------- + cleaned_dict : dict + """ + + return {str(k): v for k, v in compat.iteritems(d)} + + +@pytest.fixture(params=[ + None, # Column indexed by default. + "split", + "records", + "values", + "index"]) +def orient(request): + return request.param + + +@pytest.fixture(params=[None, True]) +def numpy(request): + return request.param + + class TestUltraJSONTests(object): @pytest.mark.skipif(compat.is_platform_32bit(), reason="not compliant on 32-bit, xref #15865") - def test_encodeDecimal(self): + def test_encode_decimal(self): sut = decimal.Decimal("1337.1337") encoded = ujson.encode(sut, double_precision=15) decoded = ujson.decode(encoded) @@ -40,116 +74,108 @@ def test_encodeDecimal(self): sut = decimal.Decimal("0.95") encoded = ujson.encode(sut, double_precision=1) assert encoded == "1.0" + decoded = ujson.decode(encoded) assert decoded == 1.0 sut = decimal.Decimal("0.94") encoded = ujson.encode(sut, double_precision=1) assert encoded == "0.9" + decoded = ujson.decode(encoded) assert decoded == 0.9 sut = decimal.Decimal("1.95") encoded = ujson.encode(sut, double_precision=1) assert encoded == "2.0" + decoded = ujson.decode(encoded) assert decoded == 2.0 sut = decimal.Decimal("-1.95") encoded = ujson.encode(sut, double_precision=1) assert encoded == "-2.0" + decoded = ujson.decode(encoded) assert decoded == -2.0 sut = decimal.Decimal("0.995") encoded = ujson.encode(sut, double_precision=2) assert encoded == "1.0" + decoded = ujson.decode(encoded) assert decoded == 1.0 sut = decimal.Decimal("0.9995") encoded = ujson.encode(sut, double_precision=3) assert encoded == "1.0" + decoded = ujson.decode(encoded) assert decoded == 1.0 sut = decimal.Decimal("0.99999999999999944") encoded = ujson.encode(sut, double_precision=15) assert encoded == "1.0" + decoded = ujson.decode(encoded) assert decoded == 1.0 - def test_encodeStringConversion(self): - input = "A string \\ / \b \f \n \r \t </script> &" + @pytest.mark.parametrize("ensure_ascii", [True, False]) + def test_encode_string_conversion(self, ensure_ascii): + string_input = "A string \\ / \b \f \n \r \t </script> &" not_html_encoded = ('"A string \\\\ \\/ \\b \\f \\n ' '\\r \\t <\\/script> &"') html_encoded = ('"A string \\\\ \\/ \\b \\f \\n \\r \\t ' '\\u003c\\/script\\u003e \\u0026"') def helper(expected_output, **encode_kwargs): - output = ujson.encode(input, **encode_kwargs) - assert input == json.loads(output) + output = ujson.encode(string_input, + ensure_ascii=ensure_ascii, + **encode_kwargs) + assert output == expected_output - assert input == ujson.decode(output) + assert string_input == json.loads(output) + assert string_input == ujson.decode(output) # Default behavior assumes encode_html_chars=False. - helper(not_html_encoded, ensure_ascii=True) - helper(not_html_encoded, ensure_ascii=False) + helper(not_html_encoded) # Make sure explicit encode_html_chars=False works. - helper(not_html_encoded, ensure_ascii=True, encode_html_chars=False) - helper(not_html_encoded, ensure_ascii=False, encode_html_chars=False) + helper(not_html_encoded, encode_html_chars=False) # Make sure explicit encode_html_chars=True does the encoding. - helper(html_encoded, ensure_ascii=True, encode_html_chars=True) - helper(html_encoded, ensure_ascii=False, encode_html_chars=True) + helper(html_encoded, encode_html_chars=True) - def test_doubleLongIssue(self): - sut = {u('a'): -4342969734183514} - encoded = json.dumps(sut) - decoded = json.loads(encoded) - assert sut == decoded + @pytest.mark.parametrize("long_number", [ + -4342969734183514, -12345678901234.56789012, -528656961.4399388 + ]) + def test_double_long_numbers(self, long_number): + sut = {u("a"): long_number} encoded = ujson.encode(sut, double_precision=15) - decoded = ujson.decode(encoded) - assert sut == decoded - def test_doubleLongDecimalIssue(self): - sut = {u('a'): -12345678901234.56789012} - encoded = json.dumps(sut) - decoded = json.loads(encoded) - assert sut == decoded - encoded = ujson.encode(sut, double_precision=15) decoded = ujson.decode(encoded) assert sut == decoded - def test_encodeNonCLocale(self): - import locale - savedlocale = locale.getlocale(locale.LC_NUMERIC) - try: - locale.setlocale(locale.LC_NUMERIC, 'it_IT.UTF-8') - except: - try: - locale.setlocale(locale.LC_NUMERIC, 'Italian_Italy') - except: - pytest.skip('Could not set locale for testing') - assert ujson.loads(ujson.dumps(4.78e60)) == 4.78e60 - assert ujson.loads('4.78', precise_float=True) == 4.78 - locale.setlocale(locale.LC_NUMERIC, savedlocale) - - def test_encodeDecodeLongDecimal(self): - sut = {u('a'): -528656961.4399388} - encoded = ujson.dumps(sut, double_precision=15) - ujson.decode(encoded) - - def test_decimalDecodeTestPrecise(self): - sut = {u('a'): 4.56} + def test_encode_non_c_locale(self): + lc_category = locale.LC_NUMERIC + + # We just need one of these locales to work. + for new_locale in ("it_IT.UTF-8", "Italian_Italy"): + if tm.can_set_locale(new_locale, lc_category): + with tm.set_locale(new_locale, lc_category): + assert ujson.loads(ujson.dumps(4.78e60)) == 4.78e60 + assert ujson.loads("4.78", precise_float=True) == 4.78 + break + + def test_decimal_decode_test_precise(self): + sut = {u("a"): 4.56} encoded = ujson.encode(sut) decoded = ujson.decode(encoded, precise_float=True) assert sut == decoded @pytest.mark.skipif(compat.is_platform_windows() and not compat.PY3, reason="buggy on win-64 for py2") - def test_encodeDoubleTinyExponential(self): + def test_encode_double_tiny_exponential(self): num = 1e-40 assert num == ujson.decode(ujson.encode(num)) num = 1e-100 @@ -159,274 +185,227 @@ def test_encodeDoubleTinyExponential(self): num = -1e-145 assert np.allclose(num, ujson.decode(ujson.encode(num))) - def test_encodeDictWithUnicodeKeys(self): - input = {u("key1"): u("value1"), u("key1"): - u("value1"), u("key1"): u("value1"), - u("key1"): u("value1"), u("key1"): - u("value1"), u("key1"): u("value1")} - output = ujson.encode(input) - - input = {u("بن"): u("value1"), u("بن"): u("value1"), - u("بن"): u("value1"), u("بن"): u("value1"), - u("بن"): u("value1"), u("بن"): u("value1"), - u("بن"): u("value1")} - output = ujson.encode(input) # noqa - - def test_encodeDoubleConversion(self): - input = math.pi - output = ujson.encode(input) - assert round(input, 5) == round(json.loads(output), 5) - assert round(input, 5) == round(ujson.decode(output), 5) - - def test_encodeWithDecimal(self): - input = 1.0 - output = ujson.encode(input) + @pytest.mark.parametrize("unicode_key", [ + u("key1"), u("بن") + ]) + def test_encode_dict_with_unicode_keys(self, unicode_key): + unicode_dict = {unicode_key: u("value1")} + assert unicode_dict == ujson.decode(ujson.encode(unicode_dict)) + + @pytest.mark.parametrize("double_input", [ + math.pi, + -math.pi # Should work with negatives too. + ]) + def test_encode_double_conversion(self, double_input): + output = ujson.encode(double_input) + assert round(double_input, 5) == round(json.loads(output), 5) + assert round(double_input, 5) == round(ujson.decode(output), 5) + + def test_encode_with_decimal(self): + decimal_input = 1.0 + output = ujson.encode(decimal_input) + assert output == "1.0" - def test_encodeDoubleNegConversion(self): - input = -math.pi - output = ujson.encode(input) - - assert round(input, 5) == round(json.loads(output), 5) - assert round(input, 5) == round(ujson.decode(output), 5) - - def test_encodeArrayOfNestedArrays(self): - input = [[[[]]]] * 20 - output = ujson.encode(input) - assert input == json.loads(output) - # assert output == json.dumps(input) - assert input == ujson.decode(output) - input = np.array(input) - tm.assert_numpy_array_equal(input, ujson.decode( - output, numpy=True, dtype=input.dtype)) - - def test_encodeArrayOfDoubles(self): - input = [31337.31337, 31337.31337, 31337.31337, 31337.31337] * 10 - output = ujson.encode(input) - assert input == json.loads(output) - # assert output == json.dumps(input) - assert input == ujson.decode(output) - tm.assert_numpy_array_equal( - np.array(input), ujson.decode(output, numpy=True)) - - def test_doublePrecisionTest(self): - input = 30.012345678901234 - output = ujson.encode(input, double_precision=15) - assert input == json.loads(output) - assert input == ujson.decode(output) - - output = ujson.encode(input, double_precision=9) - assert round(input, 9) == json.loads(output) - assert round(input, 9) == ujson.decode(output) - - output = ujson.encode(input, double_precision=3) - assert round(input, 3) == json.loads(output) - assert round(input, 3) == ujson.decode(output) - - def test_invalidDoublePrecision(self): - input = 30.12345678901234567890 - - pytest.raises(ValueError, ujson.encode, input, double_precision=20) - pytest.raises(ValueError, ujson.encode, input, double_precision=-1) - - # will throw typeError - pytest.raises(TypeError, ujson.encode, input, double_precision='9') - # will throw typeError - pytest.raises(TypeError, ujson.encode, - input, double_precision=None) - - def test_encodeStringConversion2(self): - input = "A string \\ / \b \f \n \r \t" - output = ujson.encode(input) - assert input == json.loads(output) - assert output == '"A string \\\\ \\/ \\b \\f \\n \\r \\t"' - assert input == ujson.decode(output) - pass + def test_encode_array_of_nested_arrays(self): + nested_input = [[[[]]]] * 20 + output = ujson.encode(nested_input) + + assert nested_input == json.loads(output) + assert nested_input == ujson.decode(output) + + nested_input = np.array(nested_input) + tm.assert_numpy_array_equal(nested_input, ujson.decode( + output, numpy=True, dtype=nested_input.dtype)) + + def test_encode_array_of_doubles(self): + doubles_input = [31337.31337, 31337.31337, + 31337.31337, 31337.31337] * 10 + output = ujson.encode(doubles_input) + + assert doubles_input == json.loads(output) + assert doubles_input == ujson.decode(output) + + tm.assert_numpy_array_equal(np.array(doubles_input), + ujson.decode(output, numpy=True)) + + def test_double_precision(self): + double_input = 30.012345678901234 + output = ujson.encode(double_input, double_precision=15) + + assert double_input == json.loads(output) + assert double_input == ujson.decode(output) + + for double_precision in (3, 9): + output = ujson.encode(double_input, + double_precision=double_precision) + rounded_input = round(double_input, double_precision) - def test_decodeUnicodeConversion(self): - pass + assert rounded_input == json.loads(output) + assert rounded_input == ujson.decode(output) - def test_encodeUnicodeConversion1(self): - input = "Räksmörgås اسامة بن محمد بن عوض بن لادن" - enc = ujson.encode(input) + @pytest.mark.parametrize("invalid_val", [ + 20, -1, "9", None + ]) + def test_invalid_double_precision(self, invalid_val): + double_input = 30.12345678901234567890 + expected_exception = (ValueError if isinstance(invalid_val, int) + else TypeError) + + with pytest.raises(expected_exception): + ujson.encode(double_input, double_precision=invalid_val) + + def test_encode_string_conversion2(self): + string_input = "A string \\ / \b \f \n \r \t" + output = ujson.encode(string_input) + + assert string_input == json.loads(output) + assert string_input == ujson.decode(output) + assert output == '"A string \\\\ \\/ \\b \\f \\n \\r \\t"' + + @pytest.mark.parametrize("unicode_input", [ + "Räksmörgås اسامة بن محمد بن عوض بن لادن", + "\xe6\x97\xa5\xd1\x88" + ]) + def test_encode_unicode_conversion(self, unicode_input): + enc = ujson.encode(unicode_input) dec = ujson.decode(enc) - assert enc == json_unicode(input) + + assert enc == json_unicode(unicode_input) assert dec == json.loads(enc) - def test_encodeControlEscaping(self): - input = "\x19" - enc = ujson.encode(input) + def test_encode_control_escaping(self): + escaped_input = "\x19" + enc = ujson.encode(escaped_input) dec = ujson.decode(enc) - assert input == dec - assert enc == json_unicode(input) - def test_encodeUnicodeConversion2(self): - input = "\xe6\x97\xa5\xd1\x88" - enc = ujson.encode(input) - dec = ujson.decode(enc) - assert enc == json_unicode(input) - assert dec == json.loads(enc) + assert escaped_input == dec + assert enc == json_unicode(escaped_input) - def test_encodeUnicodeSurrogatePair(self): - input = "\xf0\x90\x8d\x86" - enc = ujson.encode(input) + def test_encode_unicode_surrogate_pair(self): + surrogate_input = "\xf0\x90\x8d\x86" + enc = ujson.encode(surrogate_input) dec = ujson.decode(enc) - assert enc == json_unicode(input) + assert enc == json_unicode(surrogate_input) assert dec == json.loads(enc) - def test_encodeUnicode4BytesUTF8(self): - input = "\xf0\x91\x80\xb0TRAILINGNORMAL" - enc = ujson.encode(input) + def test_encode_unicode_4bytes_utf8(self): + four_bytes_input = "\xf0\x91\x80\xb0TRAILINGNORMAL" + enc = ujson.encode(four_bytes_input) dec = ujson.decode(enc) - assert enc == json_unicode(input) + assert enc == json_unicode(four_bytes_input) assert dec == json.loads(enc) - def test_encodeUnicode4BytesUTF8Highest(self): - input = "\xf3\xbf\xbf\xbfTRAILINGNORMAL" - enc = ujson.encode(input) + def test_encode_unicode_4bytes_utf8highest(self): + four_bytes_input = "\xf3\xbf\xbf\xbfTRAILINGNORMAL" + enc = ujson.encode(four_bytes_input) dec = ujson.decode(enc) - assert enc == json_unicode(input) + assert enc == json_unicode(four_bytes_input) assert dec == json.loads(enc) - def test_encodeArrayInArray(self): - input = [[[[]]]] - output = ujson.encode(input) + def test_encode_array_in_array(self): + arr_in_arr_input = [[[[]]]] + output = ujson.encode(arr_in_arr_input) + + assert arr_in_arr_input == json.loads(output) + assert output == json.dumps(arr_in_arr_input) + assert arr_in_arr_input == ujson.decode(output) + + tm.assert_numpy_array_equal(np.array(arr_in_arr_input), + ujson.decode(output, numpy=True)) + + @pytest.mark.parametrize("num_input", [ + 31337, + -31337, # Negative number. + -9223372036854775808 # Large negative number. + ]) + def test_encode_num_conversion(self, num_input): + output = ujson.encode(num_input) + assert num_input == json.loads(output) + assert output == json.dumps(num_input) + assert num_input == ujson.decode(output) + + def test_encode_list_conversion(self): + list_input = [1, 2, 3, 4] + output = ujson.encode(list_input) + + assert list_input == json.loads(output) + assert list_input == ujson.decode(output) + + tm.assert_numpy_array_equal(np.array(list_input), + ujson.decode(output, numpy=True)) + + def test_encode_dict_conversion(self): + dict_input = {"k1": 1, "k2": 2, "k3": 3, "k4": 4} + output = ujson.encode(dict_input) + + assert dict_input == json.loads(output) + assert dict_input == ujson.decode(output) + + @pytest.mark.parametrize("builtin_value", [None, True, False]) + def test_encode_builtin_values_conversion(self, builtin_value): + output = ujson.encode(builtin_value) + assert builtin_value == json.loads(output) + assert output == json.dumps(builtin_value) + assert builtin_value == ujson.decode(output) + + def test_encode_datetime_conversion(self): + datetime_input = datetime.datetime.fromtimestamp(time.time()) + output = ujson.encode(datetime_input, date_unit="s") + expected = calendar.timegm(datetime_input.utctimetuple()) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - tm.assert_numpy_array_equal( - np.array(input), ujson.decode(output, numpy=True)) - pass - - def test_encodeIntConversion(self): - input = 31337 - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - pass - - def test_encodeIntNegConversion(self): - input = -31337 - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - pass - - def test_encodeLongNegConversion(self): - input = -9223372036854775808 - output = ujson.encode(input) - - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - - def test_encodeListConversion(self): - input = [1, 2, 3, 4] - output = ujson.encode(input) - assert input == json.loads(output) - assert input == ujson.decode(output) - tm.assert_numpy_array_equal( - np.array(input), ujson.decode(output, numpy=True)) - pass - - def test_encodeDictConversion(self): - input = {"k1": 1, "k2": 2, "k3": 3, "k4": 4} - output = ujson.encode(input) # noqa - assert input == json.loads(output) - assert input == ujson.decode(output) - assert input == ujson.decode(output) - pass - - def test_encodeNoneConversion(self): - input = None - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - pass - - def test_encodeTrueConversion(self): - input = True - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - pass - - def test_encodeFalseConversion(self): - input = False - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - - def test_encodeDatetimeConversion(self): - ts = time.time() - input = datetime.datetime.fromtimestamp(ts) - output = ujson.encode(input, date_unit='s') - expected = calendar.timegm(input.utctimetuple()) assert int(expected) == json.loads(output) assert int(expected) == ujson.decode(output) - def test_encodeDateConversion(self): - ts = time.time() - input = datetime.date.fromtimestamp(ts) - - output = ujson.encode(input, date_unit='s') - tup = (input.year, input.month, input.day, 0, 0, 0) + def test_encode_date_conversion(self): + date_input = datetime.date.fromtimestamp(time.time()) + output = ujson.encode(date_input, date_unit="s") + tup = (date_input.year, date_input.month, date_input.day, 0, 0, 0) expected = calendar.timegm(tup) + assert int(expected) == json.loads(output) assert int(expected) == ujson.decode(output) - def test_encodeTimeConversion(self): - tests = [ - datetime.time(), - datetime.time(1, 2, 3), - datetime.time(10, 12, 15, 343243), - ] - for test in tests: - output = ujson.encode(test) - expected = '"{iso}"'.format(iso=test.isoformat()) - assert expected == output - - def test_encodeTimeConversion_pytz(self): + @pytest.mark.parametrize("test", [ + datetime.time(), + datetime.time(1, 2, 3), + datetime.time(10, 12, 15, 343243), + ]) + def test_encode_time_conversion_basic(self, test): + output = ujson.encode(test) + expected = '"{iso}"'.format(iso=test.isoformat()) + assert expected == output + + def test_encode_time_conversion_pytz(self): # see gh-11473: to_json segfaults with timezone-aware datetimes test = datetime.time(10, 12, 15, 343243, pytz.utc) output = ujson.encode(test) expected = '"{iso}"'.format(iso=test.isoformat()) assert expected == output - def test_encodeTimeConversion_dateutil(self): + def test_encode_time_conversion_dateutil(self): # see gh-11473: to_json segfaults with timezone-aware datetimes test = datetime.time(10, 12, 15, 343243, dateutil.tz.tzutc()) output = ujson.encode(test) expected = '"{iso}"'.format(iso=test.isoformat()) assert expected == output - def test_nat(self): - input = NaT - assert ujson.encode(input) == 'null', "Expected null" - - def test_npy_nat(self): - from distutils.version import LooseVersion - if LooseVersion(np.__version__) < LooseVersion('1.7.0'): - pytest.skip("numpy version < 1.7.0, is " - "{0}".format(np.__version__)) - - input = np.datetime64('NaT') - assert ujson.encode(input) == 'null', "Expected null" + @pytest.mark.parametrize("decoded_input", [ + NaT, + np.datetime64("NaT"), + np.nan, + np.inf, + -np.inf + ]) + def test_encode_as_null(self, decoded_input): + assert ujson.encode(decoded_input) == "null", "Expected null" def test_datetime_units(self): - from pandas._libs.tslib import Timestamp - val = datetime.datetime(2013, 8, 17, 21, 17, 12, 215504) stamp = Timestamp(val) @@ -444,20 +423,24 @@ def test_datetime_units(self): pytest.raises(ValueError, ujson.encode, val, date_unit='foo') - def test_encodeToUTF8(self): - input = "\xe6\x97\xa5\xd1\x88" - enc = ujson.encode(input, ensure_ascii=False) + def test_encode_to_utf8(self): + unencoded = "\xe6\x97\xa5\xd1\x88" + + enc = ujson.encode(unencoded, ensure_ascii=False) dec = ujson.decode(enc) - assert enc == json_unicode(input, ensure_ascii=False) + + assert enc == json_unicode(unencoded, ensure_ascii=False) assert dec == json.loads(enc) - def test_decodeFromUnicode(self): - input = u("{\"obj\": 31337}") - dec1 = ujson.decode(input) - dec2 = ujson.decode(str(input)) + def test_decode_from_unicode(self): + unicode_input = u("{\"obj\": 31337}") + + dec1 = ujson.decode(unicode_input) + dec2 = ujson.decode(str(unicode_input)) + assert dec1 == dec2 - def test_encodeRecursionMax(self): + def test_encode_recursion_max(self): # 8 is the max recursion depth class O2(object): @@ -468,338 +451,159 @@ class O1(object): member = 0 pass - input = O1() - input.member = O2() - input.member.member = input - - try: - output = ujson.encode(input) # noqa - assert False, "Expected overflow exception" - except(OverflowError): - pass - - def test_encodeDoubleNan(self): - input = np.nan - assert ujson.encode(input) == 'null', "Expected null" - - def test_encodeDoubleInf(self): - input = np.inf - assert ujson.encode(input) == 'null', "Expected null" - - def test_encodeDoubleNegInf(self): - input = -np.inf - assert ujson.encode(input) == 'null', "Expected null" - - def test_decodeJibberish(self): - input = "fdsa sda v9sa fdsa" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeBrokenArrayStart(self): - input = "[" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeBrokenObjectStart(self): - input = "{" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeBrokenArrayEnd(self): - input = "]" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeArrayDepthTooBig(self): - input = '[' * (1024 * 1024) - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeBrokenObjectEnd(self): - input = "}" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeObjectDepthTooBig(self): - input = '{' * (1024 * 1024) - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeStringUnterminated(self): - input = "\"TESTING" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeStringUntermEscapeSequence(self): - input = "\"TESTING\\\"" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeStringBadEscape(self): - input = "\"TESTING\\\"" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeTrueBroken(self): - input = "tru" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeFalseBroken(self): - input = "fa" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeNullBroken(self): - input = "n" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - assert False, "Wrong exception" - - def test_decodeBrokenDictKeyTypeLeakTest(self): - input = '{{1337:""}}' - for x in range(1000): - try: - ujson.decode(input) - assert False, "Expected exception!" - except ValueError: - continue - - assert False, "Wrong exception" - - def test_decodeBrokenDictLeakTest(self): - input = '{{"key":"}' - for x in range(1000): - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - continue - - assert False, "Wrong exception" - - def test_decodeBrokenListLeakTest(self): - input = '[[[true' - for x in range(1000): - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - continue - - assert False, "Wrong exception" - - def test_decodeDictWithNoKey(self): - input = "{{{{31337}}}}" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - - assert False, "Wrong exception" - - def test_decodeDictWithNoColonOrValue(self): - input = "{{{{\"key\"}}}}" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - - assert False, "Wrong exception" - - def test_decodeDictWithNoValue(self): - input = "{{{{\"key\":}}}}" - try: - ujson.decode(input) - assert False, "Expected exception!" - except(ValueError): - return - - assert False, "Wrong exception" - - def test_decodeNumericIntPos(self): - input = "31337" - assert 31337 == ujson.decode(input) - - def test_decodeNumericIntNeg(self): - input = "-31337" - assert -31337 == ujson.decode(input) + decoded_input = O1() + decoded_input.member = O2() + decoded_input.member.member = decoded_input + + with pytest.raises(OverflowError): + ujson.encode(decoded_input) + + def test_decode_jibberish(self): + jibberish = "fdsa sda v9sa fdsa" + + with pytest.raises(ValueError): + ujson.decode(jibberish) + + @pytest.mark.parametrize("broken_json", [ + "[", # Broken array start. + "{", # Broken object start. + "]", # Broken array end. + "}", # Broken object end. + ]) + def test_decode_broken_json(self, broken_json): + with pytest.raises(ValueError): + ujson.decode(broken_json) + + @pytest.mark.parametrize("too_big_char", [ + "[", + "{", + ]) + def test_decode_depth_too_big(self, too_big_char): + with pytest.raises(ValueError): + ujson.decode(too_big_char * (1024 * 1024)) + + @pytest.mark.parametrize("bad_string", [ + "\"TESTING", # Unterminated. + "\"TESTING\\\"", # Unterminated escape. + "tru", # Broken True. + "fa", # Broken False. + "n", # Broken None. + ]) + def test_decode_bad_string(self, bad_string): + with pytest.raises(ValueError): + ujson.decode(bad_string) + + @pytest.mark.parametrize("broken_json", [ + '{{1337:""}}', + '{{"key":"}', + '[[[true', + ]) + def test_decode_broken_json_leak(self, broken_json): + for _ in range(1000): + with pytest.raises(ValueError): + ujson.decode(broken_json) + + @pytest.mark.parametrize("invalid_dict", [ + "{{{{31337}}}}", # No key. + "{{{{\"key\":}}}}", # No value. + "{{{{\"key\"}}}}", # No colon or value. + ]) + def test_decode_invalid_dict(self, invalid_dict): + with pytest.raises(ValueError): + ujson.decode(invalid_dict) + + @pytest.mark.parametrize("numeric_int_as_str", [ + "31337", "-31337" # Should work with negatives. + ]) + def test_decode_numeric_int(self, numeric_int_as_str): + assert int(numeric_int_as_str) == ujson.decode(numeric_int_as_str) @pytest.mark.skipif(compat.PY3, reason="only PY2") - def test_encodeUnicode4BytesUTF8Fail(self): - input = "\xfd\xbf\xbf\xbf\xbf\xbf" - try: - enc = ujson.encode(input) # noqa - assert False, "Expected exception" - except OverflowError: - pass + def test_encode_unicode_4bytes_utf8_fail(self): + with pytest.raises(OverflowError): + ujson.encode("\xfd\xbf\xbf\xbf\xbf\xbf") + + def test_encode_null_character(self): + wrapped_input = "31337 \x00 1337" + output = ujson.encode(wrapped_input) - def test_encodeNullCharacter(self): - input = "31337 \x00 1337" - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) + assert wrapped_input == json.loads(output) + assert output == json.dumps(wrapped_input) + assert wrapped_input == ujson.decode(output) - input = "\x00" - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) + alone_input = "\x00" + output = ujson.encode(alone_input) + assert alone_input == json.loads(output) + assert output == json.dumps(alone_input) + assert alone_input == ujson.decode(output) assert '" \\u0000\\r\\n "' == ujson.dumps(u(" \u0000\r\n ")) - pass - - def test_decodeNullCharacter(self): - input = "\"31337 \\u0000 31337\"" - assert ujson.decode(input) == json.loads(input) - - def test_encodeListLongConversion(self): - input = [9223372036854775807, 9223372036854775807, 9223372036854775807, - 9223372036854775807, 9223372036854775807, 9223372036854775807] - output = ujson.encode(input) - assert input == json.loads(output) - assert input == ujson.decode(output) - tm.assert_numpy_array_equal(np.array(input), + + def test_decode_null_character(self): + wrapped_input = "\"31337 \\u0000 31337\"" + assert ujson.decode(wrapped_input) == json.loads(wrapped_input) + + def test_encode_list_long_conversion(self): + long_input = [9223372036854775807, 9223372036854775807, + 9223372036854775807, 9223372036854775807, + 9223372036854775807, 9223372036854775807] + output = ujson.encode(long_input) + + assert long_input == json.loads(output) + assert long_input == ujson.decode(output) + + tm.assert_numpy_array_equal(np.array(long_input), ujson.decode(output, numpy=True, dtype=np.int64)) - pass - - def test_encodeLongConversion(self): - input = 9223372036854775807 - output = ujson.encode(input) - assert input == json.loads(output) - assert output == json.dumps(input) - assert input == ujson.decode(output) - pass - - def test_numericIntExp(self): - input = "1337E40" - output = ujson.decode(input) - assert output == json.loads(input) - - def test_numericIntFrcExp(self): - input = "1.337E40" - output = ujson.decode(input) - tm.assert_almost_equal(output, json.loads(input)) - - def test_decodeNumericIntExpEPLUS(self): - input = "1337E+9" - output = ujson.decode(input) - tm.assert_almost_equal(output, json.loads(input)) - - def test_decodeNumericIntExpePLUS(self): - input = "1.337e+40" - output = ujson.decode(input) - tm.assert_almost_equal(output, json.loads(input)) - - def test_decodeNumericIntExpE(self): - input = "1337E40" - output = ujson.decode(input) - tm.assert_almost_equal(output, json.loads(input)) - - def test_decodeNumericIntExpe(self): - input = "1337e40" - output = ujson.decode(input) - tm.assert_almost_equal(output, json.loads(input)) - - def test_decodeNumericIntExpEMinus(self): - input = "1.337E-4" - output = ujson.decode(input) - tm.assert_almost_equal(output, json.loads(input)) - - def test_decodeNumericIntExpeMinus(self): - input = "1.337e-4" - output = ujson.decode(input) - tm.assert_almost_equal(output, json.loads(input)) - - def test_dumpToFile(self): + + def test_encode_long_conversion(self): + long_input = 9223372036854775807 + output = ujson.encode(long_input) + + assert long_input == json.loads(output) + assert output == json.dumps(long_input) + assert long_input == ujson.decode(output) + + @pytest.mark.parametrize("int_exp", [ + "1337E40", "1.337E40", "1337E+9", "1.337e+40", "1.337E-4" + ]) + def test_decode_numeric_int_exp(self, int_exp): + assert ujson.decode(int_exp) == json.loads(int_exp) + + def test_dump_to_file(self): f = StringIO() ujson.dump([1, 2, 3], f) assert "[1,2,3]" == f.getvalue() - def test_dumpToFileLikeObject(self): + def test_dump_to_file_like(self): class FileLike(object): def __init__(self): self.bytes = '' - def write(self, bytes): - self.bytes += bytes + def write(self, data_bytes): + self.bytes += data_bytes + f = FileLike() ujson.dump([1, 2, 3], f) assert "[1,2,3]" == f.bytes - def test_dumpFileArgsError(self): - try: - ujson.dump([], '') - except TypeError: - pass - else: - assert False, 'expected TypeError' + def test_dump_file_args_error(self): + with pytest.raises(TypeError): + ujson.dump([], "") - def test_loadFile(self): - f = StringIO("[1,2,3,4]") - assert [1, 2, 3, 4] == ujson.load(f) + def test_load_file(self): + data = "[1,2,3,4]" + exp_data = [1, 2, 3, 4] - f = StringIO("[1,2,3,4]") - tm.assert_numpy_array_equal( - np.array([1, 2, 3, 4]), ujson.load(f, numpy=True)) + f = StringIO(data) + assert exp_data == ujson.load(f) - def test_loadFileLikeObject(self): + f = StringIO(data) + tm.assert_numpy_array_equal(np.array(exp_data), + ujson.load(f, numpy=True)) + + def test_load_file_like(self): class FileLike(object): def read(self): @@ -808,95 +612,75 @@ def read(self): except AttributeError: self.end = True return "[1,2,3,4]" + + exp_data = [1, 2, 3, 4] + f = FileLike() - assert [1, 2, 3, 4] == ujson.load(f) + assert exp_data == ujson.load(f) f = FileLike() - tm.assert_numpy_array_equal( - np.array([1, 2, 3, 4]), ujson.load(f, numpy=True)) + tm.assert_numpy_array_equal(np.array(exp_data), + ujson.load(f, numpy=True)) - def test_loadFileArgsError(self): - try: + def test_load_file_args_error(self): + with pytest.raises(TypeError): ujson.load("[]") - except TypeError: - pass - else: - assert False, "expected TypeError" def test_version(self): assert re.match(r'^\d+\.\d+(\.\d+)?$', ujson.__version__), \ "ujson.__version__ must be a string like '1.4.0'" - def test_encodeNumericOverflow(self): - try: + def test_encode_numeric_overflow(self): + with pytest.raises(OverflowError): ujson.encode(12839128391289382193812939) - except OverflowError: - pass - else: - assert False, "expected OverflowError" - - def test_encodeNumericOverflowNested(self): - for n in range(0, 100): - class Nested(object): - x = 12839128391289382193812939 - nested = Nested() + def test_encode_numeric_overflow_nested(self): + class Nested(object): + x = 12839128391289382193812939 - try: - ujson.encode(nested) - except OverflowError: - pass - else: - assert False, "expected OverflowError" + for _ in range(0, 100): + with pytest.raises(OverflowError): + ujson.encode(Nested()) - def test_decodeNumberWith32bitSignBit(self): + @pytest.mark.parametrize("val", [ + 3590016419, 2**31, 2**32, (2**32) - 1 + ]) + def test_decode_number_with_32bit_sign_bit(self, val): # Test that numbers that fit within 32 bits but would have the # sign bit set (2**31 <= x < 2**32) are decoded properly. - boundary1 = 2**31 # noqa - boundary2 = 2**32 # noqa - docs = ( - '{"id": 3590016419}', - '{{"id": {low}}}'.format(low=2**31), - '{{"id": {high}}}'.format(high=2**32), - '{{"id": {one_less}}}'.format(one_less=(2**32) - 1), - ) - results = (3590016419, 2**31, 2**32, 2**32 - 1) - for doc, result in zip(docs, results): - assert ujson.decode(doc)['id'] == result - - def test_encodeBigEscape(self): - for x in range(10): - if compat.PY3: - base = '\u00e5'.encode('utf-8') - else: - base = "\xc3\xa5" - input = base * 1024 * 1024 * 2 - output = ujson.encode(input) # noqa - - def test_decodeBigEscape(self): - for x in range(10): - if compat.PY3: - base = '\u00e5'.encode('utf-8') - else: - base = "\xc3\xa5" + doc = '{{"id": {val}}}'.format(val=val) + assert ujson.decode(doc)["id"] == val + + def test_encode_big_escape(self): + # Make sure no Exception is raised. + for _ in range(10): + base = '\u00e5'.encode("utf-8") if compat.PY3 else "\xc3\xa5" + escape_input = base * 1024 * 1024 * 2 + ujson.encode(escape_input) + + def test_decode_big_escape(self): + # Make sure no Exception is raised. + for _ in range(10): + base = '\u00e5'.encode("utf-8") if compat.PY3 else "\xc3\xa5" quote = compat.str_to_bytes("\"") - input = quote + (base * 1024 * 1024 * 2) + quote - output = ujson.decode(input) # noqa - def test_toDict(self): + escape_input = quote + (base * 1024 * 1024 * 2) + quote + ujson.decode(escape_input) + + def test_to_dict(self): d = {u("key"): 31337} class DictTest(object): - def toDict(self): return d o = DictTest() output = ujson.encode(o) + dec = ujson.decode(output) assert dec == d - def test_defaultHandler(self): + def test_default_handler(self): class _TestObject(object): @@ -914,733 +698,427 @@ def __str__(self): assert '"foo"' == ujson.encode(_TestObject("foo"), default_handler=str) - def my_handler(obj): + def my_handler(_): return "foobar" assert '"foobar"' == ujson.encode(_TestObject("foo"), default_handler=my_handler) - def my_handler_raises(obj): + def my_handler_raises(_): raise TypeError("I raise for anything") with tm.assert_raises_regex(TypeError, "I raise for anything"): ujson.encode(_TestObject("foo"), default_handler=my_handler_raises) - def my_int_handler(obj): + def my_int_handler(_): return 42 - assert ujson.decode(ujson.encode( - _TestObject("foo"), default_handler=my_int_handler)) == 42 + assert ujson.decode(ujson.encode(_TestObject("foo"), + default_handler=my_int_handler)) == 42 - def my_obj_handler(obj): + def my_obj_handler(_): return datetime.datetime(2013, 2, 3) assert (ujson.decode(ujson.encode(datetime.datetime(2013, 2, 3))) == ujson.decode(ujson.encode(_TestObject("foo"), default_handler=my_obj_handler))) - l = [_TestObject("foo"), _TestObject("bar")] - assert (json.loads(json.dumps(l, default=str)) == - ujson.decode(ujson.encode(l, default_handler=str))) + obj_list = [_TestObject("foo"), _TestObject("bar")] + assert (json.loads(json.dumps(obj_list, default=str)) == + ujson.decode(ujson.encode(obj_list, default_handler=str))) class TestNumpyJSONTests(object): - def test_Bool(self): - b = np.bool(True) + @pytest.mark.parametrize("bool_input", [True, False]) + def test_bool(self, bool_input): + b = np.bool(bool_input) assert ujson.decode(ujson.encode(b)) == b - def test_BoolArray(self): - inpt = np.array([True, False, True, True, False, True, False, False], - dtype=np.bool) - outp = np.array(ujson.decode(ujson.encode(inpt)), dtype=np.bool) - tm.assert_numpy_array_equal(inpt, outp) - - def test_Int(self): - num = np.int(2562010) - assert np.int(ujson.decode(ujson.encode(num))) == num - - num = np.int8(127) - assert np.int8(ujson.decode(ujson.encode(num))) == num - - num = np.int16(2562010) - assert np.int16(ujson.decode(ujson.encode(num))) == num + def test_bool_array(self): + bool_array = np.array([ + True, False, True, True, + False, True, False, False], dtype=np.bool) + output = np.array(ujson.decode( + ujson.encode(bool_array)), dtype=np.bool) + tm.assert_numpy_array_equal(bool_array, output) - num = np.int32(2562010) - assert np.int32(ujson.decode(ujson.encode(num))) == num + def test_int(self, any_int_dtype): + klass = np.dtype(any_int_dtype).type + num = klass(1) - num = np.int64(2562010) - assert np.int64(ujson.decode(ujson.encode(num))) == num + assert klass(ujson.decode(ujson.encode(num))) == num - num = np.uint8(255) - assert np.uint8(ujson.decode(ujson.encode(num))) == num - - num = np.uint16(2562010) - assert np.uint16(ujson.decode(ujson.encode(num))) == num - - num = np.uint32(2562010) - assert np.uint32(ujson.decode(ujson.encode(num))) == num - - num = np.uint64(2562010) - assert np.uint64(ujson.decode(ujson.encode(num))) == num - - def test_IntArray(self): + def test_int_array(self, any_int_dtype): arr = np.arange(100, dtype=np.int) - dtypes = (np.int, np.int8, np.int16, np.int32, np.int64, - np.uint, np.uint8, np.uint16, np.uint32, np.uint64) - for dtype in dtypes: - inpt = arr.astype(dtype) - outp = np.array(ujson.decode(ujson.encode(inpt)), dtype=dtype) - tm.assert_numpy_array_equal(inpt, outp) - - def test_IntMax(self): - num = np.int(np.iinfo(np.int).max) - assert np.int(ujson.decode(ujson.encode(num))) == num - - num = np.int8(np.iinfo(np.int8).max) - assert np.int8(ujson.decode(ujson.encode(num))) == num + arr_input = arr.astype(any_int_dtype) - num = np.int16(np.iinfo(np.int16).max) - assert np.int16(ujson.decode(ujson.encode(num))) == num + arr_output = np.array(ujson.decode(ujson.encode(arr_input)), + dtype=any_int_dtype) + tm.assert_numpy_array_equal(arr_input, arr_output) - num = np.int32(np.iinfo(np.int32).max) - assert np.int32(ujson.decode(ujson.encode(num))) == num + def test_int_max(self, any_int_dtype): + if any_int_dtype in ("int64", "uint64") and compat.is_platform_32bit(): + pytest.skip("Cannot test 64-bit integer on 32-bit platform") - num = np.uint8(np.iinfo(np.uint8).max) - assert np.uint8(ujson.decode(ujson.encode(num))) == num + klass = np.dtype(any_int_dtype).type - num = np.uint16(np.iinfo(np.uint16).max) - assert np.uint16(ujson.decode(ujson.encode(num))) == num - - num = np.uint32(np.iinfo(np.uint32).max) - assert np.uint32(ujson.decode(ujson.encode(num))) == num - - if not compat.is_platform_32bit(): - num = np.int64(np.iinfo(np.int64).max) - assert np.int64(ujson.decode(ujson.encode(num))) == num - - # uint64 max will always overflow as it's encoded to signed - num = np.uint64(np.iinfo(np.int64).max) - assert np.uint64(ujson.decode(ujson.encode(num))) == num + # uint64 max will always overflow, + # as it's encoded to signed. + if any_int_dtype == "uint64": + num = np.iinfo("int64").max + else: + num = np.iinfo(any_int_dtype).max - def test_Float(self): - num = np.float(256.2013) - assert np.float(ujson.decode(ujson.encode(num))) == num + assert klass(ujson.decode(ujson.encode(num))) == num - num = np.float32(256.2013) - assert np.float32(ujson.decode(ujson.encode(num))) == num + def test_float(self, float_dtype): + klass = np.dtype(float_dtype).type + num = klass(256.2013) - num = np.float64(256.2013) - assert np.float64(ujson.decode(ujson.encode(num))) == num + assert klass(ujson.decode(ujson.encode(num))) == num - def test_FloatArray(self): + def test_float_array(self, float_dtype): arr = np.arange(12.5, 185.72, 1.7322, dtype=np.float) - dtypes = (np.float, np.float32, np.float64) + float_input = arr.astype(float_dtype) - for dtype in dtypes: - inpt = arr.astype(dtype) - outp = np.array(ujson.decode(ujson.encode( - inpt, double_precision=15)), dtype=dtype) - tm.assert_almost_equal(inpt, outp) + float_output = np.array(ujson.decode( + ujson.encode(float_input, double_precision=15)), + dtype=float_dtype) + tm.assert_almost_equal(float_input, float_output) - def test_FloatMax(self): - num = np.float(np.finfo(np.float).max / 10) - tm.assert_almost_equal(np.float(ujson.decode( - ujson.encode(num, double_precision=15))), num, 15) + def test_float_max(self, float_dtype): + klass = np.dtype(float_dtype).type + num = klass(np.finfo(float_dtype).max / 10) - num = np.float32(np.finfo(np.float32).max / 10) - tm.assert_almost_equal(np.float32(ujson.decode( - ujson.encode(num, double_precision=15))), num, 15) + tm.assert_almost_equal(klass(ujson.decode( + ujson.encode(num, double_precision=15))), num) - num = np.float64(np.finfo(np.float64).max / 10) - tm.assert_almost_equal(np.float64(ujson.decode( - ujson.encode(num, double_precision=15))), num, 15) - - def test_Arrays(self): - arr = np.arange(100) + def test_array_basic(self): + arr = np.arange(96) + arr = arr.reshape((2, 2, 2, 2, 3, 2)) - arr = arr.reshape((10, 10)) tm.assert_numpy_array_equal( np.array(ujson.decode(ujson.encode(arr))), arr) tm.assert_numpy_array_equal(ujson.decode( ujson.encode(arr), numpy=True), arr) - arr = arr.reshape((5, 5, 4)) - tm.assert_numpy_array_equal( - np.array(ujson.decode(ujson.encode(arr))), arr) - tm.assert_numpy_array_equal(ujson.decode( - ujson.encode(arr), numpy=True), arr) + @pytest.mark.parametrize("shape", [ + (10, 10), + (5, 5, 4), + (100, 1), + ]) + def test_array_reshaped(self, shape): + arr = np.arange(100) + arr = arr.reshape(shape) - arr = arr.reshape((100, 1)) tm.assert_numpy_array_equal( np.array(ujson.decode(ujson.encode(arr))), arr) tm.assert_numpy_array_equal(ujson.decode( ujson.encode(arr), numpy=True), arr) - arr = np.arange(96) - arr = arr.reshape((2, 2, 2, 2, 3, 2)) + def test_array_list(self): + arr_list = ["a", list(), dict(), dict(), list(), + 42, 97.8, ["a", "b"], {"key": "val"}] + arr = np.array(arr_list) tm.assert_numpy_array_equal( np.array(ujson.decode(ujson.encode(arr))), arr) - tm.assert_numpy_array_equal(ujson.decode( - ujson.encode(arr), numpy=True), arr) - l = ['a', list(), dict(), dict(), list(), - 42, 97.8, ['a', 'b'], {'key': 'val'}] - arr = np.array(l) - tm.assert_numpy_array_equal( - np.array(ujson.decode(ujson.encode(arr))), arr) + def test_array_float(self): + dtype = np.float32 - arr = np.arange(100.202, 200.202, 1, dtype=np.float32) + arr = np.arange(100.202, 200.202, 1, dtype=dtype) arr = arr.reshape((5, 5, 4)) - outp = np.array(ujson.decode(ujson.encode(arr)), dtype=np.float32) - tm.assert_almost_equal(arr, outp) - outp = ujson.decode(ujson.encode(arr), numpy=True, dtype=np.float32) - tm.assert_almost_equal(arr, outp) - - def test_OdArray(self): - def will_raise(): - ujson.encode(np.array(1)) - pytest.raises(TypeError, will_raise) + arr_out = np.array(ujson.decode(ujson.encode(arr)), dtype=dtype) + tm.assert_almost_equal(arr, arr_out) - def test_ArrayNumpyExcept(self): + arr_out = ujson.decode(ujson.encode(arr), numpy=True, dtype=dtype) + tm.assert_almost_equal(arr, arr_out) - input = ujson.dumps([42, {}, 'a']) - try: - ujson.decode(input, numpy=True) - assert False, "Expected exception!" - except(TypeError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps(['a', 'b', [], 'c']) - try: - ujson.decode(input, numpy=True) - assert False, "Expected exception!" - except(ValueError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps([['a'], 42]) - try: - ujson.decode(input, numpy=True) - assert False, "Expected exception!" - except(ValueError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps([42, ['a'], 42]) - try: - ujson.decode(input, numpy=True) - assert False, "Expected exception!" - except(ValueError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps([{}, []]) - try: - ujson.decode(input, numpy=True) - assert False, "Expected exception!" - except(ValueError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps([42, None]) - try: - ujson.decode(input, numpy=True) - assert False, "Expected exception!" - except(TypeError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps([{'a': 'b'}]) - try: - ujson.decode(input, numpy=True, labelled=True) - assert False, "Expected exception!" - except(ValueError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps({'a': {'b': {'c': 42}}}) - try: - ujson.decode(input, numpy=True, labelled=True) - assert False, "Expected exception!" - except(ValueError): - pass - except: - assert False, "Wrong exception" - - input = ujson.dumps([{'a': 42, 'b': 23}, {'c': 17}]) - try: - ujson.decode(input, numpy=True, labelled=True) - assert False, "Expected exception!" - except(ValueError): - pass - except: - assert False, "Wrong exception" + def test_0d_array(self): + with pytest.raises(TypeError): + ujson.encode(np.array(1)) - def test_ArrayNumpyLabelled(self): - input = {'a': []} - output = ujson.loads(ujson.dumps(input), numpy=True, labelled=True) + @pytest.mark.parametrize("bad_input,exc_type,kwargs", [ + ([{}, []], ValueError, {}), + ([42, None], TypeError, {}), + ([["a"], 42], ValueError, {}), + ([42, {}, "a"], TypeError, {}), + ([42, ["a"], 42], ValueError, {}), + (["a", "b", [], "c"], ValueError, {}), + ([{"a": "b"}], ValueError, dict(labelled=True)), + ({"a": {"b": {"c": 42}}}, ValueError, dict(labelled=True)), + ([{"a": 42, "b": 23}, {"c": 17}], ValueError, dict(labelled=True)) + ]) + def test_array_numpy_except(self, bad_input, exc_type, kwargs): + with pytest.raises(exc_type): + ujson.decode(ujson.dumps(bad_input), numpy=True, **kwargs) + + def test_array_numpy_labelled(self): + labelled_input = {"a": []} + output = ujson.loads(ujson.dumps(labelled_input), + numpy=True, labelled=True) assert (np.empty((1, 0)) == output[0]).all() - assert (np.array(['a']) == output[1]).all() + assert (np.array(["a"]) == output[1]).all() assert output[2] is None - input = [{'a': 42}] - output = ujson.loads(ujson.dumps(input), numpy=True, labelled=True) + labelled_input = [{"a": 42}] + output = ujson.loads(ujson.dumps(labelled_input), + numpy=True, labelled=True) + assert (np.array([u("a")]) == output[2]).all() assert (np.array([42]) == output[0]).all() assert output[1] is None - assert (np.array([u('a')]) == output[2]).all() - # Write out the dump explicitly so there is no dependency on iteration - # order GH10837 + # see gh-10837: write out the dump explicitly + # so there is no dependency on iteration order input_dumps = ('[{"a": 42, "b":31}, {"a": 24, "c": 99}, ' '{"a": 2.4, "b": 78}]') output = ujson.loads(input_dumps, numpy=True, labelled=True) - expectedvals = np.array( + expected_vals = np.array( [42, 31, 24, 99, 2.4, 78], dtype=int).reshape((3, 2)) - assert (expectedvals == output[0]).all() + assert (expected_vals == output[0]).all() assert output[1] is None - assert (np.array([u('a'), 'b']) == output[2]).all() + assert (np.array([u("a"), "b"]) == output[2]).all() input_dumps = ('{"1": {"a": 42, "b":31}, "2": {"a": 24, "c": 99}, ' '"3": {"a": 2.4, "b": 78}}') output = ujson.loads(input_dumps, numpy=True, labelled=True) - expectedvals = np.array( + expected_vals = np.array( [42, 31, 24, 99, 2.4, 78], dtype=int).reshape((3, 2)) - assert (expectedvals == output[0]).all() - assert (np.array(['1', '2', '3']) == output[1]).all() - assert (np.array(['a', 'b']) == output[2]).all() + assert (expected_vals == output[0]).all() + assert (np.array(["1", "2", "3"]) == output[1]).all() + assert (np.array(["a", "b"]) == output[2]).all() class TestPandasJSONTests(object): - def test_DataFrame(self): - df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ - 'a', 'b'], columns=['x', 'y', 'z']) - - # column indexed - outp = DataFrame(ujson.decode(ujson.encode(df))) - assert (df == outp).values.all() - tm.assert_index_equal(df.columns, outp.columns) - tm.assert_index_equal(df.index, outp.index) - - dec = _clean_dict(ujson.decode(ujson.encode(df, orient="split"))) - outp = DataFrame(**dec) - assert (df == outp).values.all() - tm.assert_index_equal(df.columns, outp.columns) - tm.assert_index_equal(df.index, outp.index) - - outp = DataFrame(ujson.decode(ujson.encode(df, orient="records"))) - outp.index = df.index - assert (df == outp).values.all() - tm.assert_index_equal(df.columns, outp.columns) - - outp = DataFrame(ujson.decode(ujson.encode(df, orient="values"))) - outp.index = df.index - assert (df.values == outp.values).all() - - outp = DataFrame(ujson.decode(ujson.encode(df, orient="index"))) - assert (df.transpose() == outp).values.all() - tm.assert_index_equal(df.transpose().columns, outp.columns) - tm.assert_index_equal(df.transpose().index, outp.index) - - def test_DataFrameNumpy(self): - df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ - 'a', 'b'], columns=['x', 'y', 'z']) - - # column indexed - outp = DataFrame(ujson.decode(ujson.encode(df), numpy=True)) - assert (df == outp).values.all() - tm.assert_index_equal(df.columns, outp.columns) - tm.assert_index_equal(df.index, outp.index) + def test_dataframe(self, orient, numpy): + if orient == "records" and numpy: + pytest.skip("Not idiomatic pandas") - dec = _clean_dict(ujson.decode(ujson.encode(df, orient="split"), - numpy=True)) - outp = DataFrame(**dec) - assert (df == outp).values.all() - tm.assert_index_equal(df.columns, outp.columns) - tm.assert_index_equal(df.index, outp.index) - - outp = DataFrame(ujson.decode(ujson.encode(df, orient="index"), - numpy=True)) - assert (df.transpose() == outp).values.all() - tm.assert_index_equal(df.transpose().columns, outp.columns) - tm.assert_index_equal(df.transpose().index, outp.index) - - def test_DataFrameNested(self): df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ - 'a', 'b'], columns=['x', 'y', 'z']) - - nested = {'df1': df, 'df2': df.copy()} + "a", "b"], columns=["x", "y", "z"]) + encode_kwargs = {} if orient is None else dict(orient=orient) + decode_kwargs = {} if numpy is None else dict(numpy=numpy) - exp = {'df1': ujson.decode(ujson.encode(df)), - 'df2': ujson.decode(ujson.encode(df))} - assert ujson.decode(ujson.encode(nested)) == exp + output = ujson.decode(ujson.encode(df, **encode_kwargs), + **decode_kwargs) - exp = {'df1': ujson.decode(ujson.encode(df, orient="index")), - 'df2': ujson.decode(ujson.encode(df, orient="index"))} - assert ujson.decode(ujson.encode(nested, orient="index")) == exp - - exp = {'df1': ujson.decode(ujson.encode(df, orient="records")), - 'df2': ujson.decode(ujson.encode(df, orient="records"))} - assert ujson.decode(ujson.encode(nested, orient="records")) == exp + # Ensure proper DataFrame initialization. + if orient == "split": + dec = _clean_dict(output) + output = DataFrame(**dec) + else: + output = DataFrame(output) - exp = {'df1': ujson.decode(ujson.encode(df, orient="values")), - 'df2': ujson.decode(ujson.encode(df, orient="values"))} - assert ujson.decode(ujson.encode(nested, orient="values")) == exp + # Corrections to enable DataFrame comparison. + if orient == "values": + df.columns = [0, 1, 2] + df.index = [0, 1] + elif orient == "records": + df.index = [0, 1] + elif orient == "index": + df = df.transpose() - exp = {'df1': ujson.decode(ujson.encode(df, orient="split")), - 'df2': ujson.decode(ujson.encode(df, orient="split"))} - assert ujson.decode(ujson.encode(nested, orient="split")) == exp + tm.assert_frame_equal(output, df, check_dtype=False) - def test_DataFrameNumpyLabelled(self): + def test_dataframe_nested(self, orient): df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ - 'a', 'b'], columns=['x', 'y', 'z']) - - # column indexed - outp = DataFrame(*ujson.decode(ujson.encode(df), - numpy=True, labelled=True)) - assert (df.T == outp).values.all() - tm.assert_index_equal(df.T.columns, outp.columns) - tm.assert_index_equal(df.T.index, outp.index) - - outp = DataFrame(*ujson.decode(ujson.encode(df, orient="records"), - numpy=True, labelled=True)) - outp.index = df.index - assert (df == outp).values.all() - tm.assert_index_equal(df.columns, outp.columns) - - outp = DataFrame(*ujson.decode(ujson.encode(df, orient="index"), - numpy=True, labelled=True)) - assert (df == outp).values.all() - tm.assert_index_equal(df.columns, outp.columns) - tm.assert_index_equal(df.index, outp.index) - - def test_Series(self): - s = Series([10, 20, 30, 40, 50, 60], name="series", - index=[6, 7, 8, 9, 10, 15]).sort_values() - - # column indexed - outp = Series(ujson.decode(ujson.encode(s))).sort_values() - exp = Series([10, 20, 30, 40, 50, 60], - index=['6', '7', '8', '9', '10', '15']) - tm.assert_series_equal(outp, exp) - - outp = Series(ujson.decode(ujson.encode(s), numpy=True)).sort_values() - tm.assert_series_equal(outp, exp) + "a", "b"], columns=["x", "y", "z"]) - dec = _clean_dict(ujson.decode(ujson.encode(s, orient="split"))) - outp = Series(**dec) - tm.assert_series_equal(outp, s) + nested = {"df1": df, "df2": df.copy()} + kwargs = {} if orient is None else dict(orient=orient) - dec = _clean_dict(ujson.decode(ujson.encode(s, orient="split"), - numpy=True)) - outp = Series(**dec) - - exp_np = Series(np.array([10, 20, 30, 40, 50, 60])) - exp_pd = Series([10, 20, 30, 40, 50, 60]) - outp = Series(ujson.decode(ujson.encode(s, orient="records"), - numpy=True)) - tm.assert_series_equal(outp, exp_np) + exp = {"df1": ujson.decode(ujson.encode(df, **kwargs)), + "df2": ujson.decode(ujson.encode(df, **kwargs))} + assert ujson.decode(ujson.encode(nested, **kwargs)) == exp - outp = Series(ujson.decode(ujson.encode(s, orient="records"))) - exp = Series([10, 20, 30, 40, 50, 60]) - tm.assert_series_equal(outp, exp_pd) + def test_dataframe_numpy_labelled(self, orient): + if orient in ("split", "values"): + pytest.skip("Incompatible with labelled=True") - outp = Series(ujson.decode(ujson.encode(s, orient="values"), - numpy=True)) - tm.assert_series_equal(outp, exp_np) + df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[ + "a", "b"], columns=["x", "y", "z"], dtype=np.int) + kwargs = {} if orient is None else dict(orient=orient) - outp = Series(ujson.decode(ujson.encode(s, orient="values"))) - tm.assert_series_equal(outp, exp_pd) + output = DataFrame(*ujson.decode(ujson.encode(df, **kwargs), + numpy=True, labelled=True)) - outp = Series(ujson.decode(ujson.encode( - s, orient="index"))).sort_values() - exp = Series([10, 20, 30, 40, 50, 60], - index=['6', '7', '8', '9', '10', '15']) - tm.assert_series_equal(outp, exp) + if orient is None: + df = df.T + elif orient == "records": + df.index = [0, 1] - outp = Series(ujson.decode(ujson.encode( - s, orient="index"), numpy=True)).sort_values() - tm.assert_series_equal(outp, exp) + tm.assert_frame_equal(output, df) - def test_SeriesNested(self): + def test_series(self, orient, numpy): s = Series([10, 20, 30, 40, 50, 60], name="series", index=[6, 7, 8, 9, 10, 15]).sort_values() - nested = {'s1': s, 's2': s.copy()} + encode_kwargs = {} if orient is None else dict(orient=orient) + decode_kwargs = {} if numpy is None else dict(numpy=numpy) - exp = {'s1': ujson.decode(ujson.encode(s)), - 's2': ujson.decode(ujson.encode(s))} - assert ujson.decode(ujson.encode(nested)) == exp + output = ujson.decode(ujson.encode(s, **encode_kwargs), + **decode_kwargs) - exp = {'s1': ujson.decode(ujson.encode(s, orient="split")), - 's2': ujson.decode(ujson.encode(s, orient="split"))} - assert ujson.decode(ujson.encode(nested, orient="split")) == exp + if orient == "split": + dec = _clean_dict(output) + output = Series(**dec) + else: + output = Series(output) + + if orient in (None, "index"): + s.name = None + output = output.sort_values() + s.index = ["6", "7", "8", "9", "10", "15"] + elif orient in ("records", "values"): + s.name = None + s.index = [0, 1, 2, 3, 4, 5] - exp = {'s1': ujson.decode(ujson.encode(s, orient="records")), - 's2': ujson.decode(ujson.encode(s, orient="records"))} - assert ujson.decode(ujson.encode(nested, orient="records")) == exp + tm.assert_series_equal(output, s, check_dtype=False) - exp = {'s1': ujson.decode(ujson.encode(s, orient="values")), - 's2': ujson.decode(ujson.encode(s, orient="values"))} - assert ujson.decode(ujson.encode(nested, orient="values")) == exp + def test_series_nested(self, orient): + s = Series([10, 20, 30, 40, 50, 60], name="series", + index=[6, 7, 8, 9, 10, 15]).sort_values() + nested = {"s1": s, "s2": s.copy()} + kwargs = {} if orient is None else dict(orient=orient) - exp = {'s1': ujson.decode(ujson.encode(s, orient="index")), - 's2': ujson.decode(ujson.encode(s, orient="index"))} - assert ujson.decode(ujson.encode(nested, orient="index")) == exp + exp = {"s1": ujson.decode(ujson.encode(s, **kwargs)), + "s2": ujson.decode(ujson.encode(s, **kwargs))} + assert ujson.decode(ujson.encode(nested, **kwargs)) == exp - def test_Index(self): + def test_index(self): i = Index([23, 45, 18, 98, 43, 11], name="index") - # column indexed - outp = Index(ujson.decode(ujson.encode(i)), name='index') - tm.assert_index_equal(i, outp) + # Column indexed. + output = Index(ujson.decode(ujson.encode(i)), name="index") + tm.assert_index_equal(i, output) - outp = Index(ujson.decode(ujson.encode(i), numpy=True), name='index') - tm.assert_index_equal(i, outp) + output = Index(ujson.decode(ujson.encode(i), numpy=True), name="index") + tm.assert_index_equal(i, output) dec = _clean_dict(ujson.decode(ujson.encode(i, orient="split"))) - outp = Index(**dec) - tm.assert_index_equal(i, outp) - assert i.name == outp.name + output = Index(**dec) + + tm.assert_index_equal(i, output) + assert i.name == output.name dec = _clean_dict(ujson.decode(ujson.encode(i, orient="split"), numpy=True)) - outp = Index(**dec) - tm.assert_index_equal(i, outp) - assert i.name == outp.name + output = Index(**dec) - outp = Index(ujson.decode(ujson.encode(i, orient="values")), - name='index') - tm.assert_index_equal(i, outp) + tm.assert_index_equal(i, output) + assert i.name == output.name - outp = Index(ujson.decode(ujson.encode(i, orient="values"), - numpy=True), name='index') - tm.assert_index_equal(i, outp) + output = Index(ujson.decode(ujson.encode(i, orient="values")), + name="index") + tm.assert_index_equal(i, output) - outp = Index(ujson.decode(ujson.encode(i, orient="records")), - name='index') - tm.assert_index_equal(i, outp) + output = Index(ujson.decode(ujson.encode(i, orient="values"), + numpy=True), name="index") + tm.assert_index_equal(i, output) - outp = Index(ujson.decode(ujson.encode(i, orient="records"), - numpy=True), name='index') - tm.assert_index_equal(i, outp) + output = Index(ujson.decode(ujson.encode(i, orient="records")), + name="index") + tm.assert_index_equal(i, output) - outp = Index(ujson.decode(ujson.encode(i, orient="index")), - name='index') - tm.assert_index_equal(i, outp) + output = Index(ujson.decode(ujson.encode(i, orient="records"), + numpy=True), name="index") + tm.assert_index_equal(i, output) - outp = Index(ujson.decode(ujson.encode(i, orient="index"), - numpy=True), name='index') - tm.assert_index_equal(i, outp) + output = Index(ujson.decode(ujson.encode(i, orient="index")), + name="index") + tm.assert_index_equal(i, output) - def test_datetimeindex(self): - from pandas.core.indexes.datetimes import date_range + output = Index(ujson.decode(ujson.encode(i, orient="index"), + numpy=True), name="index") + tm.assert_index_equal(i, output) - rng = date_range('1/1/2000', periods=20) + def test_datetime_index(self): + date_unit = "ns" - encoded = ujson.encode(rng, date_unit='ns') - decoded = DatetimeIndex(np.array(ujson.decode(encoded))) + rng = date_range("1/1/2000", periods=20) + encoded = ujson.encode(rng, date_unit=date_unit) + decoded = DatetimeIndex(np.array(ujson.decode(encoded))) tm.assert_index_equal(rng, decoded) ts = Series(np.random.randn(len(rng)), index=rng) - decoded = Series(ujson.decode(ujson.encode(ts, date_unit='ns'))) + decoded = Series(ujson.decode(ujson.encode(ts, date_unit=date_unit))) + idx_values = decoded.index.values.astype(np.int64) decoded.index = DatetimeIndex(idx_values) tm.assert_series_equal(ts, decoded) - def test_decodeArrayTrailingCommaFail(self): - input = "[31337,]" - try: - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeArrayLeadingCommaFail(self): - input = "[,31337]" - try: - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeArrayOnlyCommaFail(self): - input = "[,]" - try: - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeArrayUnmatchedBracketFail(self): - input = "[]]" - try: - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeArrayEmpty(self): - input = "[]" - ujson.decode(input) - - def test_decodeArrayOneItem(self): - input = "[31337]" - ujson.decode(input) - - def test_decodeBigValue(self): - input = "9223372036854775807" - ujson.decode(input) - - def test_decodeSmallValue(self): - input = "-9223372036854775808" - ujson.decode(input) - - def test_decodeTooBigValue(self): - try: - input = "9223372036854775808" - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeTooSmallValue(self): - try: - input = "-90223372036854775809" - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeVeryTooBigValue(self): - try: - input = "9223372036854775808" - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeVeryTooSmallValue(self): - try: - input = "-90223372036854775809" - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeWithTrailingWhitespaces(self): - input = "{}\n\t " - ujson.decode(input) - - def test_decodeWithTrailingNonWhitespaces(self): - try: - input = "{}\n\t a" - ujson.decode(input) - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeArrayWithBigInt(self): - try: - ujson.loads('[18446098363113800555]') - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeArrayFaultyUnicode(self): - try: - ujson.loads('[18446098363113800555]') - except ValueError: - pass - else: - assert False, "expected ValueError" - - def test_decodeFloatingPointAdditionalTests(self): - places = 15 - - tm.assert_almost_equal(-1.1234567893, - ujson.loads("-1.1234567893"), - check_less_precise=places) - tm.assert_almost_equal(-1.234567893, - ujson.loads("-1.234567893"), - check_less_precise=places) - tm.assert_almost_equal(-1.34567893, - ujson.loads("-1.34567893"), - check_less_precise=places) - tm.assert_almost_equal(-1.4567893, - ujson.loads("-1.4567893"), - check_less_precise=places) - tm.assert_almost_equal(-1.567893, - ujson.loads("-1.567893"), - check_less_precise=places) - tm.assert_almost_equal(-1.67893, - ujson.loads("-1.67893"), - check_less_precise=places) - tm.assert_almost_equal(-1.7893, ujson.loads("-1.7893"), - check_less_precise=places) - tm.assert_almost_equal(-1.893, ujson.loads("-1.893"), - check_less_precise=places) - tm.assert_almost_equal(-1.3, ujson.loads("-1.3"), - check_less_precise=places) - - tm.assert_almost_equal(1.1234567893, ujson.loads( - "1.1234567893"), check_less_precise=places) - tm.assert_almost_equal(1.234567893, ujson.loads( - "1.234567893"), check_less_precise=places) - tm.assert_almost_equal( - 1.34567893, ujson.loads("1.34567893"), check_less_precise=places) - tm.assert_almost_equal( - 1.4567893, ujson.loads("1.4567893"), check_less_precise=places) - tm.assert_almost_equal( - 1.567893, ujson.loads("1.567893"), check_less_precise=places) - tm.assert_almost_equal(1.67893, ujson.loads("1.67893"), - check_less_precise=places) - tm.assert_almost_equal(1.7893, ujson.loads("1.7893"), - check_less_precise=places) - tm.assert_almost_equal(1.893, ujson.loads("1.893"), - check_less_precise=places) - tm.assert_almost_equal(1.3, ujson.loads("1.3"), - check_less_precise=places) - - def test_encodeBigSet(self): + @pytest.mark.parametrize("invalid_arr", [ + "[31337,]", # Trailing comma. + "[,31337]", # Leading comma. + "[]]", # Unmatched bracket. + "[,]", # Only comma. + ]) + def test_decode_invalid_array(self, invalid_arr): + with pytest.raises(ValueError): + ujson.decode(invalid_arr) + + @pytest.mark.parametrize("arr", [ + [], [31337] + ]) + def test_decode_array(self, arr): + assert arr == ujson.decode(str(arr)) + + @pytest.mark.parametrize("extreme_num", [ + 9223372036854775807, -9223372036854775808 + ]) + def test_decode_extreme_numbers(self, extreme_num): + assert extreme_num == ujson.decode(str(extreme_num)) + + @pytest.mark.parametrize("too_extreme_num", [ + "9223372036854775808", "-90223372036854775809" + ]) + def test_decode_too_extreme_numbers(self, too_extreme_num): + with pytest.raises(ValueError): + ujson.decode(too_extreme_num) + + def test_decode_with_trailing_whitespaces(self): + assert {} == ujson.decode("{}\n\t ") + + def test_decode_with_trailing_non_whitespaces(self): + with pytest.raises(ValueError): + ujson.decode("{}\n\t a") + + def test_decode_array_with_big_int(self): + with pytest.raises(ValueError): + ujson.loads("[18446098363113800555]") + + @pytest.mark.parametrize("float_number", [ + 1.1234567893, 1.234567893, 1.34567893, + 1.4567893, 1.567893, 1.67893, + 1.7893, 1.893, 1.3, + ]) + @pytest.mark.parametrize("sign", [-1, 1]) + def test_decode_floating_point(self, sign, float_number): + float_number *= sign + tm.assert_almost_equal(float_number, + ujson.loads(str(float_number)), + check_less_precise=15) + + def test_encode_big_set(self): s = set() + for x in range(0, 100000): s.add(x) + + # Make sure no Exception is raised. ujson.encode(s) - def test_encodeEmptySet(self): - s = set() - assert "[]" == ujson.encode(s) + def test_encode_empty_set(self): + assert "[]" == ujson.encode(set()) - def test_encodeSet(self): - s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) + def test_encode_set(self): + s = {1, 2, 3, 4, 5, 6, 7, 8, 9} enc = ujson.encode(s) dec = ujson.decode(enc) for v in dec: assert v in s - - -def _clean_dict(d): - return {str(k): v for k, v in compat.iteritems(d)} diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index 145be7f85b193..dabafb1f49ba8 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -466,7 +466,7 @@ def test_set_locale(self): enc = codecs.lookup(enc).name new_locale = lang, enc - if not tm._can_set_locale(new_locale): + if not tm.can_set_locale(new_locale): with pytest.raises(locale.Error): with tm.set_locale(new_locale): pass diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 11e9942079aad..09f5e59535adf 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -485,6 +485,8 @@ def set_locale(new_locale, lc_var=locale.LC_ALL): A string of the form <language_country>.<encoding>. For example to set the current locale to US English with a UTF8 encoding, you would pass "en_US.UTF-8". + lc_var : int, default `locale.LC_ALL` + The category of the locale being set. Notes ----- @@ -510,21 +512,25 @@ def set_locale(new_locale, lc_var=locale.LC_ALL): locale.setlocale(lc_var, current_locale) -def _can_set_locale(lc): - """Check to see if we can set a locale without throwing an exception. +def can_set_locale(lc, lc_var=locale.LC_ALL): + """ + Check to see if we can set a locale without raising an Exception. Parameters ---------- lc : str The locale to attempt to set. + lc_var : int, default `locale.LC_ALL` + The category of the locale being set. Returns ------- - isvalid : bool + is_valid : bool Whether the passed locale can be set """ + try: - with set_locale(lc): + with set_locale(lc, lc_var=lc_var): pass except locale.Error: # horrible name for a Exception subclass return False @@ -553,7 +559,7 @@ def _valid_locales(locales, normalize): else: normalizer = lambda x: x.strip() - return list(filter(_can_set_locale, map(normalizer, locales))) + return list(filter(can_set_locale, map(normalizer, locales))) # ----------------------------------------------------------------------------- # Stdout / stderr decorators
* Actually test the outputs * Add more parameterization * Take advantage of `pytest` features, such as exception contexts This test module really needed an update 😄
https://api.github.com/repos/pandas-dev/pandas/pulls/21739
2018-07-05T00:48:06Z
2018-07-05T22:17:11Z
2018-07-05T22:17:11Z
2018-07-05T22:38:38Z
Implement tslibs.__init__, move easy bits of tslib
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 61cf582300034..c1a0e58a4fb1a 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -35,18 +35,17 @@ from cython cimport Py_ssize_t import pytz -UTC = pytz.utc from tslibs.timedeltas cimport cast_from_unit -from tslibs.timedeltas import Timedelta +from tslibs.timedeltas import Timedelta, ints_to_pytimedelta # noqa:F841 from tslibs.timezones cimport (is_utc, is_tzlocal, is_fixed_offset, treat_tz_as_pytz, get_dst_info) from tslibs.conversion cimport (tz_convert_single, _TSObject, convert_datetime_to_tsobject, get_datetime64_nanos, tz_convert_utc_to_tzlocal) -from tslibs.conversion import tz_convert_single +from tslibs.conversion import tz_convert_single, normalize_date # noqa:F841 from tslibs.nattype import NaT, nat_strings, iNaT from tslibs.nattype cimport checknull_with_nat, NPY_NAT @@ -185,29 +184,6 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, return result -def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): - # convert an i8 repr to an ndarray of timedelta or Timedelta (if box == - # True) - - cdef: - Py_ssize_t i, n = len(arr) - int64_t value - ndarray[object] result = np.empty(n, dtype=object) - - for i in range(n): - - value = arr[i] - if value == NPY_NAT: - result[i] = NaT - else: - if box: - result[i] = Timedelta(value) - else: - result[i] = timedelta(microseconds=int(value) / 1000) - - return result - - def _test_parse_iso8601(object ts): """ TESTING ONLY: Parse string into Timestamp using iso8601 parser. Used @@ -740,30 +716,3 @@ cdef inline bint _parse_today_now(str val, int64_t* iresult): iresult[0] = Timestamp.today().value return True return False - -# ---------------------------------------------------------------------- -# Some general helper functions - - -cpdef normalize_date(object dt): - """ - Normalize datetime.datetime value to midnight. Returns datetime.date as a - datetime.datetime at midnight - - Returns - ------- - normalized : datetime.datetime or Timestamp - """ - if PyDateTime_Check(dt): - if not PyDateTime_CheckExact(dt): - # i.e. a Timestamp object - return dt.replace(hour=0, minute=0, second=0, microsecond=0, - nanosecond=0) - else: - # regular datetime object - return dt.replace(hour=0, minute=0, second=0, microsecond=0) - # TODO: Make sure DST crossing is handled correctly here - elif PyDate_Check(dt): - return datetime(dt.year, dt.month, dt.day) - else: - raise TypeError('Unrecognized type: %s' % type(dt)) diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index f3aa0424f0376..22307f70ebe52 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -1,2 +1,8 @@ # -*- coding: utf-8 -*- -# cython: profile=False +# flake8: noqa + +from .conversion import normalize_date, localize_pydatetime, tz_convert_single +from .nattype import NaT, iNaT +from .np_datetime import OutOfBoundsDatetime +from .timestamps import Timestamp +from .timedeltas import delta_to_nanoseconds, ints_to_pytimedelta, Timedelta diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index f825a4c8ed2c1..fd4b0b11065ed 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -1025,6 +1025,35 @@ cdef inline str _render_tstamp(int64_t val): # ---------------------------------------------------------------------- # Normalization + +def normalize_date(object dt): + """ + Normalize datetime.datetime value to midnight. Returns datetime.date as a + datetime.datetime at midnight + + Parameters + ---------- + dt : date, datetime, or Timestamp + + Returns + ------- + normalized : datetime.datetime or Timestamp + """ + if PyDateTime_Check(dt): + if not PyDateTime_CheckExact(dt): + # i.e. a Timestamp object + return dt.replace(hour=0, minute=0, second=0, microsecond=0, + nanosecond=0) + else: + # regular datetime object + return dt.replace(hour=0, minute=0, second=0, microsecond=0) + # TODO: Make sure DST crossing is handled correctly here + elif PyDate_Check(dt): + return datetime(dt.year, dt.month, dt.day) + else: + raise TypeError('Unrecognized type: %s' % type(dt)) + + @cython.wraparound(False) @cython.boundscheck(False) def date_normalize(ndarray[int64_t] stamps, tz=None): diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 27066af0be3b9..76849f2116123 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -79,6 +79,44 @@ cdef dict timedelta_abbrevs = { 'D': 'd', _no_input = object() + +# ---------------------------------------------------------------------- +# API + +def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): + """ + convert an i8 repr to an ndarray of timedelta or Timedelta (if box == + True) + + Parameters + ---------- + arr : ndarray[int64_t] + box : bool, default False + + Returns + ------- + result : ndarray[object] + array of Timedelta or timedeltas objects + """ + cdef: + Py_ssize_t i, n = len(arr) + int64_t value + ndarray[object] result = np.empty(n, dtype=object) + + for i in range(n): + + value = arr[i] + if value == NPY_NAT: + result[i] = NaT + else: + if box: + result[i] = Timedelta(value) + else: + result[i] = timedelta(microseconds=int(value) / 1000) + + return result + + # ---------------------------------------------------------------------- cpdef int64_t delta_to_nanoseconds(delta) except? -1: diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 54d29cea44555..401ba76e341b2 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -645,7 +645,6 @@ class Timestamp(_Timestamp): return NaT if is_string_object(freq): - from pandas.tseries.frequencies import to_offset freq = to_offset(freq) return create_timestamp_from_ts(ts.value, ts.dts, ts.tzinfo, freq) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 26c23b84a9c04..818dd1b408518 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7156,7 +7156,6 @@ def first(self, offset): at_time : Select values at a particular time of the day between_time : Select values between particular times of the day """ - from pandas.tseries.frequencies import to_offset if not isinstance(self.index, DatetimeIndex): raise TypeError("'first' only supports a DatetimeIndex index") @@ -7220,7 +7219,6 @@ def last(self, offset): at_time : Select values at a particular time of the day between_time : Select values between particular times of the day """ - from pandas.tseries.frequencies import to_offset if not isinstance(self.index, DatetimeIndex): raise TypeError("'last' only supports a DatetimeIndex index") diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 0c5470e7bd932..a5cd839c1472f 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -33,7 +33,7 @@ import pandas.tseries.offsets as offsets from pandas.io.pickle import read_pickle from pandas._libs.tslibs import timezones -from pandas._libs.tslib import normalize_date, NaT, Timestamp +from pandas._libs.tslib import NaT, Timestamp import pandas._libs.tslib as tslib import pandas.util.testing as tm from pandas.tseries.holiday import USFederalHolidayCalendar @@ -59,11 +59,6 @@ def test_ole2datetime(): ole2datetime(60) -def test_normalize_date(): - actual = normalize_date(datetime(2007, 10, 1, 1, 12, 5, 10)) - assert actual == datetime(2007, 10, 1) - - def test_to_m8(): valb = datetime(2007, 10, 1) valu = _to_m8(valb) diff --git a/pandas/tests/tslibs/test_tslib.py b/pandas/tests/tslibs/test_tslib.py index 2641c016e8674..484ec71cdc4c1 100644 --- a/pandas/tests/tslibs/test_tslib.py +++ b/pandas/tests/tslibs/test_tslib.py @@ -16,3 +16,8 @@ def test_normalize_date(): result = tslib.normalize_date(value) assert (result == datetime(2012, 9, 7)) + + value = datetime(2007, 10, 1, 1, 12, 5, 10) + + actual = tslib.normalize_date(value) + assert actual == datetime(2007, 10, 1)
Easy answers to where `tslib.ints_to_pytimedelta` and `tslib.normalize_date` belong, so this moves those. Starts populating the `tslibs.__init__` namespace; leaves updating imports for later. Cleans up a couple of unnecessary imports elsewhere.
https://api.github.com/repos/pandas-dev/pandas/pulls/21738
2018-07-04T23:14:38Z
2018-07-05T10:42:46Z
2018-07-05T10:42:46Z
2018-07-06T14:04:00Z
DOC: Add nrows to DataFrame.from_records docstring
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a420266561c5a..7b5f310315485 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1215,6 +1215,8 @@ def from_records(cls, data, index=None, exclude=None, columns=None, coerce_float : boolean, default False Attempt to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets + nrows : int, default None + Number of rows to read if data is an iterator Returns -------
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/21735
2018-07-04T21:01:43Z
2018-07-05T16:23:15Z
2018-07-05T16:23:15Z
2018-07-05T16:23:28Z
Fixes example code in docstring of pandas.DataFrame.query
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a420266561c5a..24e344fa9870c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2839,9 +2839,9 @@ def query(self, expr, inplace=False, **kwargs): Examples -------- - >>> from numpy.random import randn - >>> from pandas import DataFrame - >>> df = pd.DataFrame(randn(10, 2), columns=list('ab')) + >>> import numpy as np + >>> import pandas as pd + >>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('ab')) >>> df.query('a > b') >>> df[df.a > df.b] # same result as the previous expression """
- [ ] closes #21733 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21731
2018-07-04T19:21:45Z
2018-07-06T02:35:39Z
2018-07-06T02:35:39Z
2018-07-07T23:51:13Z
implement _tz_convert_dst for de-duplication
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index f825a4c8ed2c1..9879f16124b7e 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -608,9 +608,66 @@ cpdef inline datetime localize_pydatetime(datetime dt, object tz): # ---------------------------------------------------------------------- # Timezone Conversion +cdef inline int64_t[:] _tz_convert_dst(ndarray[int64_t] values, tzinfo tz, + bint to_utc=True): + """ + tz_convert for non-UTC non-tzlocal cases where we have to check + DST transitions pointwise. + + Parameters + ---------- + values : ndarray[int64_t] + tz : tzinfo + to_utc : bool + True if converting _to_ UTC, False if converting _from_ utc + + Returns + ------- + result : ndarray[int64_t] + """ + cdef: + Py_ssize_t n = len(values) + Py_ssize_t i, j, pos + ndarray[int64_t] result = np.empty(n, dtype=np.int64) + ndarray[int64_t] tt, trans, deltas + ndarray[Py_ssize_t] posn + int64_t v + + trans, deltas, typ = get_dst_info(tz) + if not to_utc: + # We add `offset` below instead of subtracting it + deltas = -1 * deltas + + tt = values[values != NPY_NAT] + if not len(tt): + # if all NaT, return all NaT + return values + + posn = trans.searchsorted(tt, side='right') + + j = 0 + for i in range(n): + v = values[i] + if v == NPY_NAT: + result[i] = v + else: + pos = posn[j] - 1 + j += 1 + if pos < 0: + raise ValueError('First time before start of DST info') + result[i] = v - deltas[pos] + + return result + + cdef inline int64_t _tz_convert_tzlocal_utc(int64_t val, tzinfo tz, bint to_utc=True): """ + Convert the i8 representation of a datetime from a tzlocal timezone to + UTC, or vice-versa. + + Private, not intended for use outside of tslibs.conversion + Parameters ---------- val : int64_t @@ -672,6 +729,7 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): Py_ssize_t pos int64_t v, offset, utc_date pandas_datetimestruct dts + ndarray[int64_t] arr # TODO: Is there a lighter-weight way to do this? # See GH#17734 We should always be converting either from UTC or to UTC assert (is_utc(tz1) or tz1 == 'UTC') or (is_utc(tz2) or tz2 == 'UTC') @@ -683,12 +741,8 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): if is_tzlocal(tz1): utc_date = _tz_convert_tzlocal_utc(val, tz1, to_utc=True) elif get_timezone(tz1) != 'UTC': - trans, deltas, typ = get_dst_info(tz1) - pos = trans.searchsorted(val, side='right') - 1 - if pos < 0: - raise ValueError('First time before start of DST info') - offset = deltas[pos] - utc_date = val - offset + arr = np.array([val]) + utc_date = _tz_convert_dst(arr, tz1, to_utc=True)[0] else: utc_date = val @@ -696,16 +750,14 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): return utc_date elif is_tzlocal(tz2): return _tz_convert_tzlocal_utc(utc_date, tz2, to_utc=False) - - # Convert UTC to other timezone - trans, deltas, typ = get_dst_info(tz2) - - pos = trans.searchsorted(utc_date, side='right') - 1 - if pos < 0: - raise ValueError('First time before start of DST info') - - offset = deltas[pos] - return utc_date + offset + else: + # Convert UTC to other timezone + arr = np.array([utc_date]) + # Note: at least with cython 0.28.3, doing a looking `[0]` in the next + # line is sensitive to the declared return type of _tz_convert_dst; + # if it is declared as returning ndarray[int64_t], a compile-time error + # is raised. + return _tz_convert_dst(arr, tz2, to_utc=False)[0] @cython.boundscheck(False) @@ -746,34 +798,15 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): else: utc_dates[i] = _tz_convert_tzlocal_utc(v, tz1, to_utc=True) else: - trans, deltas, typ = get_dst_info(tz1) - - # all-NaT - tt = vals[vals != NPY_NAT] - if not len(tt): - return vals - - posn = trans.searchsorted(tt, side='right') - j = 0 - for i in range(n): - v = vals[i] - if v == NPY_NAT: - utc_dates[i] = NPY_NAT - else: - pos = posn[j] - 1 - j = j + 1 - if pos < 0: - raise ValueError('First time before start of DST info') - offset = deltas[pos] - utc_dates[i] = v - offset + utc_dates = np.array(_tz_convert_dst(vals, tz1, to_utc=True)) else: utc_dates = vals if get_timezone(tz2) == 'UTC': return utc_dates - result = np.zeros(n, dtype=np.int64) - if is_tzlocal(tz2): + elif is_tzlocal(tz2): + result = np.zeros(n, dtype=np.int64) for i in range(n): v = utc_dates[i] if v == NPY_NAT: @@ -781,35 +814,9 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): else: result[i] = _tz_convert_tzlocal_utc(v, tz2, to_utc=False) return result - - # Convert UTC to other timezone - trans, deltas, typ = get_dst_info(tz2) - - # use first non-NaT element - # if all-NaT, return all-NaT - if (result == NPY_NAT).all(): - return result - - # if all NaT, return all NaT - tt = utc_dates[utc_dates != NPY_NAT] - if not len(tt): - return utc_dates - - posn = trans.searchsorted(tt, side='right') - - j = 0 - for i in range(n): - v = utc_dates[i] - if vals[i] == NPY_NAT: - result[i] = vals[i] - else: - pos = posn[j] - 1 - j = j + 1 - if pos < 0: - raise ValueError('First time before start of DST info') - offset = deltas[pos] - result[i] = v + offset - return result + else: + # Convert UTC to other timezone + return np.array(_tz_convert_dst(utc_dates, tz2, to_utc=False)) # TODO: cdef scalar version to call from convert_str_to_tsobject
Analogous to #21727, this handles the `get_dst_info` case whereas that handled the `tzlocal` case. Fleshes out docstring as discussed in #21727 All the other uses of `get_dst_info` are handled _slightly_ differently. Need to figure out whether those are intentional to see if more de-duplication (or perf) is available.
https://api.github.com/repos/pandas-dev/pandas/pulls/21730
2018-07-04T19:18:41Z
2018-07-06T14:12:02Z
2018-07-06T14:12:02Z
2018-07-06T14:30:10Z
misplaced scatter/hexbin subplot colorbars
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1b2033999d67d..4704be34171ed 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -336,8 +336,7 @@ I/O Plotting ^^^^^^^^ -- Bug in :func:'DataFrame.plot.scatter' and :func:'DataFrame.plot.hexbin' caused x-axis label and ticklabels to disappear when colorbar was on in IPython inline backend (:issue:`10611` and :issue:`10678`) -- +- Bug in :func:'DataFrame.plot.scatter' and :func:'DataFrame.plot.hexbin' caused x-axis label and ticklabels to disappear when colorbar was on in IPython inline backend (:issue:`10611`, :issue:`10678`, and :issue:`20455`) - Groupby/Resample/Rolling diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 8c2ee90014302..0fb1f2b23faac 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -847,7 +847,7 @@ def _plot_colorbar(self, ax, **kwds): # https://github.com/ipython/ipython/issues/11215 img = ax.collections[0] - cbar = self.fig.colorbar(img, **kwds) + cbar = self.fig.colorbar(img, ax=ax, **kwds) points = ax.get_position().get_points() cbar_points = cbar.ax.get_position().get_points() cbar.ax.set_position([cbar_points[0, 0], diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 8ef0cf7154b88..f1ea847e76091 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1132,6 +1132,26 @@ def test_if_hexbin_xaxis_label_is_visible(self): ax.xaxis.get_majorticklabels()]) assert ax.xaxis.get_label().get_visible() + @pytest.mark.slow + def test_if_scatterplot_colorbars_are_next_to_parent_axes(self): + import matplotlib.pyplot as plt + random_array = np.random.random((1000, 3)) + df = pd.DataFrame(random_array, + columns=['A label', 'B label', 'C label']) + + fig, axes = plt.subplots(1, 2) + df.plot.scatter('A label', 'B label', c='C label', ax=axes[0]) + df.plot.scatter('A label', 'B label', c='C label', ax=axes[1]) + plt.tight_layout() + + points = np.array([ax.get_position().get_points() + for ax in fig.axes]) + axes_x_coords = points[:, :, 0] + parent_distance = axes_x_coords[1, :] - axes_x_coords[0, :] + colorbar_distance = axes_x_coords[3, :] - axes_x_coords[2, :] + assert np.isclose(parent_distance, + colorbar_distance, atol=1e-7).all() + @pytest.mark.slow def test_plot_scatter_with_categorical_data(self): # GH 16199
- [x] closes #20455 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry NOTE: I have tested the following in Jupyter lab. When I run: ```python %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd random_array = np.random.random((1000,3)) df = pd.DataFrame(random_array,columns=['A label','B label','C label']) fig, axes = plt.subplots(1, 2) df.plot.scatter('A label','B label', c='C label', ax=axes[0]) df.plot.scatter('A label','B label', c='C label', ax=axes[1]) plt.tight_layout() ``` I get: ![image](https://user-images.githubusercontent.com/26352146/42286164-eaa6ad96-7f7f-11e8-9bb5-cbe03d9820b7.png) This PR fixes the issue with colorbars. After the PR the output is: ![image](https://user-images.githubusercontent.com/26352146/42286213-213375ba-7f80-11e8-964c-a0d4bdd79526.png) This also fixes similar issue with hexbin plot. To explore different configurations try the following function: ```python %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd def make_multiplots(numrows=2,numcols=2,sharey=True,sharex=True, is_scatter = True): fig, axes = plt.subplots(numrows, numcols, sharey=sharey, sharex=sharex ) for i in range(axes.shape[0]): for j in range(axes.shape[1]): random_array = np.random.random((1000,3)) df = pd.DataFrame(random_array,columns=['A label','B label','C label']) if is_scatter: df.plot.scatter('A label', 'B label', c='C label', ax=axes[i,j]); else: df.plot.hexbin('A label', 'B label', gridsize=20, ax=axes[i,j]); make_multiplots(numrows=2,numcols=3,sharey=False, sharex=False, is_scatter=False) plt.tight_layout() ``` ![image](https://user-images.githubusercontent.com/26352146/42286309-6bbba0c6-7f80-11e8-9327-b17cf31ecb07.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/21728
2018-07-04T16:16:36Z
2018-07-05T16:47:12Z
2018-07-05T16:47:11Z
2018-07-05T16:52:12Z
Implement _tz_convert_tzlocal_utc for de-duplication
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 8cfaa1f7b5cea..f825a4c8ed2c1 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -537,7 +537,7 @@ cdef inline void localize_tso(_TSObject obj, tzinfo tz): elif obj.value == NPY_NAT: pass elif is_tzlocal(tz): - local_val = tz_convert_utc_to_tzlocal(obj.value, tz) + local_val = _tz_convert_tzlocal_utc(obj.value, tz, to_utc=False) dt64_to_dtstruct(local_val, &obj.dts) else: # Adjust datetime64 timestamp, recompute datetimestruct @@ -608,32 +608,33 @@ cpdef inline datetime localize_pydatetime(datetime dt, object tz): # ---------------------------------------------------------------------- # Timezone Conversion -cdef inline int64_t tz_convert_tzlocal_to_utc(int64_t val, tzinfo tz): +cdef inline int64_t _tz_convert_tzlocal_utc(int64_t val, tzinfo tz, + bint to_utc=True): """ Parameters ---------- val : int64_t tz : tzinfo + to_utc : bint + True if converting tzlocal _to_ UTC, False if going the other direction Returns ------- - utc_date : int64_t - - See Also - -------- - tz_convert_utc_to_tzlocal + result : int64_t """ cdef: pandas_datetimestruct dts - int64_t utc_date, delta + int64_t result, delta datetime dt dt64_to_dtstruct(val, &dts) dt = datetime(dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us, tz) delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000 - utc_date = val - delta - return utc_date + + if not to_utc: + return val + delta + return val - delta cdef inline int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz): @@ -646,27 +647,8 @@ cdef inline int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz): Returns ------- local_val : int64_t - - See Also - -------- - tz_convert_tzlocal_to_utc - - Notes - ----- - The key difference between this and tz_convert_tzlocal_to_utc is a - an addition flipped to a subtraction in the last line. """ - cdef: - pandas_datetimestruct dts - int64_t local_val, delta - datetime dt - - dt64_to_dtstruct(utc_val, &dts) - dt = datetime(dts.year, dts.month, dts.day, dts.hour, - dts.min, dts.sec, dts.us, tz) - delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000 - local_val = utc_val + delta - return local_val + return _tz_convert_tzlocal_utc(utc_val, tz, to_utc=False) cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): @@ -699,7 +681,7 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): # Convert to UTC if is_tzlocal(tz1): - utc_date = tz_convert_tzlocal_to_utc(val, tz1) + utc_date = _tz_convert_tzlocal_utc(val, tz1, to_utc=True) elif get_timezone(tz1) != 'UTC': trans, deltas, typ = get_dst_info(tz1) pos = trans.searchsorted(val, side='right') - 1 @@ -713,7 +695,7 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): if get_timezone(tz2) == 'UTC': return utc_date elif is_tzlocal(tz2): - return tz_convert_utc_to_tzlocal(utc_date, tz2) + return _tz_convert_tzlocal_utc(utc_date, tz2, to_utc=False) # Convert UTC to other timezone trans, deltas, typ = get_dst_info(tz2) @@ -762,7 +744,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): if v == NPY_NAT: utc_dates[i] = NPY_NAT else: - utc_dates[i] = tz_convert_tzlocal_to_utc(v, tz1) + utc_dates[i] = _tz_convert_tzlocal_utc(v, tz1, to_utc=True) else: trans, deltas, typ = get_dst_info(tz1) @@ -797,7 +779,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): if v == NPY_NAT: result[i] = NPY_NAT else: - result[i] = tz_convert_utc_to_tzlocal(v, tz2) + result[i] = _tz_convert_tzlocal_utc(v, tz2, to_utc=False) return result # Convert UTC to other timezone @@ -809,7 +791,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): return result # if all NaT, return all NaT - tt = utc_dates[utc_dates!=NPY_NAT] + tt = utc_dates[utc_dates != NPY_NAT] if not len(tt): return utc_dates @@ -874,7 +856,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None, if is_tzlocal(tz): for i in range(n): v = vals[i] - result[i] = tz_convert_tzlocal_to_utc(v, tz) + result[i] = _tz_convert_tzlocal_utc(v, tz, to_utc=True) return result if is_string_object(ambiguous): @@ -1116,7 +1098,7 @@ cdef ndarray[int64_t] _normalize_local(ndarray[int64_t] stamps, object tz): if stamps[i] == NPY_NAT: result[i] = NPY_NAT continue - local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) + local_val = _tz_convert_tzlocal_utc(stamps[i], tz, to_utc=False) dt64_to_dtstruct(local_val, &dts) result[i] = _normalized_stamp(&dts) else: @@ -1195,7 +1177,7 @@ def is_date_array_normalized(ndarray[int64_t] stamps, tz=None): return False elif is_tzlocal(tz): for i in range(n): - local_val = tz_convert_utc_to_tzlocal(stamps[i], tz) + local_val = _tz_convert_tzlocal_utc(stamps[i], tz, to_utc=False) dt64_to_dtstruct(local_val, &dts) if (dts.hour + dts.min + dts.sec + dts.us) > 0: return False @@ -1205,7 +1187,6 @@ def is_date_array_normalized(ndarray[int64_t] stamps, tz=None): for i in range(n): # Adjust datetime64 timestamp, recompute datetimestruct pos = trans.searchsorted(stamps[i]) - 1 - inf = tz._transition_info[pos] dt64_to_dtstruct(stamps[i] + deltas[pos], &dts) if (dts.hour + dts.min + dts.sec + dts.us) > 0:
There is a bunch of code in conversion (and a bit in resolution, period, and tslib) that can be de-duplicated. This is one part of ~5 steps in that process.
https://api.github.com/repos/pandas-dev/pandas/pulls/21727
2018-07-04T16:15:20Z
2018-07-04T18:41:54Z
2018-07-04T18:41:54Z
2018-07-05T02:42:49Z
CLN: Delay converting bins to datetimelike until necessary
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 863ebc6354136..bbdce762feee3 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -235,7 +235,7 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3, duplicates=duplicates) return _postprocess_for_cut(fac, bins, retbins, x_is_series, - series_index, name) + series_index, name, dtype) def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'): @@ -307,7 +307,7 @@ def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'): dtype=dtype, duplicates=duplicates) return _postprocess_for_cut(fac, bins, retbins, x_is_series, - series_index, name) + series_index, name, dtype) def _bins_to_cuts(x, bins, right=True, labels=None, @@ -365,8 +365,6 @@ def _bins_to_cuts(x, bins, right=True, labels=None, result = result.astype(np.float64) np.putmask(result, na_mask, np.nan) - bins = _convert_bin_to_datelike_type(bins, dtype) - return result, bins @@ -511,7 +509,7 @@ def _preprocess_for_cut(x): def _postprocess_for_cut(fac, bins, retbins, x_is_series, - series_index, name): + series_index, name, dtype): """ handles post processing for the cut method where we combine the index information if the originally passed @@ -523,6 +521,8 @@ def _postprocess_for_cut(fac, bins, retbins, x_is_series, if not retbins: return fac + bins = _convert_bin_to_datelike_type(bins, dtype) + return fac, bins
- [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` xref #20956, `q/cut` now returns datetimelike bins when `retbins=True`. Instead of always trying to convert bins to datetimelike (even when `retbins=False`), moving the conversion to `_postprocess_for_cut` until after `retbins=True` is checked cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/21724
2018-07-04T05:48:11Z
2018-07-04T12:50:22Z
2018-07-04T12:50:22Z
2018-07-04T16:04:29Z
Code deduplication in tz_convert and related
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 8cfaa1f7b5cea..a7ad7a6ca14d3 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -612,61 +612,43 @@ cdef inline int64_t tz_convert_tzlocal_to_utc(int64_t val, tzinfo tz): """ Parameters ---------- - val : int64_t + utc_val : int64_t tz : tzinfo Returns ------- - utc_date : int64_t - - See Also - -------- - tz_convert_utc_to_tzlocal + local_val : int64_t """ - cdef: - pandas_datetimestruct dts - int64_t utc_date, delta - datetime dt - - dt64_to_dtstruct(val, &dts) - dt = datetime(dts.year, dts.month, dts.day, dts.hour, - dts.min, dts.sec, dts.us, tz) - delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000 - utc_date = val - delta - return utc_date + return _tz_convert_tzlocal_utc(utc_val, tz, to_utc=False) -cdef inline int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz): +cdef inline int64_t _tz_convert_tzlocal_utc(int64_t val, tzinfo tz, + bint to_utc=True): """ Parameters ---------- - utc_val : int64_t + val : int64_t tz : tzinfo + to_utc : bint + True if converting tzlocal _to_ UTC, False if going the other direction Returns ------- - local_val : int64_t - - See Also - -------- - tz_convert_tzlocal_to_utc - - Notes - ----- - The key difference between this and tz_convert_tzlocal_to_utc is a - an addition flipped to a subtraction in the last line. + result : int64_t """ cdef: pandas_datetimestruct dts - int64_t local_val, delta + int64_t result, delta datetime dt - dt64_to_dtstruct(utc_val, &dts) + dt64_to_dtstruct(val, &dts) dt = datetime(dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.us, tz) delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000 - local_val = utc_val + delta - return local_val + + if not to_utc: + return val + delta + return val - delta cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): @@ -698,32 +680,32 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): return val # Convert to UTC - if is_tzlocal(tz1): - utc_date = tz_convert_tzlocal_to_utc(val, tz1) - elif get_timezone(tz1) != 'UTC': + if get_timezone(tz1) == 'UTC': + utc_date = val + elif is_tzlocal(tz1): + utc_date = _tz_convert_tzlocal_utc(val, tz1, to_utc=True) + else: trans, deltas, typ = get_dst_info(tz1) pos = trans.searchsorted(val, side='right') - 1 if pos < 0: raise ValueError('First time before start of DST info') offset = deltas[pos] utc_date = val - offset - else: - utc_date = val if get_timezone(tz2) == 'UTC': return utc_date elif is_tzlocal(tz2): - return tz_convert_utc_to_tzlocal(utc_date, tz2) - - # Convert UTC to other timezone - trans, deltas, typ = get_dst_info(tz2) + return _tz_convert_tzlocal_utc(utc_date, tz2, to_utc=False) + else: + # Convert UTC to other timezone + trans, deltas, typ = get_dst_info(tz2) - pos = trans.searchsorted(utc_date, side='right') - 1 - if pos < 0: - raise ValueError('First time before start of DST info') + pos = trans.searchsorted(utc_date, side='right') - 1 + if pos < 0: + raise ValueError('First time before start of DST info') - offset = deltas[pos] - return utc_date + offset + offset = deltas[pos] + return utc_date + offset @cython.boundscheck(False) @@ -754,7 +736,9 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): return np.array([], dtype=np.int64) # Convert to UTC - if get_timezone(tz1) != 'UTC': + if get_timezone(tz2) == 'UTC': + utc_dates = vals + else: utc_dates = np.empty(n, dtype=np.int64) if is_tzlocal(tz1): for i in range(n): @@ -762,7 +746,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): if v == NPY_NAT: utc_dates[i] = NPY_NAT else: - utc_dates[i] = tz_convert_tzlocal_to_utc(v, tz1) + utc_dates[i] = _tz_convert_tzlocal_utc(v, tz1, to_utc=True) else: trans, deltas, typ = get_dst_info(tz1) @@ -784,8 +768,6 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): raise ValueError('First time before start of DST info') offset = deltas[pos] utc_dates[i] = v - offset - else: - utc_dates = vals if get_timezone(tz2) == 'UTC': return utc_dates @@ -797,37 +779,37 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2): if v == NPY_NAT: result[i] = NPY_NAT else: - result[i] = tz_convert_utc_to_tzlocal(v, tz2) + result[i] = _tz_convert_tzlocal_utc(v, tz2, to_utc=False) return result + else: + # Convert UTC to other timezone + trans, deltas, typ = get_dst_info(tz2) - # Convert UTC to other timezone - trans, deltas, typ = get_dst_info(tz2) - - # use first non-NaT element - # if all-NaT, return all-NaT - if (result == NPY_NAT).all(): - return result + # use first non-NaT element + # if all-NaT, return all-NaT + if (result == NPY_NAT).all(): + return result - # if all NaT, return all NaT - tt = utc_dates[utc_dates!=NPY_NAT] - if not len(tt): - return utc_dates + # if all NaT, return all NaT + tt = utc_dates[utc_dates!=NPY_NAT] + if not len(tt): + return utc_dates - posn = trans.searchsorted(tt, side='right') + posn = trans.searchsorted(tt, side='right') - j = 0 - for i in range(n): - v = utc_dates[i] - if vals[i] == NPY_NAT: - result[i] = vals[i] - else: - pos = posn[j] - 1 - j = j + 1 - if pos < 0: - raise ValueError('First time before start of DST info') - offset = deltas[pos] - result[i] = v + offset - return result + j = 0 + for i in range(n): + v = utc_dates[i] + if vals[i] == NPY_NAT: + result[i] = vals[i] + else: + pos = posn[j] - 1 + j = j + 1 + if pos < 0: + raise ValueError('First time before start of DST info') + offset = deltas[pos] + result[i] = v + offset + return result # TODO: cdef scalar version to call from convert_str_to_tsobject @@ -874,7 +856,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None, if is_tzlocal(tz): for i in range(n): v = vals[i] - result[i] = tz_convert_tzlocal_to_utc(v, tz) + result[i] = _tz_convert_tzlocal_utc(v, tz, to_utc=True) return result if is_string_object(ambiguous): @@ -1205,7 +1187,6 @@ def is_date_array_normalized(ndarray[int64_t] stamps, tz=None): for i in range(n): # Adjust datetime64 timestamp, recompute datetimestruct pos = trans.searchsorted(stamps[i]) - 1 - inf = tz._transition_info[pos] dt64_to_dtstruct(stamps[i] + deltas[pos], &dts) if (dts.hour + dts.min + dts.sec + dts.us) > 0:
`tz_convert_tzlocal_to_utc` and `tz_convert_utc_to_tzlocal` are identical except for a `+` changed to a `-`. This implements `_tz_convert_tzlocal_utc` which has an argument that flips the sign. IIUC because it is inlined, that check should be free. An upcoming PR will do the same thing for the `get_dst_info` cases in `tz_convert` and `tz_convert_single`, at which point a bunch of duplicate code will be able to be removed. To make it more obvious how that will work, this rearranges the to-be-de-duplicated code blocks to use (near) symmetric condition-ordering and indentation.
https://api.github.com/repos/pandas-dev/pandas/pulls/21723
2018-07-04T05:32:57Z
2018-07-04T05:37:23Z
null
2018-07-04T16:10:20Z
move ndarray-returning functions to EA mixin classes
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index be3f94201f103..54e1f0726d772 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -2,11 +2,14 @@ import numpy as np -from pandas._libs import iNaT +from pandas._libs import iNaT, NaT from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds +from pandas._libs.tslibs.period import ( + DIFFERENT_FREQ_INDEX, IncompatibleFrequency) from pandas.tseries import frequencies +from pandas.core.dtypes.common import is_period_dtype import pandas.core.common as com from pandas.core.algorithms import checked_add_with_arr @@ -179,3 +182,40 @@ def _sub_nat(self): result = np.zeros(len(self), dtype=np.int64) result.fill(iNaT) return result.view('timedelta64[ns]') + + def _sub_period_array(self, other): + """ + Subtract a Period Array/Index from self. This is only valid if self + is itself a Period Array/Index, raises otherwise. Both objects must + have the same frequency. + + Parameters + ---------- + other : PeriodIndex or PeriodArray + + Returns + ------- + result : np.ndarray[object] + Array of DateOffset objects; nulls represented by NaT + """ + if not is_period_dtype(self): + raise TypeError("cannot subtract {dtype}-dtype to {cls}" + .format(dtype=other.dtype, + cls=type(self).__name__)) + + if not len(self) == len(other): + raise ValueError("cannot subtract arrays/indices of " + "unequal length") + if self.freq != other.freq: + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + + new_values = checked_add_with_arr(self.asi8, -other.asi8, + arr_mask=self._isnan, + b_mask=other._isnan) + + new_values = np.array([self.freq * x for x in new_values]) + if self.hasnans or other.hasnans: + mask = (self._isnan) | (other._isnan) + new_values[mask] = NaT + return new_values diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index fb51f3324c5ea..a5acc3d0e8593 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -3,6 +3,7 @@ import numpy as np +from pandas._libs import tslib from pandas._libs.tslib import Timestamp, NaT, iNaT from pandas._libs.tslibs import timezones @@ -108,3 +109,17 @@ def _sub_datelike_dti(self, other): mask = (self._isnan) | (other._isnan) new_values[mask] = iNaT return new_values.view('timedelta64[ns]') + + # ---------------------------------------------------------------- + # Conversion Methods - Vectorized analogues of Timedelta methods + + def to_pydatetime(self): + """ + Return Datetime Array/Index as object ndarray of datetime.datetime + objects + + Returns + ------- + datetimes : ndarray + """ + return tslib.ints_to_pydatetime(self.asi8, tz=self.tz) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 03c0128c67c99..01acaad228067 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -1,12 +1,22 @@ # -*- coding: utf-8 -*- +from datetime import timedelta +import warnings +import numpy as np + +from pandas._libs import lib from pandas._libs.tslib import NaT -from pandas._libs.tslibs.period import Period +from pandas._libs.tslibs.period import ( + Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX) +from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds from pandas.util._decorators import cache_readonly from pandas.core.dtypes.dtypes import PeriodDtype +from pandas.tseries import frequencies +from pandas.tseries.offsets import Tick, DateOffset + from .datetimelike import DatetimeLikeArrayMixin @@ -28,9 +38,70 @@ def _ndarray_values(self): def asi8(self): return self._ndarray_values.view('i8') + @property + def freq(self): + """Return the frequency object if it is set, otherwise None""" + return self._freq + + @freq.setter + def freq(self, value): + msg = ('Setting {cls}.freq has been deprecated and will be ' + 'removed in a future version; use PeriodIndex.asfreq instead. ' + 'The {cls}.freq setter is not guaranteed to work.') + warnings.warn(msg.format(cls=type(self).__name__), + FutureWarning, stacklevel=2) + self._freq = value + # ------------------------------------------------------------------ # Arithmetic Methods def _sub_datelike(self, other): assert other is not NaT return NotImplemented + + def _maybe_convert_timedelta(self, other): + """ + Convert timedelta-like input to an integer multiple of self.freq + + Parameters + ---------- + other : timedelta, np.timedelta64, DateOffset, int, np.ndarray + + Returns + ------- + converted : int, np.ndarray[int64] + + Raises + ------ + IncompatibleFrequency : if the input cannot be written as a multiple + of self.freq. Note IncompatibleFrequency subclasses ValueError. + """ + if isinstance( + other, (timedelta, np.timedelta64, Tick, np.ndarray)): + offset = frequencies.to_offset(self.freq.rule_code) + if isinstance(offset, Tick): + if isinstance(other, np.ndarray): + nanos = np.vectorize(delta_to_nanoseconds)(other) + else: + nanos = delta_to_nanoseconds(other) + offset_nanos = delta_to_nanoseconds(offset) + check = np.all(nanos % offset_nanos == 0) + if check: + return nanos // offset_nanos + elif isinstance(other, DateOffset): + freqstr = other.rule_code + base = frequencies.get_base_alias(freqstr) + if base == self.freq.rule_code: + return other.n + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + raise IncompatibleFrequency(msg) + elif lib.is_integer(other): + # integer is passed to .shift via + # _add_datetimelike_methods basically + # but ufunc may pass integer to _add_delta + return other + + # raise when input doesn't have freq + msg = "Input has different freq from {cls}(freq={freqstr})" + raise IncompatibleFrequency(msg.format(cls=type(self).__name__, + freqstr=self.freqstr)) diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index 85c5bdc566ff1..cc3478e504efb 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- +from pandas._libs import tslib from pandas._libs.tslib import Timedelta, NaT from pandas.core.dtypes.common import _TD_DTYPE @@ -31,3 +32,17 @@ def _sub_datelike(self, other): assert other is not NaT raise TypeError("cannot subtract a datelike from a {cls}" .format(cls=type(self).__name__)) + + # ---------------------------------------------------------------- + # Conversion Methods - Vectorized analogues of Timedelta methods + + def to_pytimedelta(self): + """ + Return Timedelta Array/Index as object ndarray of datetime.timedelta + objects + + Returns + ------- + datetimes : ndarray + """ + return tslib.ints_to_pytimedelta(self.asi8) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 88a1529b34960..41046e361ac90 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -13,8 +13,7 @@ import numpy as np from pandas._libs import lib, iNaT, NaT, Timedelta -from pandas._libs.tslibs.period import (Period, IncompatibleFrequency, - DIFFERENT_FREQ_INDEX) +from pandas._libs.tslibs.period import Period from pandas._libs.tslibs.timestamps import round_ns from pandas.core.dtypes.common import ( @@ -696,41 +695,6 @@ def _add_nat(self): # and datetime dtypes return self._nat_new(box=True) - def _sub_period_array(self, other): - """ - Subtract one PeriodIndex from another. This is only valid if they - have the same frequency. - - Parameters - ---------- - other : PeriodIndex - - Returns - ------- - result : np.ndarray[object] - Array of DateOffset objects; nulls represented by NaT - """ - if not is_period_dtype(self): - raise TypeError("cannot subtract {dtype}-dtype to {cls}" - .format(dtype=other.dtype, - cls=type(self).__name__)) - - if not len(self) == len(other): - raise ValueError("cannot subtract indices of unequal length") - if self.freq != other.freq: - msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) - raise IncompatibleFrequency(msg) - - new_values = checked_add_with_arr(self.asi8, -other.asi8, - arr_mask=self._isnan, - b_mask=other._isnan) - - new_values = np.array([self.freq * x for x in new_values]) - if self.hasnans or other.hasnans: - mask = (self._isnan) | (other._isnan) - new_values[mask] = NaT - return new_values - def _addsub_offset_array(self, other, op): """ Add or subtract array-like of DateOffset objects diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 7475998909ec2..3494811cc3a9b 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -987,16 +987,6 @@ def _to_embed(self, keep_tz=False, dtype=None): return self.values.copy() - def to_pydatetime(self): - """ - Return DatetimeIndex as object ndarray of datetime.datetime objects - - Returns - ------- - datetimes : ndarray - """ - return libts.ints_to_pydatetime(self.asi8, tz=self.tz) - def to_period(self, freq=None): """ Cast to PeriodIndex at a particular frequency. diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index e04d729d9a8c1..143cb8cd3ff6e 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -20,7 +20,7 @@ import pandas.tseries.frequencies as frequencies from pandas.tseries.frequencies import get_freq_code as _gfc -from pandas.tseries.offsets import Tick, DateOffset +from pandas.tseries.offsets import Tick from pandas.core.indexes.datetimes import DatetimeIndex, Int64Index, Index from pandas.core.indexes.datetimelike import DatelikeOps, DatetimeIndexOpsMixin @@ -547,19 +547,6 @@ def is_full(self): values = self.asi8 return ((values[1:] - values[:-1]) < 2).all() - @property - def freq(self): - """Return the frequency object if it is set, otherwise None""" - return self._freq - - @freq.setter - def freq(self, value): - msg = ('Setting PeriodIndex.freq has been deprecated and will be ' - 'removed in a future version; use PeriodIndex.asfreq instead. ' - 'The PeriodIndex.freq setter is not guaranteed to work.') - warnings.warn(msg, FutureWarning, stacklevel=2) - self._freq = value - def asfreq(self, freq=None, how='E'): """ Convert the PeriodIndex to the specified frequency `freq`. @@ -686,35 +673,6 @@ def to_timestamp(self, freq=None, how='start'): new_data = period.periodarr_to_dt64arr(new_data._ndarray_values, base) return DatetimeIndex(new_data, freq='infer', name=self.name) - def _maybe_convert_timedelta(self, other): - if isinstance( - other, (timedelta, np.timedelta64, Tick, np.ndarray)): - offset = frequencies.to_offset(self.freq.rule_code) - if isinstance(offset, Tick): - if isinstance(other, np.ndarray): - nanos = np.vectorize(delta_to_nanoseconds)(other) - else: - nanos = delta_to_nanoseconds(other) - offset_nanos = delta_to_nanoseconds(offset) - check = np.all(nanos % offset_nanos == 0) - if check: - return nanos // offset_nanos - elif isinstance(other, DateOffset): - freqstr = other.rule_code - base = frequencies.get_base_alias(freqstr) - if base == self.freq.rule_code: - return other.n - msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) - raise IncompatibleFrequency(msg) - elif is_integer(other): - # integer is passed to .shift via - # _add_datetimelike_methods basically - # but ufunc may pass integer to _add_delta - return other - # raise when input doesn't have freq - msg = "Input has different freq from PeriodIndex(freq={0})" - raise IncompatibleFrequency(msg.format(self.freqstr)) - def _add_offset(self, other): assert not isinstance(other, Tick) base = frequencies.get_base_alias(other.rule_code) diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 80b9bf92df14a..520504affaa02 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -34,7 +34,7 @@ from pandas.core.tools.timedeltas import ( to_timedelta, _coerce_scalar_to_timedelta_type) from pandas.tseries.offsets import Tick, DateOffset -from pandas._libs import (lib, index as libindex, tslib as libts, +from pandas._libs import (lib, index as libindex, join as libjoin, Timedelta, NaT, iNaT) from pandas._libs.tslibs.timedeltas import array_to_timedelta64 from pandas._libs.tslibs.fields import get_timedelta_field @@ -541,16 +541,6 @@ def total_seconds(self): return Index(self._maybe_mask_results(1e-9 * self.asi8), name=self.name) - def to_pytimedelta(self): - """ - Return TimedeltaIndex as object ndarray of datetime.timedelta objects - - Returns - ------- - datetimes : ndarray - """ - return libts.ints_to_pytimedelta(self.asi8) - @Appender(_index_shared_docs['astype']) def astype(self, dtype, copy=True): dtype = pandas_dtype(dtype)
Orthogonal to other EAMixin PRs. The methods this moves are unchanged. Docstrings changed e.g. "DatetimeIndex" to "Datetime Array/Index". I'm open to suggestions for better wording. The error message in `PeriodArrayMixin._maybe_convert_timedelta` is changed to use `type(self).__name__` instead of hardcoding `PeriodIndex`. Ditto the warning issued by `PeriodArrayMixin.freq.setter`.
https://api.github.com/repos/pandas-dev/pandas/pulls/21722
2018-07-04T03:37:02Z
2018-07-05T10:39:00Z
2018-07-05T10:39:00Z
2018-07-06T14:36:30Z
implement _local_timestamps in DatetimeArrayMixin
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index a5acc3d0e8593..e5159141d4b59 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2,10 +2,11 @@ import warnings import numpy as np +from pytz import utc from pandas._libs import tslib from pandas._libs.tslib import Timestamp, NaT, iNaT -from pandas._libs.tslibs import timezones +from pandas._libs.tslibs import conversion, timezones from pandas.util._decorators import cache_readonly @@ -110,6 +111,25 @@ def _sub_datelike_dti(self, other): new_values[mask] = iNaT return new_values.view('timedelta64[ns]') + # ----------------------------------------------------------------- + # Timezone Conversion and Localization Methods + + def _local_timestamps(self): + """ + Convert to an i8 (unix-like nanosecond timestamp) representation + while keeping the local timezone and not using UTC. + This is used to calculate time-of-day information as if the timestamps + were timezone-naive. + """ + values = self.asi8 + indexer = values.argsort() + result = conversion.tz_convert(values.take(indexer), utc, self.tz) + + n = len(indexer) + reverse = np.empty(n, dtype=np.int_) + reverse.put(indexer, np.arange(n)) + return result.take(reverse) + # ---------------------------------------------------------------- # Conversion Methods - Vectorized analogues of Timedelta methods diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 3494811cc3a9b..05f7af6383211 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -603,14 +603,7 @@ def _local_timestamps(self): if self.is_monotonic: return conversion.tz_convert(self.asi8, utc, self.tz) else: - values = self.asi8 - indexer = values.argsort() - result = conversion.tz_convert(values.take(indexer), utc, self.tz) - - n = len(indexer) - reverse = np.empty(n, dtype=np.int_) - reverse.put(indexer, np.arange(n)) - return result.take(reverse) + return DatetimeArrayMixin._local_timestamps(self) @classmethod def _simple_new(cls, values, name=None, freq=None, tz=None,
Broken out of #21715 because it is a blocker for a handful of orthogonal follow-ons.
https://api.github.com/repos/pandas-dev/pandas/pulls/21721
2018-07-04T02:53:02Z
2018-07-05T16:51:02Z
2018-07-05T16:51:02Z
2018-07-06T14:36:43Z
docstring and whitespace cleanup
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index a6dbaff17e543..f5f9c06a7e4c2 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -243,7 +243,7 @@ def group_shift_indexer(ndarray[int64_t] out, ndarray[int64_t] labels, label_indexer = np.zeros((ngroups, periods), dtype=np.int64) with nogil: for i in range(N): - ## reverse iterator if shifting backwards + # reverse iterator if shifting backwards ii = offset + sign * i lab = labels[ii] diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index cf5053acb229b..8cfaa1f7b5cea 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -482,7 +482,7 @@ cdef _TSObject convert_str_to_tsobject(object ts, object tz, object unit, cdef inline check_overflows(_TSObject obj): """ Check that we haven't silently overflowed in timezone conversion - + Parameters ---------- obj : _TSObject @@ -577,8 +577,6 @@ cdef inline datetime _localize_pydatetime(datetime dt, tzinfo tz): except AttributeError: return dt.replace(tzinfo=tz) -# ---------------------------------------------------------------------- -# Timezone Conversion cpdef inline datetime localize_pydatetime(datetime dt, object tz): """ @@ -607,6 +605,9 @@ cpdef inline datetime localize_pydatetime(datetime dt, object tz): return dt.replace(tzinfo=tz) +# ---------------------------------------------------------------------- +# Timezone Conversion + cdef inline int64_t tz_convert_tzlocal_to_utc(int64_t val, tzinfo tz): """ Parameters @@ -682,10 +683,8 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): Returns ------- - int64 converted - + converted: int64 """ - cdef: ndarray[int64_t] trans, deltas Py_ssize_t pos @@ -840,9 +839,17 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None, Localize tzinfo-naive i8 to given time zone (using pytz). If there are ambiguities in the values, raise AmbiguousTimeError. + Parameters + ---------- + vals : ndarray[int64_t] + tz : tzinfo or None + ambiguous : str, bool, or arraylike + If arraylike, must have the same length as vals + errors : {"raise", "coerce"}, default "raise" + Returns ------- - localized : DatetimeIndex + localized : ndarray[int64_t] """ cdef: ndarray[int64_t] trans, deltas, idx_shifted
https://api.github.com/repos/pandas-dev/pandas/pulls/21719
2018-07-03T16:11:42Z
2018-07-03T23:39:29Z
2018-07-03T23:39:29Z
2018-07-05T02:43:24Z
TST: Parametrize tests in tools/test_numeric.py
diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py index b306dba0be7f1..5321a5a93fa3d 100644 --- a/pandas/tests/tools/test_numeric.py +++ b/pandas/tests/tools/test_numeric.py @@ -162,12 +162,17 @@ def test_all_nan(self): tm.assert_series_equal(res, expected) def test_type_check(self): - # GH 11776 - df = pd.DataFrame({'a': [1, -3.14, 7], 'b': ['4', '5', '6']}) - with tm.assert_raises_regex(TypeError, "1-d array"): + # see gh-11776 + df = pd.DataFrame({"a": [1, -3.14, 7], "b": ["4", "5", "6"]}) + error_ctx = tm.assert_raises_regex(TypeError, "1-d array") + + # Check default parameters. + with error_ctx: to_numeric(df) - for errors in ['ignore', 'raise', 'coerce']: - with tm.assert_raises_regex(TypeError, "1-d array"): + + # Check each parameter value for `errors`. + for errors in ["ignore", "raise", "coerce"]: + with error_ctx: to_numeric(df, errors=errors) def test_scalar(self): @@ -227,17 +232,17 @@ def test_str(self): res = pd.to_numeric(idx.values) tm.assert_numpy_array_equal(res, exp) - def test_datetimelike(self): - for tz in [None, 'US/Eastern', 'Asia/Tokyo']: - idx = pd.date_range('20130101', periods=3, tz=tz, name='xxx') - res = pd.to_numeric(idx) - tm.assert_index_equal(res, pd.Index(idx.asi8, name='xxx')) + def test_datetime_like(self, tz_naive_fixture): + idx = pd.date_range("20130101", periods=3, + tz=tz_naive_fixture, name="xxx") + res = pd.to_numeric(idx) + tm.assert_index_equal(res, pd.Index(idx.asi8, name="xxx")) - res = pd.to_numeric(pd.Series(idx, name='xxx')) - tm.assert_series_equal(res, pd.Series(idx.asi8, name='xxx')) + res = pd.to_numeric(pd.Series(idx, name="xxx")) + tm.assert_series_equal(res, pd.Series(idx.asi8, name="xxx")) - res = pd.to_numeric(idx.values) - tm.assert_numpy_array_equal(res, idx.asi8) + res = pd.to_numeric(idx.values) + tm.assert_numpy_array_equal(res, idx.asi8) def test_timedelta(self): idx = pd.timedelta_range('1 days', periods=3, freq='D', name='xxx') @@ -255,7 +260,7 @@ def test_period(self): res = pd.to_numeric(idx) tm.assert_index_equal(res, pd.Index(idx.asi8, name='xxx')) - # ToDo: enable when we can support native PeriodDtype + # TODO: enable when we can support native PeriodDtype # res = pd.to_numeric(pd.Series(idx, name='xxx')) # tm.assert_series_equal(res, pd.Series(idx.asi8, name='xxx')) @@ -271,116 +276,147 @@ def test_non_hashable(self): with tm.assert_raises_regex(TypeError, "Invalid object type"): pd.to_numeric(s) - def test_downcast(self): + @pytest.mark.parametrize("data", [ + ["1", 2, 3], + [1, 2, 3], + np.array(["1970-01-02", "1970-01-03", + "1970-01-04"], dtype="datetime64[D]") + ]) + def test_downcast_basic(self, data): # see gh-13352 - mixed_data = ['1', 2, 3] - int_data = [1, 2, 3] - date_data = np.array(['1970-01-02', '1970-01-03', - '1970-01-04'], dtype='datetime64[D]') - - invalid_downcast = 'unsigned-integer' - msg = 'invalid downcasting method provided' + invalid_downcast = "unsigned-integer" + msg = "invalid downcasting method provided" - smallest_int_dtype = np.dtype(np.typecodes['Integer'][0]) - smallest_uint_dtype = np.dtype(np.typecodes['UnsignedInteger'][0]) + with tm.assert_raises_regex(ValueError, msg): + pd.to_numeric(data, downcast=invalid_downcast) - # support below np.float32 is rare and far between - float_32_char = np.dtype(np.float32).char - smallest_float_dtype = float_32_char + expected = np.array([1, 2, 3], dtype=np.int64) - for data in (mixed_data, int_data, date_data): - with tm.assert_raises_regex(ValueError, msg): - pd.to_numeric(data, downcast=invalid_downcast) + # Basic function tests. + res = pd.to_numeric(data) + tm.assert_numpy_array_equal(res, expected) - expected = np.array([1, 2, 3], dtype=np.int64) + res = pd.to_numeric(data, downcast=None) + tm.assert_numpy_array_equal(res, expected) - res = pd.to_numeric(data) - tm.assert_numpy_array_equal(res, expected) + # Basic dtype support. + smallest_uint_dtype = np.dtype(np.typecodes["UnsignedInteger"][0]) - res = pd.to_numeric(data, downcast=None) - tm.assert_numpy_array_equal(res, expected) + # Support below np.float32 is rare and far between. + float_32_char = np.dtype(np.float32).char + smallest_float_dtype = float_32_char - expected = np.array([1, 2, 3], dtype=smallest_int_dtype) + expected = np.array([1, 2, 3], dtype=smallest_uint_dtype) + res = pd.to_numeric(data, downcast="unsigned") + tm.assert_numpy_array_equal(res, expected) - for signed_downcast in ('integer', 'signed'): - res = pd.to_numeric(data, downcast=signed_downcast) - tm.assert_numpy_array_equal(res, expected) + expected = np.array([1, 2, 3], dtype=smallest_float_dtype) + res = pd.to_numeric(data, downcast="float") + tm.assert_numpy_array_equal(res, expected) - expected = np.array([1, 2, 3], dtype=smallest_uint_dtype) - res = pd.to_numeric(data, downcast='unsigned') - tm.assert_numpy_array_equal(res, expected) + @pytest.mark.parametrize("signed_downcast", ["integer", "signed"]) + @pytest.mark.parametrize("data", [ + ["1", 2, 3], + [1, 2, 3], + np.array(["1970-01-02", "1970-01-03", + "1970-01-04"], dtype="datetime64[D]") + ]) + def test_signed_downcast(self, data, signed_downcast): + # see gh-13352 + smallest_int_dtype = np.dtype(np.typecodes["Integer"][0]) + expected = np.array([1, 2, 3], dtype=smallest_int_dtype) - expected = np.array([1, 2, 3], dtype=smallest_float_dtype) - res = pd.to_numeric(data, downcast='float') - tm.assert_numpy_array_equal(res, expected) + res = pd.to_numeric(data, downcast=signed_downcast) + tm.assert_numpy_array_equal(res, expected) - # if we can't successfully cast the given + def test_ignore_downcast_invalid_data(self): + # If we can't successfully cast the given # data to a numeric dtype, do not bother - # with the downcast parameter - data = ['foo', 2, 3] + # with the downcast parameter. + data = ["foo", 2, 3] expected = np.array(data, dtype=object) - res = pd.to_numeric(data, errors='ignore', - downcast='unsigned') + + res = pd.to_numeric(data, errors="ignore", + downcast="unsigned") tm.assert_numpy_array_equal(res, expected) - # cannot cast to an unsigned integer because - # we have a negative number - data = ['-1', 2, 3] + def test_ignore_downcast_neg_to_unsigned(self): + # Cannot cast to an unsigned integer + # because we have a negative number. + data = ["-1", 2, 3] expected = np.array([-1, 2, 3], dtype=np.int64) - res = pd.to_numeric(data, downcast='unsigned') - tm.assert_numpy_array_equal(res, expected) - # cannot cast to an integer (signed or unsigned) - # because we have a float number - data = (['1.1', 2, 3], - [10000.0, 20000, 3000, 40000.36, 50000, 50000.00]) - expected = (np.array([1.1, 2, 3], dtype=np.float64), - np.array([10000.0, 20000, 3000, - 40000.36, 50000, 50000.00], dtype=np.float64)) + res = pd.to_numeric(data, downcast="unsigned") + tm.assert_numpy_array_equal(res, expected) - for _data, _expected in zip(data, expected): - for downcast in ('integer', 'signed', 'unsigned'): - res = pd.to_numeric(_data, downcast=downcast) - tm.assert_numpy_array_equal(res, _expected) + @pytest.mark.parametrize("downcast", ["integer", "signed", "unsigned"]) + @pytest.mark.parametrize("data,expected", [ + (["1.1", 2, 3], + np.array([1.1, 2, 3], dtype=np.float64)), + ([10000.0, 20000, 3000, 40000.36, 50000, 50000.00], + np.array([10000.0, 20000, 3000, + 40000.36, 50000, 50000.00], dtype=np.float64)) + ]) + def test_ignore_downcast_cannot_convert_float( + self, data, expected, downcast): + # Cannot cast to an integer (signed or unsigned) + # because we have a float number. + res = pd.to_numeric(data, downcast=downcast) + tm.assert_numpy_array_equal(res, expected) + @pytest.mark.parametrize("downcast,expected_dtype", [ + ("integer", np.int16), + ("signed", np.int16), + ("unsigned", np.uint16) + ]) + def test_downcast_not8bit(self, downcast, expected_dtype): # the smallest integer dtype need not be np.(u)int8 - data = ['256', 257, 258] - - for downcast, expected_dtype in zip( - ['integer', 'signed', 'unsigned'], - [np.int16, np.int16, np.uint16]): - expected = np.array([256, 257, 258], dtype=expected_dtype) - res = pd.to_numeric(data, downcast=downcast) - tm.assert_numpy_array_equal(res, expected) - - def test_downcast_limits(self): - # Test the limits of each downcast. Bug: #14401. - - i = 'integer' - u = 'unsigned' - dtype_downcast_min_max = [ - ('int8', i, [iinfo(np.int8).min, iinfo(np.int8).max]), - ('int16', i, [iinfo(np.int16).min, iinfo(np.int16).max]), - ('int32', i, [iinfo(np.int32).min, iinfo(np.int32).max]), - ('int64', i, [iinfo(np.int64).min, iinfo(np.int64).max]), - ('uint8', u, [iinfo(np.uint8).min, iinfo(np.uint8).max]), - ('uint16', u, [iinfo(np.uint16).min, iinfo(np.uint16).max]), - ('uint32', u, [iinfo(np.uint32).min, iinfo(np.uint32).max]), - ('uint64', u, [iinfo(np.uint64).min, iinfo(np.uint64).max]), - ('int16', i, [iinfo(np.int8).min, iinfo(np.int8).max + 1]), - ('int32', i, [iinfo(np.int16).min, iinfo(np.int16).max + 1]), - ('int64', i, [iinfo(np.int32).min, iinfo(np.int32).max + 1]), - ('int16', i, [iinfo(np.int8).min - 1, iinfo(np.int16).max]), - ('int32', i, [iinfo(np.int16).min - 1, iinfo(np.int32).max]), - ('int64', i, [iinfo(np.int32).min - 1, iinfo(np.int64).max]), - ('uint16', u, [iinfo(np.uint8).min, iinfo(np.uint8).max + 1]), - ('uint32', u, [iinfo(np.uint16).min, iinfo(np.uint16).max + 1]), - ('uint64', u, [iinfo(np.uint32).min, iinfo(np.uint32).max + 1]) - ] - - for dtype, downcast, min_max in dtype_downcast_min_max: - series = pd.to_numeric(pd.Series(min_max), downcast=downcast) - assert series.dtype == dtype + data = ["256", 257, 258] + + expected = np.array([256, 257, 258], dtype=expected_dtype) + res = pd.to_numeric(data, downcast=downcast) + tm.assert_numpy_array_equal(res, expected) + + @pytest.mark.parametrize("dtype,downcast,min_max", [ + ("int8", "integer", [iinfo(np.int8).min, + iinfo(np.int8).max]), + ("int16", "integer", [iinfo(np.int16).min, + iinfo(np.int16).max]), + ('int32', "integer", [iinfo(np.int32).min, + iinfo(np.int32).max]), + ('int64', "integer", [iinfo(np.int64).min, + iinfo(np.int64).max]), + ('uint8', "unsigned", [iinfo(np.uint8).min, + iinfo(np.uint8).max]), + ('uint16', "unsigned", [iinfo(np.uint16).min, + iinfo(np.uint16).max]), + ('uint32', "unsigned", [iinfo(np.uint32).min, + iinfo(np.uint32).max]), + ('uint64', "unsigned", [iinfo(np.uint64).min, + iinfo(np.uint64).max]), + ('int16', "integer", [iinfo(np.int8).min, + iinfo(np.int8).max + 1]), + ('int32', "integer", [iinfo(np.int16).min, + iinfo(np.int16).max + 1]), + ('int64', "integer", [iinfo(np.int32).min, + iinfo(np.int32).max + 1]), + ('int16', "integer", [iinfo(np.int8).min - 1, + iinfo(np.int16).max]), + ('int32', "integer", [iinfo(np.int16).min - 1, + iinfo(np.int32).max]), + ('int64', "integer", [iinfo(np.int32).min - 1, + iinfo(np.int64).max]), + ('uint16', "unsigned", [iinfo(np.uint8).min, + iinfo(np.uint8).max + 1]), + ('uint32', "unsigned", [iinfo(np.uint16).min, + iinfo(np.uint16).max + 1]), + ('uint64', "unsigned", [iinfo(np.uint32).min, + iinfo(np.uint32).max + 1]) + ]) + def test_downcast_limits(self, dtype, downcast, min_max): + # see gh-14404: test the limits of each downcast. + series = pd.to_numeric(pd.Series(min_max), downcast=downcast) + assert series.dtype == dtype def test_coerce_uint64_conflict(self): # see gh-17007 and gh-17125
Title is self-explanatory.
https://api.github.com/repos/pandas-dev/pandas/pulls/21717
2018-07-03T10:22:17Z
2018-07-03T23:38:38Z
2018-07-03T23:38:38Z
2018-07-04T00:12:47Z
implement maybe_wrap_in_index for EA Mixin dispatch
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index fb51f3324c5ea..5eac4053336ed 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2,9 +2,10 @@ import warnings import numpy as np +from pytz import utc from pandas._libs.tslib import Timestamp, NaT, iNaT -from pandas._libs.tslibs import timezones +from pandas._libs.tslibs import timezones, conversion from pandas.util._decorators import cache_readonly @@ -108,3 +109,16 @@ def _sub_datelike_dti(self, other): mask = (self._isnan) | (other._isnan) new_values[mask] = iNaT return new_values.view('timedelta64[ns]') + + # ----------------------------------------------------------------- + # Timezone Conversion and Localization Methods + + def _local_timestamps(self): + values = self.asi8 + indexer = values.argsort() + result = conversion.tz_convert(values.take(indexer), utc, self.tz) + + n = len(indexer) + reverse = np.empty(n, dtype=np.int_) + reverse.put(indexer, np.arange(n)) + return result.take(reverse) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 0ca8af335fe4a..35f475735b0a4 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -314,13 +314,9 @@ def _evaluate_compare(self, other, op): mask = (self._isnan) | (other._isnan) if is_bool_dtype(result): result[mask] = False - return result - - result[mask] = iNaT - try: - return Index(result) - except TypeError: - return result + else: + result[mask] = iNaT + return maybe_wrap_in_index(result, strict=False) def _ensure_localized(self, result): """ @@ -1137,3 +1133,29 @@ def _ensure_datetimelike_to_i8(other): # period array cannot be coerces to int other = Index(other).asi8 return other + + +def maybe_wrap_in_index(result, name=None, strict=True): + """ + After dispatching to a DatetimelikeArrayMixin method we get an ndarray + back. If possible, wrap this array in an Index. The Index constructor + will find the appropriate Index subclass. + + Parameters + ---------- + result : ndarray + name : object, default None + strict : bool, default True + + Returns + ------- + out : ndarray or Index + """ + if is_bool_dtype(result): + return result + try: + return Index(result, name=name) + except TypeError: + if not strict: + return result + raise diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 7475998909ec2..b05aff5f2f037 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -22,7 +22,6 @@ is_integer_dtype, is_datetime64_ns_dtype, is_datetimelike, is_period_dtype, - is_bool_dtype, is_string_like, is_list_like, is_scalar, @@ -42,7 +41,7 @@ import pandas.compat as compat from pandas.tseries.frequencies import to_offset, get_period_alias, Resolution from pandas.core.indexes.datetimelike import ( - DatelikeOps, TimelikeOps, DatetimeIndexOpsMixin) + DatelikeOps, TimelikeOps, DatetimeIndexOpsMixin, maybe_wrap_in_index) from pandas.tseries.offsets import ( DateOffset, generate_range, Tick, CDay, prefix_mapping) @@ -95,7 +94,7 @@ def f(self): result = fields.get_date_field(values, field) result = self._maybe_mask_results(result, convert='float64') - return Index(result, name=self.name) + return maybe_wrap_in_index(result, name=self.name) f.__name__ = name f.__doc__ = docstring @@ -149,10 +148,7 @@ def wrapper(self, other): if self.hasnans: result[self._isnan] = nat_result - # support of bool dtype indexers - if is_bool_dtype(result): - return result - return Index(result) + return maybe_wrap_in_index(result) return compat.set_function_name(wrapper, opname, cls) @@ -603,14 +599,8 @@ def _local_timestamps(self): if self.is_monotonic: return conversion.tz_convert(self.asi8, utc, self.tz) else: - values = self.asi8 - indexer = values.argsort() - result = conversion.tz_convert(values.take(indexer), utc, self.tz) - - n = len(indexer) - reverse = np.empty(n, dtype=np.int_) - reverse.put(indexer, np.arange(n)) - return result.take(reverse) + # fall back to non-optimized implementation + return DatetimeArrayMixin._local_timestamps(self) @classmethod def _simple_new(cls, values, name=None, freq=None, tz=None, @@ -2438,7 +2428,7 @@ def month_name(self, locale=None): result = fields.get_date_name_field(values, 'month_name', locale=locale) result = self._maybe_mask_results(result) - return Index(result, name=self.name) + return maybe_wrap_in_index(result, name=self.name) def day_name(self, locale=None): """ @@ -2464,7 +2454,7 @@ def day_name(self, locale=None): result = fields.get_date_name_field(values, 'day_name', locale=locale) result = self._maybe_mask_results(result) - return Index(result, name=self.name) + return maybe_wrap_in_index(result, name=self.name) DatetimeIndex._add_comparison_methods() diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index c9525b9c30270..7205b189bcc8e 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -23,7 +23,8 @@ from pandas.tseries.offsets import Tick, DateOffset from pandas.core.indexes.datetimes import DatetimeIndex, Int64Index, Index -from pandas.core.indexes.datetimelike import DatelikeOps, DatetimeIndexOpsMixin +from pandas.core.indexes.datetimelike import ( + DatelikeOps, DatetimeIndexOpsMixin, maybe_wrap_in_index) from pandas.core.tools.datetimes import parse_time_string from pandas._libs.lib import infer_dtype @@ -55,7 +56,8 @@ def _field_accessor(name, alias, docstring=None): def f(self): base, mult = _gfc(self.freq) result = get_period_field_arr(alias, self._ndarray_values, base) - return Index(result, name=self.name) + return maybe_wrap_in_index(result, name=self.name) + f.__name__ = name f.__doc__ = docstring return property(f) @@ -761,7 +763,7 @@ def _sub_period(self, other): if self.hasnans: new_data[self._isnan] = tslib.NaT - return Index(new_data) + return maybe_wrap_in_index(new_data) def shift(self, n): """ diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 8b62d9aa631e9..2d4d53ee9c041 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -7,7 +7,6 @@ _TD_DTYPE, is_integer, is_float, - is_bool_dtype, is_list_like, is_scalar, is_timedelta64_dtype, @@ -30,7 +29,7 @@ import pandas.core.dtypes.concat as _concat from pandas.util._decorators import Appender, Substitution, deprecate_kwarg from pandas.core.indexes.datetimelike import ( - TimelikeOps, DatetimeIndexOpsMixin) + TimelikeOps, DatetimeIndexOpsMixin, maybe_wrap_in_index) from pandas.core.tools.timedeltas import ( to_timedelta, _coerce_scalar_to_timedelta_type) from pandas.tseries.offsets import Tick, DateOffset @@ -47,7 +46,7 @@ def f(self): if self.hasnans: result = self._maybe_mask_results(result, convert='float64') - return Index(result, name=self.name) + return maybe_wrap_in_index(result, name=self.name) f.__name__ = name f.__doc__ = docstring @@ -89,10 +88,7 @@ def wrapper(self, other): if self.hasnans: result[self._isnan] = nat_result - # support of bool dtype indexers - if is_bool_dtype(result): - return result - return Index(result) + return maybe_wrap_in_index(result) return compat.set_function_name(wrapper, opname, cls) @@ -409,7 +405,7 @@ def _evaluate_with_timedelta_like(self, other, op): else: result = op(left, np.float64(right)) result = self._maybe_mask_results(result, convert='float64') - return Index(result, name=self.name, copy=False) + return maybe_wrap_in_index(result, name=self.name) return NotImplemented @@ -549,8 +545,8 @@ def total_seconds(self): Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0], dtype='float64') """ - return Index(self._maybe_mask_results(1e-9 * self.asi8), - name=self.name) + result = self._maybe_mask_results(1e-9 * self.asi8) + return maybe_wrap_in_index(result, name=self.name) def to_pytimedelta(self): """
Implements `maybe_wrap_in_index`, shows the easiest places where it can be used. If merged, the follow-on will be to move the affected methods to the EA mixin classes, leaving just the dispatch/wrapping behind. Implements `_local_timestamps` on the `DatetimeArrayMixin`, since that will be needed before we can move the comparison operators among others.
https://api.github.com/repos/pandas-dev/pandas/pulls/21715
2018-07-03T05:38:49Z
2018-07-04T03:44:43Z
null
2018-07-05T02:43:59Z
De-privatize tslibs functions
diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx index abaf8cad09bdb..56dcd5c405c6b 100644 --- a/pandas/_libs/tslibs/frequencies.pyx +++ b/pandas/_libs/tslibs/frequencies.pyx @@ -20,7 +20,7 @@ opattern = re.compile( r'([+\-]?\d*|[+\-]?\d*\.\d*)\s*([A-Za-z]+([\-][\dA-Za-z\-]+)?)' ) -_INVALID_FREQ_ERROR = "Invalid frequency: {0}" +INVALID_FREQ_ERR_MSG = "Invalid frequency: {0}" # --------------------------------------------------------------------- # Period codes @@ -220,7 +220,7 @@ cpdef _period_str_to_code(freqstr): try: return _period_code_map[freqstr] except KeyError: - raise ValueError(_INVALID_FREQ_ERROR.format(freqstr)) + raise ValueError(INVALID_FREQ_ERR_MSG.format(freqstr)) cpdef str get_freq_str(base, mult=1): diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 6e5794ef41757..e39731cfb66f4 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -896,7 +896,7 @@ def extract_ordinals(ndarray[object] values, freq): ordinals[i] = p.ordinal if p.freqstr != freqstr: - msg = _DIFFERENT_FREQ_INDEX.format(freqstr, p.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(freqstr, p.freqstr) raise IncompatibleFrequency(msg) except AttributeError: @@ -986,8 +986,8 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps, _DIFFERENT_FREQ = "Input has different freq={1} from Period(freq={0})" -_DIFFERENT_FREQ_INDEX = ("Input has different freq={1} " - "from PeriodIndex(freq={0})") +DIFFERENT_FREQ_INDEX = ("Input has different freq={1} " + "from PeriodIndex(freq={0})") class IncompatibleFrequency(ValueError): diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index 225ccbf590779..08d4de972bc06 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -15,7 +15,6 @@ from pandas.core.accessor import PandasDelegate from pandas.core.base import NoNewAttributesMixin, PandasObject from pandas.core.indexes.datetimes import DatetimeIndex -from pandas._libs.tslibs.period import IncompatibleFrequency # noqa from pandas.core.indexes.period import PeriodIndex from pandas.core.indexes.timedeltas import TimedeltaIndex from pandas.core.algorithms import take_1d diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 328c51aae1807..0ca8af335fe4a 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -14,7 +14,7 @@ from pandas._libs import lib, iNaT, NaT, Timedelta from pandas._libs.tslibs.period import (Period, IncompatibleFrequency, - _DIFFERENT_FREQ_INDEX) + DIFFERENT_FREQ_INDEX) from pandas._libs.tslibs.timestamps import round_ns from pandas.core.dtypes.common import ( @@ -732,7 +732,7 @@ def _sub_period_array(self, other): if not len(self) == len(other): raise ValueError("cannot subtract indices of unequal length") if self.freq != other.freq: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) new_values = checked_add_with_arr(self.asi8, -other.asi8, diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 1257266025c03..c9525b9c30270 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -30,6 +30,7 @@ from pandas._libs import tslib, index as libindex from pandas._libs.tslibs.period import (Period, IncompatibleFrequency, get_period_field_arr, + DIFFERENT_FREQ_INDEX, _validate_end_alias, _quarter_to_myear) from pandas._libs.tslibs.fields import isleapyear_arr from pandas._libs.tslibs import resolution, period @@ -71,9 +72,6 @@ def dt64arr_to_periodarr(data, freq, tz): # --- Period index sketch -_DIFFERENT_FREQ_INDEX = period._DIFFERENT_FREQ_INDEX - - def _period_index_cmp(opname, cls): """ Wrap comparison operations to convert Period-like to PeriodDtype @@ -84,13 +82,13 @@ def wrapper(self, other): op = getattr(self._ndarray_values, opname) if isinstance(other, Period): if other.freq != self.freq: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) result = op(other.ordinal) elif isinstance(other, PeriodIndex): if other.freq != self.freq: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) result = op(other._ndarray_values) @@ -523,7 +521,7 @@ def astype(self, dtype, copy=True, how='start'): def searchsorted(self, value, side='left', sorter=None): if isinstance(value, Period): if value.freq != self.freq: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, value.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, value.freqstr) raise IncompatibleFrequency(msg) value = value.ordinal elif isinstance(value, compat.string_types): @@ -706,7 +704,7 @@ def _maybe_convert_timedelta(self, other): base = frequencies.get_base_alias(freqstr) if base == self.freq.rule_code: return other.n - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) elif is_integer(other): # integer is passed to .shift via @@ -721,7 +719,7 @@ def _add_offset(self, other): assert not isinstance(other, Tick) base = frequencies.get_base_alias(other.rule_code) if base != self.freq.rule_code: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) return self.shift(other.n) @@ -753,7 +751,7 @@ def _sub_period(self, other): # If the operation is well-defined, we return an object-Index # of DateOffsets. Null entries are filled with pd.NaT if self.freq != other.freq: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) asi8 = self.asi8 @@ -837,7 +835,7 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): target = _ensure_index(target) if hasattr(target, 'freq') and target.freq != self.freq: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, target.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, target.freqstr) raise IncompatibleFrequency(msg) if isinstance(target, PeriodIndex): @@ -1010,7 +1008,7 @@ def _assert_can_do_setop(self, other): raise ValueError('can only call with other PeriodIndex-ed objects') if self.freq != other.freq: - msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) + msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) def _wrap_union_result(self, other, result): diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index 801dcb91b124e..f0442d9d40ef1 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -101,7 +101,7 @@ def test_round(self, tz): tm.assert_index_equal(rng.round(freq='H'), expected_rng) assert elt.round(freq='H') == expected_elt - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG with tm.assert_raises_regex(ValueError, msg): rng.round(freq='foo') with tm.assert_raises_regex(ValueError, msg): diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py index 38c6f257b2206..16b558916df2d 100644 --- a/pandas/tests/indexes/period/test_tools.py +++ b/pandas/tests/indexes/period/test_tools.py @@ -167,7 +167,7 @@ def test_to_period_monthish(self): prng = rng.to_period() assert prng.freq == 'M' - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG with tm.assert_raises_regex(ValueError, msg): date_range('01-Jan-2012', periods=8, freq='EOM') diff --git a/pandas/tests/indexes/timedeltas/test_scalar_compat.py b/pandas/tests/indexes/timedeltas/test_scalar_compat.py index 7d97e1fadea30..e571ec2ccf20b 100644 --- a/pandas/tests/indexes/timedeltas/test_scalar_compat.py +++ b/pandas/tests/indexes/timedeltas/test_scalar_compat.py @@ -50,7 +50,7 @@ def test_tdi_round(self): tm.assert_index_equal(td.round(freq='H'), expected_rng) assert elt.round(freq='H') == expected_elt - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG with tm.assert_raises_regex(ValueError, msg): td.round(freq='foo') with tm.assert_raises_regex(ValueError, msg): diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py index 474d19809b03c..8fde9a417f3b7 100644 --- a/pandas/tests/scalar/period/test_asfreq.py +++ b/pandas/tests/scalar/period/test_asfreq.py @@ -325,13 +325,13 @@ def test_conv_weekly(self): assert ival_W.asfreq('W') == ival_W - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG with tm.assert_raises_regex(ValueError, msg): ival_W.asfreq('WK') def test_conv_weekly_legacy(self): # frequency conversion tests: from Weekly Frequency - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG with tm.assert_raises_regex(ValueError, msg): Period(freq='WK', year=2007, month=1, day=1) @@ -738,7 +738,7 @@ def test_asfreq_MS(self): assert initial.asfreq(freq="M", how="S") == Period('2013-01', 'M') - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG with tm.assert_raises_regex(ValueError, msg): initial.asfreq(freq="MS", how="S") diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index ffc375ba12e34..eccd86a888fb9 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -515,7 +515,7 @@ def test_period_deprecated_freq(self): "U": ["MICROSECOND", "MICROSECONDLY", "microsecond"], "N": ["NANOSECOND", "NANOSECONDLY", "nanosecond"]} - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG for exp, freqs in iteritems(cases): for freq in freqs: with tm.assert_raises_regex(ValueError, msg): @@ -759,7 +759,7 @@ def test_properties_weekly_legacy(self): exp = Period(freq='W', year=2012, month=2, day=1) assert exp.days_in_month == 29 - msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR + msg = pd._libs.tslibs.frequencies.INVALID_FREQ_ERR_MSG with tm.assert_raises_regex(ValueError, msg): Period(freq='WK', year=2007, month=1, day=7) diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index fef01512b2060..9f000a6f22cd6 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -11,7 +11,7 @@ from pandas.compat import PY3 from pandas._libs.tslibs import conversion -from pandas._libs.tslibs.frequencies import _INVALID_FREQ_ERROR +from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG from pandas import Timestamp, NaT @@ -82,7 +82,7 @@ def test_round_nonstandard_freq(self): def test_round_invalid_arg(self): stamp = Timestamp('2000-01-05 05:09:15.13') - with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, INVALID_FREQ_ERR_MSG): stamp.round('foo') @pytest.mark.parametrize('freq, expected', [ diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py index c084cccbb74ac..ccd418a69c827 100644 --- a/pandas/tests/tseries/offsets/test_fiscal.py +++ b/pandas/tests/tseries/offsets/test_fiscal.py @@ -11,7 +11,7 @@ from pandas import Timestamp from pandas.tseries.frequencies import get_offset -from pandas._libs.tslibs.frequencies import _INVALID_FREQ_ERROR +from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG from pandas.tseries.offsets import FY5253Quarter, FY5253 from pandas._libs.tslibs.offsets import WeekDay @@ -45,9 +45,9 @@ def test_get_offset_name(): def test_get_offset(): - with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, INVALID_FREQ_ERR_MSG): get_offset('gibberish') - with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, INVALID_FREQ_ERR_MSG): get_offset('QS-JAN-B') pairs = [ diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 79df847d0c8aa..0c5470e7bd932 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -12,7 +12,7 @@ from pandas.core.series import Series from pandas._libs.tslibs import conversion from pandas._libs.tslibs.frequencies import (get_freq_code, get_freq_str, - _INVALID_FREQ_ERROR) + INVALID_FREQ_ERR_MSG) from pandas.tseries.frequencies import _offset_map, get_offset from pandas.core.indexes.datetimes import ( _to_m8, DatetimeIndex, _daterange_cache) @@ -2748,9 +2748,9 @@ def test_get_offset_name(self): def test_get_offset(): - with pytest.raises(ValueError, match=_INVALID_FREQ_ERROR): + with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): get_offset('gibberish') - with pytest.raises(ValueError, match=_INVALID_FREQ_ERROR): + with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): get_offset('QS-JAN-B') pairs = [ @@ -2768,7 +2768,7 @@ def test_get_offset(): def test_get_offset_legacy(): pairs = [('w@Sat', Week(weekday=5))] for name, expected in pairs: - with pytest.raises(ValueError, match=_INVALID_FREQ_ERROR): + with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG): get_offset(name) diff --git a/pandas/tests/tseries/test_frequencies.py b/pandas/tests/tseries/test_frequencies.py index 92d7eb15c929c..f90c8e449f92c 100644 --- a/pandas/tests/tseries/test_frequencies.py +++ b/pandas/tests/tseries/test_frequencies.py @@ -8,7 +8,7 @@ date_range, period_range) from pandas._libs.tslibs.frequencies import (_period_code_map, - _INVALID_FREQ_ERROR) + INVALID_FREQ_ERR_MSG) from pandas._libs.tslibs.ccalendar import MONTHS from pandas._libs.tslibs import resolution import pandas.tseries.frequencies as frequencies @@ -797,7 +797,7 @@ def test_legacy_offset_warnings(self): 'WOM@4THU', 'WOM@1FRI', 'WOM@2FRI', 'WOM@3FRI', 'WOM@4FRI'] - msg = _INVALID_FREQ_ERROR + msg = INVALID_FREQ_ERR_MSG for freq in freqs: with tm.assert_raises_regex(ValueError, msg): frequencies.get_offset(freq) diff --git a/pandas/tests/tslibs/test_libfrequencies.py b/pandas/tests/tslibs/test_libfrequencies.py index 601d542da3095..f4083dfb2bd1c 100644 --- a/pandas/tests/tslibs/test_libfrequencies.py +++ b/pandas/tests/tslibs/test_libfrequencies.py @@ -5,7 +5,7 @@ from pandas.tseries import offsets from pandas._libs.tslibs.frequencies import (get_rule_month, _period_str_to_code, - _INVALID_FREQ_ERROR, + INVALID_FREQ_ERR_MSG, is_superperiod, is_subperiod) @@ -14,7 +14,7 @@ def assert_aliases_deprecated(freq, expected, aliases): assert (_period_str_to_code(freq) == expected) for alias in aliases: - with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, INVALID_FREQ_ERR_MSG): _period_str_to_code(alias) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 0cffd818202ed..b161e7764b884 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -142,7 +142,7 @@ def to_offset(freq): else: delta = delta + offset except Exception: - raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(freq)) + raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) else: delta = None @@ -173,10 +173,10 @@ def to_offset(freq): else: delta = delta + offset except Exception: - raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(freq)) + raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) if delta is None: - raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(freq)) + raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) return delta @@ -205,7 +205,7 @@ def get_offset(name): offset = klass._from_name(*split[1:]) except (ValueError, TypeError, KeyError): # bad prefix or suffix - raise ValueError(libfreqs._INVALID_FREQ_ERROR.format(name)) + raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(name)) # cache _offset_map[name] = offset # do not return cache because it's mutable
Related: an item on the tslibs TODO list, #21698.
https://api.github.com/repos/pandas-dev/pandas/pulls/21714
2018-07-03T05:12:23Z
2018-07-03T14:53:57Z
2018-07-03T14:53:57Z
2018-07-11T20:24:22Z
Move Unchanged arith methods to EA mixins
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 180417ce5e49c..be3f94201f103 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -167,3 +167,15 @@ def _add_delta_tdi(self, other): mask = (self._isnan) | (other._isnan) new_values[mask] = iNaT return new_values.view('i8') + + def _sub_nat(self): + """Subtract pd.NaT from self""" + # GH#19124 Timedelta - datetime is not in general well-defined. + # We make an exception for pd.NaT, which in this case quacks + # like a timedelta. + # For datetime64 dtypes by convention we treat NaT as a datetime, so + # this subtraction returns a timedelta64 dtype. + # For period dtype, timedelta64 is a close-enough return dtype. + result = np.zeros(len(self), dtype=np.int64) + result.fill(iNaT) + return result.view('timedelta64[ns]') diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 1158bae748f0a..03c0128c67c99 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- +from pandas._libs.tslib import NaT from pandas._libs.tslibs.period import Period from pandas.util._decorators import cache_readonly @@ -26,3 +27,10 @@ def _ndarray_values(self): @property def asi8(self): return self._ndarray_values.view('i8') + + # ------------------------------------------------------------------ + # Arithmetic Methods + + def _sub_datelike(self, other): + assert other is not NaT + return NotImplemented diff --git a/pandas/core/arrays/timedelta.py b/pandas/core/arrays/timedelta.py index 487858c49b66a..85c5bdc566ff1 100644 --- a/pandas/core/arrays/timedelta.py +++ b/pandas/core/arrays/timedelta.py @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*- -from pandas._libs.tslib import Timedelta +from pandas._libs.tslib import Timedelta, NaT from pandas.core.dtypes.common import _TD_DTYPE +from pandas.tseries.offsets import Tick + from .datetimelike import DatetimeLikeArrayMixin @@ -15,3 +17,17 @@ def _box_func(self): @property def dtype(self): return _TD_DTYPE + + # ---------------------------------------------------------------- + # Arithmetic Methods + + def _add_offset(self, other): + assert not isinstance(other, Tick) + raise TypeError("cannot add the type {typ} to a {cls}" + .format(typ=type(other).__name__, + cls=type(self).__name__)) + + def _sub_datelike(self, other): + assert other is not NaT + raise TypeError("cannot subtract a datelike from a {cls}" + .format(cls=type(self).__name__)) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 328c51aae1807..47e7022c99a21 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -696,20 +696,6 @@ def _add_nat(self): # and datetime dtypes return self._nat_new(box=True) - def _sub_nat(self): - """Subtract pd.NaT from self""" - # GH#19124 Timedelta - datetime is not in general well-defined. - # We make an exception for pd.NaT, which in this case quacks - # like a timedelta. - # For datetime64 dtypes by convention we treat NaT as a datetime, so - # this subtraction returns a timedelta64 dtype. - # For period dtype, timedelta64 is a close-enough return dtype. - result = self._nat_new(box=False) - return result.view('timedelta64[ns]') - - def _sub_period(self, other): - return NotImplemented - def _sub_period_array(self, other): """ Subtract one PeriodIndex from another. This is only valid if they @@ -745,9 +731,6 @@ def _sub_period_array(self, other): new_values[mask] = NaT return new_values - def _add_offset(self, offset): - raise com.AbstractMethodError(self) - def _addsub_offset_array(self, other, op): """ Add or subtract array-like of DateOffset objects diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 1257266025c03..a8c12ea48784d 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -745,10 +745,6 @@ def _add_delta(self, other): ordinal_delta = self._maybe_convert_timedelta(other) return self.shift(ordinal_delta) - def _sub_datelike(self, other): - assert other is not tslib.NaT - return NotImplemented - def _sub_period(self, other): # If the operation is well-defined, we return an object-Index # of DateOffsets. Null entries are filled with pd.NaT @@ -763,6 +759,7 @@ def _sub_period(self, other): if self.hasnans: new_data[self._isnan] = tslib.NaT + # TODO: Should name=self.name be passed here? return Index(new_data) def shift(self, n): diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 8b62d9aa631e9..80b9bf92df14a 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -349,12 +349,6 @@ def _maybe_update_attributes(self, attrs): attrs['freq'] = 'infer' return attrs - def _add_offset(self, other): - assert not isinstance(other, Tick) - raise TypeError("cannot add the type {typ} to a {cls}" - .format(typ=type(other).__name__, - cls=type(self).__name__)) - def _add_delta(self, delta): """ Add a timedelta-like, Tick, or TimedeltaIndex-like object @@ -430,11 +424,6 @@ def _add_datelike(self, other): result = self._maybe_mask_results(result, fill_value=iNaT) return DatetimeIndex(result) - def _sub_datelike(self, other): - assert other is not NaT - raise TypeError("cannot subtract a datelike from a {cls}" - .format(cls=type(self).__name__)) - def _addsub_offset_array(self, other, op): # Add or subtract Array-like of DateOffset objects try:
Next steps after #19902. Breaking these up into smaller pieces than usual because I don't know what bits will prove controversial. All this PR does is take a few of the easiest no-changes-needed methods and moved them to the EA mixins.
https://api.github.com/repos/pandas-dev/pandas/pulls/21712
2018-07-03T02:55:46Z
2018-07-03T23:40:09Z
2018-07-03T23:40:09Z
2018-07-06T14:37:01Z
ENH: Add set_closed method to IntervalIndex
diff --git a/doc/source/api.rst b/doc/source/api.rst index 8dc5d0e9fc023..f19e5534fc1b3 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -1642,6 +1642,7 @@ IntervalIndex Components IntervalIndex.is_non_overlapping_monotonic IntervalIndex.get_loc IntervalIndex.get_indexer + IntervalIndex.set_closed .. _api.multiindex: diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index dfb7a3675fdd5..cc17a5cbf13eb 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -41,6 +41,7 @@ Other Enhancements (:issue:`21627`) - New method :meth:`HDFStore.walk` will recursively walk the group hierarchy of an HDF5 file (:issue:`10932`) - :meth:`Series.nlargest`, :meth:`Series.nsmallest`, :meth:`DataFrame.nlargest`, and :meth:`DataFrame.nsmallest` now accept the value ``"all"`` for the ``keep` argument. This keeps all ties for the nth largest/smallest value (:issue:`16818`) +- :class:`IntervalIndex` has gained the :meth:`~IntervalIndex.set_closed` method to change the existing ``closed`` value (:issue:`21670`) - .. _whatsnew_0240.api_breaking: diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 80619c7beb28c..e653c88ab019f 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -180,6 +180,7 @@ class IntervalIndex(IntervalMixin, Index): from_tuples get_indexer get_loc + set_closed Examples --------- @@ -708,6 +709,41 @@ def closed(self): """ return self._closed + def set_closed(self, closed): + """ + Return an IntervalIndex identical to the current one, but closed on the + specified side + + .. versionadded:: 0.24.0 + + Parameters + ---------- + closed : {'left', 'right', 'both', 'neither'} + Whether the intervals are closed on the left-side, right-side, both + or neither. + + Returns + ------- + new_index : IntervalIndex + + Examples + -------- + >>> index = pd.interval_range(0, 3) + >>> index + IntervalIndex([(0, 1], (1, 2], (2, 3]] + closed='right', + dtype='interval[int64]') + >>> index.set_closed('both') + IntervalIndex([[0, 1], [1, 2], [2, 3]] + closed='both', + dtype='interval[int64]') + """ + if closed not in _VALID_CLOSED: + msg = "invalid option for 'closed': {closed}" + raise ValueError(msg.format(closed=closed)) + + return self._shallow_copy(closed=closed) + @property def length(self): """ diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index 6a7330f8cfb68..431833f2627d8 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -977,3 +977,20 @@ def test_to_tuples_na(self, tuples, na_tuple): assert all(isna(x) for x in result_na) else: assert isna(result_na) + + @pytest.mark.parametrize('new_closed', [ + 'left', 'right', 'both', 'neither']) + def test_set_closed(self, name, closed, new_closed): + # GH 21670 + index = interval_range(0, 5, closed=closed, name=name) + result = index.set_closed(new_closed) + expected = interval_range(0, 5, closed=new_closed, name=name) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize('bad_closed', ['foo', 10, 'LEFT', True, False]) + def test_set_closed_errors(self, bad_closed): + # GH 21670 + index = interval_range(0, 5) + msg = "invalid option for 'closed': {closed}".format(closed=bad_closed) + with tm.assert_raises_regex(ValueError, msg): + index.set_closed(bad_closed)
- [X] closes #21670 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21711
2018-07-03T01:05:47Z
2018-07-03T20:14:59Z
2018-07-03T20:14:59Z
2018-09-24T17:22:36Z
remove unused cimport, parametrize test
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index b46a05a0842c3..2179999859dbb 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -435,4 +435,4 @@ def get_blkno_indexers(int64_t[:] blknos, bint group=True): res_view[i] = diff i += 1 - yield blkno, result \ No newline at end of file + yield blkno, result diff --git a/pandas/_libs/writers.pyx b/pandas/_libs/writers.pyx index 6f07d04b3fad3..77d8ca81258a0 100644 --- a/pandas/_libs/writers.pyx +++ b/pandas/_libs/writers.pyx @@ -16,8 +16,6 @@ cimport numpy as cnp from numpy cimport ndarray, uint8_t cnp.import_array() -cimport util - ctypedef fused pandas_string: str diff --git a/pandas/tests/sparse/test_libsparse.py b/pandas/tests/sparse/test_libsparse.py index 7719ea46503fd..3b90d93cee7a4 100644 --- a/pandas/tests/sparse/test_libsparse.py +++ b/pandas/tests/sparse/test_libsparse.py @@ -596,22 +596,9 @@ def _check_case(xloc, xlen, yloc, ylen, eloc, elen): check_cases(_check_case) - -# too cute? oh but how I abhor code duplication -check_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv'] - - -def make_optestf(op): - def f(self): - sparse_op = getattr(splib, 'sparse_%s_float64' % op) - python_op = getattr(operator, op) + @pytest.mark.parametrize('opname', + ['add', 'sub', 'mul', 'truediv', 'floordiv']) + def test_op(self, opname): + sparse_op = getattr(splib, 'sparse_%s_float64' % opname) + python_op = getattr(operator, opname) self._op_tests(sparse_op, python_op) - - f.__name__ = 'test_%s' % op - return f - - -for op in check_ops: - g = make_optestf(op) - setattr(TestSparseOperators, g.__name__, g) - del g
https://api.github.com/repos/pandas-dev/pandas/pulls/21710
2018-07-02T23:39:09Z
2018-07-03T14:22:38Z
2018-07-03T14:22:38Z
2018-07-03T14:47:24Z
DOC: move whatsnew on performance from 0.23.2 to 0.24.0
diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index 1ca693755b3c6..41d370f88f396 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -59,19 +59,6 @@ Fixed Regressions - Bug in :meth:`Timestamp.ceil` and :meth:`Timestamp.floor` when timestamp is a multiple of the rounding frequency (:issue:`21262`) - Fixed regression in :func:`to_clipboard` that defaulted to copying dataframes with space delimited instead of tab delimited (:issue:`21104`) -.. _whatsnew_0232.performance: - -Performance Improvements -~~~~~~~~~~~~~~~~~~~~~~~~ - -- Improved performance of membership checks in :class:`Categorical` and :class:`CategoricalIndex` - (i.e. ``x in cat``-style checks are much faster). :meth:`CategoricalIndex.contains` - is likewise much faster (:issue:`21369`, :issue:`21508`) -- Improved performance of :meth:`HDFStore.groups` (and dependent functions like - :meth:`~HDFStore.keys`. (i.e. ``x in store`` checks are much faster) - (:issue:`21372`) -- Improved performance of :meth:`MultiIndex.is_unique` (:issue:`21522`) -- Documentation Changes ~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 0ca5b9cdf1d57..f3fdde6814742 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -201,6 +201,12 @@ Performance Improvements - Improved performance of :func:`Series.describe` in case of numeric dtpyes (:issue:`21274`) - Improved performance of :func:`pandas.core.groupby.GroupBy.rank` when dealing with tied rankings (:issue:`21237`) - Improved performance of :func:`DataFrame.set_index` with columns consisting of :class:`Period` objects (:issue:`21582`,:issue:`21606`) +- Improved performance of membership checks in :class:`Categorical` and :class:`CategoricalIndex` + (i.e. ``x in cat``-style checks are much faster). :meth:`CategoricalIndex.contains` + is likewise much faster (:issue:`21369`, :issue:`21508`) +- Improved performance of :meth:`HDFStore.groups` (and dependent functions like + :meth:`~HDFStore.keys`. (i.e. ``x in store`` checks are much faster) + (:issue:`21372`) - .. _whatsnew_0240.docs:
I did not backport the performance improvements in my backporting PRs for now, so this moves that section to 0.24.0.txt. (my rationale: let's be conservative for bug fix releases, performance improvements (if they are not fixing severe performance regressions) are not strictly needed in a bug fix release).
https://api.github.com/repos/pandas-dev/pandas/pulls/21709
2018-07-02T15:51:38Z
2018-07-02T23:23:02Z
2018-07-02T23:23:02Z
2018-07-02T23:23:06Z
Release 0.23.2 backports part II
diff --git a/.travis.yml b/.travis.yml index 4e25380a7d941..2d2a0bc019c80 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,6 +35,11 @@ matrix: language: generic env: - JOB="3.5, OSX" ENV_FILE="ci/travis-35-osx.yaml" TEST_ARGS="--skip-slow --skip-network" + + - dist: trusty + env: + - JOB="3.7" ENV_FILE="ci/travis-37.yaml" TEST_ARGS="--skip-slow --skip-network" + - dist: trusty env: - JOB="2.7, locale, slow, old NumPy" ENV_FILE="ci/travis-27-locale.yaml" LOCALE_OVERRIDE="zh_CN.UTF-8" SLOW=true diff --git a/MANIFEST.in b/MANIFEST.in index 9773019c6e6e0..b417b8890fa24 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -3,27 +3,39 @@ include LICENSE include RELEASE.md include README.md include setup.py -include pyproject.toml graft doc prune doc/build +graft LICENSES + graft pandas -global-exclude *.so -global-exclude *.pyd +global-exclude *.bz2 +global-exclude *.csv +global-exclude *.dta +global-exclude *.gz +global-exclude *.h5 +global-exclude *.html +global-exclude *.json +global-exclude *.msgpack +global-exclude *.pickle +global-exclude *.png global-exclude *.pyc +global-exclude *.pyd +global-exclude *.sas7bdat +global-exclude *.so +global-exclude *.xls +global-exclude *.xlsm +global-exclude *.xlsx +global-exclude *.xpt +global-exclude *.xz +global-exclude *.zip global-exclude *~ -global-exclude \#* -global-exclude .git* global-exclude .DS_Store -global-exclude *.png +global-exclude .git* +global-exclude \#* -# include examples/data/* -# recursive-include examples *.py -# recursive-include doc/source * -# recursive-include doc/sphinxext * -# recursive-include LICENSES * include versioneer.py include pandas/_version.py include pandas/io/formats/templates/*.tpl diff --git a/ci/script_single.sh b/ci/script_single.sh index f376c920ac71b..60e2fbb33ee5d 100755 --- a/ci/script_single.sh +++ b/ci/script_single.sh @@ -25,12 +25,12 @@ if [ "$DOC" ]; then echo "We are not running pytest as this is a doc-build" elif [ "$COVERAGE" ]; then - echo pytest -s -m "single" --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas - pytest -s -m "single" --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas + echo pytest -s -m "single" -r xXs --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas + pytest -s -m "single" -r xXs --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas else - echo pytest -m "single" -r xX --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas - pytest -m "single" -r xX --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas # TODO: doctest + echo pytest -m "single" -r xXs --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas + pytest -m "single" -r xXs --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas # TODO: doctest fi diff --git a/ci/travis-37.yaml b/ci/travis-37.yaml new file mode 100644 index 0000000000000..8b255c9e6ec72 --- /dev/null +++ b/ci/travis-37.yaml @@ -0,0 +1,14 @@ +name: pandas +channels: + - defaults + - conda-forge + - c3i_test +dependencies: + - python=3.7 + - cython + - numpy + - python-dateutil + - nomkl + - pytz + - pytest + - pytest-xdist diff --git a/doc/source/install.rst b/doc/source/install.rst index 6054be112f52c..846170f9f0fa5 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -43,7 +43,7 @@ For more information, see the `Python 3 statement`_ and the `Porting to Python 3 Python version support ---------------------- -Officially Python 2.7, 3.5, and 3.6. +Officially Python 2.7, 3.5, 3.6, and 3.7. Installing pandas ----------------- diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index db25bcf8113f5..a52ba22cf36d2 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -97,8 +97,8 @@ Bug Fixes **Data-type specific** -- Bug in :meth:`Series.str.replace()` where the method throws `TypeError` on Python 3.5.2 (:issue: `21078`) -- Bug in :class:`Timedelta`: where passing a float with a unit would prematurely round the float precision (:issue: `14156`) +- Bug in :meth:`Series.str.replace()` where the method throws `TypeError` on Python 3.5.2 (:issue:`21078`) +- Bug in :class:`Timedelta`: where passing a float with a unit would prematurely round the float precision (:issue:`14156`) - Bug in :func:`pandas.testing.assert_index_equal` which raised ``AssertionError`` incorrectly, when comparing two :class:`CategoricalIndex` objects with param ``check_categorical=False`` (:issue:`19776`) **Sparse** @@ -110,12 +110,12 @@ Bug Fixes - Bug in :meth:`Series.reset_index` where appropriate error was not raised with an invalid level name (:issue:`20925`) - Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`) - Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`) -- Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, issue:`21253`) +- Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, :issue:`21253`) - Bug in :meth:`MultiIndex.sort_index` which was not guaranteed to sort correctly with ``level=1``; this was also causing data misalignment in particular :meth:`DataFrame.stack` operations (:issue:`20994`, :issue:`20945`, :issue:`21052`) **Plotting** -- New keywords (sharex, sharey) to turn on/off sharing of x/y-axis by subplots generated with pandas.DataFrame().groupby().boxplot() (:issue: `20968`) +- New keywords (sharex, sharey) to turn on/off sharing of x/y-axis by subplots generated with pandas.DataFrame().groupby().boxplot() (:issue:`20968`) **I/O** diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index 53ca4c0d1c144..61d1b83ea8f2e 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -6,10 +6,46 @@ v0.23.2 This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes and bug fixes. We recommend that all users upgrade to this version. +.. note:: + + Pandas 0.23.2 is first pandas release that's compatible with + Python 3.7 (:issue:`20552`) + + .. contents:: What's new in v0.23.2 :local: :backlinks: none +.. _whatsnew_0232.enhancements: + +Logical Reductions over Entire DataFrame +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:meth:`DataFrame.all` and :meth:`DataFrame.any` now accept ``axis=None`` to reduce over all axes to a scalar (:issue:`19976`) + +.. ipython:: python + + df = pd.DataFrame({"A": [1, 2], "B": [True, False]}) + df.all(axis=None) + + +This also provides compatibility with NumPy 1.15, which now dispatches to ``DataFrame.all``. +With NumPy 1.15 and pandas 0.23.1 or earlier, :func:`numpy.all` will no longer reduce over every axis: + +.. code-block:: python + + >>> # NumPy 1.15, pandas 0.23.1 + >>> np.any(pd.DataFrame({"A": [False], "B": [False]})) + A False + B False + dtype: bool + +With pandas 0.23.2, that will correctly return False, as it did with NumPy < 1.15. + +.. ipython:: python + + np.any(pd.DataFrame({"A": [False], "B": [False]})) + .. _whatsnew_0232.fixed_regressions: @@ -17,8 +53,14 @@ Fixed Regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`to_csv` when handling file-like object incorrectly (:issue:`21471`) +- Re-allowed duplicate level names of a ``MultiIndex``. Accessing a level that has a duplicate name by name still raises an error (:issue:`19029`). - Bug in both :meth:`DataFrame.first_valid_index` and :meth:`Series.first_valid_index` raised for a row index having duplicate values (:issue:`21441`) -- +- Fixed printing of DataFrames with hierarchical columns with long names (:issue:`21180`) +- Fixed regression in :meth:`~DataFrame.reindex` and :meth:`~DataFrame.groupby` + with a MultiIndex or multiple keys that contains categorical datetime-like values (:issue:`21390`). +- Fixed regression in unary negative operations with object dtype (:issue:`21380`) +- Bug in :meth:`Timestamp.ceil` and :meth:`Timestamp.floor` when timestamp is a multiple of the rounding frequency (:issue:`21262`) +- Fixed regression in :func:`to_clipboard` that defaulted to copying dataframes with space delimited instead of tab delimited (:issue:`21104`) .. _whatsnew_0232.performance: @@ -34,6 +76,11 @@ Documentation Changes - - +Build Changes +------------- + +- The source and binary distributions no longer include test data files, resulting in smaller download sizes. Tests relying on these data files will be skipped when using ``pandas.test()``. (:issue:`19320`) + .. _whatsnew_0232.bug_fixes: Bug Fixes diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index ba5ebdab82ddc..123ccebf83a56 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -59,42 +59,51 @@ cdef inline object create_timestamp_from_ts(int64_t value, def round_ns(values, rounder, freq): + """ Applies rounding function at given frequency Parameters ---------- - values : int, :obj:`ndarray` - rounder : function + values : :obj:`ndarray` + rounder : function, eg. 'ceil', 'floor', 'round' freq : str, obj Returns ------- - int or :obj:`ndarray` + :obj:`ndarray` """ + from pandas.tseries.frequencies import to_offset unit = to_offset(freq).nanos + + # GH21262 If the Timestamp is multiple of the freq str + # don't apply any rounding + mask = values % unit == 0 + if mask.all(): + return values + r = values.copy() + if unit < 1000: # for nano rounding, work with the last 6 digits separately # due to float precision buff = 1000000 - r = (buff * (values // buff) + unit * - (rounder((values % buff) * (1 / float(unit)))).astype('i8')) + r[~mask] = (buff * (values[~mask] // buff) + + unit * (rounder((values[~mask] % buff) * + (1 / float(unit)))).astype('i8')) else: if unit % 1000 != 0: msg = 'Precision will be lost using frequency: {}' warnings.warn(msg.format(freq)) - # GH19206 # to deal with round-off when unit is large if unit >= 1e9: divisor = 10 ** int(np.log10(unit / 1e7)) else: divisor = 10 - - r = (unit * rounder((values * (divisor / float(unit))) / divisor) - .astype('i8')) - + r[~mask] = (unit * rounder((values[~mask] * + (divisor / float(unit))) / divisor) + .astype('i8')) return r @@ -649,7 +658,10 @@ class Timestamp(_Timestamp): else: value = self.value - r = round_ns(value, rounder, freq) + value = np.array([value], dtype=np.int64) + + # Will only ever contain 1 element for timestamp + r = round_ns(value, rounder, freq)[0] result = Timestamp(r, unit='ns') if self.tz is not None: result = result.tz_localize(self.tz) diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 5ae22694d0da7..28a55133e68aa 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -40,10 +40,11 @@ from collections import namedtuple PY2 = sys.version_info[0] == 2 -PY3 = (sys.version_info[0] >= 3) -PY35 = (sys.version_info >= (3, 5)) -PY36 = (sys.version_info >= (3, 6)) -PYPY = (platform.python_implementation() == 'PyPy') +PY3 = sys.version_info[0] >= 3 +PY35 = sys.version_info >= (3, 5) +PY36 = sys.version_info >= (3, 6) +PY37 = sys.version_info >= (3, 7) +PYPY = platform.python_implementation() == 'PyPy' try: import __builtin__ as builtins diff --git a/pandas/conftest.py b/pandas/conftest.py index 9d806a91f37f7..ead357747666d 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1,5 +1,8 @@ +import os + import pytest +import pandas import numpy as np import pandas as pd from pandas.compat import PY3 @@ -15,6 +18,8 @@ def pytest_addoption(parser): help="run high memory tests") parser.addoption("--only-slow", action="store_true", help="run only slow tests") + parser.addoption("--strict-data-files", action="store_true", + help="Fail if a test is skipped for missing data file.") def pytest_runtest_setup(item): @@ -129,6 +134,43 @@ def join_type(request): return request.param +@pytest.fixture +def datapath(request): + """Get the path to a data file. + + Parameters + ---------- + path : str + Path to the file, relative to ``pandas/tests/`` + + Returns + ------- + path : path including ``pandas/tests``. + + Raises + ------ + ValueError + If the path doesn't exist and the --strict-data-files option is set. + """ + def deco(*args): + path = os.path.join('pandas', 'tests', *args) + if not os.path.exists(path): + if request.config.getoption("--strict-data-files"): + msg = "Could not find file {} and --strict-data-files is set." + raise ValueError(msg.format(path)) + else: + msg = "Could not find {}." + pytest.skip(msg.format(path)) + return path + return deco + + +@pytest.fixture +def iris(datapath): + """The iris dataset as a DataFrame.""" + return pandas.read_csv(datapath('data', 'iris.csv')) + + @pytest.fixture(params=['nlargest', 'nsmallest']) def nselect_method(request): """ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9f6e834f0a25f..2a40dd28a6fd7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6844,13 +6844,18 @@ def _count_level(self, level, axis=0, numeric_only=False): def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds): - axis = self._get_axis_number(axis) + if axis is None and filter_type == 'bool': + labels = None + constructor = None + else: + # TODO: Make other agg func handle axis=None properly + axis = self._get_axis_number(axis) + labels = self._get_agg_axis(axis) + constructor = self._constructor def f(x): return op(x, axis=axis, skipna=skipna, **kwds) - labels = self._get_agg_axis(axis) - # exclude timedelta/datetime unless we are uniform types if axis == 1 and self._is_mixed_type and self._is_datelike_mixed_type: numeric_only = True @@ -6859,6 +6864,13 @@ def f(x): try: values = self.values result = f(values) + + if (filter_type == 'bool' and is_object_dtype(values) and + axis is None): + # work around https://github.com/numpy/numpy/issues/10489 + # TODO: combine with hasattr(result, 'dtype') further down + # hard since we don't have `values` down there. + result = np.bool_(result) except Exception as e: # try by-column first @@ -6925,7 +6937,9 @@ def f(x): if axis == 0: result = coerce_to_dtypes(result, self.dtypes) - return Series(result, index=labels) + if constructor is not None: + result = Series(result, index=labels) + return result def nunique(self, axis=0, dropna=True): """ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 612ee7cb42021..02462218e8b02 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -27,6 +27,7 @@ is_dict_like, is_re_compilable, is_period_arraylike, + is_object_dtype, pandas_dtype) from pandas.core.dtypes.cast import maybe_promote, maybe_upcast_putmask from pandas.core.dtypes.inference import is_hashable @@ -1117,7 +1118,8 @@ def __neg__(self): values = com._values_from_object(self) if is_bool_dtype(values): arr = operator.inv(values) - elif (is_numeric_dtype(values) or is_timedelta64_dtype(values)): + elif (is_numeric_dtype(values) or is_timedelta64_dtype(values) + or is_object_dtype(values)): arr = operator.neg(values) else: raise TypeError("Unary negative expects numeric dtype, not {}" @@ -1128,7 +1130,8 @@ def __pos__(self): values = com._values_from_object(self) if (is_bool_dtype(values) or is_period_arraylike(values)): arr = values - elif (is_numeric_dtype(values) or is_timedelta64_dtype(values)): + elif (is_numeric_dtype(values) or is_timedelta64_dtype(values) + or is_object_dtype(values)): arr = operator.pos(values) else: raise TypeError("Unary plus expects numeric dtype, not {}" @@ -8729,6 +8732,8 @@ def pct_change(self, periods=1, fill_method='pad', limit=None, freq=None, return rs def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs): + if axis is None: + raise ValueError("Must specify 'axis' when aggregating by level.") grouped = self.groupby(level=level, axis=axis, sort=False) if hasattr(grouped, name) and skipna: return getattr(grouped, name)(**kwargs) @@ -9055,8 +9060,15 @@ def _doc_parms(cls): Parameters ---------- -axis : int, default 0 - Select the axis which can be 0 for indices and 1 for columns. +axis : {0 or 'index', 1 or 'columns', None}, default 0 + Indicate which axis or axes should be reduced. + + * 0 / 'index' : reduce the index, return a Series whose index is the + original column labels. + * 1 / 'columns' : reduce the columns, return a Series whose index is the + original index. + * None : reduce all axes, return a scalar. + skipna : boolean, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. @@ -9078,9 +9090,9 @@ def _doc_parms(cls): %(examples)s""" _all_doc = """\ -Return whether all elements are True over series or dataframe axis. +Return whether all elements are True, potentially over an axis. -Returns True if all elements within a series or along a dataframe +Returns True if all elements within a series or along a Dataframe axis are non-zero, not-empty or not-False.""" _all_examples = """\ @@ -9093,7 +9105,7 @@ def _doc_parms(cls): >>> pd.Series([True, False]).all() False -Dataframes +DataFrames Create a dataframe from a dictionary. @@ -9110,12 +9122,17 @@ def _doc_parms(cls): col2 False dtype: bool -Adding axis=1 argument will check if row-wise values all return True. +Specify ``axis='columns'`` to check if row-wise values all return True. ->>> df.all(axis=1) +>>> df.all(axis='columns') 0 True 1 False dtype: bool + +Or ``axis=None`` for whether every value is True. + +>>> df.all(axis=None) +False """ _all_see_also = """\ @@ -9481,6 +9498,11 @@ def _doc_parms(cls): 1 False dtype: bool +Aggregating over the entire DataFrame with ``axis=None``. + +>>> df.any(axis=None) +True + `any` for an empty DataFrame is an empty Series. >>> pd.DataFrame([]).any() @@ -9651,22 +9673,17 @@ def _make_logical_function(cls, name, name1, name2, axis_descr, desc, f, @Substitution(outname=name, desc=desc, name1=name1, name2=name2, axis_descr=axis_descr, examples=examples, see_also=see_also) @Appender(_bool_doc) - def logical_func(self, axis=None, bool_only=None, skipna=None, level=None, + def logical_func(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): nv.validate_logical_func(tuple(), kwargs, fname=name) - if skipna is None: - skipna = True - if axis is None: - axis = self._stat_axis_number if level is not None: if bool_only is not None: raise NotImplementedError("Option bool_only is not " "implemented with option level.") return self._agg_by_level(name, axis=axis, level=level, skipna=skipna) - return self._reduce(f, axis=axis, skipna=skipna, - numeric_only=bool_only, filter_type='bool', - name=name) + return self._reduce(f, name, axis=axis, skipna=skipna, + numeric_only=bool_only, filter_type='bool') return set_function_name(logical_func, name, cls) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index eb9d7efc06c27..23a655b9a51ee 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -160,7 +160,7 @@ class IntervalIndex(IntervalMixin, Index): dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Attributes ---------- @@ -438,7 +438,7 @@ def from_breaks(cls, breaks, closed='right', name=None, copy=False, dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples -------- @@ -568,7 +568,7 @@ def from_intervals(cls, data, closed=None, name=None, copy=False, dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples -------- @@ -619,7 +619,7 @@ def from_tuples(cls, data, closed='right', name=None, copy=False, dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples -------- @@ -671,7 +671,7 @@ def to_tuples(self, na_tuple=True): Returns NA as a tuple if True, ``(nan, nan)``, or just as the NA value itself if False, ``nan``. - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples -------- diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 80bf73cfe7dd3..9a4aa15f4cc25 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -11,6 +11,8 @@ from pandas.compat.numpy import function as nv from pandas import compat +from pandas.core.dtypes.dtypes import ( + ExtensionDtype, PandasExtensionDtype) from pandas.core.dtypes.common import ( _ensure_int64, _ensure_platform_int, @@ -672,30 +674,18 @@ def _set_names(self, names, level=None, validate=True): if level is None: level = range(self.nlevels) - used = {} else: level = [self._get_level_number(l) for l in level] - used = {self.levels[l].name: l - for l in set(range(self.nlevels)) - set(level)} # set the name for l, name in zip(level, names): if name is not None: - # GH 20527 # All items in 'names' need to be hashable: if not is_hashable(name): raise TypeError('{}.name must be a hashable type' .format(self.__class__.__name__)) - - if name in used: - raise ValueError( - 'Duplicated level name: "{}", assigned to ' - 'level {}, is already used for level ' - '{}.'.format(name, l, used[name])) - self.levels[l].rename(name, inplace=True) - used[name] = l names = property(fset=_set_names, fget=_get_names, doc="Names of levels in MultiIndex") @@ -820,20 +810,16 @@ def values(self): return self._tuples values = [] - for lev, lab in zip(self.levels, self.labels): - # Need to box timestamps, etc. - box = hasattr(lev, '_box_values') - # Try to minimize boxing. - if box and len(lev) > len(lab): - taken = lev._box_values(algos.take_1d(lev._ndarray_values, - lab)) - elif box: - taken = algos.take_1d(lev._box_values(lev._ndarray_values), - lab, - fill_value=lev._na_value) - else: - taken = algos.take_1d(np.asarray(lev._values), lab) - values.append(taken) + + for i in range(self.nlevels): + vals = self._get_level_values(i) + if is_categorical_dtype(vals): + vals = vals.get_values() + if (isinstance(vals.dtype, (PandasExtensionDtype, ExtensionDtype)) + or hasattr(vals, '_box_values')): + vals = vals.astype(object) + vals = np.array(vals, copy=False) + values.append(vals) self._tuples = lib.fast_zip(values) return self._tuples @@ -2935,6 +2921,13 @@ def isin(self, values, level=None): else: return np.lib.arraysetops.in1d(labs, sought_labels) + def _reference_duplicate_name(self, name): + """ + Returns True if the name refered to in self.names is duplicated. + """ + # count the times name equals an element in self.names. + return sum(name == n for n in self.names) > 1 + MultiIndex._add_numeric_methods_disabled() MultiIndex._add_numeric_methods_add_sub_disabled() diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 16e64192fdb20..bad0dd79aaedd 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -1143,13 +1143,26 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None, raise NotImplementedError('Panel.{0} does not implement ' 'numeric_only.'.format(name)) - axis_name = self._get_axis_name(axis) - axis_number = self._get_axis_number(axis_name) + if axis is None and filter_type == 'bool': + # labels = None + # constructor = None + axis_number = None + axis_name = None + else: + # TODO: Make other agg func handle axis=None properly + axis = self._get_axis_number(axis) + # labels = self._get_agg_axis(axis) + # constructor = self._constructor + axis_name = self._get_axis_name(axis) + axis_number = self._get_axis_number(axis_name) + f = lambda x: op(x, axis=axis_number, skipna=skipna, **kwds) with np.errstate(all='ignore'): result = f(self.values) + if axis is None and filter_type == 'bool': + return np.bool_(result) axes = self._get_plane_axes(axis_name) if result.ndim == 2 and axis_name != self._info_axis_name: result = result.T diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 2757e0797a410..3d9e84954a63b 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -115,6 +115,12 @@ def __init__(self, values, index, level=-1, value_columns=None, self.index = index.remove_unused_levels() + if isinstance(self.index, MultiIndex): + if index._reference_duplicate_name(level): + msg = ("Ambiguous reference to {level}. The index " + "names are not unique.".format(level=level)) + raise ValueError(msg) + self.level = self.index._get_level_number(level) # when index includes `nan`, need to lift levels/strides by 1 @@ -528,6 +534,12 @@ def factorize(index): N, K = frame.shape + if isinstance(frame.columns, MultiIndex): + if frame.columns._reference_duplicate_name(level): + msg = ("Ambiguous reference to {level}. The column " + "names are not unique.".format(level=level)) + raise ValueError(msg) + # Will also convert negative level numbers and check if out of bounds. level_num = frame.columns._get_level_number(level) diff --git a/pandas/core/series.py b/pandas/core/series.py index 6975dd8fc918e..6b005c673c7cd 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3212,7 +3212,8 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None, delegate = self._values if isinstance(delegate, np.ndarray): # Validate that 'axis' is consistent with Series's single axis. - self._get_axis_number(axis) + if axis is not None: + self._get_axis_number(axis) if numeric_only: raise NotImplementedError('Series.{0} does not implement ' 'numeric_only.'.format(name)) diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py index dcc221ce978b3..b3f40b3a2429c 100644 --- a/pandas/io/clipboards.py +++ b/pandas/io/clipboards.py @@ -1,6 +1,7 @@ """ io on the clipboard """ from pandas import compat, get_option, option_context, DataFrame -from pandas.compat import StringIO, PY2 +from pandas.compat import StringIO, PY2, PY3 +import warnings def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover @@ -32,7 +33,7 @@ def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover # try to decode (if needed on PY3) # Strange. linux py33 doesn't complain, win py33 does - if compat.PY3: + if PY3: try: text = compat.bytes_to_str( text, encoding=(kwargs.get('encoding') or @@ -55,11 +56,27 @@ def read_clipboard(sep=r'\s+', **kwargs): # pragma: no cover counts = {x.lstrip().count('\t') for x in lines} if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0: - sep = r'\t' + sep = '\t' + # Edge case where sep is specified to be None, return to default if sep is None and kwargs.get('delim_whitespace') is None: sep = r'\s+' + # Regex separator currently only works with python engine. + # Default to python if separator is multi-character (regex) + if len(sep) > 1 and kwargs.get('engine') is None: + kwargs['engine'] = 'python' + elif len(sep) > 1 and kwargs.get('engine') == 'c': + warnings.warn('read_clipboard with regex separator does not work' + ' properly with c engine') + + # In PY2, the c table reader first encodes text with UTF-8 but Python + # table reader uses the format of the passed string. For consistency, + # encode strings for python engine so that output from python and c + # engines produce consistent results + if kwargs.get('engine') == 'python' and PY2: + text = text.encode('utf-8') + return read_table(StringIO(text), sep=sep, **kwargs) @@ -99,7 +116,7 @@ def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover if excel: try: if sep is None: - sep = r'\t' + sep = '\t' buf = StringIO() # clipboard_set (pyperclip) expects unicode obj.to_csv(buf, sep=sep, encoding='utf-8', **kwargs) @@ -108,8 +125,11 @@ def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover text = text.decode('utf-8') clipboard_set(text) return - except: - pass + except TypeError: + warnings.warn('to_clipboard in excel mode requires a single ' + 'character separator.') + elif sep is not None: + warnings.warn('to_clipboard with excel=False ignores the sep argument') if isinstance(obj, DataFrame): # str(df) has various unhelpful defaults, like truncation diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 12201f62946ac..c46f4b5ad9c18 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -636,10 +636,14 @@ def to_string(self): mid = int(round(n_cols / 2.)) mid_ix = col_lens.index[mid] col_len = col_lens[mid_ix] - adj_dif -= (col_len + 1) # adjoin adds one + # adjoin adds one + adj_dif -= (col_len + 1) col_lens = col_lens.drop(mid_ix) n_cols = len(col_lens) - max_cols_adj = n_cols - self.index # subtract index column + # subtract index column + max_cols_adj = n_cols - self.index + # GH-21180. Ensure that we print at least two. + max_cols_adj = max(max_cols_adj, 2) self.max_cols_adj = max_cols_adj # Call again _chk_truncate to cut frame appropriately @@ -778,7 +782,7 @@ def space_format(x, y): str_columns = list(zip(*[[space_format(x, y) for y in x] for x in fmt_columns])) - if self.sparsify: + if self.sparsify and len(str_columns): str_columns = _sparsify(str_columns) str_columns = [list(x) for x in zip(*str_columns)] diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 164d6746edec0..21961906c39bb 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -130,19 +130,27 @@ def test_set_index2(self): result = df.set_index(df.C) assert result.index.name == 'C' - @pytest.mark.parametrize('level', ['a', pd.Series(range(3), name='a')]) + @pytest.mark.parametrize( + 'level', ['a', pd.Series(range(0, 8, 2), name='a')]) def test_set_index_duplicate_names(self, level): - # GH18872 + # GH18872 - GH19029 df = pd.DataFrame(np.arange(8).reshape(4, 2), columns=['a', 'b']) # Pass an existing level name: df.index.name = 'a' - pytest.raises(ValueError, df.set_index, level, append=True) - pytest.raises(ValueError, df.set_index, [level], append=True) - - # Pass twice the same level name: - df.index.name = 'c' - pytest.raises(ValueError, df.set_index, [level, level]) + expected = pd.MultiIndex.from_tuples([(0, 0), (1, 2), (2, 4), (3, 6)], + names=['a', 'a']) + result = df.set_index(level, append=True) + tm.assert_index_equal(result.index, expected) + result = df.set_index([level], append=True) + tm.assert_index_equal(result.index, expected) + + # Pass twice the same level name (only works with passing actual data) + if isinstance(level, pd.Series): + result = df.set_index([level, level]) + expected = pd.MultiIndex.from_tuples( + [(0, 0), (2, 2), (4, 4), (6, 6)], names=['a', 'a']) + tm.assert_index_equal(result.index, expected) def test_set_index_nonuniq(self): df = DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'], @@ -617,6 +625,19 @@ def test_reorder_levels(self): index=e_idx) assert_frame_equal(result, expected) + result = df.reorder_levels([0, 0, 0]) + e_idx = MultiIndex(levels=[['bar'], ['bar'], ['bar']], + labels=[[0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0]], + names=['L0', 'L0', 'L0']) + expected = DataFrame({'A': np.arange(6), 'B': np.arange(6)}, + index=e_idx) + assert_frame_equal(result, expected) + + result = df.reorder_levels(['L0', 'L0', 'L0']) + assert_frame_equal(result, expected) + def test_reset_index(self): stacked = self.frame.stack()[::2] stacked = DataFrame({'foo': stacked, 'bar': stacked}) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 4197339ff6e03..437d3a9d24730 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -15,7 +15,7 @@ from pandas.compat import lrange, PY35 from pandas import (compat, isna, notna, DataFrame, Series, MultiIndex, date_range, Timestamp, Categorical, - _np_version_under1p12, _np_version_under1p15) + _np_version_under1p12) import pandas as pd import pandas.core.nanops as nanops import pandas.core.algorithms as algorithms @@ -1139,11 +1139,35 @@ def test_any_all(self): self._check_bool_op('any', np.any, has_skipna=True, has_bool_only=True) self._check_bool_op('all', np.all, has_skipna=True, has_bool_only=True) - df = DataFrame(randn(10, 4)) > 0 - df.any(1) - df.all(1) - df.any(1, bool_only=True) - df.all(1, bool_only=True) + def test_any_all_extra(self): + df = DataFrame({ + 'A': [True, False, False], + 'B': [True, True, False], + 'C': [True, True, True], + }, index=['a', 'b', 'c']) + result = df[['A', 'B']].any(1) + expected = Series([True, True, False], index=['a', 'b', 'c']) + tm.assert_series_equal(result, expected) + + result = df[['A', 'B']].any(1, bool_only=True) + tm.assert_series_equal(result, expected) + + result = df.all(1) + expected = Series([True, False, False], index=['a', 'b', 'c']) + tm.assert_series_equal(result, expected) + + result = df.all(1, bool_only=True) + tm.assert_series_equal(result, expected) + + # Axis is None + result = df.all(axis=None).item() + assert result is False + + result = df.any(axis=None).item() + assert result is True + + result = df[['C']].all(axis=None).item() + assert result is True # skip pathological failure cases # class CantNonzero(object): @@ -1165,6 +1189,86 @@ def test_any_all(self): # df.any(1, bool_only=True) # df.all(1, bool_only=True) + @pytest.mark.parametrize('func, data, expected', [ + (np.any, {}, False), + (np.all, {}, True), + (np.any, {'A': []}, False), + (np.all, {'A': []}, True), + (np.any, {'A': [False, False]}, False), + (np.all, {'A': [False, False]}, False), + (np.any, {'A': [True, False]}, True), + (np.all, {'A': [True, False]}, False), + (np.any, {'A': [True, True]}, True), + (np.all, {'A': [True, True]}, True), + + (np.any, {'A': [False], 'B': [False]}, False), + (np.all, {'A': [False], 'B': [False]}, False), + + (np.any, {'A': [False, False], 'B': [False, True]}, True), + (np.all, {'A': [False, False], 'B': [False, True]}, False), + + # other types + (np.all, {'A': pd.Series([0.0, 1.0], dtype='float')}, False), + (np.any, {'A': pd.Series([0.0, 1.0], dtype='float')}, True), + (np.all, {'A': pd.Series([0, 1], dtype=int)}, False), + (np.any, {'A': pd.Series([0, 1], dtype=int)}, True), + pytest.param(np.all, {'A': pd.Series([0, 1], dtype='M8[ns]')}, False, + marks=[td.skip_if_np_lt_115]), + pytest.param(np.any, {'A': pd.Series([0, 1], dtype='M8[ns]')}, True, + marks=[td.skip_if_np_lt_115]), + pytest.param(np.all, {'A': pd.Series([1, 2], dtype='M8[ns]')}, True, + marks=[td.skip_if_np_lt_115]), + pytest.param(np.any, {'A': pd.Series([1, 2], dtype='M8[ns]')}, True, + marks=[td.skip_if_np_lt_115]), + pytest.param(np.all, {'A': pd.Series([0, 1], dtype='m8[ns]')}, False, + marks=[td.skip_if_np_lt_115]), + pytest.param(np.any, {'A': pd.Series([0, 1], dtype='m8[ns]')}, True, + marks=[td.skip_if_np_lt_115]), + pytest.param(np.all, {'A': pd.Series([1, 2], dtype='m8[ns]')}, True, + marks=[td.skip_if_np_lt_115]), + pytest.param(np.any, {'A': pd.Series([1, 2], dtype='m8[ns]')}, True, + marks=[td.skip_if_np_lt_115]), + (np.all, {'A': pd.Series([0, 1], dtype='category')}, False), + (np.any, {'A': pd.Series([0, 1], dtype='category')}, True), + (np.all, {'A': pd.Series([1, 2], dtype='category')}, True), + (np.any, {'A': pd.Series([1, 2], dtype='category')}, True), + + # # Mix + # GH-21484 + # (np.all, {'A': pd.Series([10, 20], dtype='M8[ns]'), + # 'B': pd.Series([10, 20], dtype='m8[ns]')}, True), + ]) + def test_any_all_np_func(self, func, data, expected): + # https://github.com/pandas-dev/pandas/issues/19976 + data = DataFrame(data) + result = func(data) + assert isinstance(result, np.bool_) + assert result.item() is expected + + # method version + result = getattr(DataFrame(data), func.__name__)(axis=None) + assert isinstance(result, np.bool_) + assert result.item() is expected + + def test_any_all_object(self): + # https://github.com/pandas-dev/pandas/issues/19976 + result = np.all(DataFrame(columns=['a', 'b'])).item() + assert result is True + + result = np.any(DataFrame(columns=['a', 'b'])).item() + assert result is False + + @pytest.mark.parametrize('method', ['any', 'all']) + def test_any_all_level_axis_none_raises(self, method): + df = DataFrame( + {"A": 1}, + index=MultiIndex.from_product([['A', 'B'], ['a', 'b']], + names=['out', 'in']) + ) + xpr = "Must specify 'axis' when aggregating by level." + with tm.assert_raises_regex(ValueError, xpr): + getattr(df, method)(axis=None, level='out') + def _check_bool_op(self, name, alternative, frame=None, has_skipna=True, has_bool_only=False): if frame is None: @@ -2071,9 +2175,6 @@ def test_clip_against_list_like(self, inplace, lower, axis, res): result = original tm.assert_frame_equal(result, expected, check_exact=True) - @pytest.mark.xfail( - not _np_version_under1p15, - reason="failing under numpy-dev gh-19976") @pytest.mark.parametrize("axis", [0, 1, None]) def test_clip_against_frame(self, axis): df = DataFrame(np.random.randn(1000, 2)) diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 0e0d6598f5101..004fb4eb0c128 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -10,7 +10,7 @@ import numpy as np from pandas.compat import lrange, lzip, u -from pandas import (compat, DataFrame, Series, Index, MultiIndex, +from pandas import (compat, DataFrame, Series, Index, MultiIndex, Categorical, date_range, isna) import pandas as pd @@ -1129,6 +1129,19 @@ def test_reindex_multi(self): assert_frame_equal(result, expected) + def test_reindex_multi_categorical_time(self): + # https://github.com/pandas-dev/pandas/issues/21390 + midx = pd.MultiIndex.from_product( + [Categorical(['a', 'b', 'c']), + Categorical(date_range("2012-01-01", periods=3, freq='H'))]) + df = pd.DataFrame({'a': range(len(midx))}, index=midx) + df2 = df.iloc[[0, 1, 2, 3, 4, 5, 6, 8]] + + result = df2.reindex(midx) + expected = pd.DataFrame( + {'a': [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx) + assert_frame_equal(result, expected) + data = [[1, 2, 3], [1, 2, 3]] @pytest.mark.parametrize('actual', [ diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index 5df50f3d7835b..fdf50805ad818 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -3,6 +3,7 @@ from __future__ import print_function from collections import deque from datetime import datetime +from decimal import Decimal import operator import pytest @@ -282,6 +283,17 @@ def test_neg_numeric(self, df, expected): assert_frame_equal(-df, expected) assert_series_equal(-df['a'], expected['a']) + @pytest.mark.parametrize('df, expected', [ + (np.array([1, 2], dtype=object), np.array([-1, -2], dtype=object)), + ([Decimal('1.0'), Decimal('2.0')], [Decimal('-1.0'), Decimal('-2.0')]), + ]) + def test_neg_object(self, df, expected): + # GH 21380 + df = pd.DataFrame({'a': df}) + expected = pd.DataFrame({'a': expected}) + assert_frame_equal(-df, expected) + assert_series_equal(-df['a'], expected['a']) + @pytest.mark.parametrize('df', [ pd.DataFrame({'a': ['a', 'b']}), pd.DataFrame({'a': pd.to_datetime(['2017-01-22', '1970-01-01'])}), @@ -307,6 +319,15 @@ def test_pos_numeric(self, df): @pytest.mark.parametrize('df', [ pd.DataFrame({'a': ['a', 'b']}), + pd.DataFrame({'a': np.array([-1, 2], dtype=object)}), + pd.DataFrame({'a': [Decimal('-1.0'), Decimal('2.0')]}), + ]) + def test_pos_object(self, df): + # GH 21380 + assert_frame_equal(+df, df) + assert_series_equal(+df['a'], df['a']) + + @pytest.mark.parametrize('df', [ pd.DataFrame({'a': pd.to_datetime(['2017-01-22', '1970-01-01'])}), ]) def test_pos_raises(self, df): diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index d05321abefca6..ebf6c5e37b916 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -560,6 +560,16 @@ def test_unstack_dtypes(self): assert left.shape == (3, 2) tm.assert_frame_equal(left, right) + def test_unstack_non_unique_index_names(self): + idx = MultiIndex.from_tuples([('a', 'b'), ('c', 'd')], + names=['c1', 'c1']) + df = DataFrame([1, 2], index=idx) + with pytest.raises(ValueError): + df.unstack('c1') + + with pytest.raises(ValueError): + df.T.stack('c1') + def test_unstack_unused_levels(self): # GH 17845: unused labels in index make unstack() cast int to float idx = pd.MultiIndex.from_product([['a'], ['A', 'B', 'C', 'D']])[:-1] diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index e0793b8e1bd64..d021396a7acb3 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -6,6 +6,7 @@ import numpy as np import pandas as pd +from pandas.compat import PY37 from pandas import (Index, MultiIndex, CategoricalIndex, DataFrame, Categorical, Series, qcut) from pandas.util.testing import assert_frame_equal, assert_series_equal @@ -205,6 +206,7 @@ def test_level_get_group(observed): assert_frame_equal(result, expected) +@pytest.mark.xfail(PY37, reason="flaky on 3.7, xref gh-21636") @pytest.mark.parametrize('ordered', [True, False]) def test_apply(ordered): # GH 10138 @@ -553,15 +555,11 @@ def test_as_index(): columns=['cat', 'A', 'B']) tm.assert_frame_equal(result, expected) - # another not in-axis grouper - s = Series(['a', 'b', 'b'], name='cat2') + # another not in-axis grouper (conflicting names in index) + s = Series(['a', 'b', 'b'], name='cat') result = df.groupby(['cat', s], as_index=False, observed=True).sum() tm.assert_frame_equal(result, expected) - # GH18872: conflicting names in desired index - with pytest.raises(ValueError): - df.groupby(['cat', s.rename('cat')], observed=True).sum() - # is original index dropped? group_columns = ['cat', 'A'] expected = DataFrame( @@ -852,3 +850,23 @@ def test_empty_prod(): result = df.groupby("A", observed=False).B.prod(min_count=1) expected = pd.Series([2, 1, np.nan], expected_idx, name='B') tm.assert_series_equal(result, expected) + + +def test_groupby_multiindex_categorical_datetime(): + # https://github.com/pandas-dev/pandas/issues/21390 + + df = pd.DataFrame({ + 'key1': pd.Categorical(list('abcbabcba')), + 'key2': pd.Categorical( + list(pd.date_range('2018-06-01 00', freq='1T', periods=3)) * 3), + 'values': np.arange(9), + }) + result = df.groupby(['key1', 'key2']).mean() + + idx = pd.MultiIndex.from_product( + [pd.Categorical(['a', 'b', 'c']), + pd.Categorical(pd.date_range('2018-06-01 00', freq='1T', periods=3))], + names=['key1', 'key2']) + expected = pd.DataFrame( + {'values': [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx) + assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index 9180bb0af3af3..801dcb91b124e 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -134,6 +134,21 @@ def test_round(self, tz): ts = '2016-10-17 12:00:00.001501031' DatetimeIndex([ts]).round('1010ns') + def test_no_rounding_occurs(self, tz): + # GH 21262 + rng = date_range(start='2016-01-01', periods=5, + freq='2Min', tz=tz) + + expected_rng = DatetimeIndex([ + Timestamp('2016-01-01 00:00:00', tz=tz, freq='2T'), + Timestamp('2016-01-01 00:02:00', tz=tz, freq='2T'), + Timestamp('2016-01-01 00:04:00', tz=tz, freq='2T'), + Timestamp('2016-01-01 00:06:00', tz=tz, freq='2T'), + Timestamp('2016-01-01 00:08:00', tz=tz, freq='2T'), + ]) + + tm.assert_index_equal(rng.round(freq='2T'), expected_rng) + @pytest.mark.parametrize('test_input, rounder, freq, expected', [ (['2117-01-01 00:00:45'], 'floor', '15s', ['2117-01-01 00:00:45']), (['2117-01-01 00:00:45'], 'ceil', '15s', ['2117-01-01 00:00:45']), @@ -143,6 +158,10 @@ def test_round(self, tz): ['1823-01-01 00:00:01.000000020']), (['1823-01-01 00:00:01'], 'floor', '1s', ['1823-01-01 00:00:01']), (['1823-01-01 00:00:01'], 'ceil', '1s', ['1823-01-01 00:00:01']), + (['2018-01-01 00:15:00'], 'ceil', '15T', ['2018-01-01 00:15:00']), + (['2018-01-01 00:15:00'], 'floor', '15T', ['2018-01-01 00:15:00']), + (['1823-01-01 03:00:00'], 'ceil', '3H', ['1823-01-01 03:00:00']), + (['1823-01-01 03:00:00'], 'floor', '3H', ['1823-01-01 03:00:00']), (('NaT', '1823-01-01 00:00:01'), 'floor', '1s', ('NaT', '1823-01-01 00:00:01')), (('NaT', '1823-01-01 00:00:01'), 'ceil', '1s', diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index df506ae9486ee..a7e90207c9ad7 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -12,8 +12,8 @@ import pandas as pd -from pandas import (CategoricalIndex, DataFrame, Index, MultiIndex, - compat, date_range, period_range) +from pandas import (CategoricalIndex, Categorical, DataFrame, Index, + MultiIndex, compat, date_range, period_range) from pandas.compat import PY3, long, lrange, lzip, range, u, PYPY from pandas.errors import PerformanceWarning, UnsortedIndexError from pandas.core.dtypes.dtypes import CategoricalDtype @@ -655,22 +655,27 @@ def test_constructor_nonhashable_names(self): # With .set_names() tm.assert_raises_regex(TypeError, message, mi.set_names, names=renamed) - @pytest.mark.parametrize('names', [['a', 'b', 'a'], ['1', '1', '2'], - ['1', 'a', '1']]) + @pytest.mark.parametrize('names', [['a', 'b', 'a'], [1, 1, 2], + [1, 'a', 1]]) def test_duplicate_level_names(self, names): - # GH18872 - pytest.raises(ValueError, pd.MultiIndex.from_product, - [[0, 1]] * 3, names=names) + # GH18872, GH19029 + mi = pd.MultiIndex.from_product([[0, 1]] * 3, names=names) + assert mi.names == names # With .rename() mi = pd.MultiIndex.from_product([[0, 1]] * 3) - tm.assert_raises_regex(ValueError, "Duplicated level name:", - mi.rename, names) + mi = mi.rename(names) + assert mi.names == names # With .rename(., level=) - mi.rename(names[0], level=1, inplace=True) - tm.assert_raises_regex(ValueError, "Duplicated level name:", - mi.rename, names[:2], level=[0, 2]) + mi.rename(names[1], level=1, inplace=True) + mi = mi.rename([names[0], names[2]], level=[0, 2]) + assert mi.names == names + + def test_duplicate_level_names_access_raises(self): + self.index.names = ['foo', 'foo'] + tm.assert_raises_regex(KeyError, 'Level foo not found', + self.index._get_level_number, 'foo') def assert_multiindex_copied(self, copy, original): # Levels should be (at least, shallow copied) @@ -1181,12 +1186,12 @@ def test_iter(self): ('baz', 'two'), ('qux', 'one'), ('qux', 'two')] assert result == expected - def test_legacy_pickle(self): + def test_legacy_pickle(self, datapath): if PY3: pytest.skip("testing for legacy pickles not " "support on py3") - path = tm.get_data_path('multiindex_v1.pickle') + path = datapath('indexes', 'data', 'multiindex_v1.pickle') obj = pd.read_pickle(path) obj2 = MultiIndex.from_tuples(obj.values) @@ -1202,10 +1207,10 @@ def test_legacy_pickle(self): assert_almost_equal(res, exp) assert_almost_equal(exp, exp2) - def test_legacy_v2_unpickle(self): + def test_legacy_v2_unpickle(self, datapath): # 0.7.3 -> 0.8.0 format manage - path = tm.get_data_path('mindex_073.pickle') + path = datapath('indexes', 'data', 'mindex_073.pickle') obj = pd.read_pickle(path) obj2 = MultiIndex.from_tuples(obj.values) @@ -1590,6 +1595,14 @@ def test_get_indexer_nearest(self): with pytest.raises(NotImplementedError): midx.get_indexer(['a'], method='pad', tolerance=2) + def test_get_indexer_categorical_time(self): + # https://github.com/pandas-dev/pandas/issues/21390 + midx = MultiIndex.from_product( + [Categorical(['a', 'b', 'c']), + Categorical(date_range("2012-01-01", periods=3, freq='H'))]) + result = midx.get_indexer(midx) + tm.assert_numpy_array_equal(result, np.arange(9, dtype=np.intp)) + def test_hash_collisions(self): # non-smoke test that we don't get hash collisions diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index 8deb51e190bab..7623587803b41 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -1,32 +1,23 @@ -import os - import pytest from pandas.io.parsers import read_table -from pandas.util import testing as tm - - -@pytest.fixture -def parser_data(request): - return os.path.join(tm.get_data_path(), '..', 'parser', 'data') @pytest.fixture -def tips_file(parser_data): +def tips_file(datapath): """Path to the tips dataset""" - return os.path.join(parser_data, 'tips.csv') + return datapath('io', 'parser', 'data', 'tips.csv') @pytest.fixture -def jsonl_file(parser_data): +def jsonl_file(datapath): """Path a JSONL dataset""" - return os.path.join(parser_data, 'items.jsonl') + return datapath('io', 'parser', 'data', 'items.jsonl') @pytest.fixture -def salaries_table(parser_data): +def salaries_table(datapath): """DataFrame with the salaries dataset""" - path = os.path.join(parser_data, 'salaries.csv') - return read_table(path) + return read_table(datapath('io', 'parser', 'data', 'salaries.csv')) @pytest.fixture diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index f221df93dd412..191e3f37f1c37 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -305,6 +305,44 @@ def test_repr_non_interactive(self): assert not has_truncated_repr(df) assert not has_expanded_repr(df) + def test_repr_truncates_terminal_size(self): + # https://github.com/pandas-dev/pandas/issues/21180 + # TODO: use mock fixutre. + # This is being backported, so doing it directly here. + try: + from unittest import mock + except ImportError: + mock = pytest.importorskip("mock") + + terminal_size = (118, 96) + p1 = mock.patch('pandas.io.formats.console.get_terminal_size', + return_value=terminal_size) + p2 = mock.patch('pandas.io.formats.format.get_terminal_size', + return_value=terminal_size) + + index = range(5) + columns = pd.MultiIndex.from_tuples([ + ('This is a long title with > 37 chars.', 'cat'), + ('This is a loooooonger title with > 43 chars.', 'dog'), + ]) + df = pd.DataFrame(1, index=index, columns=columns) + + with p1, p2: + result = repr(df) + + h1, h2 = result.split('\n')[:2] + assert 'long' in h1 + assert 'loooooonger' in h1 + assert 'cat' in h2 + assert 'dog' in h2 + + # regular columns + df2 = pd.DataFrame({"A" * 41: [1, 2], 'B' * 41: [1, 2]}) + with p1, p2: + result = repr(df2) + + assert df2.columns[0] in result.split('\n')[0] + def test_repr_max_columns_max_rows(self): term_width, term_height = get_terminal_size() if term_width < 10 or term_height < 10: @@ -916,8 +954,8 @@ def test_unicode_problem_decoding_as_ascii(self): dm = DataFrame({u('c/\u03c3'): Series({'test': np.nan})}) compat.text_type(dm.to_string()) - def test_string_repr_encoding(self): - filepath = tm.get_data_path('unicode_series.csv') + def test_string_repr_encoding(self, datapath): + filepath = datapath('io', 'formats', 'data', 'unicode_series.csv') df = pd.read_csv(filepath, header=None, encoding='latin1') repr(df) repr(df[1]) diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index c9074ca49e5be..05ceace20f5a4 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -21,11 +21,11 @@ def test_compression_roundtrip(compression): assert_frame_equal(df, pd.read_json(result)) -def test_read_zipped_json(): - uncompressed_path = tm.get_data_path("tsframe_v012.json") +def test_read_zipped_json(datapath): + uncompressed_path = datapath("io", "json", "data", "tsframe_v012.json") uncompressed_df = pd.read_json(uncompressed_path) - compressed_path = tm.get_data_path("tsframe_v012.json.zip") + compressed_path = datapath("io", "json", "data", "tsframe_v012.json.zip") compressed_df = pd.read_json(compressed_path, compression='zip') assert_frame_equal(uncompressed_df, compressed_df) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 7e497c395266f..bcbac4400c953 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -37,8 +37,9 @@ class TestPandasContainer(object): - def setup_method(self, method): - self.dirpath = tm.get_data_path() + @pytest.fixture(scope="function", autouse=True) + def setup(self, datapath): + self.dirpath = datapath("io", "json", "data") self.ts = tm.makeTimeSeries() self.ts.name = 'ts' @@ -59,7 +60,8 @@ def setup_method(self, method): self.mixed_frame = _mixed_frame.copy() self.categorical = _cat_frame.copy() - def teardown_method(self, method): + yield + del self.dirpath del self.ts diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index b39122e5e7906..fb510f1a74556 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -77,7 +77,7 @@ def test_read_csv(self): else: prefix = u("file://") - fname = prefix + compat.text_type(self.csv1) + fname = prefix + compat.text_type(os.path.abspath(self.csv1)) self.read_csv(fname, index_col=0, parse_dates=True) def test_1000_sep(self): @@ -651,21 +651,19 @@ def test_read_csv_parse_simple_list(self): tm.assert_frame_equal(df, expected) @tm.network - def test_url(self): + def test_url(self, datapath): # HTTP(S) url = ('https://raw.github.com/pandas-dev/pandas/master/' 'pandas/tests/io/parser/data/salaries.csv') url_table = self.read_table(url) - dirpath = tm.get_data_path() - localtable = os.path.join(dirpath, 'salaries.csv') + localtable = datapath('io', 'parser', 'data', 'salaries.csv') local_table = self.read_table(localtable) tm.assert_frame_equal(url_table, local_table) # TODO: ftp testing @pytest.mark.slow - def test_file(self): - dirpath = tm.get_data_path() - localtable = os.path.join(dirpath, 'salaries.csv') + def test_file(self, datapath): + localtable = datapath('io', 'parser', 'data', 'salaries.csv') local_table = self.read_table(localtable) try: @@ -755,8 +753,8 @@ def test_utf16_bom_skiprows(self): tm.assert_frame_equal(result, expected) - def test_utf16_example(self): - path = tm.get_data_path('utf16_ex.txt') + def test_utf16_example(self, datapath): + path = datapath('io', 'parser', 'data', 'utf16_ex.txt') # it works! and is the right length result = self.read_table(path, encoding='utf-16') @@ -767,8 +765,8 @@ def test_utf16_example(self): result = self.read_table(buf, encoding='utf-16') assert len(result) == 50 - def test_unicode_encoding(self): - pth = tm.get_data_path('unicode_series.csv') + def test_unicode_encoding(self, datapath): + pth = datapath('io', 'parser', 'data', 'unicode_series.csv') result = self.read_csv(pth, header=None, encoding='latin-1') result = result.set_index(0) @@ -1513,10 +1511,9 @@ def test_internal_eof_byte_to_file(self): result = self.read_csv(path) tm.assert_frame_equal(result, expected) - def test_sub_character(self): + def test_sub_character(self, datapath): # see gh-16893 - dirpath = tm.get_data_path() - filename = os.path.join(dirpath, "sub_char.csv") + filename = datapath('io', 'parser', 'data', 'sub_char.csv') expected = DataFrame([[1, 2, 3]], columns=["a", "\x1ab", "c"]) result = self.read_csv(filename) diff --git a/pandas/tests/io/parser/compression.py b/pandas/tests/io/parser/compression.py index e84db66561c49..e4950af19ea95 100644 --- a/pandas/tests/io/parser/compression.py +++ b/pandas/tests/io/parser/compression.py @@ -120,9 +120,9 @@ def test_read_csv_infer_compression(self): tm.assert_frame_equal(expected, df) - def test_read_csv_compressed_utf16_example(self): + def test_read_csv_compressed_utf16_example(self, datapath): # GH18071 - path = tm.get_data_path('utf16_ex_small.zip') + path = datapath('io', 'parser', 'data', 'utf16_ex_small.zip') result = self.read_csv(path, encoding='utf-16', compression='zip', sep='\t') diff --git a/pandas/tests/io/parser/dtypes.py b/pandas/tests/io/parser/dtypes.py index b91ce04673e29..8060ebf2fbcd4 100644 --- a/pandas/tests/io/parser/dtypes.py +++ b/pandas/tests/io/parser/dtypes.py @@ -125,9 +125,9 @@ def test_categorical_dtype_high_cardinality_numeric(self): np.sort(actual.a.cat.categories), ordered=True) tm.assert_frame_equal(actual, expected) - def test_categorical_dtype_encoding(self): + def test_categorical_dtype_encoding(self, datapath): # GH 10153 - pth = tm.get_data_path('unicode_series.csv') + pth = datapath('io', 'parser', 'data', 'unicode_series.csv') encoding = 'latin-1' expected = self.read_csv(pth, header=None, encoding=encoding) expected[1] = Categorical(expected[1]) @@ -135,7 +135,7 @@ def test_categorical_dtype_encoding(self): dtype={1: 'category'}) tm.assert_frame_equal(actual, expected) - pth = tm.get_data_path('utf16_ex.txt') + pth = datapath('io', 'parser', 'data', 'utf16_ex.txt') encoding = 'utf-16' expected = self.read_table(pth, encoding=encoding) expected = expected.apply(Categorical) diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index fdf45f307e953..e2243b8087a5b 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -48,10 +48,16 @@ def check_compressed_urls(salaries_table, compression, extension, mode, tm.assert_frame_equal(url_table, salaries_table) +@pytest.fixture +def tips_df(datapath): + """DataFrame with the tips dataset.""" + return read_csv(datapath('io', 'parser', 'data', 'tips.csv')) + + @pytest.mark.usefixtures("s3_resource") class TestS3(object): - def test_parse_public_s3_bucket(self): + def test_parse_public_s3_bucket(self, tips_df): pytest.importorskip('s3fs') # more of an integration test due to the not-public contents portion # can probably mock this though. @@ -60,45 +66,40 @@ def test_parse_public_s3_bucket(self): ext, compression=comp) assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv( - tm.get_data_path('tips.csv')), df) + tm.assert_frame_equal(df, tips_df) # Read public file from bucket with not-public contents df = read_csv('s3://cant_get_it/tips.csv') assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv(tm.get_data_path('tips.csv')), df) + tm.assert_frame_equal(df, tips_df) - def test_parse_public_s3n_bucket(self): + def test_parse_public_s3n_bucket(self, tips_df): # Read from AWS s3 as "s3n" URL df = read_csv('s3n://pandas-test/tips.csv', nrows=10) assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv( - tm.get_data_path('tips.csv')).iloc[:10], df) + tm.assert_frame_equal(tips_df.iloc[:10], df) - def test_parse_public_s3a_bucket(self): + def test_parse_public_s3a_bucket(self, tips_df): # Read from AWS s3 as "s3a" URL df = read_csv('s3a://pandas-test/tips.csv', nrows=10) assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv( - tm.get_data_path('tips.csv')).iloc[:10], df) + tm.assert_frame_equal(tips_df.iloc[:10], df) - def test_parse_public_s3_bucket_nrows(self): + def test_parse_public_s3_bucket_nrows(self, tips_df): for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: df = read_csv('s3://pandas-test/tips.csv' + ext, nrows=10, compression=comp) assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv( - tm.get_data_path('tips.csv')).iloc[:10], df) + tm.assert_frame_equal(tips_df.iloc[:10], df) - def test_parse_public_s3_bucket_chunked(self): + def test_parse_public_s3_bucket_chunked(self, tips_df): # Read with a chunksize chunksize = 5 - local_tips = read_csv(tm.get_data_path('tips.csv')) for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: df_reader = read_csv('s3://pandas-test/tips.csv' + ext, chunksize=chunksize, compression=comp) @@ -109,14 +110,13 @@ def test_parse_public_s3_bucket_chunked(self): df = df_reader.get_chunk() assert isinstance(df, DataFrame) assert not df.empty - true_df = local_tips.iloc[ + true_df = tips_df.iloc[ chunksize * i_chunk: chunksize * (i_chunk + 1)] tm.assert_frame_equal(true_df, df) - def test_parse_public_s3_bucket_chunked_python(self): + def test_parse_public_s3_bucket_chunked_python(self, tips_df): # Read with a chunksize using the Python parser chunksize = 5 - local_tips = read_csv(tm.get_data_path('tips.csv')) for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: df_reader = read_csv('s3://pandas-test/tips.csv' + ext, chunksize=chunksize, compression=comp, @@ -127,36 +127,33 @@ def test_parse_public_s3_bucket_chunked_python(self): df = df_reader.get_chunk() assert isinstance(df, DataFrame) assert not df.empty - true_df = local_tips.iloc[ + true_df = tips_df.iloc[ chunksize * i_chunk: chunksize * (i_chunk + 1)] tm.assert_frame_equal(true_df, df) - def test_parse_public_s3_bucket_python(self): + def test_parse_public_s3_bucket_python(self, tips_df): for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: df = read_csv('s3://pandas-test/tips.csv' + ext, engine='python', compression=comp) assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv( - tm.get_data_path('tips.csv')), df) + tm.assert_frame_equal(df, tips_df) - def test_infer_s3_compression(self): + def test_infer_s3_compression(self, tips_df): for ext in ['', '.gz', '.bz2']: df = read_csv('s3://pandas-test/tips.csv' + ext, engine='python', compression='infer') assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv( - tm.get_data_path('tips.csv')), df) + tm.assert_frame_equal(df, tips_df) - def test_parse_public_s3_bucket_nrows_python(self): + def test_parse_public_s3_bucket_nrows_python(self, tips_df): for ext, comp in [('', None), ('.gz', 'gzip'), ('.bz2', 'bz2')]: df = read_csv('s3://pandas-test/tips.csv' + ext, engine='python', nrows=10, compression=comp) assert isinstance(df, DataFrame) assert not df.empty - tm.assert_frame_equal(read_csv( - tm.get_data_path('tips.csv')).iloc[:10], df) + tm.assert_frame_equal(tips_df.iloc[:10], df) def test_s3_fails(self): with pytest.raises(IOError): diff --git a/pandas/tests/io/parser/test_parsers.py b/pandas/tests/io/parser/test_parsers.py index 7717102b64fc5..b6f13039641a2 100644 --- a/pandas/tests/io/parser/test_parsers.py +++ b/pandas/tests/io/parser/test_parsers.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- import os +import pytest import pandas.util.testing as tm from pandas import read_csv, read_table, DataFrame @@ -45,8 +46,9 @@ def read_table(self, *args, **kwargs): def float_precision_choices(self): raise com.AbstractMethodError(self) - def setup_method(self, method): - self.dirpath = tm.get_data_path() + @pytest.fixture(autouse=True) + def setup_method(self, datapath): + self.dirpath = datapath('io', 'parser', 'data') self.csv1 = os.path.join(self.dirpath, 'test1.csv') self.csv2 = os.path.join(self.dirpath, 'test2.csv') self.xls1 = os.path.join(self.dirpath, 'test.xls') diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index e8d9d8b52164b..c7026e3e0fc88 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -28,8 +28,9 @@ class TestTextReader(object): - def setup_method(self, method): - self.dirpath = tm.get_data_path() + @pytest.fixture(autouse=True) + def setup_method(self, datapath): + self.dirpath = datapath('io', 'parser', 'data') self.csv1 = os.path.join(self.dirpath, 'test1.csv') self.csv2 = os.path.join(self.dirpath, 'test2.csv') self.xls1 = os.path.join(self.dirpath, 'test.xls') diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py index b80263021c269..101ee3e619f5b 100644 --- a/pandas/tests/io/sas/test_sas7bdat.py +++ b/pandas/tests/io/sas/test_sas7bdat.py @@ -11,8 +11,9 @@ class TestSAS7BDAT(object): - def setup_method(self, method): - self.dirpath = tm.get_data_path() + @pytest.fixture(autouse=True) + def setup_method(self, datapath): + self.dirpath = datapath("io", "sas", "data") self.data = [] self.test_ix = [list(range(1, 16)), [16]] for j in 1, 2: @@ -123,9 +124,8 @@ def test_iterator_read_too_much(self): rdr.close() -def test_encoding_options(): - dirpath = tm.get_data_path() - fname = os.path.join(dirpath, "test1.sas7bdat") +def test_encoding_options(datapath): + fname = datapath("io", "sas", "data", "test1.sas7bdat") df1 = pd.read_sas(fname) df2 = pd.read_sas(fname, encoding='utf-8') for col in df1.columns: @@ -143,43 +143,39 @@ def test_encoding_options(): assert(x == y.decode()) -def test_productsales(): - dirpath = tm.get_data_path() - fname = os.path.join(dirpath, "productsales.sas7bdat") +def test_productsales(datapath): + fname = datapath("io", "sas", "data", "productsales.sas7bdat") df = pd.read_sas(fname, encoding='utf-8') - fname = os.path.join(dirpath, "productsales.csv") + fname = datapath("io", "sas", "data", "productsales.csv") df0 = pd.read_csv(fname, parse_dates=['MONTH']) vn = ["ACTUAL", "PREDICT", "QUARTER", "YEAR"] df0[vn] = df0[vn].astype(np.float64) tm.assert_frame_equal(df, df0) -def test_12659(): - dirpath = tm.get_data_path() - fname = os.path.join(dirpath, "test_12659.sas7bdat") +def test_12659(datapath): + fname = datapath("io", "sas", "data", "test_12659.sas7bdat") df = pd.read_sas(fname) - fname = os.path.join(dirpath, "test_12659.csv") + fname = datapath("io", "sas", "data", "test_12659.csv") df0 = pd.read_csv(fname) df0 = df0.astype(np.float64) tm.assert_frame_equal(df, df0) -def test_airline(): - dirpath = tm.get_data_path() - fname = os.path.join(dirpath, "airline.sas7bdat") +def test_airline(datapath): + fname = datapath("io", "sas", "data", "airline.sas7bdat") df = pd.read_sas(fname) - fname = os.path.join(dirpath, "airline.csv") + fname = datapath("io", "sas", "data", "airline.csv") df0 = pd.read_csv(fname) df0 = df0.astype(np.float64) tm.assert_frame_equal(df, df0, check_exact=False) -def test_date_time(): +def test_date_time(datapath): # Support of different SAS date/datetime formats (PR #15871) - dirpath = tm.get_data_path() - fname = os.path.join(dirpath, "datetime.sas7bdat") + fname = datapath("io", "sas", "data", "datetime.sas7bdat") df = pd.read_sas(fname) - fname = os.path.join(dirpath, "datetime.csv") + fname = datapath("io", "sas", "data", "datetime.csv") df0 = pd.read_csv(fname, parse_dates=['Date1', 'Date2', 'DateTime', 'DateTimeHi', 'Taiw']) # GH 19732: Timestamps imported from sas will incur floating point errors @@ -187,9 +183,8 @@ def test_date_time(): tm.assert_frame_equal(df, df0) -def test_zero_variables(): +def test_zero_variables(datapath): # Check if the SAS file has zero variables (PR #18184) - dirpath = tm.get_data_path() - fname = os.path.join(dirpath, "zero_variables.sas7bdat") + fname = datapath("io", "sas", "data", "zero_variables.sas7bdat") with pytest.raises(EmptyDataError): pd.read_sas(fname) diff --git a/pandas/tests/io/sas/test_xport.py b/pandas/tests/io/sas/test_xport.py index de31c3e36a8d5..6e5b2ab067aa5 100644 --- a/pandas/tests/io/sas/test_xport.py +++ b/pandas/tests/io/sas/test_xport.py @@ -1,3 +1,4 @@ +import pytest import pandas as pd import pandas.util.testing as tm from pandas.io.sas.sasreader import read_sas @@ -18,8 +19,9 @@ def numeric_as_float(data): class TestXport(object): - def setup_method(self, method): - self.dirpath = tm.get_data_path() + @pytest.fixture(autouse=True) + def setup_method(self, datapath): + self.dirpath = datapath("io", "sas", "data") self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt") self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt") self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt") diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index 98c0effabec84..a6b331685e72a 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -9,10 +9,11 @@ from pandas import DataFrame from pandas import read_clipboard from pandas import get_option +from pandas.compat import PY2 from pandas.util import testing as tm from pandas.util.testing import makeCustomDataframe as mkdf from pandas.io.clipboard.exceptions import PyperclipException -from pandas.io.clipboard import clipboard_set +from pandas.io.clipboard import clipboard_set, clipboard_get try: @@ -22,73 +23,120 @@ _DEPS_INSTALLED = 0 +def build_kwargs(sep, excel): + kwargs = {} + if excel != 'default': + kwargs['excel'] = excel + if sep != 'default': + kwargs['sep'] = sep + return kwargs + + +@pytest.fixture(params=['delims', 'utf8', 'string', 'long', 'nonascii', + 'colwidth', 'mixed', 'float', 'int']) +def df(request): + data_type = request.param + + if data_type == 'delims': + return pd.DataFrame({'a': ['"a,\t"b|c', 'd\tef´'], + 'b': ['hi\'j', 'k\'\'lm']}) + elif data_type == 'utf8': + return pd.DataFrame({'a': ['µasd', 'Ωœ∑´'], + 'b': ['øπ∆˚¬', 'œ∑´®']}) + elif data_type == 'string': + return mkdf(5, 3, c_idx_type='s', r_idx_type='i', + c_idx_names=[None], r_idx_names=[None]) + elif data_type == 'long': + max_rows = get_option('display.max_rows') + return mkdf(max_rows + 1, 3, + data_gen_f=lambda *args: randint(2), + c_idx_type='s', r_idx_type='i', + c_idx_names=[None], r_idx_names=[None]) + elif data_type == 'nonascii': + return pd.DataFrame({'en': 'in English'.split(), + 'es': 'en español'.split()}) + elif data_type == 'colwidth': + _cw = get_option('display.max_colwidth') + 1 + return mkdf(5, 3, data_gen_f=lambda *args: 'x' * _cw, + c_idx_type='s', r_idx_type='i', + c_idx_names=[None], r_idx_names=[None]) + elif data_type == 'mixed': + return DataFrame({'a': np.arange(1.0, 6.0) + 0.01, + 'b': np.arange(1, 6), + 'c': list('abcde')}) + elif data_type == 'float': + return mkdf(5, 3, data_gen_f=lambda r, c: float(r) + 0.01, + c_idx_type='s', r_idx_type='i', + c_idx_names=[None], r_idx_names=[None]) + elif data_type == 'int': + return mkdf(5, 3, data_gen_f=lambda *args: randint(2), + c_idx_type='s', r_idx_type='i', + c_idx_names=[None], r_idx_names=[None]) + else: + raise ValueError + + @pytest.mark.single @pytest.mark.skipif(not _DEPS_INSTALLED, reason="clipboard primitives not installed") class TestClipboard(object): - - @classmethod - def setup_class(cls): - cls.data = {} - cls.data['string'] = mkdf(5, 3, c_idx_type='s', r_idx_type='i', - c_idx_names=[None], r_idx_names=[None]) - cls.data['int'] = mkdf(5, 3, data_gen_f=lambda *args: randint(2), - c_idx_type='s', r_idx_type='i', - c_idx_names=[None], r_idx_names=[None]) - cls.data['float'] = mkdf(5, 3, - data_gen_f=lambda r, c: float(r) + 0.01, - c_idx_type='s', r_idx_type='i', - c_idx_names=[None], r_idx_names=[None]) - cls.data['mixed'] = DataFrame({'a': np.arange(1.0, 6.0) + 0.01, - 'b': np.arange(1, 6), - 'c': list('abcde')}) - - # Test columns exceeding "max_colwidth" (GH8305) - _cw = get_option('display.max_colwidth') + 1 - cls.data['colwidth'] = mkdf(5, 3, data_gen_f=lambda *args: 'x' * _cw, - c_idx_type='s', r_idx_type='i', - c_idx_names=[None], r_idx_names=[None]) - # Test GH-5346 - max_rows = get_option('display.max_rows') - cls.data['longdf'] = mkdf(max_rows + 1, 3, - data_gen_f=lambda *args: randint(2), - c_idx_type='s', r_idx_type='i', - c_idx_names=[None], r_idx_names=[None]) - # Test for non-ascii text: GH9263 - cls.data['nonascii'] = pd.DataFrame({'en': 'in English'.split(), - 'es': 'en español'.split()}) - # unicode round trip test for GH 13747, GH 12529 - cls.data['utf8'] = pd.DataFrame({'a': ['µasd', 'Ωœ∑´'], - 'b': ['øπ∆˚¬', 'œ∑´®']}) - cls.data_types = list(cls.data.keys()) - - @classmethod - def teardown_class(cls): - del cls.data_types, cls.data - - def check_round_trip_frame(self, data_type, excel=None, sep=None, + def check_round_trip_frame(self, data, excel=None, sep=None, encoding=None): - data = self.data[data_type] data.to_clipboard(excel=excel, sep=sep, encoding=encoding) - if sep is not None: - result = read_clipboard(sep=sep, index_col=0, encoding=encoding) - else: - result = read_clipboard(encoding=encoding) + result = read_clipboard(sep=sep or '\t', index_col=0, + encoding=encoding) tm.assert_frame_equal(data, result, check_dtype=False) - def test_round_trip_frame_sep(self): - for dt in self.data_types: - self.check_round_trip_frame(dt, sep=',') - self.check_round_trip_frame(dt, sep=r'\s+') - self.check_round_trip_frame(dt, sep='|') - - def test_round_trip_frame_string(self): - for dt in self.data_types: - self.check_round_trip_frame(dt, excel=False) - - def test_round_trip_frame(self): - for dt in self.data_types: - self.check_round_trip_frame(dt) + # Test that default arguments copy as tab delimited + def test_round_trip_frame(self, df): + self.check_round_trip_frame(df) + + # Test that explicit delimiters are respected + @pytest.mark.parametrize('sep', ['\t', ',', '|']) + def test_round_trip_frame_sep(self, df, sep): + self.check_round_trip_frame(df, sep=sep) + + # Test white space separator + def test_round_trip_frame_string(self, df): + df.to_clipboard(excel=False, sep=None) + result = read_clipboard() + assert df.to_string() == result.to_string() + assert df.shape == result.shape + + # Two character separator is not supported in to_clipboard + # Test that multi-character separators are not silently passed + def test_excel_sep_warning(self, df): + with tm.assert_produces_warning(): + df.to_clipboard(excel=True, sep=r'\t') + + # Separator is ignored when excel=False and should produce a warning + def test_copy_delim_warning(self, df): + with tm.assert_produces_warning(): + df.to_clipboard(excel=False, sep='\t') + + # Tests that the default behavior of to_clipboard is tab + # delimited and excel="True" + @pytest.mark.parametrize('sep', ['\t', None, 'default']) + @pytest.mark.parametrize('excel', [True, None, 'default']) + def test_clipboard_copy_tabs_default(self, sep, excel, df): + kwargs = build_kwargs(sep, excel) + df.to_clipboard(**kwargs) + if PY2: + # to_clipboard copies unicode, to_csv produces bytes. This is + # expected behavior + assert clipboard_get().encode('utf-8') == df.to_csv(sep='\t') + else: + assert clipboard_get() == df.to_csv(sep='\t') + + # Tests reading of white space separated tables + @pytest.mark.parametrize('sep', [None, 'default']) + @pytest.mark.parametrize('excel', [False]) + def test_clipboard_copy_strings(self, sep, excel, df): + kwargs = build_kwargs(sep, excel) + df.to_clipboard(**kwargs) + result = read_clipboard(sep=r'\s+') + assert result.to_string() == df.to_string() + assert df.shape == result.shape def test_read_clipboard_infer_excel(self): # gh-19010: avoid warnings @@ -124,15 +172,13 @@ def test_read_clipboard_infer_excel(self): tm.assert_frame_equal(res, exp) - def test_invalid_encoding(self): + def test_invalid_encoding(self, df): # test case for testing invalid encoding - data = self.data['string'] with pytest.raises(ValueError): - data.to_clipboard(encoding='ascii') + df.to_clipboard(encoding='ascii') with pytest.raises(NotImplementedError): pd.read_clipboard(encoding='ascii') - def test_round_trip_valid_encodings(self): - for enc in ['UTF-8', 'utf-8', 'utf8']: - for dt in self.data_types: - self.check_round_trip_frame(dt, encoding=enc) + @pytest.mark.parametrize('enc', ['UTF-8', 'utf-8', 'utf8']) + def test_round_trip_valid_encodings(self, enc, df): + self.check_round_trip_frame(df, encoding=enc) diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index a89156db38ae3..5c9739be73393 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -149,27 +149,22 @@ def test_read_non_existant(self, reader, module, error_class, fn_ext): reader(path) @pytest.mark.parametrize('reader, module, path', [ - (pd.read_csv, 'os', os.path.join(HERE, 'data', 'iris.csv')), - (pd.read_table, 'os', os.path.join(HERE, 'data', 'iris.csv')), - (pd.read_fwf, 'os', os.path.join(HERE, 'data', - 'fixed_width_format.txt')), - (pd.read_excel, 'xlrd', os.path.join(HERE, 'data', 'test1.xlsx')), - (pd.read_feather, 'feather', os.path.join(HERE, 'data', - 'feather-0_3_1.feather')), - (pd.read_hdf, 'tables', os.path.join(HERE, 'data', 'legacy_hdf', - 'datetimetz_object.h5')), - (pd.read_stata, 'os', os.path.join(HERE, 'data', 'stata10_115.dta')), - (pd.read_sas, 'os', os.path.join(HERE, 'sas', 'data', - 'test1.sas7bdat')), - (pd.read_json, 'os', os.path.join(HERE, 'json', 'data', - 'tsframe_v012.json')), - (pd.read_msgpack, 'os', os.path.join(HERE, 'msgpack', 'data', - 'frame.mp')), - (pd.read_pickle, 'os', os.path.join(HERE, 'data', - 'categorical_0_14_1.pickle')), + (pd.read_csv, 'os', ('io', 'data', 'iris.csv')), + (pd.read_table, 'os', ('io', 'data', 'iris.csv')), + (pd.read_fwf, 'os', ('io', 'data', 'fixed_width_format.txt')), + (pd.read_excel, 'xlrd', ('io', 'data', 'test1.xlsx')), + (pd.read_feather, 'feather', ('io', 'data', 'feather-0_3_1.feather')), + (pd.read_hdf, 'tables', ('io', 'data', 'legacy_hdf', + 'datetimetz_object.h5')), + (pd.read_stata, 'os', ('io', 'data', 'stata10_115.dta')), + (pd.read_sas, 'os', ('io', 'sas', 'data', 'test1.sas7bdat')), + (pd.read_json, 'os', ('io', 'json', 'data', 'tsframe_v012.json')), + (pd.read_msgpack, 'os', ('io', 'msgpack', 'data', 'frame.mp')), + (pd.read_pickle, 'os', ('io', 'data', 'categorical_0_14_1.pickle')), ]) - def test_read_fspath_all(self, reader, module, path): + def test_read_fspath_all(self, reader, module, path, datapath): pytest.importorskip(module) + path = datapath(*path) mypath = CustomFSPath(path) result = reader(mypath) @@ -232,13 +227,14 @@ def test_write_fspath_hdf5(self): tm.assert_frame_equal(result, expected) -class TestMMapWrapper(object): +@pytest.fixture +def mmap_file(datapath): + return datapath('io', 'data', 'test_mmap.csv') + - def setup_method(self, method): - self.mmap_file = os.path.join(tm.get_data_path(), - 'test_mmap.csv') +class TestMMapWrapper(object): - def test_constructor_bad_file(self): + def test_constructor_bad_file(self, mmap_file): non_file = StringIO('I am not a file') non_file.fileno = lambda: -1 @@ -252,15 +248,15 @@ def test_constructor_bad_file(self): tm.assert_raises_regex(err, msg, common.MMapWrapper, non_file) - target = open(self.mmap_file, 'r') + target = open(mmap_file, 'r') target.close() msg = "I/O operation on closed file" tm.assert_raises_regex( ValueError, msg, common.MMapWrapper, target) - def test_get_attr(self): - with open(self.mmap_file, 'r') as target: + def test_get_attr(self, mmap_file): + with open(mmap_file, 'r') as target: wrapper = common.MMapWrapper(target) attrs = dir(wrapper.mmap) @@ -273,8 +269,8 @@ def test_get_attr(self): assert not hasattr(wrapper, 'foo') - def test_next(self): - with open(self.mmap_file, 'r') as target: + def test_next(self, mmap_file): + with open(mmap_file, 'r') as target: wrapper = common.MMapWrapper(target) lines = target.readlines() diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 05423474f330a..4e2b2af0ebfe7 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -39,8 +39,9 @@ @td.skip_if_no('xlrd', '0.9') class SharedItems(object): - def setup_method(self, method): - self.dirpath = tm.get_data_path() + @pytest.fixture(autouse=True) + def setup_method(self, datapath): + self.dirpath = datapath("io", "data") self.frame = _frame.copy() self.frame2 = _frame2.copy() self.tsframe = _tsframe.copy() @@ -49,7 +50,6 @@ def setup_method(self, method): def get_csv_refdf(self, basename): """ Obtain the reference data from read_csv with the Python engine. - Test data path is defined by pandas.util.testing.get_data_path() Parameters ---------- @@ -68,8 +68,7 @@ def get_csv_refdf(self, basename): def get_excelfile(self, basename, ext): """ - Return test data ExcelFile instance. Test data path is defined by - pandas.util.testing.get_data_path() + Return test data ExcelFile instance. Parameters ---------- @@ -86,8 +85,7 @@ def get_excelfile(self, basename, ext): def get_exceldf(self, basename, ext, *args, **kwds): """ - Return test data DataFrame. Test data path is defined by - pandas.util.testing.get_data_path() + Return test data DataFrame. Parameters ---------- diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index a56946b82b027..9c6a8de7ed446 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -1,6 +1,5 @@ from __future__ import print_function -import glob import os import re import threading @@ -25,8 +24,18 @@ import pandas.util._test_decorators as td from pandas.util.testing import makeCustomDataframe as mkdf, network +HERE = os.path.dirname(__file__) -DATA_PATH = tm.get_data_path() + +@pytest.fixture(params=[ + 'chinese_utf-16.html', + 'chinese_utf-32.html', + 'chinese_utf-8.html', + 'letz_latin1.html', +]) +def html_encoding_file(request, datapath): + """Parametrized fixture for HTML encoding test filenames.""" + return datapath('io', 'data', 'html_encoding', request.param) def assert_framelist_equal(list1, list2, *args, **kwargs): @@ -44,11 +53,11 @@ def assert_framelist_equal(list1, list2, *args, **kwargs): @td.skip_if_no('bs4') -def test_bs4_version_fails(monkeypatch): +def test_bs4_version_fails(monkeypatch, datapath): import bs4 monkeypatch.setattr(bs4, '__version__', '4.2') with tm.assert_raises_regex(ValueError, "minimum version"): - read_html(os.path.join(DATA_PATH, "spam.html"), flavor='bs4') + read_html(datapath("io", "data", "spam.html"), flavor='bs4') def test_invalid_flavor(): @@ -59,8 +68,8 @@ def test_invalid_flavor(): @td.skip_if_no('bs4') @td.skip_if_no('lxml') -def test_same_ordering(): - filename = os.path.join(DATA_PATH, 'valid_markup.html') +def test_same_ordering(datapath): + filename = datapath('io', 'data', 'valid_markup.html') dfs_lxml = read_html(filename, index_col=0, flavor=['lxml']) dfs_bs4 = read_html(filename, index_col=0, flavor=['bs4']) assert_framelist_equal(dfs_lxml, dfs_bs4) @@ -72,11 +81,14 @@ def test_same_ordering(): pytest.param('lxml', marks=pytest.mark.skipif( not td.safe_import('lxml'), reason='No lxml'))], scope="class") class TestReadHtml(object): - spam_data = os.path.join(DATA_PATH, 'spam.html') - spam_data_kwargs = {} - if PY3: - spam_data_kwargs['encoding'] = 'UTF-8' - banklist_data = os.path.join(DATA_PATH, 'banklist.html') + + @pytest.fixture(autouse=True) + def set_files(self, datapath): + self.spam_data = datapath('io', 'data', 'spam.html') + self.spam_data_kwargs = {} + if PY3: + self.spam_data_kwargs['encoding'] = 'UTF-8' + self.banklist_data = datapath("io", "data", "banklist.html") @pytest.fixture(autouse=True, scope="function") def set_defaults(self, flavor, request): @@ -272,7 +284,8 @@ def test_invalid_url(self): @pytest.mark.slow def test_file_url(self): url = self.banklist_data - dfs = self.read_html(file_path_to_url(url), 'First', + dfs = self.read_html(file_path_to_url(os.path.abspath(url)), + 'First', attrs={'id': 'table'}) assert isinstance(dfs, list) for df in dfs: @@ -326,7 +339,7 @@ def test_multiindex_header_index_skiprows(self): @pytest.mark.slow def test_regex_idempotency(self): url = self.banklist_data - dfs = self.read_html(file_path_to_url(url), + dfs = self.read_html(file_path_to_url(os.path.abspath(url)), match=re.compile(re.compile('Florida')), attrs={'id': 'table'}) assert isinstance(dfs, list) @@ -352,9 +365,9 @@ def test_python_docs_table(self): assert sorted(zz) == sorted(['Repo', 'What']) @pytest.mark.slow - def test_thousands_macau_stats(self): + def test_thousands_macau_stats(self, datapath): all_non_nan_table_index = -2 - macau_data = os.path.join(DATA_PATH, 'macau.html') + macau_data = datapath("io", "data", "macau.html") dfs = self.read_html(macau_data, index_col=0, attrs={'class': 'style1'}) df = dfs[all_non_nan_table_index] @@ -362,9 +375,9 @@ def test_thousands_macau_stats(self): assert not any(s.isna().any() for _, s in df.iteritems()) @pytest.mark.slow - def test_thousands_macau_index_col(self): + def test_thousands_macau_index_col(self, datapath): all_non_nan_table_index = -2 - macau_data = os.path.join(DATA_PATH, 'macau.html') + macau_data = datapath('io', 'data', 'macau.html') dfs = self.read_html(macau_data, index_col=0, header=0) df = dfs[all_non_nan_table_index] @@ -518,8 +531,8 @@ def test_countries_municipalities(self): res2 = self.read_html(data2, header=0) assert_framelist_equal(res1, res2) - def test_nyse_wsj_commas_table(self): - data = os.path.join(DATA_PATH, 'nyse_wsj.html') + def test_nyse_wsj_commas_table(self, datapath): + data = datapath('io', 'data', 'nyse_wsj.html') df = self.read_html(data, index_col=0, header=0, attrs={'class': 'mdcTable'})[0] @@ -530,7 +543,7 @@ def test_nyse_wsj_commas_table(self): tm.assert_index_equal(df.columns, columns) @pytest.mark.slow - def test_banklist_header(self): + def test_banklist_header(self, datapath): from pandas.io.html import _remove_whitespace def try_remove_ws(x): @@ -541,7 +554,7 @@ def try_remove_ws(x): df = self.read_html(self.banklist_data, 'Metcalf', attrs={'id': 'table'})[0] - ground_truth = read_csv(os.path.join(DATA_PATH, 'banklist.csv'), + ground_truth = read_csv(datapath('io', 'data', 'banklist.csv'), converters={'Updated Date': Timestamp, 'Closing Date': Timestamp}) assert df.shape == ground_truth.shape @@ -658,19 +671,19 @@ def test_parse_dates_combine(self): newdf = DataFrame({'datetime': raw_dates}) tm.assert_frame_equal(newdf, res[0]) - def test_computer_sales_page(self): - data = os.path.join(DATA_PATH, 'computer_sales_page.html') + def test_computer_sales_page(self, datapath): + data = datapath('io', 'data', 'computer_sales_page.html') with tm.assert_raises_regex(ParserError, r"Passed header=\[0,1\] are " r"too many rows for this " r"multi_index of columns"): self.read_html(data, header=[0, 1]) - data = os.path.join(DATA_PATH, 'computer_sales_page.html') + data = datapath('io', 'data', 'computer_sales_page.html') assert self.read_html(data, header=[1, 2]) - def test_wikipedia_states_table(self): - data = os.path.join(DATA_PATH, 'wikipedia_states.html') + def test_wikipedia_states_table(self, datapath): + data = datapath('io', 'data', 'wikipedia_states.html') assert os.path.isfile(data), '%r is not a file' % data assert os.path.getsize(data), '%r is an empty file' % data result = self.read_html(data, 'Arizona', header=1)[0] @@ -784,15 +797,15 @@ def test_multiple_header_rows(self): html_df = read_html(html, )[0] tm.assert_frame_equal(expected_df, html_df) - def test_works_on_valid_markup(self): - filename = os.path.join(DATA_PATH, 'valid_markup.html') + def test_works_on_valid_markup(self, datapath): + filename = datapath('io', 'data', 'valid_markup.html') dfs = self.read_html(filename, index_col=0) assert isinstance(dfs, list) assert isinstance(dfs[0], DataFrame) @pytest.mark.slow - def test_fallback_success(self): - banklist_data = os.path.join(DATA_PATH, 'banklist.html') + def test_fallback_success(self, datapath): + banklist_data = datapath('io', 'data', 'banklist.html') self.read_html(banklist_data, '.*Water.*', flavor=['lxml', 'html5lib']) def test_to_html_timestamp(self): @@ -835,22 +848,23 @@ def test_displayed_only(self, displayed_only, exp0, exp1): else: assert len(dfs) == 1 # Should not parse hidden table - @pytest.mark.parametrize("f", glob.glob( - os.path.join(DATA_PATH, 'html_encoding', '*.html'))) - def test_encode(self, f): - _, encoding = os.path.splitext(os.path.basename(f))[0].split('_') + def test_encode(self, html_encoding_file): + _, encoding = os.path.splitext( + os.path.basename(html_encoding_file) + )[0].split('_') try: - with open(f, 'rb') as fobj: + with open(html_encoding_file, 'rb') as fobj: from_string = self.read_html(fobj.read(), encoding=encoding, index_col=0).pop() - with open(f, 'rb') as fobj: + with open(html_encoding_file, 'rb') as fobj: from_file_like = self.read_html(BytesIO(fobj.read()), encoding=encoding, index_col=0).pop() - from_filename = self.read_html(f, encoding=encoding, + from_filename = self.read_html(html_encoding_file, + encoding=encoding, index_col=0).pop() tm.assert_frame_equal(from_string, from_file_like) tm.assert_frame_equal(from_string, from_filename) @@ -906,7 +920,7 @@ def seekable(self): assert self.read_html(bad) @pytest.mark.slow - def test_importcheck_thread_safety(self): + def test_importcheck_thread_safety(self, datapath): # see gh-16928 class ErrorThread(threading.Thread): @@ -921,7 +935,7 @@ def run(self): # force import check by reinitalising global vars in html.py reload(pandas.io.html) - filename = os.path.join(DATA_PATH, 'valid_markup.html') + filename = datapath('io', 'data', 'valid_markup.html') helper_thread1 = ErrorThread(target=self.read_html, args=(filename,)) helper_thread2 = ErrorThread(target=self.read_html, args=(filename,)) diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index cfac77291803d..491d5fe33cc33 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -3,6 +3,7 @@ from warnings import catch_warnings import os import datetime +import glob import numpy as np from distutils.version import LooseVersion @@ -837,13 +838,13 @@ def test_default_encoding(self): assert_frame_equal(result, frame) -def legacy_packers_versions(): - # yield the packers versions - path = tm.get_data_path('legacy_msgpack') - for v in os.listdir(path): - p = os.path.join(path, v) - if os.path.isdir(p): - yield v +files = glob.glob(os.path.join(os.path.dirname(__file__), "data", + "legacy_msgpack", "*", "*.msgpack")) + + +@pytest.fixture(params=files) +def legacy_packer(request, datapath): + return datapath(request.param) class TestMsgpack(object): @@ -920,24 +921,20 @@ def compare_frame_dt_mixed_tzs(self, result, expected, typ, version): else: tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize('version', legacy_packers_versions()) def test_msgpacks_legacy(self, current_packers_data, all_packers_data, - version): - - pth = tm.get_data_path('legacy_msgpack/{0}'.format(version)) - n = 0 - for f in os.listdir(pth): - # GH12142 0.17 files packed in P2 can't be read in P3 - if (compat.PY3 and version.startswith('0.17.') and - f.split('.')[-4][-1] == '2'): - continue - vf = os.path.join(pth, f) - try: - with catch_warnings(record=True): - self.compare(current_packers_data, all_packers_data, - vf, version) - except ImportError: - # blosc not installed - continue - n += 1 - assert n > 0, 'Msgpack files are not tested' + legacy_packer, datapath): + + version = os.path.basename(os.path.dirname(legacy_packer)) + + # GH12142 0.17 files packed in P2 can't be read in P3 + if (compat.PY3 and version.startswith('0.17.') and + legacy_packer.split('.')[-4][-1] == '2'): + msg = "Files packed in Py2 can't be read in Py3 ({})" + pytest.skip(msg.format(version)) + try: + with catch_warnings(record=True): + self.compare(current_packers_data, all_packers_data, + legacy_packer, version) + except ImportError: + # blosc not installed + pass diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index fbe2174e603e2..45cbbd43cd6a8 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -12,7 +12,7 @@ 3. Move the created pickle to "data/legacy_pickle/<version>" directory. """ - +import glob import pytest from warnings import catch_warnings @@ -184,27 +184,25 @@ def compare_sp_frame_float(result, expected, typ, version): tm.assert_sp_frame_equal(result, expected) +files = glob.glob(os.path.join(os.path.dirname(__file__), "data", + "legacy_pickle", "*", "*.pickle")) + + +@pytest.fixture(params=files) +def legacy_pickle(request, datapath): + return datapath(request.param) + + # --------------------- # tests # --------------------- -def legacy_pickle_versions(): - # yield the pickle versions - path = tm.get_data_path('legacy_pickle') - for v in os.listdir(path): - p = os.path.join(path, v) - if os.path.isdir(p): - for f in os.listdir(p): - yield (v, f) - - -@pytest.mark.parametrize('version, f', legacy_pickle_versions()) -def test_pickles(current_pickle_data, version, f): +def test_pickles(current_pickle_data, legacy_pickle): if not is_platform_little_endian(): pytest.skip("known failure on non-little endian") - vf = tm.get_data_path('legacy_pickle/{}/{}'.format(version, f)) + version = os.path.basename(os.path.dirname(legacy_pickle)) with catch_warnings(record=True): - compare(current_pickle_data, vf, version) + compare(current_pickle_data, legacy_pickle, version) def test_round_trip_current(current_pickle_data): @@ -260,12 +258,11 @@ def python_unpickler(path): compare_element(result, expected, typ) -def test_pickle_v0_14_1(): +def test_pickle_v0_14_1(datapath): cat = pd.Categorical(values=['a', 'b', 'c'], ordered=False, categories=['a', 'b', 'c', 'd']) - pickle_path = os.path.join(tm.get_data_path(), - 'categorical_0_14_1.pickle') + pickle_path = datapath('io', 'data', 'categorical_0_14_1.pickle') # This code was executed once on v0.14.1 to generate the pickle: # # cat = Categorical(labels=np.arange(3), levels=['a', 'b', 'c', 'd'], @@ -275,14 +272,13 @@ def test_pickle_v0_14_1(): tm.assert_categorical_equal(cat, pd.read_pickle(pickle_path)) -def test_pickle_v0_15_2(): +def test_pickle_v0_15_2(datapath): # ordered -> _ordered # GH 9347 cat = pd.Categorical(values=['a', 'b', 'c'], ordered=False, categories=['a', 'b', 'c', 'd']) - pickle_path = os.path.join(tm.get_data_path(), - 'categorical_0_15_2.pickle') + pickle_path = datapath('io', 'data', 'categorical_0_15_2.pickle') # This code was executed once on v0.15.2 to generate the pickle: # # cat = Categorical(labels=np.arange(3), levels=['a', 'b', 'c', 'd'], diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 5ac91c15047ff..7dafc9603f96d 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -1842,6 +1842,12 @@ def make_index(names=None): 'a', 'b'], index=make_index(['date', 'a', 't'])) pytest.raises(ValueError, store.append, 'df', df) + # dup within level + _maybe_remove(store, 'df') + df = DataFrame(np.zeros((12, 2)), columns=['a', 'b'], + index=make_index(['date', 'date', 'date'])) + pytest.raises(ValueError, store.append, 'df', df) + # fully names _maybe_remove(store, 'df') df = DataFrame(np.zeros((12, 2)), columns=[ @@ -4452,28 +4458,27 @@ def f(): store.select('df') tm.assert_raises_regex(ClosedFileError, 'file is not open', f) - def test_pytables_native_read(self): - + def test_pytables_native_read(self, datapath): with ensure_clean_store( - tm.get_data_path('legacy_hdf/pytables_native.h5'), + datapath('io', 'data', 'legacy_hdf/pytables_native.h5'), mode='r') as store: d2 = store['detector/readout'] assert isinstance(d2, DataFrame) @pytest.mark.skipif(PY35 and is_platform_windows(), reason="native2 read fails oddly on windows / 3.5") - def test_pytables_native2_read(self): + def test_pytables_native2_read(self, datapath): with ensure_clean_store( - tm.get_data_path('legacy_hdf/pytables_native2.h5'), + datapath('io', 'data', 'legacy_hdf', 'pytables_native2.h5'), mode='r') as store: str(store) d1 = store['detector'] assert isinstance(d1, DataFrame) - def test_legacy_table_read(self): + def test_legacy_table_read(self, datapath): # legacy table types with ensure_clean_store( - tm.get_data_path('legacy_hdf/legacy_table.h5'), + datapath('io', 'data', 'legacy_hdf', 'legacy_table.h5'), mode='r') as store: with catch_warnings(record=True): @@ -5120,7 +5125,7 @@ def test_fspath(self): with pd.HDFStore(path) as store: assert os.fspath(store) == str(path) - def test_read_py2_hdf_file_in_py3(self): + def test_read_py2_hdf_file_in_py3(self, datapath): # GH 16781 # tests reading a PeriodIndex DataFrame written in Python2 in Python3 @@ -5135,8 +5140,8 @@ def test_read_py2_hdf_file_in_py3(self): ['2015-01-01', '2015-01-02', '2015-01-05'], freq='B')) with ensure_clean_store( - tm.get_data_path( - 'legacy_hdf/periodindex_0.20.1_x86_64_darwin_2.7.13.h5'), + datapath('io', 'data', 'legacy_hdf', + 'periodindex_0.20.1_x86_64_darwin_2.7.13.h5'), mode='r') as store: result = store['p'] assert_frame_equal(result, expected) @@ -5533,14 +5538,14 @@ def test_store_timezone(self): assert_frame_equal(result, df) - def test_legacy_datetimetz_object(self): + def test_legacy_datetimetz_object(self, datapath): # legacy from < 0.17.0 # 8260 expected = DataFrame(dict(A=Timestamp('20130102', tz='US/Eastern'), B=Timestamp('20130603', tz='CET')), index=range(5)) with ensure_clean_store( - tm.get_data_path('legacy_hdf/datetimetz_object.h5'), + datapath('io', 'data', 'legacy_hdf', 'datetimetz_object.h5'), mode='r') as store: result = store['df'] assert_frame_equal(result, expected) diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index f3ab74d37a2bc..f8f742c5980ac 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -22,7 +22,6 @@ import pytest import sqlite3 import csv -import os import warnings import numpy as np @@ -184,9 +183,11 @@ class MixInBase(object): def teardown_method(self, method): - for tbl in self._get_all_tables(): - self.drop_table(tbl) - self._close_conn() + # if setup fails, there may not be a connection to close. + if hasattr(self, 'conn'): + for tbl in self._get_all_tables(): + self.drop_table(tbl) + self._close_conn() class MySQLMixIn(MixInBase): @@ -253,9 +254,9 @@ def _get_exec(self): else: return self.conn.cursor() - def _load_iris_data(self): + def _load_iris_data(self, datapath): import io - iris_csv_file = os.path.join(tm.get_data_path(), 'iris.csv') + iris_csv_file = datapath('io', 'data', 'iris.csv') self.drop_table('iris') self._get_exec().execute(SQL_STRINGS['create_iris'][self.flavor]) @@ -503,9 +504,10 @@ class _TestSQLApi(PandasSQLTest): flavor = 'sqlite' mode = None - def setup_method(self, method): + @pytest.fixture(autouse=True) + def setup_method(self, datapath): self.conn = self.connect() - self._load_iris_data() + self._load_iris_data(datapath) self._load_iris_view() self._load_test1_data() self._load_test2_data() @@ -1025,8 +1027,9 @@ class _EngineToConnMixin(object): A mixin that causes setup_connect to create a conn rather than an engine. """ - def setup_method(self, method): - super(_EngineToConnMixin, self).setup_method(method) + @pytest.fixture(autouse=True) + def setup_method(self, datapath): + super(_EngineToConnMixin, self).setup_method(datapath) engine = self.conn conn = engine.connect() self.__tx = conn.begin() @@ -1034,12 +1037,14 @@ def setup_method(self, method): self.__engine = engine self.conn = conn - def teardown_method(self, method): + yield + self.__tx.rollback() self.conn.close() self.conn = self.__engine self.pandasSQL = sql.SQLDatabase(self.__engine) - super(_EngineToConnMixin, self).teardown_method(method) + # XXX: + # super(_EngineToConnMixin, self).teardown_method(method) @pytest.mark.single @@ -1136,7 +1141,7 @@ class _TestSQLAlchemy(SQLAlchemyMixIn, PandasSQLTest): """ flavor = None - @classmethod + @pytest.fixture(autouse=True, scope='class') def setup_class(cls): cls.setup_import() cls.setup_driver() @@ -1149,10 +1154,11 @@ def setup_class(cls): msg = "{0} - can't connect to {1} server".format(cls, cls.flavor) pytest.skip(msg) - def setup_method(self, method): + @pytest.fixture(autouse=True) + def setup_method(self, datapath): self.setup_connect() - self._load_iris_data() + self._load_iris_data(datapath) self._load_raw_sql() self._load_test1_data() @@ -1920,11 +1926,12 @@ class TestSQLiteFallback(SQLiteMixIn, PandasSQLTest): def connect(cls): return sqlite3.connect(':memory:') - def setup_method(self, method): + @pytest.fixture(autouse=True) + def setup_method(self, datapath): self.conn = self.connect() self.pandasSQL = sql.SQLiteDatabase(self.conn) - self._load_iris_data() + self._load_iris_data(datapath) self._load_test1_data() @@ -2135,8 +2142,9 @@ def _skip_if_no_pymysql(): @pytest.mark.single class TestXSQLite(SQLiteMixIn): - def setup_method(self, method): - self.method = method + @pytest.fixture(autouse=True) + def setup_method(self, request, datapath): + self.method = request.function self.conn = sqlite3.connect(':memory:') def test_basic(self): @@ -2215,8 +2223,7 @@ def test_execute_fail(self): with pytest.raises(Exception): sql.execute('INSERT INTO test VALUES("foo", "bar", 7)', self.conn) - @tm.capture_stdout - def test_execute_closed_connection(self): + def test_execute_closed_connection(self, request, datapath): create_sql = """ CREATE TABLE test ( @@ -2236,7 +2243,7 @@ def test_execute_closed_connection(self): tquery("select * from test", con=self.conn) # Initialize connection again (needed for tearDown) - self.setup_method(self.method) + self.setup_method(request, datapath) def test_na_roundtrip(self): pass @@ -2341,7 +2348,7 @@ def clean_up(test_table_to_drop): "if SQLAlchemy is not installed") class TestXMySQL(MySQLMixIn): - @classmethod + @pytest.fixture(autouse=True, scope='class') def setup_class(cls): _skip_if_no_pymysql() @@ -2370,7 +2377,8 @@ def setup_class(cls): "[pandas] in your system's mysql default file, " "typically located at ~/.my.cnf or /etc/.my.cnf. ") - def setup_method(self, method): + @pytest.fixture(autouse=True) + def setup_method(self, request, datapath): _skip_if_no_pymysql() import pymysql try: @@ -2396,7 +2404,7 @@ def setup_method(self, method): "[pandas] in your system's mysql default file, " "typically located at ~/.my.cnf or /etc/.my.cnf. ") - self.method = method + self.method = request.function def test_basic(self): _skip_if_no_pymysql() @@ -2501,8 +2509,7 @@ def test_execute_fail(self): with pytest.raises(Exception): sql.execute('INSERT INTO test VALUES("foo", "bar", 7)', self.conn) - @tm.capture_stdout - def test_execute_closed_connection(self): + def test_execute_closed_connection(self, request, datapath): _skip_if_no_pymysql() drop_sql = "DROP TABLE IF EXISTS test" create_sql = """ @@ -2525,7 +2532,7 @@ def test_execute_closed_connection(self): tquery("select * from test", con=self.conn) # Initialize connection again (needed for tearDown) - self.setup_method(self.method) + self.setup_method(request, datapath) def test_na_roundtrip(self): _skip_if_no_pymysql() diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index f3a465da4e87f..cff63516f4086 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -25,8 +25,8 @@ @pytest.fixture -def dirpath(): - return tm.get_data_path() +def dirpath(datapath): + return datapath("io", "data") @pytest.fixture @@ -39,8 +39,9 @@ def parsed_114(dirpath): class TestStata(object): - def setup_method(self, method): - self.dirpath = tm.get_data_path() + @pytest.fixture(autouse=True) + def setup_method(self, datapath): + self.dirpath = datapath("io", "data") self.dta1_114 = os.path.join(self.dirpath, 'stata1_114.dta') self.dta1_117 = os.path.join(self.dirpath, 'stata1_117.dta') diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index f65791329f2f1..09687dd97bd43 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -74,11 +74,6 @@ def setup_method(self, method): else: self.default_figsize = (8.0, 6.0) self.default_tick_position = 'left' if self.mpl_ge_2_0_0 else 'default' - # common test data - from pandas import read_csv - base = os.path.join(os.path.dirname(curpath()), os.pardir) - path = os.path.join(base, 'tests', 'data', 'iris.csv') - self.iris = read_csv(path) n = 100 with tm.RNGContext(42): diff --git a/pandas/tests/plotting/test_deprecated.py b/pandas/tests/plotting/test_deprecated.py index 2c2d371921d2f..a45b17ec98261 100644 --- a/pandas/tests/plotting/test_deprecated.py +++ b/pandas/tests/plotting/test_deprecated.py @@ -46,10 +46,9 @@ def test_boxplot_deprecated(self): by='indic') @pytest.mark.slow - def test_radviz_deprecated(self): - df = self.iris + def test_radviz_deprecated(self, iris): with tm.assert_produces_warning(FutureWarning): - plotting.radviz(frame=df, class_column='Name') + plotting.radviz(frame=iris, class_column='Name') @pytest.mark.slow def test_plot_params(self): diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index c82c939584dc7..0473610ea2f8f 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -100,11 +100,11 @@ def test_scatter_matrix_axis(self): axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) @pytest.mark.slow - def test_andrews_curves(self): + def test_andrews_curves(self, iris): from pandas.plotting import andrews_curves from matplotlib import cm - df = self.iris + df = iris _check_plot_works(andrews_curves, frame=df, class_column='Name') @@ -165,11 +165,11 @@ def test_andrews_curves(self): andrews_curves(data=df, class_column='Name') @pytest.mark.slow - def test_parallel_coordinates(self): + def test_parallel_coordinates(self, iris): from pandas.plotting import parallel_coordinates from matplotlib import cm - df = self.iris + df = iris ax = _check_plot_works(parallel_coordinates, frame=df, class_column='Name') @@ -234,11 +234,11 @@ def test_parallel_coordinates_with_sorted_labels(self): assert prev[1] < nxt[1] and prev[0] < nxt[0] @pytest.mark.slow - def test_radviz(self): + def test_radviz(self, iris): from pandas.plotting import radviz from matplotlib import cm - df = self.iris + df = iris _check_plot_works(radviz, frame=df, class_column='Name') rgba = ('#556270', '#4ECDC4', '#C7F464') @@ -272,8 +272,8 @@ def test_radviz(self): self._check_colors(handles, facecolors=colors) @pytest.mark.slow - def test_subplot_titles(self): - df = self.iris.drop('Name', axis=1).head() + def test_subplot_titles(self, iris): + df = iris.drop('Name', axis=1).head() # Use the column names as the subplot titles title = list(df.columns) diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index cebbcc41c3e17..59b53cd23010e 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -1,4 +1,3 @@ -import os import pytest import pytz @@ -13,8 +12,8 @@ class TestAsOfMerge(object): - def read_data(self, name, dedupe=False): - path = os.path.join(tm.get_data_path(), name) + def read_data(self, datapath, name, dedupe=False): + path = datapath('reshape', 'merge', 'data', name) x = read_csv(path) if dedupe: x = (x.drop_duplicates(['time', 'ticker'], keep='last') @@ -23,15 +22,17 @@ def read_data(self, name, dedupe=False): x.time = to_datetime(x.time) return x - def setup_method(self, method): + @pytest.fixture(autouse=True) + def setup_method(self, datapath): - self.trades = self.read_data('trades.csv') - self.quotes = self.read_data('quotes.csv', dedupe=True) - self.asof = self.read_data('asof.csv') - self.tolerance = self.read_data('tolerance.csv') - self.allow_exact_matches = self.read_data('allow_exact_matches.csv') + self.trades = self.read_data(datapath, 'trades.csv') + self.quotes = self.read_data(datapath, 'quotes.csv', dedupe=True) + self.asof = self.read_data(datapath, 'asof.csv') + self.tolerance = self.read_data(datapath, 'tolerance.csv') + self.allow_exact_matches = self.read_data(datapath, + 'allow_exact_matches.csv') self.allow_exact_matches_and_tolerance = self.read_data( - 'allow_exact_matches_and_tolerance.csv') + datapath, 'allow_exact_matches_and_tolerance.csv') def test_examples1(self): """ doc-string examples """ @@ -423,11 +424,11 @@ def test_multiby_indexed(self): pd.merge_asof(left, right, left_index=True, right_index=True, left_by=['k1', 'k2'], right_by=['k1']) - def test_basic2(self): + def test_basic2(self, datapath): - expected = self.read_data('asof2.csv') - trades = self.read_data('trades2.csv') - quotes = self.read_data('quotes2.csv', dedupe=True) + expected = self.read_data(datapath, 'asof2.csv') + trades = self.read_data(datapath, 'trades2.csv') + quotes = self.read_data(datapath, 'quotes2.csv', dedupe=True) result = merge_asof(trades, quotes, on='time', @@ -467,14 +468,14 @@ def test_valid_join_keys(self): merge_asof(trades, quotes, by='ticker') - def test_with_duplicates(self): + def test_with_duplicates(self, datapath): q = pd.concat([self.quotes, self.quotes]).sort_values( ['time', 'ticker']).reset_index(drop=True) result = merge_asof(self.trades, q, on='time', by='ticker') - expected = self.read_data('asof.csv') + expected = self.read_data(datapath, 'asof.csv') assert_frame_equal(result, expected) def test_with_duplicates_no_on(self): diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 3ec60d50f2792..b71954163f9e1 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1729,9 +1729,15 @@ def test_crosstab_with_numpy_size(self): tm.assert_frame_equal(result, expected) def test_crosstab_dup_index_names(self): - # GH 13279, GH 18872 + # GH 13279 s = pd.Series(range(3), name='foo') - pytest.raises(ValueError, pd.crosstab, s, s) + + result = pd.crosstab(s, s) + expected_index = pd.Index(range(3), name='foo') + expected = pd.DataFrame(np.eye(3, dtype=np.int64), + index=expected_index, + columns=expected_index) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("names", [['a', ('b', 'c')], [('a', 'b'), 'c']]) diff --git a/pandas/tests/reshape/test_tile.py b/pandas/tests/reshape/test_tile.py index 5ea27f9e34e1c..807fb2530603a 100644 --- a/pandas/tests/reshape/test_tile.py +++ b/pandas/tests/reshape/test_tile.py @@ -282,10 +282,10 @@ def test_round_frac(self): result = tmod._round_frac(0.000123456, precision=2) assert result == 0.00012 - def test_qcut_binning_issues(self): + def test_qcut_binning_issues(self, datapath): # #1978, 1979 - path = os.path.join(tm.get_data_path(), 'cut_data.csv') - arr = np.loadtxt(path) + cut_file = datapath(os.path.join('reshape', 'data', 'cut_data.csv')) + arr = np.loadtxt(cut_file) result = qcut(arr, 20) diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index aecddab8477fc..dbe31ccb11114 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -118,6 +118,25 @@ def test_ceil_floor_edge(self, test_input, rounder, freq, expected): expected = Timestamp(expected) assert result == expected + @pytest.mark.parametrize('test_input, freq, expected', [ + ('2018-01-01 00:02:06', '2s', '2018-01-01 00:02:06'), + ('2018-01-01 00:02:00', '2T', '2018-01-01 00:02:00'), + ('2018-01-01 00:04:00', '4T', '2018-01-01 00:04:00'), + ('2018-01-01 00:15:00', '15T', '2018-01-01 00:15:00'), + ('2018-01-01 00:20:00', '20T', '2018-01-01 00:20:00'), + ('2018-01-01 03:00:00', '3H', '2018-01-01 03:00:00'), + ]) + @pytest.mark.parametrize('rounder', ['ceil', 'floor', 'round']) + def test_round_minute_freq(self, test_input, freq, expected, rounder): + # Ensure timestamps that shouldnt round dont! + # GH#21262 + + dt = Timestamp(test_input) + expected = Timestamp(expected) + func = getattr(dt, rounder) + result = func(freq) + assert result == expected + def test_ceil(self): dt = Timestamp('20130101 09:10:11') result = dt.ceil('D') @@ -257,7 +276,6 @@ def test_timestamp(self): if PY3: # datetime.timestamp() converts in the local timezone with tm.set_timezone('UTC'): - # should agree with datetime.timestamp method dt = ts.to_pydatetime() assert dt.timestamp() == ts.timestamp() diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 7973b27601237..128ab0572ba55 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -2717,3 +2717,10 @@ def test_panel_index(): np.repeat([1, 2, 3], 4)], names=['time', 'panel']) tm.assert_index_equal(index, expected) + + +def test_panel_np_all(): + with catch_warnings(record=True): + wp = Panel({"A": DataFrame({'b': [1, 2]})}) + result = np.all(wp) + assert result == np.bool_(True) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 5369b1a94a956..00701ca2be946 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -1,4 +1,3 @@ -import os from distutils.version import LooseVersion from datetime import date, datetime, timedelta @@ -455,14 +454,15 @@ def test_add(self, offset_types, tz): assert isinstance(result, Timestamp) assert result == expected_localize - def test_pickle_v0_15_2(self): + def test_pickle_v0_15_2(self, datapath): offsets = {'DateOffset': DateOffset(years=1), 'MonthBegin': MonthBegin(1), 'Day': Day(1), 'YearBegin': YearBegin(1), 'Week': Week(1)} - pickle_path = os.path.join(tm.get_data_path(), - 'dateoffset_0_15_2.pickle') + + pickle_path = datapath('tseries', 'offsets', 'data', + 'dateoffset_0_15_2.pickle') # This code was executed once on v0.15.2 to generate the pickle: # with open(pickle_path, 'wb') as f: pickle.dump(offsets, f) # @@ -528,7 +528,10 @@ def test_repr(self): assert repr(self.offset) == '<BusinessDay>' assert repr(self.offset2) == '<2 * BusinessDays>' - expected = '<BusinessDay: offset=datetime.timedelta(1)>' + if compat.PY37: + expected = '<BusinessDay: offset=datetime.timedelta(days=1)>' + else: + expected = '<BusinessDay: offset=datetime.timedelta(1)>' assert repr(self.offset + timedelta(1)) == expected def test_with_offset(self): @@ -1642,7 +1645,10 @@ def test_repr(self): assert repr(self.offset) == '<CustomBusinessDay>' assert repr(self.offset2) == '<2 * CustomBusinessDays>' - expected = '<BusinessDay: offset=datetime.timedelta(1)>' + if compat.PY37: + expected = '<BusinessDay: offset=datetime.timedelta(days=1)>' + else: + expected = '<BusinessDay: offset=datetime.timedelta(1)>' assert repr(self.offset + timedelta(1)) == expected def test_with_offset(self): @@ -1848,12 +1854,10 @@ def _check_roundtrip(obj): _check_roundtrip(self.offset2) _check_roundtrip(self.offset * 2) - def test_pickle_compat_0_14_1(self): + def test_pickle_compat_0_14_1(self, datapath): hdays = [datetime(2013, 1, 1) for ele in range(4)] - - pth = tm.get_data_path() - - cday0_14_1 = read_pickle(os.path.join(pth, 'cday-0.14.1.pickle')) + pth = datapath('tseries', 'offsets', 'data', 'cday-0.14.1.pickle') + cday0_14_1 = read_pickle(pth) cday = CDay(holidays=hdays) assert cday == cday0_14_1 diff --git a/pandas/tests/util/test_testing.py b/pandas/tests/util/test_testing.py index ab7c4fb528452..4d34987e14f75 100644 --- a/pandas/tests/util/test_testing.py +++ b/pandas/tests/util/test_testing.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +import os import pandas as pd import pytest import numpy as np @@ -841,3 +842,15 @@ def test_locale(self): # GH9744 locales = tm.get_locales() assert len(locales) >= 1 + + +def test_datapath_missing(datapath, request): + if not request.config.getoption("--strict-data-files"): + pytest.skip("Need to set '--strict-data-files'") + + with pytest.raises(ValueError): + datapath('not_a_file') + + result = datapath('data', 'iris.csv') + expected = os.path.join('pandas', 'tests', 'data', 'iris.csv') + assert result == expected diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index 89d90258f58e0..c6ab24403d58d 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -23,13 +23,13 @@ def test_foo(): For more information, refer to the ``pytest`` documentation on ``skipif``. """ - import pytest import locale from distutils.version import LooseVersion from pandas.compat import (is_platform_windows, is_platform_32bit, PY3, import_lzma) +from pandas.compat.numpy import _np_version_under1p15 from pandas.core.computation.expressions import (_USE_NUMEXPR, _NUMEXPR_INSTALLED) @@ -160,6 +160,9 @@ def decorated_func(func): skip_if_no_mpl = pytest.mark.skipif(_skip_if_no_mpl(), reason="Missing matplotlib dependency") + +skip_if_np_lt_115 = pytest.mark.skipif(_np_version_under1p15, + reason="NumPy 1.15 or greater required") skip_if_mpl = pytest.mark.skipif(not _skip_if_no_mpl(), reason="matplotlib is present") skip_if_mpl_1_5 = pytest.mark.skipif(_skip_if_mpl_1_5(), diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 6384eca9849f6..b7edbff00a4b9 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -6,7 +6,6 @@ import sys import tempfile import warnings -import inspect import os import subprocess import locale @@ -751,15 +750,6 @@ def ensure_clean(filename=None, return_filelike=False): print("Exception on removing file: {error}".format(error=e)) -def get_data_path(f=''): - """Return the path of a data file, these are relative to the current test - directory. - """ - # get our callers file - _, filename, _, _, _, _ = inspect.getouterframes(inspect.currentframe())[1] - base_dir = os.path.abspath(os.path.dirname(filename)) - return os.path.join(base_dir, 'data', f) - # ----------------------------------------------------------------------------- # Comparators diff --git a/setup.cfg b/setup.cfg index 6d9657737a8bd..9ec967c25e225 100644 --- a/setup.cfg +++ b/setup.cfg @@ -32,4 +32,5 @@ markers = slow: mark a test as slow network: mark a test as network high_memory: mark a test as a high-memory only -doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL +addopts = --strict-data-files +doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL \ No newline at end of file diff --git a/setup.py b/setup.py index 90ec8e91a0700..5d6bbbcf7b862 100755 --- a/setup.py +++ b/setup.py @@ -217,6 +217,7 @@ def build_extensions(self): 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', 'Programming Language :: Cython', 'Topic :: Scientific/Engineering'] @@ -733,11 +734,7 @@ def pxd(name): maintainer=AUTHOR, version=versioneer.get_version(), packages=find_packages(include=['pandas', 'pandas.*']), - package_data={'': ['data/*', 'templates/*', '_libs/*.dll'], - 'pandas.tests.io': ['data/legacy_hdf/*.h5', - 'data/legacy_pickle/*/*.pickle', - 'data/legacy_msgpack/*/*.msgpack', - 'data/html_encoding/*.html']}, + package_data={'': ['templates/*', '_libs/*.dll']}, ext_modules=extensions, maintainer_email=EMAIL, description=DESCRIPTION,
https://api.github.com/repos/pandas-dev/pandas/pulls/21708
2018-07-02T15:47:07Z
2018-07-05T17:34:18Z
2018-07-05T17:34:18Z
2018-07-05T17:34:28Z
DOC: consistent sphinx title levels
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 0ca5b9cdf1d57..b275796237191 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -45,14 +45,13 @@ Other Enhancements .. _whatsnew_0240.api_breaking: - Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. _whatsnew_0240.api.datetimelike.normalize: Tick DateOffset Normalize Restrictions --------------------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Creating a ``Tick`` object (:class:`Day`, :class:`Hour`, :class:`Minute`, :class:`Second`, :class:`Milli`, :class:`Micro`, :class:`Nano`) with @@ -129,22 +128,11 @@ Previous Behavior: In [3]: pi - pi[0] Out[3]: Int64Index([0, 1, 2], dtype='int64') -Datetimelike API Changes -^^^^^^^^^^^^^^^^^^^^^^^^ - -- For :class:`DatetimeIndex` and :class:`TimedeltaIndex` with non-``None`` ``freq`` attribute, addition or subtraction of integer-dtyped array or ``Index`` will return an object of the same class (:issue:`19959`) -- :class:`DateOffset` objects are now immutable. Attempting to alter one of these will now raise ``AttributeError`` (:issue:`21341`) -- :class:`PeriodIndex` subtraction of another ``PeriodIndex`` will now return an object-dtype :class:`Index` of :class:`DateOffset` objects instead of raising a ``TypeError`` (:issue:`20049`) - -.. _whatsnew_0240.api.other: - -Other API Changes -^^^^^^^^^^^^^^^^^ -.. _whatsnew_0240.api.other.incompatibilities: +.. _whatsnew_0240.api.incompatibilities: Series and Index Data-Dtype Incompatibilities ---------------------------------------------- +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``Series`` and ``Index`` constructors now raise when the data is incompatible with a passed ``dtype=`` (:issue:`15832`) @@ -167,6 +155,18 @@ Current Behavior: ... OverflowError: Trying to coerce negative values to unsigned integers +Datetimelike API Changes +^^^^^^^^^^^^^^^^^^^^^^^^ + +- For :class:`DatetimeIndex` and :class:`TimedeltaIndex` with non-``None`` ``freq`` attribute, addition or subtraction of integer-dtyped array or ``Index`` will return an object of the same class (:issue:`19959`) +- :class:`DateOffset` objects are now immutable. Attempting to alter one of these will now raise ``AttributeError`` (:issue:`21341`) +- :class:`PeriodIndex` subtraction of another ``PeriodIndex`` will now return an object-dtype :class:`Index` of :class:`DateOffset` objects instead of raising a ``TypeError`` (:issue:`20049`) + +.. _whatsnew_0240.api.other: + +Other API Changes +^^^^^^^^^^^^^^^^^ + - :class:`DatetimeIndex` now accepts :class:`Int64Index` arguments as epoch timestamps (:issue:`20997`) - -
To fix the sphinx build warnings
https://api.github.com/repos/pandas-dev/pandas/pulls/21706
2018-07-02T13:39:18Z
2018-07-02T14:37:47Z
2018-07-02T14:37:47Z
2018-07-02T14:37:51Z
BUG : Adding *kwargs for name retention in Index args
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index a99c913f95e82..783c5de70ae2d 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -98,7 +98,7 @@ def _convert_and_box_cache(arg, cache_array, box, errors, name=None): result = Series(arg).map(cache_array) if box: if errors == 'ignore': - return Index(result) + return Index(result, name=name) else: return DatetimeIndex(result, name=name) return result.values @@ -135,7 +135,7 @@ def _return_parsed_timezone_results(result, timezones, box, tz): in zip(result, timezones)]) if box: from pandas import Index - return Index(tz_results) + return Index(tz_results, name=name) return tz_results @@ -526,6 +526,119 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, pandas.DataFrame.astype : Cast argument to a specified dtype. pandas.to_timedelta : Convert argument to timedelta. """ + from pandas.core.indexes.datetimes import DatetimeIndex + + tz = 'utc' if utc else None + + def _convert_listlike(arg, box, format, name=None, tz=tz): + + if isinstance(arg, (list, tuple)): + arg = np.array(arg, dtype='O') + + # these are shortcutable + if is_datetime64tz_dtype(arg): + if not isinstance(arg, DatetimeIndex): + return DatetimeIndex(arg, tz=tz, name=name) + if utc: + arg = arg.tz_convert(None).tz_localize('UTC') + return arg + + elif is_datetime64_ns_dtype(arg): + if box and not isinstance(arg, DatetimeIndex): + try: + return DatetimeIndex(arg, tz=tz, name=name) + except ValueError: + pass + + return arg + + elif unit is not None: + if format is not None: + raise ValueError("cannot specify both format and unit") + arg = getattr(arg, 'values', arg) + result = tslib.array_with_unit_to_datetime(arg, unit, + errors=errors) + if box: + if errors == 'ignore': + from pandas import Index + return Index(result, name=name) + + return DatetimeIndex(result, tz=tz, name=name) + return result + elif getattr(arg, 'ndim', 1) > 1: + raise TypeError('arg must be a string, datetime, list, tuple, ' + '1-d array, or Series') + + arg = _ensure_object(arg) + require_iso8601 = False + + if infer_datetime_format and format is None: + format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst) + + if format is not None: + # There is a special fast-path for iso8601 formatted + # datetime strings, so in those cases don't use the inferred + # format because this path makes process slower in this + # special case + format_is_iso8601 = _format_is_iso(format) + if format_is_iso8601: + require_iso8601 = not infer_datetime_format + format = None + + try: + result = None + + if format is not None: + # shortcut formatting here + if format == '%Y%m%d': + try: + result = _attempt_YYYYMMDD(arg, errors=errors) + except: + raise ValueError("cannot convert the input to " + "'%Y%m%d' date format") + + # fallback + if result is None: + try: + result, timezones = array_strptime( + arg, format, exact=exact, errors=errors) + if '%Z' in format or '%z' in format: + return _return_parsed_timezone_results( + result, timezones, box, tz) + except tslib.OutOfBoundsDatetime: + if errors == 'raise': + raise + result = arg + except ValueError: + # if format was inferred, try falling back + # to array_to_datetime - terminate here + # for specified formats + if not infer_datetime_format: + if errors == 'raise': + raise + result = arg + + if result is None and (format is None or infer_datetime_format): + result = tslib.array_to_datetime( + arg, + errors=errors, + utc=utc, + dayfirst=dayfirst, + yearfirst=yearfirst, + require_iso8601=require_iso8601 + ) + + if is_datetime64_dtype(result) and box: + result = DatetimeIndex(result, tz=tz, name=name) + return result + + except ValueError as e: + try: + values, tz = conversion.datetime_to_datetime64(arg) + return DatetimeIndex._simple_new(values, name=name, tz=tz) + except (ValueError, TypeError): + raise e + if arg is None: return None
- [x] closes #21697 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21703
2018-07-02T07:12:45Z
2018-07-20T13:32:59Z
null
2018-07-20T13:32:59Z
CLN: to_datetime internals
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 18802d98a347e..a99c913f95e82 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -1,3 +1,4 @@ +from functools import partial from datetime import datetime, timedelta, time from collections import MutableMapping @@ -38,7 +39,7 @@ def _guess_datetime_format_for_array(arr, **kwargs): return _guess_datetime_format(arr[non_nan_elements[0]], **kwargs) -def _maybe_cache(arg, format, cache, tz, convert_listlike): +def _maybe_cache(arg, format, cache, convert_listlike): """ Create a cache of unique dates from an array of dates @@ -49,8 +50,6 @@ def _maybe_cache(arg, format, cache, tz, convert_listlike): Strftime format to parse time cache : boolean True attempts to create a cache of converted values - tz : string - Timezone of the dates convert_listlike : function Conversion function to apply on dates @@ -66,7 +65,7 @@ def _maybe_cache(arg, format, cache, tz, convert_listlike): from pandas import Index if not Index(arg).is_unique: unique_dates = algorithms.unique(arg) - cache_dates = convert_listlike(unique_dates, True, format, tz=tz) + cache_dates = convert_listlike(unique_dates, True, format) cache_array = Series(cache_dates, index=unique_dates) return cache_array @@ -140,6 +139,227 @@ def _return_parsed_timezone_results(result, timezones, box, tz): return tz_results +def _convert_listlike_datetimes(arg, box, format, name=None, tz=None, + unit=None, errors=None, + infer_datetime_format=None, dayfirst=None, + yearfirst=None, exact=None): + """ + Helper function for to_datetime. Performs the conversions of 1D listlike + of dates + + Parameters + ---------- + arg : list, tuple, ndarray, Series, Index + date to be parced + box : boolean + True boxes result as an Index-like, False returns an ndarray + name : object + None or string for the Index name + tz : object + None or 'utc' + unit : string + None or string of the frequency of the passed data + errors : string + error handing behaviors from to_datetime, 'raise', 'coerce', 'ignore' + infer_datetime_format : boolean + inferring format behavior from to_datetime + dayfirst : boolean + dayfirst parsing behavior from to_datetime + yearfirst : boolean + yearfirst parsing behavior from to_datetime + exact : boolean + exact format matching behavior from to_datetime + + Returns + ------- + ndarray of parsed dates + Returns: + + - Index-like if box=True + - ndarray of Timestamps if box=False + """ + from pandas import DatetimeIndex + if isinstance(arg, (list, tuple)): + arg = np.array(arg, dtype='O') + + # these are shortcutable + if is_datetime64tz_dtype(arg): + if not isinstance(arg, DatetimeIndex): + return DatetimeIndex(arg, tz=tz, name=name) + if tz == 'utc': + arg = arg.tz_convert(None).tz_localize(tz) + return arg + + elif is_datetime64_ns_dtype(arg): + if box and not isinstance(arg, DatetimeIndex): + try: + return DatetimeIndex(arg, tz=tz, name=name) + except ValueError: + pass + + return arg + + elif unit is not None: + if format is not None: + raise ValueError("cannot specify both format and unit") + arg = getattr(arg, 'values', arg) + result = tslib.array_with_unit_to_datetime(arg, unit, + errors=errors) + if box: + if errors == 'ignore': + from pandas import Index + return Index(result) + + return DatetimeIndex(result, tz=tz, name=name) + return result + elif getattr(arg, 'ndim', 1) > 1: + raise TypeError('arg must be a string, datetime, list, tuple, ' + '1-d array, or Series') + + arg = _ensure_object(arg) + require_iso8601 = False + + if infer_datetime_format and format is None: + format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst) + + if format is not None: + # There is a special fast-path for iso8601 formatted + # datetime strings, so in those cases don't use the inferred + # format because this path makes process slower in this + # special case + format_is_iso8601 = _format_is_iso(format) + if format_is_iso8601: + require_iso8601 = not infer_datetime_format + format = None + + try: + result = None + + if format is not None: + # shortcut formatting here + if format == '%Y%m%d': + try: + result = _attempt_YYYYMMDD(arg, errors=errors) + except: + raise ValueError("cannot convert the input to " + "'%Y%m%d' date format") + + # fallback + if result is None: + try: + result, timezones = array_strptime( + arg, format, exact=exact, errors=errors) + if '%Z' in format or '%z' in format: + return _return_parsed_timezone_results( + result, timezones, box, tz) + except tslib.OutOfBoundsDatetime: + if errors == 'raise': + raise + result = arg + except ValueError: + # if format was inferred, try falling back + # to array_to_datetime - terminate here + # for specified formats + if not infer_datetime_format: + if errors == 'raise': + raise + result = arg + + if result is None and (format is None or infer_datetime_format): + result = tslib.array_to_datetime( + arg, + errors=errors, + utc=tz == 'utc', + dayfirst=dayfirst, + yearfirst=yearfirst, + require_iso8601=require_iso8601 + ) + + if is_datetime64_dtype(result) and box: + result = DatetimeIndex(result, tz=tz, name=name) + return result + + except ValueError as e: + try: + values, tz = conversion.datetime_to_datetime64(arg) + return DatetimeIndex._simple_new(values, name=name, tz=tz) + except (ValueError, TypeError): + raise e + + +def _adjust_to_origin(arg, origin, unit): + """ + Helper function for to_datetime. + Adjust input argument to the specified origin + + Parameters + ---------- + arg : list, tuple, ndarray, Series, Index + date to be adjusted + origin : 'julian' or Timestamp + origin offset for the arg + unit : string + passed unit from to_datetime, must be 'D' + + Returns + ------- + ndarray or scalar of adjusted date(s) + """ + if origin == 'julian': + original = arg + j0 = tslib.Timestamp(0).to_julian_date() + if unit != 'D': + raise ValueError("unit must be 'D' for origin='julian'") + try: + arg = arg - j0 + except: + raise ValueError("incompatible 'arg' type for given " + "'origin'='julian'") + + # premptively check this for a nice range + j_max = tslib.Timestamp.max.to_julian_date() - j0 + j_min = tslib.Timestamp.min.to_julian_date() - j0 + if np.any(arg > j_max) or np.any(arg < j_min): + raise tslib.OutOfBoundsDatetime( + "{original} is Out of Bounds for " + "origin='julian'".format(original=original)) + else: + # arg must be numeric + if not ((is_scalar(arg) and (is_integer(arg) or is_float(arg))) or + is_numeric_dtype(np.asarray(arg))): + raise ValueError( + "'{arg}' is not compatible with origin='{origin}'; " + "it must be numeric with a unit specified ".format( + arg=arg, + origin=origin)) + + # we are going to offset back to unix / epoch time + try: + offset = tslib.Timestamp(origin) + except tslib.OutOfBoundsDatetime: + raise tslib.OutOfBoundsDatetime( + "origin {origin} is Out of Bounds".format(origin=origin)) + except ValueError: + raise ValueError("origin {origin} cannot be converted " + "to a Timestamp".format(origin=origin)) + + if offset.tz is not None: + raise ValueError( + "origin offset {} must be tz-naive".format(offset)) + offset -= tslib.Timestamp(0) + + # convert the offset to the unit of the arg + # this should be lossless in terms of precision + offset = offset // tslib.Timedelta(1, unit=unit) + + # scalars & ndarray-like can handle the addition + if is_list_like(arg) and not isinstance( + arg, (ABCSeries, ABCIndexClass, np.ndarray)): + arg = np.asarray(arg) + arg = arg + offset + return arg + + def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', @@ -306,207 +526,46 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, pandas.DataFrame.astype : Cast argument to a specified dtype. pandas.to_timedelta : Convert argument to timedelta. """ - from pandas.core.indexes.datetimes import DatetimeIndex - - tz = 'utc' if utc else None - - def _convert_listlike(arg, box, format, name=None, tz=tz): - - if isinstance(arg, (list, tuple)): - arg = np.array(arg, dtype='O') - - # these are shortcutable - if is_datetime64tz_dtype(arg): - if not isinstance(arg, DatetimeIndex): - return DatetimeIndex(arg, tz=tz, name=name) - if utc: - arg = arg.tz_convert(None).tz_localize('UTC') - return arg - - elif is_datetime64_ns_dtype(arg): - if box and not isinstance(arg, DatetimeIndex): - try: - return DatetimeIndex(arg, tz=tz, name=name) - except ValueError: - pass - - return arg - - elif unit is not None: - if format is not None: - raise ValueError("cannot specify both format and unit") - arg = getattr(arg, 'values', arg) - result = tslib.array_with_unit_to_datetime(arg, unit, - errors=errors) - if box: - if errors == 'ignore': - from pandas import Index - return Index(result) - - return DatetimeIndex(result, tz=tz, name=name) - return result - elif getattr(arg, 'ndim', 1) > 1: - raise TypeError('arg must be a string, datetime, list, tuple, ' - '1-d array, or Series') - - arg = _ensure_object(arg) - require_iso8601 = False - - if infer_datetime_format and format is None: - format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst) - - if format is not None: - # There is a special fast-path for iso8601 formatted - # datetime strings, so in those cases don't use the inferred - # format because this path makes process slower in this - # special case - format_is_iso8601 = _format_is_iso(format) - if format_is_iso8601: - require_iso8601 = not infer_datetime_format - format = None - - try: - result = None - - if format is not None: - # shortcut formatting here - if format == '%Y%m%d': - try: - result = _attempt_YYYYMMDD(arg, errors=errors) - except: - raise ValueError("cannot convert the input to " - "'%Y%m%d' date format") - - # fallback - if result is None: - try: - result, timezones = array_strptime( - arg, format, exact=exact, errors=errors) - if '%Z' in format or '%z' in format: - return _return_parsed_timezone_results( - result, timezones, box, tz) - except tslib.OutOfBoundsDatetime: - if errors == 'raise': - raise - result = arg - except ValueError: - # if format was inferred, try falling back - # to array_to_datetime - terminate here - # for specified formats - if not infer_datetime_format: - if errors == 'raise': - raise - result = arg - - if result is None and (format is None or infer_datetime_format): - result = tslib.array_to_datetime( - arg, - errors=errors, - utc=utc, - dayfirst=dayfirst, - yearfirst=yearfirst, - require_iso8601=require_iso8601 - ) - - if is_datetime64_dtype(result) and box: - result = DatetimeIndex(result, tz=tz, name=name) - return result - - except ValueError as e: - try: - values, tz = conversion.datetime_to_datetime64(arg) - return DatetimeIndex._simple_new(values, name=name, tz=tz) - except (ValueError, TypeError): - raise e - if arg is None: return None - # handle origin - if origin == 'julian': + if origin != 'unix': + arg = _adjust_to_origin(arg, origin, unit) - original = arg - j0 = tslib.Timestamp(0).to_julian_date() - if unit != 'D': - raise ValueError("unit must be 'D' for origin='julian'") - try: - arg = arg - j0 - except: - raise ValueError("incompatible 'arg' type for given " - "'origin'='julian'") - - # premptively check this for a nice range - j_max = tslib.Timestamp.max.to_julian_date() - j0 - j_min = tslib.Timestamp.min.to_julian_date() - j0 - if np.any(arg > j_max) or np.any(arg < j_min): - raise tslib.OutOfBoundsDatetime( - "{original} is Out of Bounds for " - "origin='julian'".format(original=original)) - - elif origin not in ['unix', 'julian']: - - # arg must be a numeric - original = arg - if not ((is_scalar(arg) and (is_integer(arg) or is_float(arg))) or - is_numeric_dtype(np.asarray(arg))): - raise ValueError( - "'{arg}' is not compatible with origin='{origin}'; " - "it must be numeric with a unit specified ".format( - arg=arg, - origin=origin)) - - # we are going to offset back to unix / epoch time - try: - offset = tslib.Timestamp(origin) - except tslib.OutOfBoundsDatetime: - raise tslib.OutOfBoundsDatetime( - "origin {origin} is Out of Bounds".format(origin=origin)) - except ValueError: - raise ValueError("origin {origin} cannot be converted " - "to a Timestamp".format(origin=origin)) - - if offset.tz is not None: - raise ValueError( - "origin offset {} must be tz-naive".format(offset)) - offset -= tslib.Timestamp(0) - - # convert the offset to the unit of the arg - # this should be lossless in terms of precision - offset = offset // tslib.Timedelta(1, unit=unit) - - # scalars & ndarray-like can handle the addition - if is_list_like(arg) and not isinstance( - arg, (ABCSeries, ABCIndexClass, np.ndarray)): - arg = np.asarray(arg) - arg = arg + offset + tz = 'utc' if utc else None + convert_listlike = partial(_convert_listlike_datetimes, tz=tz, unit=unit, + dayfirst=dayfirst, yearfirst=yearfirst, + errors=errors, exact=exact, + infer_datetime_format=infer_datetime_format) if isinstance(arg, tslib.Timestamp): result = arg elif isinstance(arg, ABCSeries): - cache_array = _maybe_cache(arg, format, cache, tz, _convert_listlike) + cache_array = _maybe_cache(arg, format, cache, convert_listlike) if not cache_array.empty: result = arg.map(cache_array) else: from pandas import Series - values = _convert_listlike(arg._values, True, format) + values = convert_listlike(arg._values, True, format) result = Series(values, index=arg.index, name=arg.name) elif isinstance(arg, (ABCDataFrame, MutableMapping)): result = _assemble_from_unit_mappings(arg, errors=errors) elif isinstance(arg, ABCIndexClass): - cache_array = _maybe_cache(arg, format, cache, tz, _convert_listlike) + cache_array = _maybe_cache(arg, format, cache, convert_listlike) if not cache_array.empty: result = _convert_and_box_cache(arg, cache_array, box, errors, name=arg.name) else: - result = _convert_listlike(arg, box, format, name=arg.name) + convert_listlike = partial(convert_listlike, name=arg.name) + result = convert_listlike(arg, box, format) elif is_list_like(arg): - cache_array = _maybe_cache(arg, format, cache, tz, _convert_listlike) + cache_array = _maybe_cache(arg, format, cache, convert_listlike) if not cache_array.empty: result = _convert_and_box_cache(arg, cache_array, box, errors) else: - result = _convert_listlike(arg, box, format) + result = convert_listlike(arg, box, format) else: - result = _convert_listlike(np.array([arg]), box, format)[0] + result = convert_listlike(np.array([arg]), box, format)[0] return result
- [x] tests passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` The internals of `to_datetime` is getting a bit unwieldy, so split out the `_convert_listlike` logic and origin shifting logic to ` _convert_listlike_datetime` and `adjust_to_origin` methods respectively outside of `to_datetime`. The logic was not changed.
https://api.github.com/repos/pandas-dev/pandas/pulls/21702
2018-07-02T00:39:06Z
2018-07-03T14:23:31Z
2018-07-03T14:23:31Z
2018-07-03T15:13:32Z
implement tslibs.arraylike
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 4c72e09a4851b..2387607569431 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -37,6 +37,9 @@ from cython cimport Py_ssize_t import pytz UTC = pytz.utc +from tslibs.arraylike import ( # noqa:F841 + format_array_from_datetime, array_to_datetime, array_with_unit_to_datetime, + ints_to_pytimedelta, ints_to_pydatetime) from tslibs.timedeltas cimport cast_from_unit from tslibs.timedeltas import Timedelta @@ -57,156 +60,6 @@ from tslibs.timestamps cimport (create_timestamp_from_ts, _NS_UPPER_BOUND, _NS_LOWER_BOUND) from tslibs.timestamps import Timestamp -cdef bint PY2 = str == bytes - - -cdef inline object create_datetime_from_ts( - int64_t value, pandas_datetimestruct dts, - object tz, object freq): - """ convenience routine to construct a datetime.datetime from its parts """ - return datetime(dts.year, dts.month, dts.day, dts.hour, - dts.min, dts.sec, dts.us, tz) - -cdef inline object create_date_from_ts( - int64_t value, pandas_datetimestruct dts, - object tz, object freq): - """ convenience routine to construct a datetime.date from its parts """ - return date(dts.year, dts.month, dts.day) - -cdef inline object create_time_from_ts( - int64_t value, pandas_datetimestruct dts, - object tz, object freq): - """ convenience routine to construct a datetime.time from its parts """ - return time(dts.hour, dts.min, dts.sec, dts.us) - - -def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, - box="datetime"): - """ - Convert an i8 repr to an ndarray of datetimes, date, time or Timestamp - - Parameters - ---------- - arr : array of i8 - tz : str, default None - convert to this timezone - freq : str/Offset, default None - freq to convert - box : {'datetime', 'timestamp', 'date', 'time'}, default 'datetime' - If datetime, convert to datetime.datetime - If date, convert to datetime.date - If time, convert to datetime.time - If Timestamp, convert to pandas.Timestamp - - Returns - ------- - result : array of dtype specified by box - """ - - cdef: - Py_ssize_t i, n = len(arr) - ndarray[int64_t] trans, deltas - pandas_datetimestruct dts - object dt - int64_t value - ndarray[object] result = np.empty(n, dtype=object) - object (*func_create)(int64_t, pandas_datetimestruct, object, object) - - if box == "date": - assert (tz is None), "tz should be None when converting to date" - - func_create = create_date_from_ts - elif box == "timestamp": - func_create = create_timestamp_from_ts - - if is_string_object(freq): - freq = to_offset(freq) - elif box == "time": - func_create = create_time_from_ts - elif box == "datetime": - func_create = create_datetime_from_ts - else: - raise ValueError("box must be one of 'datetime', 'date', 'time' or" - " 'timestamp'") - - if tz is not None: - if is_utc(tz): - for i in range(n): - value = arr[i] - if value == NPY_NAT: - result[i] = NaT - else: - dt64_to_dtstruct(value, &dts) - result[i] = func_create(value, dts, tz, freq) - elif is_tzlocal(tz) or is_fixed_offset(tz): - for i in range(n): - value = arr[i] - if value == NPY_NAT: - result[i] = NaT - else: - # Python datetime objects do not support nanosecond - # resolution (yet, PEP 564). Need to compute new value - # using the i8 representation. - local_value = tz_convert_utc_to_tzlocal(value, tz) - dt64_to_dtstruct(local_value, &dts) - result[i] = func_create(value, dts, tz, freq) - else: - trans, deltas, typ = get_dst_info(tz) - - for i in range(n): - - value = arr[i] - if value == NPY_NAT: - result[i] = NaT - else: - - # Adjust datetime64 timestamp, recompute datetimestruct - pos = trans.searchsorted(value, side='right') - 1 - if treat_tz_as_pytz(tz): - # find right representation of dst etc in pytz timezone - new_tz = tz._tzinfos[tz._transition_info[pos]] - else: - # no zone-name change for dateutil tzs - dst etc - # represented in single object. - new_tz = tz - - dt64_to_dtstruct(value + deltas[pos], &dts) - result[i] = func_create(value, dts, new_tz, freq) - else: - for i in range(n): - - value = arr[i] - if value == NPY_NAT: - result[i] = NaT - else: - dt64_to_dtstruct(value, &dts) - result[i] = func_create(value, dts, None, freq) - - return result - - -def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): - # convert an i8 repr to an ndarray of timedelta or Timedelta (if box == - # True) - - cdef: - Py_ssize_t i, n = len(arr) - int64_t value - ndarray[object] result = np.empty(n, dtype=object) - - for i in range(n): - - value = arr[i] - if value == NPY_NAT: - result[i] = NaT - else: - if box: - result[i] = Timedelta(value) - else: - result[i] = timedelta(microseconds=int(value) / 1000) - - return result - def _test_parse_iso8601(object ts): """ @@ -252,512 +105,6 @@ cpdef inline object _localize_pydatetime(object dt, object tz): return dt.replace(tzinfo=tz) -def format_array_from_datetime(ndarray[int64_t] values, object tz=None, - object format=None, object na_rep=None): - """ - return a np object array of the string formatted values - - Parameters - ---------- - values : a 1-d i8 array - tz : the timezone (or None) - format : optional, default is None - a strftime capable string - na_rep : optional, default is None - a nat format - - """ - cdef: - int64_t val, ns, N = len(values) - ndarray[int64_t] consider_values - bint show_ms = 0, show_us = 0, show_ns = 0, basic_format = 0 - ndarray[object] result = np.empty(N, dtype=object) - object ts, res - pandas_datetimestruct dts - - if na_rep is None: - na_rep = 'NaT' - - # if we don't have a format nor tz, then choose - # a format based on precision - basic_format = format is None and tz is None - if basic_format: - consider_values = values[values != NPY_NAT] - show_ns = (consider_values % 1000).any() - - if not show_ns: - consider_values //= 1000 - show_us = (consider_values % 1000).any() - - if not show_ms: - consider_values //= 1000 - show_ms = (consider_values % 1000).any() - - for i in range(N): - val = values[i] - - if val == NPY_NAT: - result[i] = na_rep - elif basic_format: - - dt64_to_dtstruct(val, &dts) - res = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (dts.year, - dts.month, - dts.day, - dts.hour, - dts.min, - dts.sec) - - if show_ns: - ns = dts.ps / 1000 - res += '.%.9d' % (ns + 1000 * dts.us) - elif show_us: - res += '.%.6d' % dts.us - elif show_ms: - res += '.%.3d' % (dts.us /1000) - - result[i] = res - - else: - - ts = Timestamp(val, tz=tz) - if format is None: - result[i] = str(ts) - else: - - # invalid format string - # requires dates > 1900 - try: - result[i] = ts.strftime(format) - except ValueError: - result[i] = str(ts) - - return result - - -cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'): - """ - convert the ndarray according to the unit - if errors: - - raise: return converted values or raise OutOfBoundsDatetime - if out of range on the conversion or - ValueError for other conversions (e.g. a string) - - ignore: return non-convertible values as the same unit - - coerce: NaT for non-convertibles - - """ - cdef: - Py_ssize_t i, j, n=len(values) - int64_t m - ndarray[float64_t] fvalues - ndarray mask - bint is_ignore = errors=='ignore' - bint is_coerce = errors=='coerce' - bint is_raise = errors=='raise' - bint need_to_iterate = True - ndarray[int64_t] iresult - ndarray[object] oresult - - assert is_ignore or is_coerce or is_raise - - if unit == 'ns': - if issubclass(values.dtype.type, np.integer): - return values.astype('M8[ns]') - return array_to_datetime(values.astype(object), errors=errors) - - m = cast_from_unit(None, unit) - - if is_raise: - - # try a quick conversion to i8 - # if we have nulls that are not type-compat - # then need to iterate - try: - iresult = values.astype('i8', casting='same_kind', copy=False) - mask = iresult == iNaT - iresult[mask] = 0 - fvalues = iresult.astype('f8') * m - need_to_iterate = False - except: - pass - - # check the bounds - if not need_to_iterate: - - if ((fvalues < _NS_LOWER_BOUND).any() - or (fvalues > _NS_UPPER_BOUND).any()): - raise OutOfBoundsDatetime( - "cannot convert input with unit '{0}'".format(unit)) - result = (iresult * m).astype('M8[ns]') - iresult = result.view('i8') - iresult[mask] = iNaT - return result - - result = np.empty(n, dtype='M8[ns]') - iresult = result.view('i8') - - try: - for i in range(n): - val = values[i] - - if checknull_with_nat(val): - iresult[i] = NPY_NAT - - elif is_integer_object(val) or is_float_object(val): - - if val != val or val == NPY_NAT: - iresult[i] = NPY_NAT - else: - try: - iresult[i] = cast_from_unit(val, unit) - except OverflowError: - if is_raise: - raise OutOfBoundsDatetime( - "cannot convert input {0} with the unit " - "'{1}'".format(val, unit)) - elif is_ignore: - raise AssertionError - iresult[i] = NPY_NAT - - elif is_string_object(val): - if len(val) == 0 or val in nat_strings: - iresult[i] = NPY_NAT - - else: - try: - iresult[i] = cast_from_unit(float(val), unit) - except ValueError: - if is_raise: - raise ValueError( - "non convertible value {0} with the unit " - "'{1}'".format(val, unit)) - elif is_ignore: - raise AssertionError - iresult[i] = NPY_NAT - except: - if is_raise: - raise OutOfBoundsDatetime( - "cannot convert input {0} with the unit " - "'{1}'".format(val, unit)) - elif is_ignore: - raise AssertionError - iresult[i] = NPY_NAT - - else: - - if is_raise: - raise ValueError("unit='{0}' not valid with non-numerical " - "val='{1}'".format(unit, val)) - if is_ignore: - raise AssertionError - - iresult[i] = NPY_NAT - - return result - - except AssertionError: - pass - - # we have hit an exception - # and are in ignore mode - # redo as object - - oresult = np.empty(n, dtype=object) - for i in range(n): - val = values[i] - - if checknull_with_nat(val): - oresult[i] = NaT - elif is_integer_object(val) or is_float_object(val): - - if val != val or val == NPY_NAT: - oresult[i] = NaT - else: - try: - oresult[i] = Timestamp(cast_from_unit(val, unit)) - except: - oresult[i] = val - - elif is_string_object(val): - if len(val) == 0 or val in nat_strings: - oresult[i] = NaT - - else: - oresult[i] = val - - return oresult - - -cpdef array_to_datetime(ndarray[object] values, errors='raise', - dayfirst=False, yearfirst=False, - format=None, utc=None, - require_iso8601=False): - cdef: - Py_ssize_t i, n = len(values) - object val, py_dt - ndarray[int64_t] iresult - ndarray[object] oresult - pandas_datetimestruct dts - bint utc_convert = bool(utc) - bint seen_integer = 0 - bint seen_string = 0 - bint seen_datetime = 0 - bint is_raise = errors=='raise' - bint is_ignore = errors=='ignore' - bint is_coerce = errors=='coerce' - _TSObject _ts - int out_local=0, out_tzoffset=0 - - # specify error conditions - assert is_raise or is_ignore or is_coerce - - try: - result = np.empty(n, dtype='M8[ns]') - iresult = result.view('i8') - for i in range(n): - val = values[i] - - if checknull_with_nat(val): - iresult[i] = NPY_NAT - - elif PyDateTime_Check(val): - seen_datetime = 1 - if val.tzinfo is not None: - if utc_convert: - try: - _ts = convert_datetime_to_tsobject(val, None) - iresult[i] = _ts.value - except OutOfBoundsDatetime: - if is_coerce: - iresult[i] = NPY_NAT - continue - raise - else: - raise ValueError('Tz-aware datetime.datetime cannot ' - 'be converted to datetime64 unless ' - 'utc=True') - else: - iresult[i] = pydatetime_to_dt64(val, &dts) - if not PyDateTime_CheckExact(val): - # i.e. a Timestamp object - iresult[i] += val.nanosecond - try: - check_dts_bounds(&dts) - except OutOfBoundsDatetime: - if is_coerce: - iresult[i] = NPY_NAT - continue - raise - - elif PyDate_Check(val): - seen_datetime = 1 - iresult[i] = pydate_to_dt64(val, &dts) - try: - check_dts_bounds(&dts) - except OutOfBoundsDatetime: - if is_coerce: - iresult[i] = NPY_NAT - continue - raise - - elif is_datetime64_object(val): - seen_datetime = 1 - if get_datetime64_value(val) == NPY_NAT: - iresult[i] = NPY_NAT - else: - try: - iresult[i] = get_datetime64_nanos(val) - except OutOfBoundsDatetime: - if is_coerce: - iresult[i] = NPY_NAT - continue - raise - - elif is_integer_object(val) or is_float_object(val): - # these must be ns unit by-definition - seen_integer = 1 - - if val != val or val == NPY_NAT: - iresult[i] = NPY_NAT - elif is_raise or is_ignore: - iresult[i] = val - else: - # coerce - # we now need to parse this as if unit='ns' - # we can ONLY accept integers at this point - # if we have previously (or in future accept - # datetimes/strings, then we must coerce) - try: - iresult[i] = cast_from_unit(val, 'ns') - except: - iresult[i] = NPY_NAT - - elif is_string_object(val): - # string - seen_string = 1 - - if len(val) == 0 or val in nat_strings: - iresult[i] = NPY_NAT - continue - if PyUnicode_Check(val) and PY2: - val = val.encode('utf-8') - - try: - _string_to_dts(val, &dts, &out_local, &out_tzoffset) - except ValueError: - # A ValueError at this point is a _parsing_ error - # specifically _not_ OutOfBoundsDatetime - if _parse_today_now(val, &iresult[i]): - continue - elif require_iso8601: - # if requiring iso8601 strings, skip trying - # other formats - if is_coerce: - iresult[i] = NPY_NAT - continue - elif is_raise: - raise ValueError("time data {val} doesn't match " - "format specified" - .format(val=val)) - return values - - try: - py_dt = parse_datetime_string(val, dayfirst=dayfirst, - yearfirst=yearfirst) - except Exception: - if is_coerce: - iresult[i] = NPY_NAT - continue - raise TypeError("invalid string coercion to datetime") - - try: - _ts = convert_datetime_to_tsobject(py_dt, None) - iresult[i] = _ts.value - except OutOfBoundsDatetime: - if is_coerce: - iresult[i] = NPY_NAT - continue - raise - except: - # TODO: What exception are we concerned with here? - if is_coerce: - iresult[i] = NPY_NAT - continue - raise - else: - # No error raised by string_to_dts, pick back up - # where we left off - value = dtstruct_to_dt64(&dts) - if out_local == 1: - tz = pytz.FixedOffset(out_tzoffset) - value = tz_convert_single(value, tz, 'UTC') - iresult[i] = value - try: - check_dts_bounds(&dts) - except OutOfBoundsDatetime: - # GH#19382 for just-barely-OutOfBounds falling back to - # dateutil parser will return incorrect result because - # it will ignore nanoseconds - if is_coerce: - iresult[i] = NPY_NAT - continue - elif require_iso8601: - if is_raise: - raise ValueError("time data {val} doesn't " - "match format specified" - .format(val=val)) - return values - raise - - else: - if is_coerce: - iresult[i] = NPY_NAT - else: - raise TypeError("{0} is not convertible to datetime" - .format(type(val))) - - if seen_datetime and seen_integer: - # we have mixed datetimes & integers - - if is_coerce: - # coerce all of the integers/floats to NaT, preserve - # the datetimes and other convertibles - for i in range(n): - val = values[i] - if is_integer_object(val) or is_float_object(val): - result[i] = NPY_NAT - elif is_raise: - raise ValueError( - "mixed datetimes and integers in passed array") - else: - raise TypeError - - return result - except OutOfBoundsDatetime: - if is_raise: - raise - - oresult = np.empty(n, dtype=object) - for i in range(n): - val = values[i] - - # set as nan except if its a NaT - if checknull_with_nat(val): - if PyFloat_Check(val): - oresult[i] = np.nan - else: - oresult[i] = NaT - elif is_datetime64_object(val): - if get_datetime64_value(val) == NPY_NAT: - oresult[i] = NaT - else: - oresult[i] = val.item() - else: - oresult[i] = val - return oresult - except TypeError: - oresult = np.empty(n, dtype=object) - - for i in range(n): - val = values[i] - if checknull_with_nat(val): - oresult[i] = val - elif is_string_object(val): - - if len(val) == 0 or val in nat_strings: - oresult[i] = 'NaT' - continue - - try: - oresult[i] = parse_datetime_string(val, dayfirst=dayfirst, - yearfirst=yearfirst) - pydatetime_to_dt64(oresult[i], &dts) - check_dts_bounds(&dts) - except Exception: - if is_raise: - raise - return values - # oresult[i] = val - else: - if is_raise: - raise - return values - - return oresult - - -cdef inline bint _parse_today_now(str val, int64_t* iresult): - # We delay this check for as long as possible - # because it catches relatively rare cases - if val == 'now': - # Note: this is *not* the same as Timestamp('now') - iresult[0] = Timestamp.utcnow().value - return True - elif val == 'today': - iresult[0] = Timestamp.today().value - return True - return False - # ---------------------------------------------------------------------- # Some general helper functions diff --git a/pandas/_libs/tslibs/arraylike.pyx b/pandas/_libs/tslibs/arraylike.pyx new file mode 100644 index 0000000000000..65dc719efbcad --- /dev/null +++ b/pandas/_libs/tslibs/arraylike.pyx @@ -0,0 +1,717 @@ +# -*- coding: utf-8 -*- + +cimport numpy as cnp +from numpy cimport int64_t, ndarray, float64_t +import numpy as np +cnp.import_array() + + +from cpython cimport PyFloat_Check, PyUnicode_Check + +from util cimport (is_integer_object, is_float_object, is_string_object, + is_datetime64_object) + +from cpython.datetime cimport (PyDateTime_Check, PyDate_Check, + PyDateTime_CheckExact, + PyDateTime_IMPORT, + timedelta, datetime, date, time) +# import datetime C API +PyDateTime_IMPORT + + +from np_datetime cimport (check_dts_bounds, + pandas_datetimestruct, + _string_to_dts, + dt64_to_dtstruct, dtstruct_to_dt64, + pydatetime_to_dt64, pydate_to_dt64, + get_datetime64_value) +from np_datetime import OutOfBoundsDatetime + +from parsing import parse_datetime_string + +cimport cython +from cython cimport Py_ssize_t + + +import pytz +UTC = pytz.utc + + +from timedeltas cimport cast_from_unit +from timedeltas import Timedelta +from timezones cimport (is_utc, is_tzlocal, is_fixed_offset, + treat_tz_as_pytz, get_dst_info) +from conversion cimport (tz_convert_single, _TSObject, + convert_datetime_to_tsobject, + get_datetime64_nanos, + tz_convert_utc_to_tzlocal) +from conversion import tz_convert_single + +from nattype import NaT, nat_strings, iNaT +from nattype cimport checknull_with_nat, NPY_NAT + +from timestamps cimport (create_timestamp_from_ts, + _NS_UPPER_BOUND, _NS_LOWER_BOUND) +from timestamps import Timestamp + +cdef bint PY2 = str == bytes + + +# ------------------------------------------------------------------ +# Parsing/Casting from array-like inputs + + +cpdef array_to_datetime(ndarray[object] values, errors='raise', + dayfirst=False, yearfirst=False, + format=None, utc=None, + require_iso8601=False): + cdef: + Py_ssize_t i, n = len(values) + object val, py_dt + ndarray[int64_t] iresult + ndarray[object] oresult + pandas_datetimestruct dts + bint utc_convert = bool(utc) + bint seen_integer = 0 + bint seen_string = 0 + bint seen_datetime = 0 + bint is_raise = errors=='raise' + bint is_ignore = errors=='ignore' + bint is_coerce = errors=='coerce' + _TSObject _ts + int out_local=0, out_tzoffset=0 + + # specify error conditions + assert is_raise or is_ignore or is_coerce + + try: + result = np.empty(n, dtype='M8[ns]') + iresult = result.view('i8') + for i in range(n): + val = values[i] + + if checknull_with_nat(val): + iresult[i] = NPY_NAT + + elif PyDateTime_Check(val): + seen_datetime = 1 + if val.tzinfo is not None: + if utc_convert: + try: + _ts = convert_datetime_to_tsobject(val, None) + iresult[i] = _ts.value + except OutOfBoundsDatetime: + if is_coerce: + iresult[i] = NPY_NAT + continue + raise + else: + raise ValueError('Tz-aware datetime.datetime cannot ' + 'be converted to datetime64 unless ' + 'utc=True') + else: + iresult[i] = pydatetime_to_dt64(val, &dts) + if not PyDateTime_CheckExact(val): + # i.e. a Timestamp object + iresult[i] += val.nanosecond + try: + check_dts_bounds(&dts) + except OutOfBoundsDatetime: + if is_coerce: + iresult[i] = NPY_NAT + continue + raise + + elif PyDate_Check(val): + seen_datetime = 1 + iresult[i] = pydate_to_dt64(val, &dts) + try: + check_dts_bounds(&dts) + except OutOfBoundsDatetime: + if is_coerce: + iresult[i] = NPY_NAT + continue + raise + + elif is_datetime64_object(val): + seen_datetime = 1 + if get_datetime64_value(val) == NPY_NAT: + iresult[i] = NPY_NAT + else: + try: + iresult[i] = get_datetime64_nanos(val) + except OutOfBoundsDatetime: + if is_coerce: + iresult[i] = NPY_NAT + continue + raise + + elif is_integer_object(val) or is_float_object(val): + # these must be ns unit by-definition + seen_integer = 1 + + if val != val or val == NPY_NAT: + iresult[i] = NPY_NAT + elif is_raise or is_ignore: + iresult[i] = val + else: + # coerce + # we now need to parse this as if unit='ns' + # we can ONLY accept integers at this point + # if we have previously (or in future accept + # datetimes/strings, then we must coerce) + try: + iresult[i] = cast_from_unit(val, 'ns') + except: + iresult[i] = NPY_NAT + + elif is_string_object(val): + # string + seen_string = 1 + + if len(val) == 0 or val in nat_strings: + iresult[i] = NPY_NAT + continue + if PyUnicode_Check(val) and PY2: + val = val.encode('utf-8') + + try: + _string_to_dts(val, &dts, &out_local, &out_tzoffset) + except ValueError: + # A ValueError at this point is a _parsing_ error + # specifically _not_ OutOfBoundsDatetime + if _parse_today_now(val, &iresult[i]): + continue + elif require_iso8601: + # if requiring iso8601 strings, skip trying + # other formats + if is_coerce: + iresult[i] = NPY_NAT + continue + elif is_raise: + raise ValueError("time data {val} doesn't match " + "format specified" + .format(val=val)) + return values + + try: + py_dt = parse_datetime_string(val, dayfirst=dayfirst, + yearfirst=yearfirst) + except Exception: + if is_coerce: + iresult[i] = NPY_NAT + continue + raise TypeError("invalid string coercion to datetime") + + try: + _ts = convert_datetime_to_tsobject(py_dt, None) + iresult[i] = _ts.value + except OutOfBoundsDatetime: + if is_coerce: + iresult[i] = NPY_NAT + continue + raise + except: + # TODO: What exception are we concerned with here? + if is_coerce: + iresult[i] = NPY_NAT + continue + raise + else: + # No error raised by string_to_dts, pick back up + # where we left off + value = dtstruct_to_dt64(&dts) + if out_local == 1: + tz = pytz.FixedOffset(out_tzoffset) + value = tz_convert_single(value, tz, 'UTC') + iresult[i] = value + try: + check_dts_bounds(&dts) + except OutOfBoundsDatetime: + # GH#19382 for just-barely-OutOfBounds falling back to + # dateutil parser will return incorrect result because + # it will ignore nanoseconds + if is_coerce: + iresult[i] = NPY_NAT + continue + elif require_iso8601: + if is_raise: + raise ValueError("time data {val} doesn't " + "match format specified" + .format(val=val)) + return values + raise + + else: + if is_coerce: + iresult[i] = NPY_NAT + else: + raise TypeError("{0} is not convertible to datetime" + .format(type(val))) + + if seen_datetime and seen_integer: + # we have mixed datetimes & integers + + if is_coerce: + # coerce all of the integers/floats to NaT, preserve + # the datetimes and other convertibles + for i in range(n): + val = values[i] + if is_integer_object(val) or is_float_object(val): + result[i] = NPY_NAT + elif is_raise: + raise ValueError( + "mixed datetimes and integers in passed array") + else: + raise TypeError + + return result + except OutOfBoundsDatetime: + if is_raise: + raise + + oresult = np.empty(n, dtype=object) + for i in range(n): + val = values[i] + + # set as nan except if its a NaT + if checknull_with_nat(val): + if PyFloat_Check(val): + oresult[i] = np.nan + else: + oresult[i] = NaT + elif is_datetime64_object(val): + if get_datetime64_value(val) == NPY_NAT: + oresult[i] = NaT + else: + oresult[i] = val.item() + else: + oresult[i] = val + return oresult + except TypeError: + oresult = np.empty(n, dtype=object) + + for i in range(n): + val = values[i] + if checknull_with_nat(val): + oresult[i] = val + elif is_string_object(val): + + if len(val) == 0 or val in nat_strings: + oresult[i] = 'NaT' + continue + + try: + oresult[i] = parse_datetime_string(val, dayfirst=dayfirst, + yearfirst=yearfirst) + pydatetime_to_dt64(oresult[i], &dts) + check_dts_bounds(&dts) + except Exception: + if is_raise: + raise + return values + # oresult[i] = val + else: + if is_raise: + raise + return values + + return oresult + + +cdef inline bint _parse_today_now(str val, int64_t* iresult): + # We delay this check for as long as possible + # because it catches relatively rare cases + if val == 'now': + # Note: this is *not* the same as Timestamp('now') + iresult[0] = Timestamp.utcnow().value + return True + elif val == 'today': + iresult[0] = Timestamp.today().value + return True + return False + + +cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'): + """ + convert the ndarray according to the unit + if errors: + - raise: return converted values or raise OutOfBoundsDatetime + if out of range on the conversion or + ValueError for other conversions (e.g. a string) + - ignore: return non-convertible values as the same unit + - coerce: NaT for non-convertibles + + """ + cdef: + Py_ssize_t i, j, n=len(values) + int64_t m + ndarray[float64_t] fvalues + ndarray mask + bint is_ignore = errors=='ignore' + bint is_coerce = errors=='coerce' + bint is_raise = errors=='raise' + bint need_to_iterate = True + ndarray[int64_t] iresult + ndarray[object] oresult + + assert is_ignore or is_coerce or is_raise + + if unit == 'ns': + if issubclass(values.dtype.type, np.integer): + return values.astype('M8[ns]') + return array_to_datetime(values.astype(object), errors=errors) + + m = cast_from_unit(None, unit) + + if is_raise: + + # try a quick conversion to i8 + # if we have nulls that are not type-compat + # then need to iterate + try: + iresult = values.astype('i8', casting='same_kind', copy=False) + mask = iresult == iNaT + iresult[mask] = 0 + fvalues = iresult.astype('f8') * m + need_to_iterate = False + except: + pass + + # check the bounds + if not need_to_iterate: + + if ((fvalues < _NS_LOWER_BOUND).any() + or (fvalues > _NS_UPPER_BOUND).any()): + raise OutOfBoundsDatetime( + "cannot convert input with unit '{0}'".format(unit)) + result = (iresult * m).astype('M8[ns]') + iresult = result.view('i8') + iresult[mask] = iNaT + return result + + result = np.empty(n, dtype='M8[ns]') + iresult = result.view('i8') + + try: + for i in range(n): + val = values[i] + + if checknull_with_nat(val): + iresult[i] = NPY_NAT + + elif is_integer_object(val) or is_float_object(val): + + if val != val or val == NPY_NAT: + iresult[i] = NPY_NAT + else: + try: + iresult[i] = cast_from_unit(val, unit) + except OverflowError: + if is_raise: + raise OutOfBoundsDatetime( + "cannot convert input {0} with the unit " + "'{1}'".format(val, unit)) + elif is_ignore: + raise AssertionError + iresult[i] = NPY_NAT + + elif is_string_object(val): + if len(val) == 0 or val in nat_strings: + iresult[i] = NPY_NAT + + else: + try: + iresult[i] = cast_from_unit(float(val), unit) + except ValueError: + if is_raise: + raise ValueError( + "non convertible value {0} with the unit " + "'{1}'".format(val, unit)) + elif is_ignore: + raise AssertionError + iresult[i] = NPY_NAT + except: + if is_raise: + raise OutOfBoundsDatetime( + "cannot convert input {0} with the unit " + "'{1}'".format(val, unit)) + elif is_ignore: + raise AssertionError + iresult[i] = NPY_NAT + + else: + + if is_raise: + raise ValueError("unit='{0}' not valid with non-numerical " + "val='{1}'".format(unit, val)) + if is_ignore: + raise AssertionError + + iresult[i] = NPY_NAT + + return result + + except AssertionError: + pass + + # we have hit an exception + # and are in ignore mode + # redo as object + + oresult = np.empty(n, dtype=object) + for i in range(n): + val = values[i] + + if checknull_with_nat(val): + oresult[i] = NaT + elif is_integer_object(val) or is_float_object(val): + + if val != val or val == NPY_NAT: + oresult[i] = NaT + else: + try: + oresult[i] = Timestamp(cast_from_unit(val, unit)) + except: + oresult[i] = val + + elif is_string_object(val): + if len(val) == 0 or val in nat_strings: + oresult[i] = NaT + + else: + oresult[i] = val + + return oresult + + +# ------------------------------------------------------------------ +# Casting from specifically integer arrays + +cdef inline object create_datetime_from_ts( + int64_t value, pandas_datetimestruct dts, + object tz, object freq): + """ convenience routine to construct a datetime.datetime from its parts """ + return datetime(dts.year, dts.month, dts.day, dts.hour, + dts.min, dts.sec, dts.us, tz) + +cdef inline object create_date_from_ts( + int64_t value, pandas_datetimestruct dts, + object tz, object freq): + """ convenience routine to construct a datetime.date from its parts """ + return date(dts.year, dts.month, dts.day) + +cdef inline object create_time_from_ts( + int64_t value, pandas_datetimestruct dts, + object tz, object freq): + """ convenience routine to construct a datetime.time from its parts """ + return time(dts.hour, dts.min, dts.sec, dts.us) + + +def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, + box="datetime"): + """ + Convert an i8 repr to an ndarray of datetimes, date, time or Timestamp + + Parameters + ---------- + arr : array of i8 + tz : str, default None + convert to this timezone + freq : str/Offset, default None + freq to convert + box : {'datetime', 'timestamp', 'date', 'time'}, default 'datetime' + If datetime, convert to datetime.datetime + If date, convert to datetime.date + If time, convert to datetime.time + If Timestamp, convert to pandas.Timestamp + + Returns + ------- + result : array of dtype specified by box + """ + + cdef: + Py_ssize_t i, n = len(arr) + ndarray[int64_t] trans, deltas + pandas_datetimestruct dts + object dt + int64_t value + ndarray[object] result = np.empty(n, dtype=object) + object (*func_create)(int64_t, pandas_datetimestruct, object, object) + + if box == "date": + assert tz is None, "tz should be None when converting to date" + func_create = create_date_from_ts + elif box == "timestamp": + func_create = create_timestamp_from_ts + if is_string_object(freq): + from pandas.tseries.frequencies import to_offset + freq = to_offset(freq) + elif box == "time": + func_create = create_time_from_ts + elif box == "datetime": + func_create = create_datetime_from_ts + else: + raise ValueError("box must be one of 'datetime', 'date', 'time' or" + " 'timestamp'") + + if tz is not None: + if is_utc(tz): + for i in range(n): + value = arr[i] + if value == NPY_NAT: + result[i] = NaT + else: + dt64_to_dtstruct(value, &dts) + result[i] = func_create(value, dts, tz, freq) + elif is_tzlocal(tz) or is_fixed_offset(tz): + for i in range(n): + value = arr[i] + if value == NPY_NAT: + result[i] = NaT + else: + # Python datetime objects do not support nanosecond + # resolution (yet, PEP 564). Need to compute new value + # using the i8 representation. + local_value = tz_convert_utc_to_tzlocal(value, tz) + dt64_to_dtstruct(local_value, &dts) + result[i] = func_create(value, dts, tz, freq) + else: + trans, deltas, typ = get_dst_info(tz) + + for i in range(n): + + value = arr[i] + if value == NPY_NAT: + result[i] = NaT + else: + + # Adjust datetime64 timestamp, recompute datetimestruct + pos = trans.searchsorted(value, side='right') - 1 + if treat_tz_as_pytz(tz): + # find right representation of dst etc in pytz timezone + new_tz = tz._tzinfos[tz._transition_info[pos]] + else: + # no zone-name change for dateutil tzs - dst etc + # represented in single object. + new_tz = tz + + dt64_to_dtstruct(value + deltas[pos], &dts) + result[i] = func_create(value, dts, new_tz, freq) + else: + for i in range(n): + + value = arr[i] + if value == NPY_NAT: + result[i] = NaT + else: + dt64_to_dtstruct(value, &dts) + result[i] = func_create(value, dts, None, freq) + + return result + + +def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): + # convert an i8 repr to an ndarray of timedelta or Timedelta (if box == + # True) + + cdef: + Py_ssize_t i, n = len(arr) + int64_t value + ndarray[object] result = np.empty(n, dtype=object) + + for i in range(n): + + value = arr[i] + if value == NPY_NAT: + result[i] = NaT + else: + if box: + result[i] = Timedelta(value) + else: + result[i] = timedelta(microseconds=int(value) / 1000) + + return result + + +# ------------------------------------------------------------------ + +def format_array_from_datetime(ndarray[int64_t] values, object tz=None, + object format=None, object na_rep=None): + """ + Return a numpy object array of the string formatted values + + Parameters + ---------- + values : a 1-d i8 array + tz : the timezone (or None) + format : optional, default is None + a strftime capable string + na_rep : optional, default is None + a nat format + """ + cdef: + int64_t val, ns, N = len(values) + ndarray[int64_t] consider_values + bint show_ms = 0, show_us = 0, show_ns = 0, basic_format = 0 + ndarray[object] result = np.empty(N, dtype=object) + object ts, res + pandas_datetimestruct dts + + if na_rep is None: + na_rep = 'NaT' + + # if we don't have a format nor tz, then choose + # a format based on precision + basic_format = format is None and tz is None + if basic_format: + consider_values = values[values != NPY_NAT] + show_ns = (consider_values % 1000).any() + + if not show_ns: + consider_values //= 1000 + show_us = (consider_values % 1000).any() + + if not show_ms: + consider_values //= 1000 + show_ms = (consider_values % 1000).any() + + for i in range(N): + val = values[i] + + if val == NPY_NAT: + result[i] = na_rep + elif basic_format: + + dt64_to_dtstruct(val, &dts) + res = '%d-%.2d-%.2d %.2d:%.2d:%.2d' % (dts.year, + dts.month, + dts.day, + dts.hour, + dts.min, + dts.sec) + + if show_ns: + ns = dts.ps / 1000 + res += '.%.9d' % (ns + 1000 * dts.us) + elif show_us: + res += '.%.6d' % dts.us + elif show_ms: + res += '.%.3d' % (dts.us /1000) + + result[i] = res + + else: + ts = Timestamp(val, tz=tz) + if format is None: + result[i] = str(ts) + else: + # invalid format string + # requires dates > 1900 + try: + result[i] = ts.strftime(format) + except ValueError: + result[i] = str(ts) + + return result diff --git a/setup.py b/setup.py index 75e2b18409e19..3a47556eb4adb 100755 --- a/setup.py +++ b/setup.py @@ -316,6 +316,7 @@ class CheckSDist(sdist_class): 'pandas/_libs/sparse.pyx', 'pandas/_libs/ops.pyx', 'pandas/_libs/parsers.pyx', + 'pandas/_libs/tslibs/arraylike.pyx', 'pandas/_libs/tslibs/ccalendar.pyx', 'pandas/_libs/tslibs/period.pyx', 'pandas/_libs/tslibs/strptime.pyx', @@ -565,6 +566,16 @@ def pxd(name): '_libs/tslibs/offsets'], 'depends': tseries_depends, 'sources': np_datetime_sources}, + '_libs.tslibs.arraylike': { + 'pyxfile': '_libs/tslibs/arraylike', + 'pxdfiles': ['_libs/src/util', + '_libs/tslibs/conversion', + '_libs/tslibs/timedeltas', + '_libs/tslibs/timestamps', + '_libs/tslibs/timezones', + '_libs/tslibs/nattype'], + 'depends': tseries_depends, + 'sources': np_datetime_sources}, '_libs.tslibs.ccalendar': { 'pyxfile': '_libs/tslibs/ccalendar'}, '_libs.tslibs.conversion': {
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21700
2018-07-01T21:48:44Z
2018-07-05T02:36:08Z
null
2018-07-11T20:23:05Z
PERF: CategoricalIndex.get_loc should avoid expensive cast of .codes to int64
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 739ad6a3d278b..5af431dd9f3ae 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -2,7 +2,8 @@ import numpy as np import pandas.util.testing as tm -from pandas import (Series, DataFrame, MultiIndex, Int64Index, Float64Index, +from pandas import (Series, DataFrame, MultiIndex, + Int64Index, UInt64Index, Float64Index, IntervalIndex, CategoricalIndex, IndexSlice, concat, date_range) from .pandas_vb_common import setup, Panel # noqa @@ -11,7 +12,7 @@ class NumericSeriesIndexing(object): goal_time = 0.2 - params = [Int64Index, Float64Index] + params = [Int64Index, UInt64Index, Float64Index] param = ['index'] def setup(self, index): diff --git a/asv_bench/benchmarks/indexing_engines.py b/asv_bench/benchmarks/indexing_engines.py new file mode 100644 index 0000000000000..b01639ca3580d --- /dev/null +++ b/asv_bench/benchmarks/indexing_engines.py @@ -0,0 +1,60 @@ +import numpy as np + +from pandas._libs.index import (Int64Engine, Int32Engine, + Int16Engine, Int8Engine, + UInt64Engine, UInt32Engine, + UInt16Engine, UInt8Engine, + Float64Engine, Float32Engine, + ObjectEngine, + ) + + +class NumericEngineIndexing(object): + + goal_time = 0.2 + params = [[Int64Engine, Int32Engine, Int16Engine, Int8Engine, + UInt64Engine, UInt32Engine, UInt16Engine, UInt8Engine, + Float64Engine, Float32Engine, + ], + ['monotonic_incr', 'monotonic_decr', 'non_monotonic'] + ] + param_names = ['engine', 'index_type'] + + def setup(self, engine, index_type): + N = 10**5 + values = list([1] * N + [2] * N + [3] * N) + array_ = { + 'monotonic_incr': np.array(values, dtype=engine._dtype), + 'monotonic_decr': np.array(list(reversed(values)), + dtype=engine._dtype), + 'non_monotonic': np.array([1, 2, 3] * N, dtype=engine._dtype), + }[index_type] + + self.data = engine(lambda: array_, len(array_)) + + def time_get_loc(self, engine, index_type): + self.data.get_loc(2) + + +class ObjectEngineIndexing(object): + + goal_time = 0.2 + params = [[ObjectEngine], + ['monotonic_incr', 'monotonic_decr', 'non_monotonic'] + ] + param_names = ['engine', 'index_type'] + + def setup(self, engine, index_type): + N = 10**5 + values = list('a' * N + 'b' * N + 'c' * N) + array_ = { + 'monotonic_incr': np.array(values, dtype=engine._dtype), + 'monotonic_decr': np.array(list(reversed(values)), + dtype=engine._dtype), + 'non_monotonic': np.array(list('abc') * N, dtype=engine._dtype), + }[index_type] + + self.data = engine(lambda: array_, len(array_)) + + def time_get_loc(self, engine, index_type): + self.data.get_loc(2) diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 9d559acfa59e7..280b622445e72 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -591,9 +591,10 @@ Removal of prior version deprecations/changes Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- Very large improvement in performance of slicing when the index is a :class:`CategoricalIndex`, - both when indexing by label (using .loc) and position(.iloc). - Likewise, slicing a ``CategoricalIndex`` itself (i.e. ``ci[100:200]``) shows similar speed improvements (:issue:`21659`) +- Slicing Series and Dataframe with an monotonically increasing :class:`CategoricalIndex` + is now very fast and has speed comparable to slicing with an ``Int64Index``. + The speed increase is both when indexing by label (using .loc) and position(.iloc) (:issue:`20395`) +- Slicing a ``CategoricalIndex`` itself (i.e. ``ci[1000:2000]``) shows similar speed improvements as above (:issue:`21659`) - Improved performance of :func:`Series.describe` in case of numeric dtpyes (:issue:`21274`) - Improved performance of :func:`pandas.core.groupby.GroupBy.rank` when dealing with tied rankings (:issue:`21237`) - Improved performance of :func:`DataFrame.set_index` with columns consisting of :class:`Period` objects (:issue:`21582`, :issue:`21606`) diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index d2914dc8ac751..c211f2b6aceb9 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -10,11 +10,13 @@ from libc.math cimport fabs, sqrt import numpy as np cimport numpy as cnp from numpy cimport (ndarray, - NPY_INT64, NPY_UINT64, NPY_INT32, NPY_INT16, NPY_INT8, - NPY_FLOAT32, NPY_FLOAT64, + NPY_INT64, NPY_INT32, NPY_INT16, NPY_INT8, + NPY_UINT64, NPY_UINT32, NPY_UINT16, NPY_UINT8, + NPY_FLOAT64, NPY_FLOAT32, NPY_OBJECT, - int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, - uint32_t, uint64_t, float32_t, float64_t, + int64_t, int32_t, int16_t, int8_t, + uint64_t, uint32_t, uint16_t, uint8_t, + float64_t, float32_t, double_t) cnp.import_array() @@ -359,9 +361,13 @@ ctypedef fused algos_t: float64_t float32_t object - int32_t int64_t + int32_t + int16_t + int8_t uint64_t + uint32_t + uint16_t uint8_t diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in index 40b1b1a282670..544ebc9cb26e2 100644 --- a/pandas/_libs/algos_common_helper.pxi.in +++ b/pandas/_libs/algos_common_helper.pxi.in @@ -133,11 +133,14 @@ def ensure_object(object arr): # name, c_type, dtype dtypes = [('float64', 'FLOAT64', 'float64'), ('float32', 'FLOAT32', 'float32'), - ('int8', 'INT8', 'int8'), - ('int16', 'INT16', 'int16'), - ('int32', 'INT32', 'int32'), ('int64', 'INT64', 'int64'), + ('int32', 'INT32', 'int32'), + ('int16', 'INT16', 'int16'), + ('int8', 'INT8', 'int8'), ('uint64', 'UINT64', 'uint64'), + ('uint32', 'UINT32', 'uint32'), + ('uint16', 'UINT16', 'uint16'), + ('uint8', 'UINT8', 'uint8'), # ('platform_int', 'INT', 'int_'), # ('object', 'OBJECT', 'object_'), ] diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 562c1ba218141..c86b5fbba772f 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -5,8 +5,11 @@ import cython import numpy as np cimport numpy as cnp -from numpy cimport (ndarray, float64_t, int32_t, - int64_t, uint8_t, uint64_t, intp_t, +from numpy cimport (ndarray, + float64_t, float32_t, + int64_t, int32_t, int16_t, int8_t, + uint64_t, uint32_t, uint16_t, uint8_t, + intp_t, # Note: NPY_DATETIME, NPY_TIMEDELTA are only available # for cimport in cython>=0.27.3 NPY_DATETIME, NPY_TIMEDELTA) diff --git a/pandas/_libs/index_class_helper.pxi.in b/pandas/_libs/index_class_helper.pxi.in index 4ea35da0626f3..1d5915e5b9afd 100644 --- a/pandas/_libs/index_class_helper.pxi.in +++ b/pandas/_libs/index_class_helper.pxi.in @@ -12,9 +12,17 @@ WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in # name, dtype, ctype dtypes = [('Float64', 'float64', 'float64_t'), - ('UInt64', 'uint64', 'uint64_t'), + ('Float32', 'float32', 'float32_t'), ('Int64', 'int64', 'int64_t'), - ('Object', 'object', 'object')] + ('Int32', 'int32', 'int32_t'), + ('Int16', 'int16', 'int16_t'), + ('Int8', 'int8', 'int8_t'), + ('UInt64', 'uint64', 'uint64_t'), + ('UInt32', 'uint32', 'uint32_t'), + ('UInt16', 'uint16', 'uint16_t'), + ('UInt8', 'uint8', 'uint8_t'), + ('Object', 'object', 'object'), + ] }} {{for name, dtype, ctype in dtypes}} @@ -22,8 +30,10 @@ dtypes = [('Float64', 'float64', 'float64_t'), cdef class {{name}}Engine(IndexEngine): + _dtype = '{{dtype}}' + def _call_monotonic(self, values): - return algos.is_monotonic_{{dtype}}(values, timelike=False) + return algos.is_monotonic(values, timelike=False) def get_backfill_indexer(self, other, limit=None): return algos.backfill_{{dtype}}(self._get_index_values(), @@ -36,10 +46,33 @@ cdef class {{name}}Engine(IndexEngine): cdef _make_hash_table(self, n): {{if name == 'Object'}} return _hash.PyObjectHashTable(n) + {{elif name in {'Int8', 'Int16', 'Int32'} }} + # {{name}}HashTable is not available, so we use Int64HashTable + return _hash.Int64HashTable(n) + {{elif name in {'UInt8', 'UInt16', 'UInt32'} }} + # {{name}}HashTable is not available, so we use UInt64HashTable + return _hash.UInt64HashTable(n) + {{elif name in {'Float32'} }} + # {{name}}HashTable is not available, so we use Float64HashTable + return _hash.Float64HashTable(n) {{else}} return _hash.{{name}}HashTable(n) {{endif}} + {{if name in {'Int8', 'Int16', 'Int32'} }} + cpdef _call_map_locations(self, values): + # self.mapping is of type Int64HashTable, so convert dtype of values + self.mapping.map_locations(algos.ensure_int64(values)) + {{elif name in {'UInt8', 'UInt16', 'UInt32'} }} + cpdef _call_map_locations(self, values): + # self.mapping is of type UInt64HashTable, so convert dtype of values + self.mapping.map_locations(algos.ensure_uint64(values)) + {{elif name in {'Float32'} }} + cpdef _call_map_locations(self, values): + # self.mapping is of type Float64HashTable, so convert dtype of values + self.mapping.map_locations(algos.ensure_float64(values)) + {{endif}} + {{if name != 'Float64' and name != 'Object'}} cdef _check_type(self, object val): hash(val) @@ -60,7 +93,7 @@ cdef class {{name}}Engine(IndexEngine): ndarray[{{ctype}}] values int count = 0 - {{if name != 'Float64'}} + {{if name not in {'Float64', 'Float32'} }} if not util.is_integer_object(val): raise KeyError(val) {{endif}} diff --git a/pandas/conftest.py b/pandas/conftest.py index 621de3ffd4b12..5671facdd0180 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -102,14 +102,29 @@ def ip(): @pytest.fixture(params=[True, False, None]) -def observed(request): +def _true_false_none(request): + """ + Base fixture for fixtures that return True, False and None. + """ + return request.param + + +@pytest.fixture +def observed(_true_false_none): """ pass in the observed keyword to groupby for [True, False] This indicates whether categoricals should return values for values which are not in the grouper [False / None], or only values which appear in the grouper [True]. [None] is supported for future compatiblity if we decide to change the default (and would need to warn if this parameter is not passed)""" - return request.param + return _true_false_none + + +@pytest.fixture +def ordered(_true_false_none): + """Return the allowed parameters for Categorical/CategoricalIndex.ordered. + """ + return _true_false_none _all_arithmetic_operators = ['__add__', '__radd__', diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b42bbdafcab45..12a8b36d7ef48 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3085,6 +3085,10 @@ def _get_unique_index(self, dropna=False): ------- loc : int if unique index, slice if monotonic index, else mask + Raises + ------ + KeyError : If key is not in self + Examples --------- >>> unique_index = pd.Index(list('abc')) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 45703c220a4be..e91de21147833 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -83,7 +83,13 @@ class CategoricalIndex(Index, accessor.PandasDelegate): """ _typ = 'categoricalindex' - _engine_type = libindex.Int64Engine + + @property + def _engine_type(self): + # self.codes can have dtype int8, int16, int 32 or int64, so we need + # to return the corresponding engine type (libindex.Int8Engine, etc.). + engine_name = "{}Engine".format(self.codes.dtype.name.capitalize()) + return getattr(libindex, engine_name) _attributes = ['name'] def __new__(cls, data=None, categories=None, ordered=None, dtype=None, @@ -377,7 +383,7 @@ def argsort(self, *args, **kwargs): def _engine(self): # we are going to look things up with the codes themselves - return self._engine_type(lambda: self.codes.astype('i8'), len(self)) + return self._engine_type(lambda: self.codes, len(self)) # introspection @cache_readonly @@ -426,6 +432,10 @@ def get_loc(self, key, method=None): ------- loc : int if unique index, slice if monotonic index, else mask + Raises + ------ + KeyError : If key is not in self + Examples --------- >>> unique_index = pd.CategoricalIndex(list('abc')) @@ -440,10 +450,12 @@ def get_loc(self, key, method=None): >>> non_monotonic_index.get_loc('b') array([False, True, False, True], dtype=bool) """ - codes = self.categories.get_loc(key) - if (codes == -1): - raise KeyError(key) - return self._engine.get_loc(codes) + code = self.categories.get_loc(key) + + # dtype must be same as dtype for self.codes else searchsorted is slow + code = self.codes.dtype.type(code) + + return self._engine.get_loc(code) def get_value(self, series, key): """ diff --git a/pandas/tests/indexes/conftest.py b/pandas/tests/indexes/conftest.py index 6d88ef0cfa6c5..8e889ed795408 100644 --- a/pandas/tests/indexes/conftest.py +++ b/pandas/tests/indexes/conftest.py @@ -4,6 +4,7 @@ import pandas.util.testing as tm from pandas.core.indexes.api import Index, MultiIndex +from pandas._libs import index as li from pandas.compat import lzip, long @@ -45,3 +46,15 @@ def zero(request): # For testing division by (or of) zero for Index with length 5, this # gives several scalar-zeros and length-5 vector-zeros return request.param + + +@pytest.fixture( + params=[ + 'Int64', 'Int32', 'Int16', 'Int8', + 'UInt64', 'UInt32', 'UInt16', 'UInt8', + 'Float64', 'Float32', + ]) +def numeric_indexing_engine(request): + """Return the various numeric indexing engines in pd._libs.index + """ + return getattr(li, "{}Engine".format(request.param)) diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index d49a6a6abc7c9..64fad2a87c364 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -14,6 +14,7 @@ from pandas import Categorical, IntervalIndex, compat from pandas.util.testing import assert_almost_equal import pandas.core.config as cf +from pandas._libs import index as libindex import pandas as pd if PY3: @@ -1117,3 +1118,33 @@ def test_take_invalid_kwargs(self): msg = "the 'mode' parameter is not supported" tm.assert_raises_regex(ValueError, msg, idx.take, indices, mode='clip') + + +class TestCategoricalIndexEngine(object): + + def setup_method(self): + self.n_categories = {np.int8: 1, np.int16: 129, np.int32: 32769} + + self.engines = {np.int8: libindex.Int8Engine, + np.int16: libindex.Int16Engine, + np.int32: libindex.Int32Engine, + np.int64: libindex.Int64Engine} + + @pytest.mark.parametrize('dtype', [np.int8, np.int16, np.int32, np.int64]) + def test_engine_type(self, dtype): + """ + Check that a CategoricalIndex has the correct engine type. + """ + if dtype != np.int64: + n_categories = self.n_categories[dtype] + index = CategoricalIndex(np.arange(n_categories)) + else: + # having actual (2 ** 32) + 1 distinct categories is too + # memory-intensive, so we set codes.dtype manually + index = CategoricalIndex(['a', 'b', 'c']) + index._values._codes = index._values._codes.astype('int64') + + engine = self.engines[dtype] + + assert isinstance(index._engine, engine) + assert index.codes.dtype.type == dtype diff --git a/pandas/tests/indexes/test_engine.py b/pandas/tests/indexes/test_engine.py new file mode 100644 index 0000000000000..75a587a6c6a64 --- /dev/null +++ b/pandas/tests/indexes/test_engine.py @@ -0,0 +1,157 @@ +# -*- coding: utf-8 -*- + +import numpy as np +import pytest + +import pandas as pd +from pandas._libs.index import (Int64Engine, UInt64Engine, + Float64Engine, ObjectEngine) + + +class TestNumericEngine(object): + + def setup_class(cls): + cls.data = [1, 2, 3] + + def test_engine_type(self, numeric_indexing_engine): + index = pd.Index(self.data, dtype=numeric_indexing_engine._dtype) + if issubclass(index.dtype.type, np.signedinteger): + assert isinstance(index._engine, Int64Engine) + elif issubclass(index.dtype.type, np.unsignedinteger): + assert isinstance(index._engine, UInt64Engine) + elif issubclass(index.dtype.type, np.floating): + assert isinstance(index._engine, Float64Engine) + else: + raise TypeError("unexpected dtype {}".format(index.dtype)) + + def test_is_monotonic_ordered(self, numeric_indexing_engine): + codes = np.array(self.data, dtype=numeric_indexing_engine._dtype) + e = numeric_indexing_engine(lambda: codes, len(codes)) + + assert e.is_monotonic_increasing + assert not e.is_monotonic_decreasing + + # reverse sort order + reversed_data = list(reversed(self.data)) + codes = np.array(reversed_data, dtype=numeric_indexing_engine._dtype) + e = numeric_indexing_engine(lambda: codes, len(codes)) + + assert not e.is_monotonic_increasing + assert e.is_monotonic_decreasing + + def test_is_not_monotonic_ordered(self, numeric_indexing_engine): + data = [1, 0, 2] + codes = np.array(data, dtype=numeric_indexing_engine._dtype) + e = numeric_indexing_engine(lambda: codes, len(codes)) + + assert not e.is_monotonic_increasing + assert not e.is_monotonic_decreasing + + @pytest.mark.parametrize('values, expected', [ + ([1, 2, 3], True), + ([1, 1, 2], False), + ]) + def test_is_unique(self, values, expected, numeric_indexing_engine): + codes = np.array(values, dtype=numeric_indexing_engine._dtype) + e = numeric_indexing_engine(lambda: codes, len(codes)) + + assert e.is_unique is expected + + @pytest.mark.parametrize('values, value, expected', [ + ([1, 2, 3], 2, 1), + ([1, 2, 2, 3], 2, slice(1, 3)), + ([3, 2, 2, 1], 2, np.array([False, True, True, False])), + ([1, 2, 2, 1], 2, np.array([False, True, True, False])), + ([1, 3, 2], 2, 2), + ]) + def test_get_loc(self, values, value, expected, numeric_indexing_engine): + codes = np.array(values, dtype=numeric_indexing_engine._dtype) + e = numeric_indexing_engine(lambda: codes, len(codes)) + result = e.get_loc(value) + + if isinstance(expected, np.ndarray): + assert (result == expected).all() + else: + assert result == expected + + @pytest.mark.parametrize('values, value, error', [ + ([1, 2, 3], 4, KeyError), + ([1, 2, 3], '4', KeyError), + ]) + def test_get_loc_raises(self, values, value, error, + numeric_indexing_engine): + codes = np.array(values, dtype=numeric_indexing_engine._dtype) + e = numeric_indexing_engine(lambda: codes, len(codes)) + with pytest.raises(error): + e.get_loc(value) + + +class TestObjectEngine(object): + + def setup_class(cls): + cls.data = list('abc') + cls.dtype = object + cls.Engine = ObjectEngine + + def test_engine_type(self): + index = pd.Index(self.data) + assert isinstance(index._engine, self.Engine) + + def test_is_monotonic_ordered(self): + codes = np.array(self.data, dtype=self.dtype) + e = self.Engine(lambda: codes, len(codes)) + + assert e.is_monotonic_increasing + assert not e.is_monotonic_decreasing + + # reverse sort order + reversed_data = list(reversed(self.data)) + codes = np.array(reversed_data, dtype=self.dtype) + e = self.Engine(lambda: codes, len(codes)) + + assert not e.is_monotonic_increasing + assert e.is_monotonic_decreasing + + def test_is_not_monotonic_ordered(self): + codes = np.array(list('cab'), dtype=self.dtype) + e = self.Engine(lambda: codes, len(codes)) + + assert not e.is_monotonic_increasing + assert not e.is_monotonic_decreasing + + @pytest.mark.parametrize('values, expected', [ + (list('abc'), True), + (list('aab'), False), + ]) + def test_is_unique(self, values, expected): + codes = np.array(values, dtype=self.dtype) + e = self.Engine(lambda: codes, len(codes)) + + assert e.is_unique is expected + + @pytest.mark.parametrize('values, value, expected', [ + (list('abc'), 'b', 1), + (list('abbc'), 'b', slice(1, 3)), + (list('cbba'), 'b', np.array([False, True, True, False])), + (list('abba'), 'b', np.array([False, True, True, False])), + (list('acb'), 'b', 2), + ]) + def test_get_loc(self, values, value, expected): + codes = np.array(values, dtype=self.dtype) + e = self.Engine(lambda: codes, len(codes)) + result = e.get_loc(value) + + if isinstance(expected, np.ndarray): + assert (result == expected).all() + else: + assert result == expected + + @pytest.mark.parametrize('values, value, error', [ + (list('abc'), 'd', KeyError), + (list('abc'), 4, KeyError), + ]) + def test_get_loc_raises(self, values, value, error): + codes = np.array(values, dtype=self.dtype) + e = self.Engine(lambda: codes, len(codes)) + with pytest.raises(error): + e.get_loc(value)
- [x] closes #20395 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This is the the final puzzle for #20395. The problem with the current implementation is that ``CategoricalIndex._engine`` constantly recodes int8 arrays to int64 arrays: https://github.com/pandas-dev/pandas/blob/dc45fbafef172e357cb5decdeab22de67160f5b7/pandas/core/indexes/category.py#L365-L369 Notice the ``lambda: self.codes.astype('i8')`` part, which means that every time ``_engine.vgetter`` is called, an int64-array is created. This is very expensive and we would ideally want to just use the original array dtype (int8, int16 or whatever) always and avoid this conversion. A complicating issue is that it is *not* enough to just avoid the int64 transformation, as ``array.searchsorted`` apparantly needs a dtype-compatible input or else it is *also* very slow: ```python >>> n = 1_000_000 >>> ci = pd.CategoricalIndex(list('a' * n + 'b' * n + 'c' * n)) >>> %timeit ci.codes.searchsorted(1) # search for left location of 'b' 7.38 ms # slow >>> code = np.int8(1) >>> %timeit ci.codes.searchsorted(code) 2.57 µs # fast ``` ### Solution options As CategoricalIndex.codes may be int8, int16, etc, the solution must be to (1) have an indexing engine for each integer dtype or an indexing engine that accepts all int types, not just int64 *and* (2) that the key must be translated into the same dtype as the codes array before calling searchsorted. So either: 1. Change Int64Engine to be a IntEngine (i.e. accept all integer dtypes) 2. Make new IntEngine classes, with the appropriate flexibility for accepting all integer dtypes, but defers to Int64 version if/when needed (e.g. if codes is int8, but we only have ``algos.is_monotonic_int64`` for checking monotonicity) 3. Do everything in Python. I assume option 1 is not desired, and option 3 assumedly likewise. In the updated PR I've made a proposal in Cython, that attains the needed speed. Benchmarks from ``asv_bench/indexing.py`` ``` before after ratio [dc45fbaf] [bc03b8bd] - 1.54±0.02ms 9.80±0μs 0.01 indexing.CategoricalIndexIndexing.time_get_loc_scalar('monotonic_incr') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/21699
2018-07-01T19:35:53Z
2018-10-19T02:23:17Z
null
2019-02-02T18:45:55Z
add unit test for writing to already open file
diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 36c4ae547ad4e..20dfeb10daf46 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -300,3 +300,19 @@ def test_to_csv_stdout_file(self): output = sys.stdout.getvalue() assert output == expected_ascii assert not sys.stdout.closed + + def test_to_csv_write_to_open_file(self): + # GH 21696 + df = pd.DataFrame({'a': ['x', 'y', 'z']}) + expected = '''\ +manual header +x +y +z +''' + with tm.ensure_clean('test.txt') as path: + with open(path, 'w') as f: + f.write('manual header\n') + df.to_csv(f, header=None, index=None) + with open(path, 'r') as f: + assert f.read() == expected
- [ ] closes - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry closes #21577 The added unit test will pass for `0.23.0`, fails for `0.23.1`, passes for `master`.
https://api.github.com/repos/pandas-dev/pandas/pulls/21696
2018-07-01T10:35:01Z
2018-07-02T23:28:27Z
2018-07-02T23:28:26Z
2018-07-03T09:57:19Z
move _add__ and __sub__ to liboffsets, implement _Tick
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index be3f11ea4da1f..1b319e12f06d5 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -368,12 +368,31 @@ class _BaseOffset(object): if name not in ['n', 'normalize']} return {name: kwds[name] for name in kwds if kwds[name] is not None} + def __add__(self, other): + if getattr(other, "_typ", None) in ["datetimeindex", + "series", "period"]: + # defer to the other class's implementation + return other + self + try: + return self.apply(other) + except ApplyTypeError: + return NotImplemented + + def __sub__(self, other): + if isinstance(other, datetime): + raise TypeError('Cannot subtract datetime from offset.') + elif type(other) == type(self): + return type(self)(self.n - other.n, normalize=self.normalize, + **self.kwds) + else: # pragma: no cover + return NotImplemented + def __call__(self, other): return self.apply(other) def __mul__(self, other): - return self.__class__(n=other * self.n, normalize=self.normalize, - **self.kwds) + return type(self)(n=other * self.n, normalize=self.normalize, + **self.kwds) def __neg__(self): # Note: we are defering directly to __mul__ instead of __rmul__, as @@ -495,6 +514,14 @@ class BaseOffset(_BaseOffset): return -self + other +class _Tick(object): + """ + dummy class to mix into tseries.offsets.Tick so that in tslibs.period we + can do isinstance checks on _Tick and avoid importing tseries.offsets + """ + pass + + # ---------------------------------------------------------------------- # RelativeDelta Arithmetic diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 6e5794ef41757..3a29f9fb00865 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -52,8 +52,7 @@ from resolution import Resolution from nattype import nat_strings, NaT, iNaT from nattype cimport _nat_scalar_rules, NPY_NAT, is_null_datetimelike from offsets cimport to_offset - -from pandas.tseries import offsets +from offsets import _Tick cdef bint PY2 = str == bytes @@ -1060,9 +1059,9 @@ cdef class _Period(object): int64_t nanos, offset_nanos if (PyDelta_Check(other) or util.is_timedelta64_object(other) or - isinstance(other, offsets.Tick)): + isinstance(other, _Tick)): offset = to_offset(self.freq.rule_code) - if isinstance(offset, offsets.Tick): + if isinstance(offset, _Tick): nanos = delta_to_nanoseconds(other) offset_nanos = delta_to_nanoseconds(offset) if nanos % offset_nanos == 0: diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index f9c9ec09844d6..d78d199f1404b 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -7,7 +7,7 @@ from pandas import compat import numpy as np -from pandas.core.dtypes.generic import ABCSeries, ABCDatetimeIndex, ABCPeriod +from pandas.core.dtypes.generic import ABCPeriod from pandas.core.tools.datetimes import to_datetime import pandas.core.common as com @@ -288,25 +288,6 @@ def _repr_attrs(self): def name(self): return self.rule_code - def __add__(self, other): - if isinstance(other, (ABCDatetimeIndex, ABCSeries)): - return other + self - elif isinstance(other, ABCPeriod): - return other + self - try: - return self.apply(other) - except ApplyTypeError: - return NotImplemented - - def __sub__(self, other): - if isinstance(other, datetime): - raise TypeError('Cannot subtract datetime from offset.') - elif type(other) == type(self): - return self.__class__(self.n - other.n, normalize=self.normalize, - **self.kwds) - else: # pragma: no cover - return NotImplemented - def rollback(self, dt): """Roll provided date backward to next offset only if not on offset""" dt = as_timestamp(dt) @@ -2106,7 +2087,7 @@ def f(self, other): return f -class Tick(SingleConstructorOffset): +class Tick(liboffsets._Tick, SingleConstructorOffset): _inc = Timedelta(microseconds=1000) _prefix = 'undefined' _attributes = frozenset(['n', 'normalize'])
Last one for now. Moving `__add__` and `__sub__` to liboffsets has been viable for a while now, just getting around to it. Implements a dummy `_Tick` class that gets mixed in to `Tick`. Then in `tslibs.period` we can replace `isinstance(obj, offsets.Tick)` checks with `isinstnace(obj, _Tick)`, obviating the need for the import of `tseries.offsets`. This moves us closer to being able to import `Period` directly in `_libs.__init__`, which has been a long-time goal (see the comment there). In conjunction with #21693 and #21690, I think that gets us the rest of the way there.
https://api.github.com/repos/pandas-dev/pandas/pulls/21694
2018-07-01T02:47:44Z
2018-07-03T14:24:16Z
2018-07-03T14:24:15Z
2018-07-03T14:46:54Z
use liboffsets to_offset function
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 6588b5476e2b9..4c72e09a4851b 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -51,6 +51,8 @@ from tslibs.conversion import tz_convert_single from tslibs.nattype import NaT, nat_strings, iNaT from tslibs.nattype cimport checknull_with_nat, NPY_NAT +from tslibs.offsets cimport to_offset + from tslibs.timestamps cimport (create_timestamp_from_ts, _NS_UPPER_BOUND, _NS_LOWER_BOUND) from tslibs.timestamps import Timestamp @@ -118,7 +120,6 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, func_create = create_timestamp_from_ts if is_string_object(freq): - from pandas.tseries.frequencies import to_offset freq = to_offset(freq) elif box == "time": func_create = create_time_from_ts diff --git a/pandas/_libs/tslibs/offsets.pxd b/pandas/_libs/tslibs/offsets.pxd new file mode 100644 index 0000000000000..2829a27b9905c --- /dev/null +++ b/pandas/_libs/tslibs/offsets.pxd @@ -0,0 +1,3 @@ +# -*- coding: utf-8 -*- + +cdef to_offset(object obj) diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 6985d3b8df363..631ceab003f83 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -55,9 +55,9 @@ from parsing import parse_time_string, NAT_SENTINEL from resolution import Resolution from nattype import nat_strings, NaT, iNaT from nattype cimport _nat_scalar_rules, NPY_NAT +from offsets cimport to_offset from pandas.tseries import offsets -from pandas.tseries import frequencies cdef extern from "period_helper.h": @@ -1015,7 +1015,7 @@ cdef class _Period(object): code, stride = get_freq_code(freq) freq = get_freq_str(code, stride) - freq = frequencies.to_offset(freq) + freq = to_offset(freq) if freq.n <= 0: raise ValueError('Frequency must be positive, because it' @@ -1063,7 +1063,7 @@ cdef class _Period(object): if (PyDelta_Check(other) or util.is_timedelta64_object(other) or isinstance(other, offsets.Tick)): - offset = frequencies.to_offset(self.freq.rule_code) + offset = to_offset(self.freq.rule_code) if isinstance(offset, offsets.Tick): nanos = delta_to_nanoseconds(other) offset_nanos = delta_to_nanoseconds(offset) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index f68dc421a1ee9..27066af0be3b9 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -33,6 +33,7 @@ from np_datetime cimport (cmp_scalar, reverse_ops, td64_to_tdstruct, from nattype import nat_strings, NaT from nattype cimport checknull_with_nat, NPY_NAT +from offsets cimport to_offset # ---------------------------------------------------------------------- # Constants @@ -1050,7 +1051,6 @@ class Timedelta(_Timedelta): cdef: int64_t result, unit - from pandas.tseries.frequencies import to_offset unit = to_offset(freq).nanos result = unit * rounder(self.value / float(unit)) return Timedelta(result, unit='ns') diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 123ccebf83a56..54d29cea44555 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -30,6 +30,7 @@ from nattype cimport NPY_NAT from np_datetime import OutOfBoundsDatetime from np_datetime cimport (reverse_ops, cmp_scalar, check_dts_bounds, pandas_datetimestruct, dt64_to_dtstruct) +from offsets cimport to_offset from timedeltas import Timedelta from timedeltas cimport delta_to_nanoseconds from timezones cimport ( @@ -59,7 +60,6 @@ cdef inline object create_timestamp_from_ts(int64_t value, def round_ns(values, rounder, freq): - """ Applies rounding function at given frequency @@ -73,8 +73,6 @@ def round_ns(values, rounder, freq): ------- :obj:`ndarray` """ - - from pandas.tseries.frequencies import to_offset unit = to_offset(freq).nanos # GH21262 If the Timestamp is multiple of the freq str diff --git a/setup.py b/setup.py index 621655dd05dbc..75e2b18409e19 100755 --- a/setup.py +++ b/setup.py @@ -538,7 +538,8 @@ def pxd(name): '_libs/tslibs/ccalendar', '_libs/tslibs/timedeltas', '_libs/tslibs/timezones', - '_libs/tslibs/nattype'], + '_libs/tslibs/nattype', + '_libs/tslibs/offsets'], 'depends': tseries_depends + ['pandas/_libs/src/period_helper.h'], 'sources': np_datetime_sources + ['pandas/_libs/src/period_helper.c']}, '_libs.properties': { @@ -560,7 +561,8 @@ def pxd(name): '_libs/tslibs/timedeltas', '_libs/tslibs/timestamps', '_libs/tslibs/timezones', - '_libs/tslibs/nattype'], + '_libs/tslibs/nattype', + '_libs/tslibs/offsets'], 'depends': tseries_depends, 'sources': np_datetime_sources}, '_libs.tslibs.ccalendar': { @@ -619,7 +621,8 @@ def pxd(name): '_libs.tslibs.timedeltas': { 'pyxfile': '_libs/tslibs/timedeltas', 'pxdfiles': ['_libs/src/util', - '_libs/tslibs/nattype'], + '_libs/tslibs/nattype', + '_libs/tslibs/offsets'], 'depends': np_datetime_headers, 'sources': np_datetime_sources}, '_libs.tslibs.timestamps': { @@ -628,6 +631,7 @@ def pxd(name): '_libs/tslibs/ccalendar', '_libs/tslibs/conversion', '_libs/tslibs/nattype', + '_libs/tslibs/offsets', '_libs/tslibs/timedeltas', '_libs/tslibs/timezones'], 'depends': tseries_depends,
https://api.github.com/repos/pandas-dev/pandas/pulls/21693
2018-07-01T01:26:10Z
2018-07-02T11:05:59Z
2018-07-02T11:05:59Z
2018-11-08T18:10:15Z
move is_null_datetimelike to nattype for self-containment
diff --git a/pandas/_libs/missing.pxd b/pandas/_libs/missing.pxd index f3d990db1c3fd..b90975df8e247 100644 --- a/pandas/_libs/missing.pxd +++ b/pandas/_libs/missing.pxd @@ -1,6 +1,11 @@ # -*- coding: utf-8 -*- # cython: profile=False -cdef bint is_null_datetimelike(object val) +from tslibs.nattype cimport is_null_datetimelike + cpdef bint checknull(object val) cpdef bint checknull_old(object val) + +cdef bint is_null_datetime64(v) +cdef bint is_null_timedelta64(v) +cdef bint is_null_period(v) diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index dfd044131afb4..79c30ac5f3778 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -15,6 +15,7 @@ cimport util from tslibs.np_datetime cimport get_timedelta64_value, get_datetime64_value from tslibs.nattype import NaT +from tslibs.nattype cimport is_null_datetimelike cdef double INF = <double> np.inf cdef double NEGINF = -INF @@ -22,22 +23,6 @@ cdef double NEGINF = -INF cdef int64_t NPY_NAT = util.get_nat() -cdef inline bint is_null_datetimelike(object val): - # determine if we have a null for a timedelta/datetime (or integer - # versions) - if util._checknull(val): - return True - elif val is NaT: - return True - elif util.is_timedelta64_object(val): - return val.view('int64') == NPY_NAT - elif util.is_datetime64_object(val): - return val.view('int64') == NPY_NAT - elif util.is_integer_object(val): - return val == NPY_NAT - return False - - cdef inline bint _check_all_nulls(object val): """ utility to check if a value is any type of null """ cdef bint res @@ -308,3 +293,37 @@ cpdef bint isneginf_scalar(object val): return True else: return False + + +cdef inline bint is_null_datetime64(v): + # determine if we have a null for a datetime (or integer versions), + # excluding np.timedelta64('nat') + if util._checknull(v): + return True + elif v is NaT: + return True + elif util.is_datetime64_object(v): + return v.view('int64') == NPY_NAT + return False + + +cdef inline bint is_null_timedelta64(v): + # determine if we have a null for a timedelta (or integer versions), + # excluding np.datetime64('nat') + if util._checknull(v): + return True + elif v is NaT: + return True + elif util.is_timedelta64_object(v): + return v.view('int64') == NPY_NAT + return False + + +cdef inline bint is_null_period(v): + # determine if we have a null for a Period (or integer versions), + # excluding np.datetime64('nat') and np.timedelta64('nat') + if util._checknull(v): + return True + elif v is NaT: + return True + return False diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index cf887ce1a6387..8cf69057a7e74 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -28,6 +28,8 @@ cdef extern from "numpy/arrayobject.h": cdef object fields cdef tuple names +from missing cimport is_null_datetime64, is_null_timedelta64, is_null_period + from util cimport UINT8_MAX, UINT64_MAX, INT64_MAX, INT64_MIN # core.common import for fast inference checks @@ -574,40 +576,6 @@ cpdef object infer_datetimelike_array(object arr): return 'mixed' -cdef inline bint is_null_datetime64(v): - # determine if we have a null for a datetime (or integer versions), - # excluding np.timedelta64('nat') - if util._checknull(v): - return True - elif v is NaT: - return True - elif util.is_datetime64_object(v): - return v.view('int64') == iNaT - return False - - -cdef inline bint is_null_timedelta64(v): - # determine if we have a null for a timedelta (or integer versions), - # excluding np.datetime64('nat') - if util._checknull(v): - return True - elif v is NaT: - return True - elif util.is_timedelta64_object(v): - return v.view('int64') == iNaT - return False - - -cdef inline bint is_null_period(v): - # determine if we have a null for a Period (or integer versions), - # excluding np.datetime64('nat') and np.timedelta64('nat') - if util._checknull(v): - return True - elif v is NaT: - return True - return False - - cdef inline bint is_datetime(object o): return PyDateTime_Check(o) diff --git a/pandas/_libs/tslibs/nattype.pxd b/pandas/_libs/tslibs/nattype.pxd index 96e02142d501b..24ce797575b2a 100644 --- a/pandas/_libs/tslibs/nattype.pxd +++ b/pandas/_libs/tslibs/nattype.pxd @@ -7,3 +7,4 @@ cdef int64_t NPY_NAT cdef bint _nat_scalar_rules[6] cdef bint checknull_with_nat(object val) +cdef bint is_null_datetimelike(object val) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index be76b55fa169b..2fe8fab2e2e19 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -16,6 +16,7 @@ cimport numpy as cnp from numpy cimport int64_t cnp.import_array() +cimport util from util cimport (get_nat, is_integer_object, is_float_object, is_datetime64_object, is_timedelta64_object) @@ -587,3 +588,28 @@ cdef inline bint checknull_with_nat(object val): """ utility to check if a value is a nat or not """ return val is None or ( PyFloat_Check(val) and val != val) or val is NaT + + +cdef inline bint is_null_datetimelike(object val): + """ + Determine if we have a null for a timedelta/datetime (or integer versions) + + Parameters + ---------- + val : object + + Returns + ------- + null_datetimelike : bool + """ + if util._checknull(val): + return True + elif val is NaT: + return True + elif util.is_timedelta64_object(val): + return val.view('int64') == NPY_NAT + elif util.is_datetime64_object(val): + return val.view('int64') == NPY_NAT + elif util.is_integer_object(val): + return val == NPY_NAT + return False diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 6661eb2bccb3c..6e5794ef41757 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -36,8 +36,6 @@ cdef extern from "../src/datetime/np_datetime.h": cimport util from util cimport is_period_object, is_string_object, INT32_MIN -from pandas._libs.missing cimport is_null_datetimelike - from timestamps import Timestamp from timezones cimport is_utc, is_tzlocal, get_utcoffset, get_dst_info from timedeltas cimport delta_to_nanoseconds @@ -52,7 +50,7 @@ from frequencies cimport (get_freq_code, get_base_alias, from parsing import parse_time_string, NAT_SENTINEL from resolution import Resolution from nattype import nat_strings, NaT, iNaT -from nattype cimport _nat_scalar_rules, NPY_NAT +from nattype cimport _nat_scalar_rules, NPY_NAT, is_null_datetimelike from offsets cimport to_offset from pandas.tseries import offsets diff --git a/setup.py b/setup.py index 75e2b18409e19..29b19fed0e2d4 100755 --- a/setup.py +++ b/setup.py @@ -531,17 +531,6 @@ def pxd(name): 'pyxfile': '_libs/ops', 'pxdfiles': ['_libs/src/util', '_libs/missing']}, - '_libs.tslibs.period': { - 'pyxfile': '_libs/tslibs/period', - 'pxdfiles': ['_libs/src/util', - '_libs/missing', - '_libs/tslibs/ccalendar', - '_libs/tslibs/timedeltas', - '_libs/tslibs/timezones', - '_libs/tslibs/nattype', - '_libs/tslibs/offsets'], - 'depends': tseries_depends + ['pandas/_libs/src/period_helper.h'], - 'sources': np_datetime_sources + ['pandas/_libs/src/period_helper.c']}, '_libs.properties': { 'pyxfile': '_libs/properties', 'include': []}, @@ -603,6 +592,16 @@ def pxd(name): '_libs.tslibs.parsing': { 'pyxfile': '_libs/tslibs/parsing', 'pxdfiles': ['_libs/src/util']}, + '_libs.tslibs.period': { + 'pyxfile': '_libs/tslibs/period', + 'pxdfiles': ['_libs/src/util', + '_libs/tslibs/ccalendar', + '_libs/tslibs/timedeltas', + '_libs/tslibs/timezones', + '_libs/tslibs/nattype', + '_libs/tslibs/offsets'], + 'depends': tseries_depends + ['pandas/_libs/src/period_helper.h'], + 'sources': np_datetime_sources + ['pandas/_libs/src/period_helper.c']}, '_libs.tslibs.resolution': { 'pyxfile': '_libs/tslibs/resolution', 'pxdfiles': ['_libs/src/util',
ATM `is_null_datetimelike` is used _only_ in `tslibs.period`. The dependency structure is simplified nicely if we put that function is `tslibs.nattype` instead of in `_libs.missing`. This also takes a couple of missing-themed functions out of inference.pyx Finally, moves the libperiod block in setup.py to down with the rest of the tslibs blocks to restore alphabetical order.
https://api.github.com/repos/pandas-dev/pandas/pulls/21692
2018-07-01T01:19:04Z
2018-07-02T23:31:46Z
2018-07-02T23:31:46Z
2018-07-02T23:37:28Z
move and de-privatize _localize_pydatetime, move shift_day to liboffsets
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 4c72e09a4851b..61cf582300034 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -235,23 +235,6 @@ def _test_parse_iso8601(object ts): return Timestamp(obj.value) -cpdef inline object _localize_pydatetime(object dt, object tz): - """ - Take a datetime/Timestamp in UTC and localizes to timezone tz. - """ - if tz is None: - return dt - elif isinstance(dt, Timestamp): - return dt.tz_localize(tz) - elif tz == 'UTC' or tz is UTC: - return UTC.localize(dt) - try: - # datetime.replace with pytz may be incorrect result - return tz.localize(dt) - except AttributeError: - return dt.replace(tzinfo=tz) - - def format_array_from_datetime(ndarray[int64_t] values, object tz=None, object format=None, object na_rep=None): """ diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index 8f887dc3af203..448dbd27e8278 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -31,3 +31,5 @@ cpdef int64_t pydt_to_i8(object pydt) except? -1 cdef maybe_datetimelike_to_i8(object val) cdef int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz) + +cpdef datetime localize_pydatetime(datetime dt, object tz) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 2e1a1e732203e..cf5053acb229b 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -565,7 +565,7 @@ cdef inline datetime _localize_pydatetime(datetime dt, tzinfo tz): """ Take a datetime/Timestamp in UTC and localizes to timezone tz. - NB: Unlike the version in tslib, this treats datetime and Timestamp objects + NB: Unlike the public version, this treats datetime and Timestamp objects identically, i.e. discards nanos from Timestamps. It also assumes that the `tz` input is not None. """ @@ -580,6 +580,33 @@ cdef inline datetime _localize_pydatetime(datetime dt, tzinfo tz): # ---------------------------------------------------------------------- # Timezone Conversion +cpdef inline datetime localize_pydatetime(datetime dt, object tz): + """ + Take a datetime/Timestamp in UTC and localizes to timezone tz. + + Parameters + ---------- + dt : datetime or Timestamp + tz : tzinfo, "UTC", or None + + Returns + ------- + localized : datetime or Timestamp + """ + if tz is None: + return dt + elif not PyDateTime_CheckExact(dt): + # i.e. is a Timestamp + return dt.tz_localize(tz) + elif tz == 'UTC' or tz is UTC: + return UTC.localize(dt) + try: + # datetime.replace with pytz may be incorrect result + return tz.localize(dt) + except AttributeError: + return dt.replace(tzinfo=tz) + + cdef inline int64_t tz_convert_tzlocal_to_utc(int64_t val, tzinfo tz): """ Parameters diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 841db80cf094e..be3f11ea4da1f 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -5,9 +5,13 @@ cimport cython from cython cimport Py_ssize_t import time -from cpython.datetime cimport datetime, timedelta, time as dt_time +from cpython.datetime cimport (PyDateTime_IMPORT, PyDateTime_CheckExact, + datetime, timedelta, + time as dt_time) +PyDateTime_IMPORT from dateutil.relativedelta import relativedelta +from pytz import UTC import numpy as np cimport numpy as cnp @@ -19,7 +23,7 @@ from util cimport is_string_object, is_integer_object from ccalendar import MONTHS, DAYS from ccalendar cimport get_days_in_month, dayofweek -from conversion cimport tz_convert_single, pydt_to_i8 +from conversion cimport tz_convert_single, pydt_to_i8, localize_pydatetime from frequencies cimport get_freq_code from nattype cimport NPY_NAT from np_datetime cimport (pandas_datetimestruct, @@ -494,6 +498,31 @@ class BaseOffset(_BaseOffset): # ---------------------------------------------------------------------- # RelativeDelta Arithmetic +cpdef datetime shift_day(datetime other, int days): + """ + Increment the datetime `other` by the given number of days, retaining + the time-portion of the datetime. For tz-naive datetimes this is + equivalent to adding a timedelta. For tz-aware datetimes it is similar to + dateutil's relativedelta.__add__, but handles pytz tzinfo objects. + + Parameters + ---------- + other : datetime or Timestamp + days : int + + Returns + ------- + shifted: datetime or Timestamp + """ + if other.tzinfo is None: + return other + timedelta(days=days) + + tz = other.tzinfo + naive = other.replace(tzinfo=None) + shifted = naive + timedelta(days=days) + return localize_pydatetime(shifted, tz) + + cdef inline int year_add_months(pandas_datetimestruct dts, int months) nogil: """new year number after shifting pandas_datetimestruct number of months""" return dts.year + (dts.month + months - 1) / 12 diff --git a/pandas/tests/indexes/datetimes/test_arithmetic.py b/pandas/tests/indexes/datetimes/test_arithmetic.py index cb0715c32167a..555f804800588 100644 --- a/pandas/tests/indexes/datetimes/test_arithmetic.py +++ b/pandas/tests/indexes/datetimes/test_arithmetic.py @@ -15,7 +15,7 @@ DatetimeIndex, TimedeltaIndex, date_range) from pandas.core import ops -from pandas._libs import tslib +from pandas._libs.tslibs.conversion import localize_pydatetime from pandas._libs.tslibs.offsets import shift_months @@ -56,10 +56,7 @@ def test_dti_cmp_datetimelike(self, other, tz): if isinstance(other, np.datetime64): # no tzaware version available return - elif isinstance(other, Timestamp): - other = other.tz_localize(dti.tzinfo) - else: - other = tslib._localize_pydatetime(other, dti.tzinfo) + other = localize_pydatetime(other, dti.tzinfo) result = dti == other expected = np.array([True, False]) diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 573940edaa08f..3697d183d2fc6 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -15,8 +15,7 @@ import pandas.util._test_decorators as td import pandas as pd -from pandas._libs import tslib -from pandas._libs.tslibs import timezones +from pandas._libs.tslibs import timezones, conversion from pandas.compat import lrange, zip, PY3 from pandas import (DatetimeIndex, date_range, bdate_range, Timestamp, isna, to_datetime, Index) @@ -911,12 +910,12 @@ def test_with_tz(self, tz): central = dr.tz_convert(tz) assert central.tz is tz naive = central[0].to_pydatetime().replace(tzinfo=None) - comp = tslib._localize_pydatetime(naive, tz).tzinfo + comp = conversion.localize_pydatetime(naive, tz).tzinfo assert central[0].tz is comp # compare vs a localized tz naive = dr[0].to_pydatetime().replace(tzinfo=None) - comp = tslib._localize_pydatetime(naive, tz).tzinfo + comp = conversion.localize_pydatetime(naive, tz).tzinfo assert central[0].tz is comp # datetimes with tzinfo set @@ -946,7 +945,7 @@ def test_dti_convert_tz_aware_datetime_datetime(self, tz): dates = [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)] - dates_aware = [tslib._localize_pydatetime(x, tz) for x in dates] + dates_aware = [conversion.localize_pydatetime(x, tz) for x in dates] result = DatetimeIndex(dates_aware) assert timezones.tz_compare(result.tz, tz) diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index b02fef707a6fe..fef01512b2060 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -10,7 +10,7 @@ import pandas.util._test_decorators as td from pandas.compat import PY3 -from pandas._libs import tslib +from pandas._libs.tslibs import conversion from pandas._libs.tslibs.frequencies import _INVALID_FREQ_ERROR from pandas import Timestamp, NaT @@ -242,7 +242,7 @@ def test_replace_across_dst(self, tz, normalize): # GH#18319 check that 1) timezone is correctly normalized and # 2) that hour is not incorrectly changed by this normalization ts_naive = Timestamp('2017-12-03 16:03:30') - ts_aware = tslib._localize_pydatetime(ts_naive, tz) + ts_aware = conversion.localize_pydatetime(ts_naive, tz) # Preliminary sanity-check assert ts_aware == normalize(ts_aware) diff --git a/pandas/tests/series/test_timezones.py b/pandas/tests/series/test_timezones.py index f2433163352ac..d59e7fd445f17 100644 --- a/pandas/tests/series/test_timezones.py +++ b/pandas/tests/series/test_timezones.py @@ -10,8 +10,7 @@ from dateutil.tz import tzoffset import pandas.util.testing as tm -from pandas._libs import tslib -from pandas._libs.tslibs import timezones +from pandas._libs.tslibs import timezones, conversion from pandas.compat import lrange from pandas.core.indexes.datetimes import date_range from pandas import Series, Timestamp, DatetimeIndex, Index @@ -298,7 +297,7 @@ def test_getitem_pydatetime_tz(self, tzstr): time_pandas = Timestamp('2012-12-24 17:00', tz=tzstr) dt = datetime(2012, 12, 24, 17, 0) - time_datetime = tslib._localize_pydatetime(dt, tz) + time_datetime = conversion.localize_pydatetime(dt, tz) assert ts[time_pandas] == ts[time_datetime] def test_series_truncate_datetimeindex_tz(self): diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index b93a0206479ca..79df847d0c8aa 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -10,6 +10,7 @@ from pandas.compat.numpy import np_datetime64_compat from pandas.core.series import Series +from pandas._libs.tslibs import conversion from pandas._libs.tslibs.frequencies import (get_freq_code, get_freq_str, _INVALID_FREQ_ERROR) from pandas.tseries.frequencies import _offset_map, get_offset @@ -319,7 +320,7 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected, for tz in self.timezones: expected_localize = expected.tz_localize(tz) tz_obj = timezones.maybe_get_tz(tz) - dt_tz = tslib._localize_pydatetime(dt, tz_obj) + dt_tz = conversion.localize_pydatetime(dt, tz_obj) result = func(dt_tz) assert isinstance(result, Timestamp) diff --git a/pandas/tests/tslibs/test_timezones.py b/pandas/tests/tslibs/test_timezones.py index 1bb355f267938..12f04505d953d 100644 --- a/pandas/tests/tslibs/test_timezones.py +++ b/pandas/tests/tslibs/test_timezones.py @@ -5,8 +5,7 @@ import pytz import dateutil.tz -from pandas._libs import tslib -from pandas._libs.tslibs import timezones +from pandas._libs.tslibs import timezones, conversion from pandas import Timestamp @@ -51,17 +50,17 @@ def test_infer_tz(eastern, localize): end = localize(eastern, end_naive) assert (timezones.infer_tzinfo(start, end) is - tslib._localize_pydatetime(start_naive, eastern).tzinfo) + conversion.localize_pydatetime(start_naive, eastern).tzinfo) assert (timezones.infer_tzinfo(start, None) is - tslib._localize_pydatetime(start_naive, eastern).tzinfo) + conversion.localize_pydatetime(start_naive, eastern).tzinfo) assert (timezones.infer_tzinfo(None, end) is - tslib._localize_pydatetime(end_naive, eastern).tzinfo) + conversion.localize_pydatetime(end_naive, eastern).tzinfo) start = utc.localize(start_naive) end = utc.localize(end_naive) assert timezones.infer_tzinfo(start, end) is utc - end = tslib._localize_pydatetime(end_naive, eastern) + end = conversion.localize_pydatetime(end_naive, eastern) with pytest.raises(Exception): timezones.infer_tzinfo(start, end) with pytest.raises(Exception): diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 1cfd3f476f8ab..f9c9ec09844d6 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -16,7 +16,9 @@ from pandas._libs import tslib, Timestamp, OutOfBoundsDatetime, Timedelta from pandas.util._decorators import cache_readonly -from pandas._libs.tslibs import ccalendar, frequencies as libfrequencies +from pandas._libs.tslibs import ( + ccalendar, conversion, + frequencies as libfrequencies) from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds import pandas._libs.tslibs.offsets as liboffsets from pandas._libs.tslibs.offsets import ( @@ -76,7 +78,7 @@ def wrapper(self, other): result = func(self, other) if self._adjust_dst: - result = tslib._localize_pydatetime(result, tz) + result = conversion.localize_pydatetime(result, tz) result = Timestamp(result) if self.normalize: @@ -94,7 +96,7 @@ def wrapper(self, other): result = Timestamp(value + nano) if tz is not None and result.tzinfo is None: - result = tslib._localize_pydatetime(result, tz) + result = conversion.localize_pydatetime(result, tz) except OutOfBoundsDatetime: result = func(self, as_datetime(other)) @@ -104,37 +106,12 @@ def wrapper(self, other): result = tslib.normalize_date(result) if tz is not None and result.tzinfo is None: - result = tslib._localize_pydatetime(result, tz) + result = conversion.localize_pydatetime(result, tz) return result return wrapper -def shift_day(other, days): - """ - Increment the datetime `other` by the given number of days, retaining - the time-portion of the datetime. For tz-naive datetimes this is - equivalent to adding a timedelta. For tz-aware datetimes it is similar to - dateutil's relativedelta.__add__, but handles pytz tzinfo objects. - - Parameters - ---------- - other : datetime or Timestamp - days : int - - Returns - ------- - shifted: datetime or Timestamp - """ - if other.tzinfo is None: - return other + timedelta(days=days) - - tz = other.tzinfo - naive = other.replace(tzinfo=None) - shifted = naive + timedelta(days=days) - return tslib._localize_pydatetime(shifted, tz) - - # --------------------------------------------------------------------- # DateOffset @@ -221,7 +198,7 @@ def apply(self, other): if tzinfo is not None and self._use_relativedelta: # bring tz back from UTC calculation - other = tslib._localize_pydatetime(other, tzinfo) + other = conversion.localize_pydatetime(other, tzinfo) return as_timestamp(other) else: @@ -1355,7 +1332,7 @@ def apply(self, other): shifted = shift_month(other, months, 'start') to_day = self._get_offset_day(shifted) - return shift_day(shifted, to_day - shifted.day) + return liboffsets.shift_day(shifted, to_day - shifted.day) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): @@ -1781,9 +1758,9 @@ def apply(self, other): next_year = self.get_year_end( datetime(other.year + 1, self.startingMonth, 1)) - prev_year = tslib._localize_pydatetime(prev_year, other.tzinfo) - cur_year = tslib._localize_pydatetime(cur_year, other.tzinfo) - next_year = tslib._localize_pydatetime(next_year, other.tzinfo) + prev_year = conversion.localize_pydatetime(prev_year, other.tzinfo) + cur_year = conversion.localize_pydatetime(cur_year, other.tzinfo) + next_year = conversion.localize_pydatetime(next_year, other.tzinfo) # Note: next_year.year == other.year + 1, so we will always # have other < next_year @@ -1984,7 +1961,7 @@ def _rollback_to_year(self, other): qtr_lens = self.get_weeks(norm) # check thet qtr_lens is consistent with self._offset addition - end = shift_day(start, days=7 * sum(qtr_lens)) + end = liboffsets.shift_day(start, days=7 * sum(qtr_lens)) assert self._offset.onOffset(end), (start, end, qtr_lens) tdelta = norm - start @@ -2024,7 +2001,7 @@ def apply(self, other): # Note: we always have 0 <= n < 4 weeks = sum(qtr_lens[:n]) if weeks: - res = shift_day(res, days=weeks * 7) + res = liboffsets.shift_day(res, days=weeks * 7) return res @@ -2061,7 +2038,7 @@ def onOffset(self, dt): current = next_year_end for qtr_len in qtr_lens: - current = shift_day(current, days=qtr_len * 7) + current = liboffsets.shift_day(current, days=qtr_len * 7) if dt == current: return True return False @@ -2096,8 +2073,8 @@ def apply(self, other): current_easter = easter(other.year) current_easter = datetime(current_easter.year, current_easter.month, current_easter.day) - current_easter = tslib._localize_pydatetime(current_easter, - other.tzinfo) + current_easter = conversion.localize_pydatetime(current_easter, + other.tzinfo) n = self.n if n >= 0 and other < current_easter:
The only non-test place where tslib._localize_pydatetime is used is in tseries.offsets. This moves that func to liboffsets, de-privatizes it, and moves tseris.offsets.shift_day up to liboffsets. To avoid import proliferation this keeps localize_pydatetime in the tslib namespace so the tests can get at it. Adds some typing to localize_pydatetime and fleshes out the docstring.
https://api.github.com/repos/pandas-dev/pandas/pulls/21691
2018-07-01T00:47:02Z
2018-07-02T23:33:44Z
2018-07-02T23:33:44Z
2018-07-02T23:36:35Z
Misc cleanups, test parametrization
diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index 1fa07dbed6822..cf887ce1a6387 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -1225,7 +1225,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0, ndarray[int64_t] idatetimes ndarray[int64_t] itimedeltas Seen seen = Seen() - object val, onan + object val float64_t fval, fnan n = len(objects) @@ -1244,7 +1244,6 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0, timedeltas = np.empty(n, dtype='m8[ns]') itimedeltas = timedeltas.view(np.int64) - onan = np.nan fnan = np.nan for i from 0 <= i < n: diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 3cbef82437544..2e1a1e732203e 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -1002,7 +1002,7 @@ cdef inline bisect_right_i8(int64_t *data, int64_t val, Py_ssize_t n): cdef inline str _render_tstamp(int64_t val): """ Helper function to render exception messages""" - from pandas._libs.tslib import Timestamp + from timestamps import Timestamp return str(Timestamp(val)) diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 6985d3b8df363..0eaa3ead5cff6 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -15,8 +15,6 @@ from libc.stdlib cimport free, malloc from libc.time cimport strftime, tm from libc.string cimport strlen, memset -from pandas.compat import PY2 - cimport cython from cpython.datetime cimport (PyDateTime_Check, PyDelta_Check, @@ -59,6 +57,8 @@ from nattype cimport _nat_scalar_rules, NPY_NAT from pandas.tseries import offsets from pandas.tseries import frequencies +cdef bint PY2 = str == bytes + cdef extern from "period_helper.h": int FR_ANN diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 210b201cd08ea..8565857fa945f 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -26,9 +26,9 @@ from conversion import tz_convert from conversion cimport tz_convert_utc_to_tzlocal from ccalendar import MONTH_ALIASES, int_to_weekday from ccalendar cimport get_days_in_month +from timestamps import Timestamp from pandas._libs.properties import cache_readonly -from pandas._libs.tslib import Timestamp from pandas.core.algorithms import unique # TODO: Avoid this non-cython import diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index e09c1b3f19d1a..fa9f9fc90387a 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -7,7 +7,7 @@ import dateutil import numpy as np from dateutil.parser import parse -from datetime import datetime, date, time +from datetime import datetime, time from distutils.version import LooseVersion import pandas as pd @@ -1251,92 +1251,90 @@ def test_day_not_in_month_ignore(self, cache): class TestDatetimeParsingWrappers(object): + @pytest.mark.parametrize('date_str,expected', list({ + '2011-01-01': datetime(2011, 1, 1), + '2Q2005': datetime(2005, 4, 1), + '2Q05': datetime(2005, 4, 1), + '2005Q1': datetime(2005, 1, 1), + '05Q1': datetime(2005, 1, 1), + '2011Q3': datetime(2011, 7, 1), + '11Q3': datetime(2011, 7, 1), + '3Q2011': datetime(2011, 7, 1), + '3Q11': datetime(2011, 7, 1), + + # quarterly without space + '2000Q4': datetime(2000, 10, 1), + '00Q4': datetime(2000, 10, 1), + '4Q2000': datetime(2000, 10, 1), + '4Q00': datetime(2000, 10, 1), + '2000q4': datetime(2000, 10, 1), + '2000-Q4': datetime(2000, 10, 1), + '00-Q4': datetime(2000, 10, 1), + '4Q-2000': datetime(2000, 10, 1), + '4Q-00': datetime(2000, 10, 1), + '00q4': datetime(2000, 10, 1), + '2005': datetime(2005, 1, 1), + '2005-11': datetime(2005, 11, 1), + '2005 11': datetime(2005, 11, 1), + '11-2005': datetime(2005, 11, 1), + '11 2005': datetime(2005, 11, 1), + '200511': datetime(2020, 5, 11), + '20051109': datetime(2005, 11, 9), + '20051109 10:15': datetime(2005, 11, 9, 10, 15), + '20051109 08H': datetime(2005, 11, 9, 8, 0), + '2005-11-09 10:15': datetime(2005, 11, 9, 10, 15), + '2005-11-09 08H': datetime(2005, 11, 9, 8, 0), + '2005/11/09 10:15': datetime(2005, 11, 9, 10, 15), + '2005/11/09 08H': datetime(2005, 11, 9, 8, 0), + "Thu Sep 25 10:36:28 2003": datetime(2003, 9, 25, 10, 36, 28), + "Thu Sep 25 2003": datetime(2003, 9, 25), + "Sep 25 2003": datetime(2003, 9, 25), + "January 1 2014": datetime(2014, 1, 1), + + # GHE10537 + '2014-06': datetime(2014, 6, 1), + '06-2014': datetime(2014, 6, 1), + '2014-6': datetime(2014, 6, 1), + '6-2014': datetime(2014, 6, 1), + + '20010101 12': datetime(2001, 1, 1, 12), + '20010101 1234': datetime(2001, 1, 1, 12, 34), + '20010101 123456': datetime(2001, 1, 1, 12, 34, 56)}.items())) @pytest.mark.parametrize('cache', [True, False]) - def test_parsers(self, cache): + def test_parsers(self, date_str, expected, cache): # dateutil >= 2.5.0 defaults to yearfirst=True # https://github.com/dateutil/dateutil/issues/217 yearfirst = True - cases = {'2011-01-01': datetime(2011, 1, 1), - '2Q2005': datetime(2005, 4, 1), - '2Q05': datetime(2005, 4, 1), - '2005Q1': datetime(2005, 1, 1), - '05Q1': datetime(2005, 1, 1), - '2011Q3': datetime(2011, 7, 1), - '11Q3': datetime(2011, 7, 1), - '3Q2011': datetime(2011, 7, 1), - '3Q11': datetime(2011, 7, 1), - - # quarterly without space - '2000Q4': datetime(2000, 10, 1), - '00Q4': datetime(2000, 10, 1), - '4Q2000': datetime(2000, 10, 1), - '4Q00': datetime(2000, 10, 1), - '2000q4': datetime(2000, 10, 1), - '2000-Q4': datetime(2000, 10, 1), - '00-Q4': datetime(2000, 10, 1), - '4Q-2000': datetime(2000, 10, 1), - '4Q-00': datetime(2000, 10, 1), - '00q4': datetime(2000, 10, 1), - '2005': datetime(2005, 1, 1), - '2005-11': datetime(2005, 11, 1), - '2005 11': datetime(2005, 11, 1), - '11-2005': datetime(2005, 11, 1), - '11 2005': datetime(2005, 11, 1), - '200511': datetime(2020, 5, 11), - '20051109': datetime(2005, 11, 9), - '20051109 10:15': datetime(2005, 11, 9, 10, 15), - '20051109 08H': datetime(2005, 11, 9, 8, 0), - '2005-11-09 10:15': datetime(2005, 11, 9, 10, 15), - '2005-11-09 08H': datetime(2005, 11, 9, 8, 0), - '2005/11/09 10:15': datetime(2005, 11, 9, 10, 15), - '2005/11/09 08H': datetime(2005, 11, 9, 8, 0), - "Thu Sep 25 10:36:28 2003": datetime(2003, 9, 25, 10, - 36, 28), - "Thu Sep 25 2003": datetime(2003, 9, 25), - "Sep 25 2003": datetime(2003, 9, 25), - "January 1 2014": datetime(2014, 1, 1), - - # GH 10537 - '2014-06': datetime(2014, 6, 1), - '06-2014': datetime(2014, 6, 1), - '2014-6': datetime(2014, 6, 1), - '6-2014': datetime(2014, 6, 1), - - '20010101 12': datetime(2001, 1, 1, 12), - '20010101 1234': datetime(2001, 1, 1, 12, 34), - '20010101 123456': datetime(2001, 1, 1, 12, 34, 56), - } - - for date_str, expected in compat.iteritems(cases): - result1, _, _ = parsing.parse_time_string(date_str, - yearfirst=yearfirst) - result2 = to_datetime(date_str, yearfirst=yearfirst) - result3 = to_datetime([date_str], yearfirst=yearfirst) - # result5 is used below - result4 = to_datetime(np.array([date_str], dtype=object), - yearfirst=yearfirst, cache=cache) - result6 = DatetimeIndex([date_str], yearfirst=yearfirst) - # result7 is used below - result8 = DatetimeIndex(Index([date_str]), yearfirst=yearfirst) - result9 = DatetimeIndex(Series([date_str]), yearfirst=yearfirst) - - for res in [result1, result2]: - assert res == expected - for res in [result3, result4, result6, result8, result9]: - exp = DatetimeIndex([pd.Timestamp(expected)]) - tm.assert_index_equal(res, exp) - - # these really need to have yearfirst, but we don't support - if not yearfirst: - result5 = Timestamp(date_str) - assert result5 == expected - result7 = date_range(date_str, freq='S', periods=1, - yearfirst=yearfirst) - assert result7 == expected - - # NaT + result1, _, _ = parsing.parse_time_string(date_str, + yearfirst=yearfirst) + result2 = to_datetime(date_str, yearfirst=yearfirst) + result3 = to_datetime([date_str], yearfirst=yearfirst) + # result5 is used below + result4 = to_datetime(np.array([date_str], dtype=object), + yearfirst=yearfirst, cache=cache) + result6 = DatetimeIndex([date_str], yearfirst=yearfirst) + # result7 is used below + result8 = DatetimeIndex(Index([date_str]), yearfirst=yearfirst) + result9 = DatetimeIndex(Series([date_str]), yearfirst=yearfirst) + + for res in [result1, result2]: + assert res == expected + for res in [result3, result4, result6, result8, result9]: + exp = DatetimeIndex([pd.Timestamp(expected)]) + tm.assert_index_equal(res, exp) + + # these really need to have yearfirst, but we don't support + if not yearfirst: + result5 = Timestamp(date_str) + assert result5 == expected + result7 = date_range(date_str, freq='S', periods=1, + yearfirst=yearfirst) + assert result7 == expected + + def test_parsers_nat(self): + # Test that each of several string-accepting methods return pd.NaT result1, _, _ = parsing.parse_time_string('NaT') result2 = to_datetime('NaT') result3 = Timestamp('NaT') @@ -1516,18 +1514,6 @@ def test_parsers_timezone_minute_offsets_roundtrip(self, cache): assert dt_string_repr == repr(converted_time) -def test_normalize_date(): - value = date(2012, 9, 7) - - result = tslib.normalize_date(value) - assert (result == datetime(2012, 9, 7)) - - value = datetime(2012, 9, 7, 12) - - result = tslib.normalize_date(value) - assert (result == datetime(2012, 9, 7)) - - @pytest.fixture(params=['D', 's', 'ms', 'us', 'ns']) def units(request): return request.param diff --git a/pandas/tests/tslibs/test_tslib.py b/pandas/tests/tslibs/test_tslib.py new file mode 100644 index 0000000000000..2641c016e8674 --- /dev/null +++ b/pandas/tests/tslibs/test_tslib.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +"""Tests for functions from pandas._libs.tslibs""" + +from datetime import datetime, date + +from pandas._libs import tslib + + +def test_normalize_date(): + value = date(2012, 9, 7) + + result = tslib.normalize_date(value) + assert (result == datetime(2012, 9, 7)) + + value = datetime(2012, 9, 7, 12) + + result = tslib.normalize_date(value) + assert (result == datetime(2012, 9, 7))
No coherent theme: remove an unused variable in inference.pyx, make some imports more direct, parametrize a big test, and move a tslib-specific test to test_tslibs
https://api.github.com/repos/pandas-dev/pandas/pulls/21690
2018-07-01T00:35:05Z
2018-07-02T11:12:29Z
2018-07-02T11:12:29Z
2018-07-02T23:37:45Z
Accept constant memoryviews in HashTable.lookup
diff --git a/ci/appveyor-27.yaml b/ci/appveyor-27.yaml index 10511ac0e00ca..114dcfb0c6440 100644 --- a/ci/appveyor-27.yaml +++ b/ci/appveyor-27.yaml @@ -24,7 +24,7 @@ dependencies: - xlsxwriter - xlwt # universal - - cython + - cython>=0.28.2 - pytest - pytest-xdist - moto diff --git a/ci/appveyor-36.yaml b/ci/appveyor-36.yaml index 868724419c464..63e45d0544ad9 100644 --- a/ci/appveyor-36.yaml +++ b/ci/appveyor-36.yaml @@ -22,6 +22,6 @@ dependencies: - xlsxwriter - xlwt # universal - - cython + - cython>=0.28.2 - pytest - pytest-xdist diff --git a/ci/circle-27-compat.yaml b/ci/circle-27-compat.yaml index 81a48d4edf11c..b5be569eb28a4 100644 --- a/ci/circle-27-compat.yaml +++ b/ci/circle-27-compat.yaml @@ -4,7 +4,7 @@ channels: - conda-forge dependencies: - bottleneck=1.0.0 - - cython=0.24 + - cython=0.28.2 - jinja2=2.8 - numexpr=2.4.4 # we test that we correctly don't use an unsupported numexpr - numpy=1.9.2 diff --git a/ci/circle-35-ascii.yaml b/ci/circle-35-ascii.yaml index 602c414b49bb2..745678791458d 100644 --- a/ci/circle-35-ascii.yaml +++ b/ci/circle-35-ascii.yaml @@ -2,7 +2,7 @@ name: pandas channels: - defaults dependencies: - - cython + - cython>=0.28.2 - nomkl - numpy - python-dateutil diff --git a/ci/circle-36-locale.yaml b/ci/circle-36-locale.yaml index cc852c1e2aeeb..091a5a637becd 100644 --- a/ci/circle-36-locale.yaml +++ b/ci/circle-36-locale.yaml @@ -4,7 +4,7 @@ channels: - conda-forge dependencies: - beautifulsoup4 - - cython + - cython>=0.28.2 - html5lib - ipython - jinja2 diff --git a/ci/circle-36-locale_slow.yaml b/ci/circle-36-locale_slow.yaml index f44e98e1ee09d..649f93f7aa427 100644 --- a/ci/circle-36-locale_slow.yaml +++ b/ci/circle-36-locale_slow.yaml @@ -4,7 +4,7 @@ channels: - conda-forge dependencies: - beautifulsoup4 - - cython + - cython>=0.28.2 - gcsfs - html5lib - ipython diff --git a/ci/environment-dev.yaml b/ci/environment-dev.yaml index 5733857b55dd4..797506547b773 100644 --- a/ci/environment-dev.yaml +++ b/ci/environment-dev.yaml @@ -3,7 +3,7 @@ channels: - defaults - conda-forge dependencies: - - Cython + - Cython>=0.28.2 - NumPy - flake8 - moto diff --git a/ci/travis-27-locale.yaml b/ci/travis-27-locale.yaml index 1312c1296d46a..78cbe8f59a8e0 100644 --- a/ci/travis-27-locale.yaml +++ b/ci/travis-27-locale.yaml @@ -4,7 +4,7 @@ channels: - conda-forge dependencies: - bottleneck=1.0.0 - - cython=0.24 + - cython=0.28.2 - lxml - matplotlib=1.4.3 - numpy=1.9.2 diff --git a/ci/travis-27.yaml b/ci/travis-27.yaml index 482b888b88062..9cb20734dc63d 100644 --- a/ci/travis-27.yaml +++ b/ci/travis-27.yaml @@ -5,7 +5,7 @@ channels: dependencies: - beautifulsoup4 - bottleneck - - cython=0.24 + - cython=0.28.2 - fastparquet - feather-format - flake8=3.4.1 diff --git a/ci/travis-35-osx.yaml b/ci/travis-35-osx.yaml index e74abac4c9775..fff7acc64d537 100644 --- a/ci/travis-35-osx.yaml +++ b/ci/travis-35-osx.yaml @@ -4,7 +4,7 @@ channels: dependencies: - beautifulsoup4 - bottleneck - - cython + - cython>=0.28.2 - html5lib - jinja2 - lxml diff --git a/ci/travis-36-doc.yaml b/ci/travis-36-doc.yaml index c22dddbe0ba3f..153a81197a6c7 100644 --- a/ci/travis-36-doc.yaml +++ b/ci/travis-36-doc.yaml @@ -6,7 +6,7 @@ channels: dependencies: - beautifulsoup4 - bottleneck - - cython + - cython>=0.28.2 - fastparquet - feather-format - html5lib diff --git a/ci/travis-36-numpydev.yaml b/ci/travis-36-numpydev.yaml index 455d65feb4242..038c6537622dd 100644 --- a/ci/travis-36-numpydev.yaml +++ b/ci/travis-36-numpydev.yaml @@ -4,7 +4,7 @@ channels: dependencies: - python=3.6* - pytz - - Cython + - Cython>=0.28.2 # universal - pytest - pytest-xdist diff --git a/ci/travis-36-slow.yaml b/ci/travis-36-slow.yaml index 6c475dc48723c..f6738e3837186 100644 --- a/ci/travis-36-slow.yaml +++ b/ci/travis-36-slow.yaml @@ -4,7 +4,7 @@ channels: - conda-forge dependencies: - beautifulsoup4 - - cython + - cython>=0.28.2 - html5lib - lxml - matplotlib diff --git a/ci/travis-36.yaml b/ci/travis-36.yaml index ff4f1a4a86f99..7eceba76cab96 100644 --- a/ci/travis-36.yaml +++ b/ci/travis-36.yaml @@ -4,7 +4,7 @@ channels: - conda-forge dependencies: - beautifulsoup4 - - cython + - cython>=0.28.2 - dask - fastparquet - feather-format diff --git a/ci/travis-37.yaml b/ci/travis-37.yaml index 8b255c9e6ec72..1dc2930bf7287 100644 --- a/ci/travis-37.yaml +++ b/ci/travis-37.yaml @@ -5,7 +5,7 @@ channels: - c3i_test dependencies: - python=3.7 - - cython + - cython>=0.28.2 - numpy - python-dateutil - nomkl diff --git a/doc/source/install.rst b/doc/source/install.rst index a8c5194124829..087bca0d5cd3c 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -253,7 +253,7 @@ Optional Dependencies ~~~~~~~~~~~~~~~~~~~~~ * `Cython <http://www.cython.org>`__: Only necessary to build development - version. Version 0.24 or higher. + version. Version 0.28.2 or higher. * `SciPy <http://www.scipy.org>`__: miscellaneous statistical functions, Version 0.14.0 or higher * `xarray <http://xarray.pydata.org>`__: pandas like handling for > 2 dims, needed for converting Panels to xarray objects. Version 0.7.0 or higher is recommended. * `PyTables <http://www.pytables.org>`__: necessary for HDF5-based storage. Version 3.0.0 or higher required, Version 3.2.1 or higher highly recommended. diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 7362e11b22189..5e8d8fddea392 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -410,12 +410,17 @@ Reshaping - - +Build Changes +^^^^^^^^^^^^^ + +- Building pandas for development now requires ``cython >= 0.28.2`` (:issue:`21688`) - Other ^^^^^ - :meth: `~pandas.io.formats.style.Styler.background_gradient` now takes a ``text_color_threshold`` parameter to automatically lighten the text color based on the luminance of the background color. This improves readability with dark background colors without the need to limit the background colormap range. (:issue:`21258`) +- Require at least 0.28.2 version of ``cython`` to support read-only memoryviews (:issue:`21688`) - - - diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in index 4d2b6f845eb71..ff6570e2106b2 100644 --- a/pandas/_libs/hashtable_class_helper.pxi.in +++ b/pandas/_libs/hashtable_class_helper.pxi.in @@ -120,7 +120,7 @@ cdef class {{name}}Vector: append_data_{{dtype}}(self.data, x) - cdef extend(self, {{arg}}[:] x): + cdef extend(self, const {{arg}}[:] x): for i in range(len(x)): self.append(x[i]) @@ -253,56 +253,10 @@ dtypes = [('Float64', 'float64', True, 'nan'), ('UInt64', 'uint64', False, 0), ('Int64', 'int64', False, 'iNaT')] -def get_dispatch(dtypes): - for (name, dtype, float_group, default_na_value) in dtypes: - unique_template = """\ - cdef: - Py_ssize_t i, n = len(values) - int ret = 0 - {dtype}_t val - khiter_t k - bint seen_na = 0 - {name}Vector uniques = {name}Vector() - {name}VectorData *ud - - ud = uniques.data - - with nogil: - for i in range(n): - val = values[i] - IF {float_group}: - if val == val: - k = kh_get_{dtype}(self.table, val) - if k == self.table.n_buckets: - kh_put_{dtype}(self.table, val, &ret) - if needs_resize(ud): - with gil: - uniques.resize() - append_data_{dtype}(ud, val) - elif not seen_na: - seen_na = 1 - if needs_resize(ud): - with gil: - uniques.resize() - append_data_{dtype}(ud, NAN) - ELSE: - k = kh_get_{dtype}(self.table, val) - if k == self.table.n_buckets: - kh_put_{dtype}(self.table, val, &ret) - if needs_resize(ud): - with gil: - uniques.resize() - append_data_{dtype}(ud, val) - return uniques.to_array() - """ - - unique_template = unique_template.format(name=name, dtype=dtype, float_group=float_group) - - yield (name, dtype, float_group, default_na_value, unique_template) }} -{{for name, dtype, float_group, default_na_value, unique_template in get_dispatch(dtypes)}} +{{for name, dtype, float_group, default_na_value in dtypes}} cdef class {{name}}HashTable(HashTable): @@ -351,7 +305,7 @@ cdef class {{name}}HashTable(HashTable): raise KeyError(key) @cython.boundscheck(False) - def map(self, {{dtype}}_t[:] keys, int64_t[:] values): + def map(self, const {{dtype}}_t[:] keys, const int64_t[:] values): cdef: Py_ssize_t i, n = len(values) int ret = 0 @@ -379,7 +333,7 @@ cdef class {{name}}HashTable(HashTable): self.table.vals[k] = i @cython.boundscheck(False) - def lookup(self, {{dtype}}_t[:] values): + def lookup(self, const {{dtype}}_t[:] values): cdef: Py_ssize_t i, n = len(values) int ret = 0 @@ -404,7 +358,7 @@ cdef class {{name}}HashTable(HashTable): return uniques.to_array(), labels @cython.boundscheck(False) - def get_labels(self, {{dtype}}_t[:] values, {{name}}Vector uniques, + def get_labels(self, const {{dtype}}_t[:] values, {{name}}Vector uniques, Py_ssize_t count_prior, Py_ssize_t na_sentinel, object na_value=None): cdef: @@ -461,7 +415,7 @@ cdef class {{name}}HashTable(HashTable): return np.asarray(labels) @cython.boundscheck(False) - def get_labels_groupby(self, {{dtype}}_t[:] values): + def get_labels_groupby(self, const {{dtype}}_t[:] values): cdef: Py_ssize_t i, n = len(values) int64_t[:] labels @@ -506,20 +460,46 @@ cdef class {{name}}HashTable(HashTable): return np.asarray(labels), arr_uniques @cython.boundscheck(False) - def unique(self, ndarray[{{dtype}}_t, ndim=1] values): - if values.flags.writeable: - # If the value is writeable (mutable) then use memview - return self.unique_memview(values) + def unique(self, const {{dtype}}_t[:] values): + cdef: + Py_ssize_t i, n = len(values) + int ret = 0 + {{dtype}}_t val + khiter_t k + bint seen_na = 0 + {{name}}Vector uniques = {{name}}Vector() + {{name}}VectorData *ud - # We cannot use the memoryview version on readonly-buffers due to - # a limitation of Cython's typed memoryviews. Instead we can use - # the slightly slower Cython ndarray type directly. - # see https://github.com/cython/cython/issues/1605 -{{unique_template}} + ud = uniques.data - @cython.boundscheck(False) - def unique_memview(self, {{dtype}}_t[:] values): -{{unique_template}} + with nogil: + for i in range(n): + val = values[i] + {{if float_group}} + if val == val: + k = kh_get_{{dtype}}(self.table, val) + if k == self.table.n_buckets: + kh_put_{{dtype}}(self.table, val, &ret) + if needs_resize(ud): + with gil: + uniques.resize() + append_data_{{dtype}}(ud, val) + elif not seen_na: + seen_na = 1 + if needs_resize(ud): + with gil: + uniques.resize() + append_data_{{dtype}}(ud, NAN) + {{else}} + k = kh_get_{{dtype}}(self.table, val) + if k == self.table.n_buckets: + kh_put_{{dtype}}(self.table, val, &ret) + if needs_resize(ud): + with gil: + uniques.resize() + append_data_{{dtype}}(ud, val) + {{endif}} + return uniques.to_array() {{endfor}} diff --git a/pandas/conftest.py b/pandas/conftest.py index 255e0e165041b..84f1d8f29f1f1 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -138,6 +138,14 @@ def compression_only(request): return request.param +@pytest.fixture(params=[True, False]) +def writable(request): + """ + Fixture that an array is writable + """ + return request.param + + @pytest.fixture(scope='module') def datetime_tz_utc(): from datetime import timezone diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 46bd879c2db87..de3c9574a4471 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -1077,15 +1077,19 @@ class TestGroupVarFloat32(GroupVarTestMixin): class TestHashTable(object): - def test_lookup_nan(self): + def test_lookup_nan(self, writable): xs = np.array([2.718, 3.14, np.nan, -7, 5, 2, 3]) + # GH 21688 ensure we can deal with readonly memory views + xs.setflags(write=writable) m = ht.Float64HashTable() m.map_locations(xs) tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.int64)) - def test_lookup_overflow(self): + def test_lookup_overflow(self, writable): xs = np.array([1, 2, 2**63], dtype=np.uint64) + # GH 21688 ensure we can deal with readonly memory views + xs.setflags(write=writable) m = ht.UInt64HashTable() m.map_locations(xs) tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), @@ -1096,12 +1100,14 @@ def test_get_unique(self): exp = np.array([1, 2, 2**63], dtype=np.uint64) tm.assert_numpy_array_equal(s.unique(), exp) - def test_vector_resize(self): + def test_vector_resize(self, writable): # Test for memory errors after internal vector # reallocations (pull request #7157) def _test_vector_resize(htable, uniques, dtype, nvals, safely_resizes): vals = np.array(np.random.randn(1000), dtype=dtype) + # GH 21688 ensure we can deal with readonly memory views + vals.setflags(write=writable) # get_labels may append to uniques htable.get_labels(vals[:nvals], uniques, 0, -1) # to_array() set an external_view_exists flag on uniques. diff --git a/setup.py b/setup.py index 29b19fed0e2d4..8018d71b74655 100755 --- a/setup.py +++ b/setup.py @@ -32,7 +32,7 @@ def is_platform_mac(): return sys.platform == 'darwin' -min_cython_ver = '0.24' +min_cython_ver = '0.28.2' try: import Cython ver = Cython.__version__
xref https://github.com/pandas-dev/pandas/pull/10070 xref https://github.com/pandas-dev/pandas/issues/12813 building an ExtensionArray for nullable ints using a `pyarrow.Array`, the underlying memoryview is marked as constant. The HashTable Cython code uses the memoryview in the `lookup` function but in a read-only fashion. Without the `const` specifier Cython raises an error that the memoryview is read-only. Not sure how to test this in a small scope (i.e. without using `pyarrow`) or if this small change is worth mentioning in the changelog. - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21688
2018-06-30T07:32:55Z
2018-07-07T19:52:39Z
2018-07-07T19:52:39Z
2018-07-08T18:21:55Z
API: remove ordered requirement in Categorical.searchsorted
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 3406f52b06a61..2668734031ee1 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -173,7 +173,7 @@ Categorical - Added test to assert the :func:`fillna` raises the correct ValueError message when the value isn't a value from categories (:issue:`13628`) - Bug in :meth:`Categorical.astype` where ``NaN`` values were handled incorrectly when casting to int (:issue:`28406`) -- +- :meth:`Categorical.searchsorted` and :meth:`CategoricalIndex.searchsorted` now work on unordered categoricals also (:issue:`21667`) - diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 870628500af21..33d1de01fa3db 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1399,13 +1399,6 @@ def memory_usage(self, deep=False): @Substitution(klass="Categorical") @Appender(_shared_docs["searchsorted"]) def searchsorted(self, value, side="left", sorter=None): - if not self.ordered: - raise ValueError( - "Categorical not ordered\nyou can use " - ".as_ordered() to change the Categorical to an " - "ordered one" - ) - from pandas.core.series import Series codes = _get_codes_for_values(Series(value).values, self.categories) diff --git a/pandas/core/base.py b/pandas/core/base.py index 910b05c47071d..7df3ae97ccad2 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1515,6 +1515,12 @@ def factorize(self, sort=False, na_sentinel=-1): corresponding elements in `value` were inserted before the indices, the order of `self` would be preserved. + .. note:: + + The %(klass)s *must* be monotonically sorted, otherwise + wrong locations will likely be returned. Pandas does *not* + check this for you. + Parameters ---------- value : array_like @@ -1540,6 +1546,7 @@ def factorize(self, sort=False, na_sentinel=-1): See Also -------- + sort_values numpy.searchsorted Notes @@ -1578,6 +1585,13 @@ def factorize(self, sort=False, na_sentinel=-1): >>> x.searchsorted(['bread'], side='right') array([3]) + + If the values are not monotonically sorted, wrong locations + may be returned: + + >>> x = pd.Series([2, 1, 3]) + >>> x.searchsorted(1) + 0 # wrong result, correct would be 1 """ @Substitution(klass="Index") diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index d8831d7e6bf36..86750244d5fb5 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -78,42 +78,36 @@ def test_mode(self, values, categories, exp_mode): exp = Categorical(exp_mode, categories=categories, ordered=True) tm.assert_categorical_equal(res, exp) - def test_searchsorted(self): + def test_searchsorted(self, ordered_fixture): # https://github.com/pandas-dev/pandas/issues/8420 # https://github.com/pandas-dev/pandas/issues/14522 - c1 = Categorical( - ["cheese", "milk", "apple", "bread", "bread"], - categories=["cheese", "milk", "apple", "bread"], - ordered=True, - ) - s1 = Series(c1) - c2 = Categorical( + cat = Categorical( ["cheese", "milk", "apple", "bread", "bread"], categories=["cheese", "milk", "apple", "bread"], - ordered=False, + ordered=ordered_fixture, ) - s2 = Series(c2) + ser = Series(cat) # Searching for single item argument, side='left' (default) - res_cat = c1.searchsorted("apple") + res_cat = cat.searchsorted("apple") assert res_cat == 2 assert is_scalar(res_cat) - res_ser = s1.searchsorted("apple") + res_ser = ser.searchsorted("apple") assert res_ser == 2 assert is_scalar(res_ser) # Searching for single item array, side='left' (default) - res_cat = c1.searchsorted(["bread"]) - res_ser = s1.searchsorted(["bread"]) + res_cat = cat.searchsorted(["bread"]) + res_ser = ser.searchsorted(["bread"]) exp = np.array([3], dtype=np.intp) tm.assert_numpy_array_equal(res_cat, exp) tm.assert_numpy_array_equal(res_ser, exp) # Searching for several items array, side='right' - res_cat = c1.searchsorted(["apple", "bread"], side="right") - res_ser = s1.searchsorted(["apple", "bread"], side="right") + res_cat = cat.searchsorted(["apple", "bread"], side="right") + res_ser = ser.searchsorted(["apple", "bread"], side="right") exp = np.array([3, 5], dtype=np.intp) tm.assert_numpy_array_equal(res_cat, exp) tm.assert_numpy_array_equal(res_ser, exp) @@ -121,22 +115,15 @@ def test_searchsorted(self): # Searching for a single value that is not from the Categorical msg = r"Value\(s\) to be inserted must be in categories" with pytest.raises(KeyError, match=msg): - c1.searchsorted("cucumber") + cat.searchsorted("cucumber") with pytest.raises(KeyError, match=msg): - s1.searchsorted("cucumber") + ser.searchsorted("cucumber") # Searching for multiple values one of each is not from the Categorical with pytest.raises(KeyError, match=msg): - c1.searchsorted(["bread", "cucumber"]) + cat.searchsorted(["bread", "cucumber"]) with pytest.raises(KeyError, match=msg): - s1.searchsorted(["bread", "cucumber"]) - - # searchsorted call for unordered Categorical - msg = "Categorical not ordered" - with pytest.raises(ValueError, match=msg): - c2.searchsorted("apple") - with pytest.raises(ValueError, match=msg): - s2.searchsorted("apple") + ser.searchsorted(["bread", "cucumber"]) def test_unique(self): # categories are reordered based on value when ordered=False
- [x] closes #21667 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry ``searchsorted`` is mainly a tool to find value locations in a sorted array. As such it doesn't make sense to restrict it to not work with unordered categoricals. For example, doing searchsorted on ordered, but unsorted arrays gives wrong result, so orderedness is a relatively irrelevant thing to check for in searchsorted. The current solution to first convert to a ordered Categorical is inelegant and requires setting up different code paths depending on the situation: ```python if categorical.ordered: val = c.searchsorted(key) else: val = c.as_ordered().searchsorted(key) ``` I've also added to the doc string of searchsorted to make clear that sortedness is required for a correct result (this is not an issue that is limited to categoricals, but all Arrays)
https://api.github.com/repos/pandas-dev/pandas/pulls/21686
2018-06-29T17:25:34Z
2019-10-02T03:15:41Z
2019-10-02T03:15:40Z
2019-10-02T21:21:22Z
Release 0.23.2 backports part I
diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt new file mode 100644 index 0000000000000..53ca4c0d1c144 --- /dev/null +++ b/doc/source/whatsnew/v0.23.2.txt @@ -0,0 +1,93 @@ +.. _whatsnew_0232: + +v0.23.2 +------- + +This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes +and bug fixes. We recommend that all users upgrade to this version. + +.. contents:: What's new in v0.23.2 + :local: + :backlinks: none + + +.. _whatsnew_0232.fixed_regressions: + +Fixed Regressions +~~~~~~~~~~~~~~~~~ + +- Fixed regression in :meth:`to_csv` when handling file-like object incorrectly (:issue:`21471`) +- Bug in both :meth:`DataFrame.first_valid_index` and :meth:`Series.first_valid_index` raised for a row index having duplicate values (:issue:`21441`) +- + +.. _whatsnew_0232.performance: + +Performance Improvements +~~~~~~~~~~~~~~~~~~~~~~~~ + +- +- + +Documentation Changes +~~~~~~~~~~~~~~~~~~~~~ + +- +- + +.. _whatsnew_0232.bug_fixes: + +Bug Fixes +~~~~~~~~~ + +**Groupby/Resample/Rolling** + +- +- + +**Timedelta** + +- Bug in :class:`Timedelta` where non-zero timedeltas shorter than 1 microsecond were considered False (:issue:`21484`) + +**Conversion** + +- Bug in constructing :class:`Index` with an iterator or generator (:issue:`21470`) +- Bug in :meth:`Series.nlargest` for signed and unsigned integer dtypes when the minimum value is present (:issue:`21426`) + + +**Indexing** + +- Bug in :meth:`Index.get_indexer_non_unique` with categorical key (:issue:`21448`) +- Bug in comparison operations for :class:`MultiIndex` where error was raised on equality / inequality comparison involving a MultiIndex with ``nlevels == 1`` (:issue:`21149`) +- Bug in :meth:`DataFrame.drop` behaviour is not consistent for unique and non-unique indexes (:issue:`21494`) +- Bug in :func:`DataFrame.duplicated` with a large number of columns causing a 'maximum recursion depth exceeded' (:issue:`21524`). +- + +**I/O** + +- Bug in :func:`read_csv` that caused it to incorrectly raise an error when ``nrows=0``, ``low_memory=True``, and ``index_col`` was not ``None`` (:issue:`21141`) +- Bug in :func:`json_normalize` when formatting the ``record_prefix`` with integer columns (:issue:`21536`) +- + +**Plotting** + +- +- + +**Reshaping** + +- +- + +**Categorical** + +- Bug in rendering :class:`Series` with ``Categorical`` dtype in rare conditions under Python 2.7 (:issue:`21002`) +- + +**Timezones** + +- Bug in :class:`Timestamp` and :class:`DatetimeIndex` where passing a :class:`Timestamp` localized after a DST transition would return a datetime before the DST transition (:issue:`20854`) +- Bug in comparing :class:`DataFrame`s with tz-aware :class:`DatetimeIndex` columns with a DST transition that raised a ``KeyError`` (:issue:`19970`) + +**Other** + +- diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx index c6f182ac5003f..4489847518a1d 100644 --- a/pandas/_libs/hashing.pyx +++ b/pandas/_libs/hashing.pyx @@ -8,8 +8,7 @@ import numpy as np from numpy cimport ndarray, uint8_t, uint32_t, uint64_t from util cimport _checknull -from cpython cimport (PyString_Check, - PyBytes_Check, +from cpython cimport (PyBytes_Check, PyUnicode_Check) from libc.stdlib cimport malloc, free @@ -62,9 +61,7 @@ def hash_object_array(ndarray[object] arr, object key, object encoding='utf8'): cdef list datas = [] for i in range(n): val = arr[i] - if PyString_Check(val): - data = <bytes>val.encode(encoding) - elif PyBytes_Check(val): + if PyBytes_Check(val): data = <bytes>val elif PyUnicode_Check(val): data = <bytes>val.encode(encoding) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index f4841e6abb7e8..3cbef82437544 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -347,25 +347,11 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, object tz, if tz is not None: tz = maybe_get_tz(tz) - # sort of a temporary hack if ts.tzinfo is not None: - if hasattr(tz, 'normalize') and hasattr(ts.tzinfo, '_utcoffset'): - ts = tz.normalize(ts) - obj.value = pydatetime_to_dt64(ts, &obj.dts) - obj.tzinfo = ts.tzinfo - else: - # tzoffset - try: - tz = ts.astimezone(tz).tzinfo - except: - pass - obj.value = pydatetime_to_dt64(ts, &obj.dts) - ts_offset = get_utcoffset(ts.tzinfo, ts) - obj.value -= int(ts_offset.total_seconds() * 1e9) - tz_offset = get_utcoffset(tz, ts) - obj.value += int(tz_offset.total_seconds() * 1e9) - dt64_to_dtstruct(obj.value, &obj.dts) - obj.tzinfo = tz + # Convert the current timezone to the passed timezone + ts = ts.astimezone(tz) + obj.value = pydatetime_to_dt64(ts, &obj.dts) + obj.tzinfo = ts.tzinfo elif not is_utc(tz): ts = _localize_pydatetime(ts, tz) obj.value = pydatetime_to_dt64(ts, &obj.dts) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index e2b0b33053f83..769f3ca5fa8bf 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -899,6 +899,9 @@ cdef class _Timedelta(timedelta): def __str__(self): return self._repr_base(format='long') + def __bool__(self): + return self.value != 0 + def isoformat(self): """ Format Timedelta as ISO 8601 Duration like diff --git a/pandas/conftest.py b/pandas/conftest.py index d5f399c7cd63d..9d806a91f37f7 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -129,6 +129,14 @@ def join_type(request): return request.param +@pytest.fixture(params=['nlargest', 'nsmallest']) +def nselect_method(request): + """ + Fixture for trying all nselect methods + """ + return request.param + + @pytest.fixture(params=[None, np.nan, pd.NaT, float('nan'), np.float('NaN')]) def nulls_fixture(request): """ @@ -170,3 +178,66 @@ def string_dtype(request): * 'U' """ return request.param + + +@pytest.fixture(params=["float32", "float64"]) +def float_dtype(request): + """ + Parameterized fixture for float dtypes. + + * float32 + * float64 + """ + + return request.param + + +UNSIGNED_INT_DTYPES = ["uint8", "uint16", "uint32", "uint64"] +SIGNED_INT_DTYPES = ["int8", "int16", "int32", "int64"] +ALL_INT_DTYPES = UNSIGNED_INT_DTYPES + SIGNED_INT_DTYPES + + +@pytest.fixture(params=SIGNED_INT_DTYPES) +def sint_dtype(request): + """ + Parameterized fixture for signed integer dtypes. + + * int8 + * int16 + * int32 + * int64 + """ + + return request.param + + +@pytest.fixture(params=UNSIGNED_INT_DTYPES) +def uint_dtype(request): + """ + Parameterized fixture for unsigned integer dtypes. + + * uint8 + * uint16 + * uint32 + * uint64 + """ + + return request.param + + +@pytest.fixture(params=ALL_INT_DTYPES) +def any_int_dtype(request): + """ + Parameterized fixture for any integer dtypes. + + * int8 + * uint8 + * int16 + * uint16 + * int32 + * uint32 + * int64 + * uint64 + """ + + return request.param diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 88bc497f9f22d..bcde32696c1ff 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1131,9 +1131,12 @@ def compute(self, method): return dropped[slc].sort_values(ascending=ascending).head(n) # fast method - arr, _, _ = _ensure_data(dropped.values) + arr, pandas_dtype, _ = _ensure_data(dropped.values) if method == 'nlargest': arr = -arr + if is_integer_dtype(pandas_dtype): + # GH 21426: ensure reverse ordering at boundaries + arr -= 1 if self.keep == 'last': arr = arr[::-1] diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index a1a8f098b582e..b587a4c0bc722 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -3,7 +3,6 @@ import numpy as np from warnings import warn import textwrap -import types from pandas import compat from pandas.compat import u, lzip @@ -28,7 +27,7 @@ is_categorical, is_categorical_dtype, is_list_like, is_sequence, - is_scalar, + is_scalar, is_iterator, is_dict_like) from pandas.core.algorithms import factorize, take_1d, unique1d, take @@ -2473,7 +2472,7 @@ def _convert_to_list_like(list_like): if isinstance(list_like, list): return list_like if (is_sequence(list_like) or isinstance(list_like, tuple) or - isinstance(list_like, types.GeneratorType)): + is_iterator(list_like)): return list(list_like) elif is_scalar(list_like): return [list_like] diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9e4eda1bc4dc7..612ee7cb42021 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3129,7 +3129,7 @@ def _drop_axis(self, labels, axis, level=None, errors='raise'): """ axis = self._get_axis_number(axis) axis_name = self._get_axis_name(axis) - axis, axis_ = self._get_axis(axis), axis + axis = self._get_axis(axis) if axis.is_unique: if level is not None: @@ -3138,24 +3138,25 @@ def _drop_axis(self, labels, axis, level=None, errors='raise'): new_axis = axis.drop(labels, level=level, errors=errors) else: new_axis = axis.drop(labels, errors=errors) - dropped = self.reindex(**{axis_name: new_axis}) - try: - dropped.axes[axis_].set_names(axis.names, inplace=True) - except AttributeError: - pass - result = dropped + result = self.reindex(**{axis_name: new_axis}) + # Case for non-unique axis else: labels = _ensure_object(com._index_labels_to_array(labels)) if level is not None: if not isinstance(axis, MultiIndex): raise AssertionError('axis must be a MultiIndex') indexer = ~axis.get_level_values(level).isin(labels) + + # GH 18561 MultiIndex.drop should raise if label is absent + if errors == 'raise' and indexer.all(): + raise KeyError('{} not found in axis'.format(labels)) else: indexer = ~axis.isin(labels) - - if errors == 'raise' and indexer.all(): - raise KeyError('{} not found in axis'.format(labels)) + # Check if label doesn't exist along axis + labels_missing = (axis.get_indexer_for(labels) == -1).any() + if errors == 'raise' and labels_missing: + raise KeyError('{} not found in axis'.format(labels)) slicer = [slice(None)] * self.ndim slicer[self._get_axis_number(axis_name)] = indexer @@ -8969,18 +8970,17 @@ def _find_valid_index(self, how): is_valid = is_valid.any(1) # reduce axis 1 if how == 'first': - # First valid value case - i = is_valid.idxmax() - if not is_valid[i]: - return None - return i - - elif how == 'last': - # Last valid value case - i = is_valid.values[::-1].argmax() - if not is_valid.iat[len(self) - i - 1]: - return None - return self.index[len(self) - i - 1] + idxpos = is_valid.values[::].argmax() + + if how == 'last': + idxpos = len(self) - 1 - is_valid.values[::-1].argmax() + + chk_notna = is_valid.iat[idxpos] + idx = self.index[idxpos] + + if not chk_notna: + return None + return idx @Appender(_shared_docs['valid_index'] % {'position': 'first', 'klass': 'NDFrame'}) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 90238af9b3632..59527afe6c1f7 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -31,6 +31,7 @@ is_dtype_equal, is_dtype_union_equal, is_object_dtype, + is_categorical, is_categorical_dtype, is_interval_dtype, is_period_dtype, @@ -96,7 +97,8 @@ def cmp_method(self, other): if needs_i8_conversion(self) and needs_i8_conversion(other): return self._evaluate_compare(other, op) - if is_object_dtype(self) and self.nlevels == 1: + from .multi import MultiIndex + if is_object_dtype(self) and not isinstance(self, MultiIndex): # don't pass MultiIndex with np.errstate(all='ignore'): result = ops._comp_method_OBJECT_ARRAY(op, self.values, other) @@ -187,6 +189,9 @@ class Index(IndexOpsMixin, PandasObject): ---------- data : array-like (1-dimensional) dtype : NumPy dtype (default: object) + If dtype is None, we find the dtype that best fits the data. + If an actual dtype is provided, we coerce to that dtype if it's safe. + Otherwise, an error will be raised. copy : bool Make a copy of input ndarray name : object @@ -312,7 +317,14 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, if is_integer_dtype(dtype): inferred = lib.infer_dtype(data) if inferred == 'integer': - data = np.array(data, copy=copy, dtype=dtype) + try: + data = np.array(data, copy=copy, dtype=dtype) + except OverflowError: + # gh-15823: a more user-friendly error message + raise OverflowError( + "the elements provided in the data cannot " + "all be casted to the dtype {dtype}" + .format(dtype=dtype)) elif inferred in ['floating', 'mixed-integer-float']: if isna(data).any(): raise ValueError('cannot convert float ' @@ -424,12 +436,14 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, elif data is None or is_scalar(data): cls._scalar_data_error(data) else: - if tupleize_cols and is_list_like(data) and data: + if tupleize_cols and is_list_like(data): + # GH21470: convert iterable to list before determining if empty if is_iterator(data): data = list(data) - # we must be all tuples, otherwise don't construct - # 10697 - if all(isinstance(e, tuple) for e in data): + + if data and all(isinstance(e, tuple) for e in data): + # we must be all tuples, otherwise don't construct + # 10697 from .multi import MultiIndex return MultiIndex.from_tuples( data, names=name or kwargs.get('names')) @@ -3347,6 +3361,8 @@ def _filter_indexer_tolerance(self, target, indexer, tolerance): @Appender(_index_shared_docs['get_indexer_non_unique'] % _index_doc_kwargs) def get_indexer_non_unique(self, target): target = _ensure_index(target) + if is_categorical(target): + target = target.astype(target.dtype.categories.dtype) pself, ptarget = self._maybe_promote(target) if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) @@ -4376,7 +4392,7 @@ def drop(self, labels, errors='raise'): Raises ------ KeyError - If none of the labels are found in the selected axis + If not all of the labels are found in the selected axis """ arr_dtype = 'object' if self.dtype == 'object' else None labels = com._index_labels_to_array(labels, dtype=arr_dtype) @@ -4385,7 +4401,7 @@ def drop(self, labels, errors='raise'): if mask.any(): if errors != 'ignore': raise KeyError( - 'labels %s not contained in axis' % labels[mask]) + '{} not found in axis'.format(labels[mask])) indexer = indexer[~mask] return self.delete(indexer) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 150eca32e229d..587090fa72def 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -598,7 +598,12 @@ def get_indexer_non_unique(self, target): target = ibase._ensure_index(target) if isinstance(target, CategoricalIndex): - target = target.categories + # Indexing on codes is more efficient if categories are the same: + if target.categories is self.categories: + target = target.codes + indexer, missing = self._engine.get_indexer_non_unique(target) + return _ensure_platform_int(indexer), missing + target = target.values codes = self.categories.get_indexer(target) indexer, missing = self._engine.get_indexer_non_unique(codes) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index fbcf06a28c1e5..80bf73cfe7dd3 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -852,14 +852,6 @@ def _has_complex_internals(self): # to disable groupby tricks return True - @cache_readonly - def is_monotonic(self): - """ - return if the index is monotonic increasing (only equal or - increasing) values. - """ - return self.is_monotonic_increasing - @cache_readonly def is_monotonic_increasing(self): """ @@ -887,10 +879,6 @@ def is_monotonic_decreasing(self): # monotonic decreasing if and only if reverse is monotonic increasing return self[::-1].is_monotonic_increasing - @cache_readonly - def is_unique(self): - return not self.duplicated().any() - @cache_readonly def _have_mixed_levels(self): """ return a boolean list indicated if we have mixed levels """ @@ -1719,7 +1707,6 @@ def drop(self, labels, level=None, errors='raise'): if errors != 'ignore': raise ValueError('labels %s not contained in axis' % labels[mask]) - indexer = indexer[~mask] except Exception: pass diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index e550976d1deeb..212f44e55c489 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -52,7 +52,21 @@ def _int64_cut_off(shape): return i return len(shape) - def loop(labels, shape): + def maybe_lift(lab, size): + # promote nan values (assigned -1 label in lab array) + # so that all output values are non-negative + return (lab + 1, size + 1) if (lab == -1).any() else (lab, size) + + labels = map(_ensure_int64, labels) + if not xnull: + labels, shape = map(list, zip(*map(maybe_lift, labels, shape))) + + labels = list(labels) + shape = list(shape) + + # Iteratively process all the labels in chunks sized so less + # than _INT64_MAX unique int ids will be required for each chunk + while True: # how many levels can be done without overflow: nlev = _int64_cut_off(shape) @@ -74,7 +88,7 @@ def loop(labels, shape): out[mask] = -1 if nlev == len(shape): # all levels done! - return out + break # compress what has been done so far in order to avoid overflow # to retain lexical ranks, obs_ids should be sorted @@ -83,16 +97,7 @@ def loop(labels, shape): labels = [comp_ids] + labels[nlev:] shape = [len(obs_ids)] + shape[nlev:] - return loop(labels, shape) - - def maybe_lift(lab, size): # pormote nan values - return (lab + 1, size + 1) if (lab == -1).any() else (lab, size) - - labels = map(_ensure_int64, labels) - if not xnull: - labels, shape = map(list, zip(*map(maybe_lift, labels, shape))) - - return loop(list(labels), list(shape)) + return out def get_compressed_ids(labels, sizes): diff --git a/pandas/io/common.py b/pandas/io/common.py index a492b7c0b8e8e..ac9077f2db50e 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -445,6 +445,10 @@ def __init__(self, file, mode, compression=zipfile.ZIP_DEFLATED, **kwargs): def write(self, data): super(BytesZipFile, self).writestr(self.filename, data) + @property + def closed(self): + return self.fp is None + class MMapWrapper(BaseIterator): """ diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 7f660e2644fa4..60518f596e9af 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -5,11 +5,13 @@ from __future__ import print_function +import warnings + import csv as csvlib +from zipfile import ZipFile import numpy as np from pandas.core.dtypes.missing import notna -from pandas.core.dtypes.inference import is_file_like from pandas.core.index import Index, MultiIndex from pandas import compat from pandas.compat import (StringIO, range, zip) @@ -128,19 +130,31 @@ def save(self): else: encoding = self.encoding - # PR 21300 uses string buffer to receive csv writing and dump into - # file-like output with compression as option. GH 21241, 21118 - f = StringIO() - if not is_file_like(self.path_or_buf): - # path_or_buf is path - path_or_buf = self.path_or_buf - elif hasattr(self.path_or_buf, 'name'): - # path_or_buf is file handle - path_or_buf = self.path_or_buf.name - else: - # path_or_buf is file-like IO objects. + # GH 21227 internal compression is not used when file-like passed. + if self.compression and hasattr(self.path_or_buf, 'write'): + msg = ("compression has no effect when passing file-like " + "object as input.") + warnings.warn(msg, RuntimeWarning, stacklevel=2) + + # when zip compression is called. + is_zip = isinstance(self.path_or_buf, ZipFile) or ( + not hasattr(self.path_or_buf, 'write') + and self.compression == 'zip') + + if is_zip: + # zipfile doesn't support writing string to archive. uses string + # buffer to receive csv writing and dump into zip compression + # file handle. GH 21241, 21118 + f = StringIO() + close = False + elif hasattr(self.path_or_buf, 'write'): f = self.path_or_buf - path_or_buf = None + close = False + else: + f, handles = _get_handle(self.path_or_buf, self.mode, + encoding=encoding, + compression=self.compression) + close = True try: writer_kwargs = dict(lineterminator=self.line_terminator, @@ -157,13 +171,18 @@ def save(self): self._save() finally: - # GH 17778 handles zip compression for byte strings separately. - buf = f.getvalue() - if path_or_buf: - f, handles = _get_handle(path_or_buf, self.mode, - encoding=encoding, - compression=self.compression) - f.write(buf) + if is_zip: + # GH 17778 handles zip compression separately. + buf = f.getvalue() + if hasattr(self.path_or_buf, 'write'): + self.path_or_buf.write(buf) + else: + f, handles = _get_handle(self.path_or_buf, self.mode, + encoding=encoding, + compression=self.compression) + f.write(buf) + close = True + if close: f.close() for _fh in handles: _fh.close() diff --git a/pandas/io/json/normalize.py b/pandas/io/json/normalize.py index b845a43b9ca9e..2004a24c2ec5a 100644 --- a/pandas/io/json/normalize.py +++ b/pandas/io/json/normalize.py @@ -170,6 +170,11 @@ def json_normalize(data, record_path=None, meta=None, 3 Summit 1234 John Kasich Ohio OH 4 Cuyahoga 1337 John Kasich Ohio OH + >>> data = {'A': [1, 2]} + >>> json_normalize(data, 'A', record_prefix='Prefix.') + Prefix.0 + 0 1 + 1 2 """ def _pull_field(js, spec): result = js @@ -259,7 +264,8 @@ def _recursive_extract(data, path, seen_meta, level=0): result = DataFrame(records) if record_prefix is not None: - result.rename(columns=lambda x: record_prefix + x, inplace=True) + result = result.rename( + columns=lambda x: "{p}{c}".format(p=record_prefix, c=x)) # Data types, a problem for k, v in compat.iteritems(meta_vals): diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 2c8f98732c92f..65df2bffb4abf 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -3209,12 +3209,22 @@ def _get_empty_meta(columns, index_col, index_names, dtype=None): col = columns[k] if is_integer(k) else k dtype[col] = v - if index_col is None or index_col is False: + # Even though we have no data, the "index" of the empty DataFrame + # could for example still be an empty MultiIndex. Thus, we need to + # check whether we have any index columns specified, via either: + # + # 1) index_col (column indices) + # 2) index_names (column names) + # + # Both must be non-null to ensure a successful construction. Otherwise, + # we have to create a generic emtpy Index. + if (index_col is None or index_col is False) or index_names is None: index = Index([]) else: data = [Series([], dtype=dtype[name]) for name in index_names] index = _ensure_index_from_sequences(data, names=index_names) index_col.sort() + for i, n in enumerate(index_col): columns.pop(n - i) diff --git a/pandas/tests/categorical/test_indexing.py b/pandas/tests/categorical/test_indexing.py index 9c27b1101e5ca..cf7b5cfa55882 100644 --- a/pandas/tests/categorical/test_indexing.py +++ b/pandas/tests/categorical/test_indexing.py @@ -5,7 +5,7 @@ import numpy as np import pandas.util.testing as tm -from pandas import Categorical, Index, PeriodIndex +from pandas import Categorical, Index, CategoricalIndex, PeriodIndex from pandas.tests.categorical.common import TestCategorical @@ -103,3 +103,21 @@ def f(): s.categories = [1, 2] pytest.raises(ValueError, f) + + # Combinations of sorted/unique: + @pytest.mark.parametrize("idx_values", [[1, 2, 3, 4], [1, 3, 2, 4], + [1, 3, 3, 4], [1, 2, 2, 4]]) + # Combinations of missing/unique + @pytest.mark.parametrize("key_values", [[1, 2], [1, 5], [1, 1], [5, 5]]) + @pytest.mark.parametrize("key_class", [Categorical, CategoricalIndex]) + def test_get_indexer_non_unique(self, idx_values, key_values, key_class): + # GH 21448 + key = key_class(key_values, categories=range(1, 5)) + # Test for flat index and CategoricalIndex with same/different cats: + for dtype in None, 'category', key.dtype: + idx = Index(idx_values, dtype=dtype) + expected, exp_miss = idx.get_indexer_non_unique(key_values) + result, res_miss = idx.get_indexer_non_unique(key) + + tm.assert_numpy_array_equal(expected, result) + tm.assert_numpy_array_equal(exp_miss, res_miss) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index d1a4a5f615b86..4197339ff6e03 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -12,7 +12,7 @@ from numpy.random import randn import numpy as np -from pandas.compat import lrange, product, PY35 +from pandas.compat import lrange, PY35 from pandas import (compat, isna, notna, DataFrame, Series, MultiIndex, date_range, Timestamp, Categorical, _np_version_under1p12, _np_version_under1p15) @@ -1507,6 +1507,23 @@ def test_duplicated_with_misspelled_column_name(self, subset): with pytest.raises(KeyError): df.drop_duplicates(subset) + @pytest.mark.slow + def test_duplicated_do_not_fail_on_wide_dataframes(self): + # gh-21524 + # Given the wide dataframe with a lot of columns + # with different (important!) values + data = {'col_{0:02d}'.format(i): np.random.randint(0, 1000, 30000) + for i in range(100)} + df = pd.DataFrame(data).T + result = df.duplicated() + + # Then duplicates produce the bool pd.Series as a result + # and don't fail during calculation. + # Actual values doesn't matter here, though usually + # it's all False in this case + assert isinstance(result, pd.Series) + assert result.dtype == np.bool + def test_drop_duplicates_with_duplicate_column_names(self): # GH17836 df = DataFrame([ @@ -2240,54 +2257,49 @@ class TestNLargestNSmallest(object): # ---------------------------------------------------------------------- # Top / bottom - @pytest.mark.parametrize( - 'method, n, order', - product(['nsmallest', 'nlargest'], range(1, 11), - [['a'], - ['c'], - ['a', 'b'], - ['a', 'c'], - ['b', 'a'], - ['b', 'c'], - ['a', 'b', 'c'], - ['c', 'a', 'b'], - ['c', 'b', 'a'], - ['b', 'c', 'a'], - ['b', 'a', 'c'], - - # dups! - ['b', 'c', 'c'], - - ])) - def test_n(self, df_strings, method, n, order): + @pytest.mark.parametrize('order', [ + ['a'], + ['c'], + ['a', 'b'], + ['a', 'c'], + ['b', 'a'], + ['b', 'c'], + ['a', 'b', 'c'], + ['c', 'a', 'b'], + ['c', 'b', 'a'], + ['b', 'c', 'a'], + ['b', 'a', 'c'], + + # dups! + ['b', 'c', 'c']]) + @pytest.mark.parametrize('n', range(1, 11)) + def test_n(self, df_strings, nselect_method, n, order): # GH10393 df = df_strings if 'b' in order: error_msg = self.dtype_error_msg_template.format( - column='b', method=method, dtype='object') + column='b', method=nselect_method, dtype='object') with tm.assert_raises_regex(TypeError, error_msg): - getattr(df, method)(n, order) + getattr(df, nselect_method)(n, order) else: - ascending = method == 'nsmallest' - result = getattr(df, method)(n, order) + ascending = nselect_method == 'nsmallest' + result = getattr(df, nselect_method)(n, order) expected = df.sort_values(order, ascending=ascending).head(n) tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize( - 'method, columns', - product(['nsmallest', 'nlargest'], - product(['group'], ['category_string', 'string']) - )) - def test_n_error(self, df_main_dtypes, method, columns): + @pytest.mark.parametrize('columns', [ + ('group', 'category_string'), ('group', 'string')]) + def test_n_error(self, df_main_dtypes, nselect_method, columns): df = df_main_dtypes + col = columns[1] error_msg = self.dtype_error_msg_template.format( - column=columns[1], method=method, dtype=df[columns[1]].dtype) + column=col, method=nselect_method, dtype=df[col].dtype) # escape some characters that may be in the repr error_msg = (error_msg.replace('(', '\\(').replace(")", "\\)") .replace("[", "\\[").replace("]", "\\]")) with tm.assert_raises_regex(TypeError, error_msg): - getattr(df, method)(2, columns) + getattr(df, nselect_method)(2, columns) def test_n_all_dtypes(self, df_main_dtypes): df = df_main_dtypes @@ -2308,15 +2320,14 @@ def test_n_identical_values(self): expected = pd.DataFrame({'a': [1] * 3, 'b': [1, 2, 3]}) tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize( - 'n, order', - product([1, 2, 3, 4, 5], - [['a', 'b', 'c'], - ['c', 'b', 'a'], - ['a'], - ['b'], - ['a', 'b'], - ['c', 'b']])) + @pytest.mark.parametrize('order', [ + ['a', 'b', 'c'], + ['c', 'b', 'a'], + ['a'], + ['b'], + ['a', 'b'], + ['c', 'b']]) + @pytest.mark.parametrize('n', range(1, 6)) def test_n_duplicate_index(self, df_duplicates, n, order): # GH 13412 diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 28e82f7585850..0e0d6598f5101 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -1151,3 +1151,18 @@ def test_raise_on_drop_duplicate_index(self, actual): expected_no_err = actual.T.drop('c', axis=1, level=level, errors='ignore') assert_frame_equal(expected_no_err.T, actual) + + @pytest.mark.parametrize('index', [[1, 2, 3], [1, 1, 2]]) + @pytest.mark.parametrize('drop_labels', [[], [1], [2]]) + def test_drop_empty_list(self, index, drop_labels): + # GH 21494 + expected_index = [i for i in index if i not in drop_labels] + frame = pd.DataFrame(index=index).drop(drop_labels) + tm.assert_frame_equal(frame, pd.DataFrame(index=expected_index)) + + @pytest.mark.parametrize('index', [[1, 2, 3], [1, 2, 2]]) + @pytest.mark.parametrize('drop_labels', [[1, 4], [4, 5]]) + def test_drop_non_empty_list(self, index, drop_labels): + # GH 21494 + with tm.assert_raises_regex(KeyError, 'not found in axis'): + pd.DataFrame(index=index).drop(drop_labels) diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 90fbc6e628369..fb9bd74d9876d 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -506,7 +506,15 @@ def test_asfreq_fillvalue(self): actual_series = ts.asfreq(freq='1S', fill_value=9.0) assert_series_equal(expected_series, actual_series) - def test_first_last_valid(self): + @pytest.mark.parametrize("data,idx,expected_first,expected_last", [ + ({'A': [1, 2, 3]}, [1, 1, 2], 1, 2), + ({'A': [1, 2, 3]}, [1, 2, 2], 1, 2), + ({'A': [1, 2, 3, 4]}, ['d', 'd', 'd', 'd'], 'd', 'd'), + ({'A': [1, np.nan, 3]}, [1, 1, 2], 1, 2), + ({'A': [np.nan, np.nan, 3]}, [1, 1, 2], 2, 2), + ({'A': [1, np.nan, 3]}, [1, 2, 2], 1, 2)]) + def test_first_last_valid(self, data, idx, + expected_first, expected_last): N = len(self.frame.index) mat = randn(N) mat[:5] = nan @@ -539,6 +547,11 @@ def test_first_last_valid(self): assert frame.first_valid_index().freq == frame.index.freq assert frame.last_valid_index().freq == frame.index.freq + # GH 21441 + df = DataFrame(data, index=idx) + assert expected_first == df.first_valid_index() + assert expected_last == df.last_valid_index() + def test_first_subset(self): ts = tm.makeTimeDataFrame(freq='12h') result = ts.first('10d') diff --git a/pandas/tests/frame/test_timezones.py b/pandas/tests/frame/test_timezones.py index fa589a0aa4817..3956968173070 100644 --- a/pandas/tests/frame/test_timezones.py +++ b/pandas/tests/frame/test_timezones.py @@ -133,3 +133,13 @@ def test_frame_reset_index(self, tz): xp = df.index.tz rs = roundtripped.index.tz assert xp == rs + + @pytest.mark.parametrize('tz', [None, 'America/New_York']) + def test_boolean_compare_transpose_tzindex_with_dst(self, tz): + # GH 19970 + idx = date_range('20161101', '20161130', freq='4H', tz=tz) + df = DataFrame({'a': range(len(idx)), 'b': range(len(idx))}, + index=idx) + result = df.T == df.T + expected = DataFrame(True, index=list('ab'), columns=idx) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index 60dc336a85388..3ad25ae73109e 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -9,6 +9,7 @@ import numpy as np from pandas.compat import (lmap, range, lrange, StringIO, u) +from pandas.io.common import _get_handle import pandas.core.common as com from pandas.errors import ParserError from pandas import (DataFrame, Index, Series, MultiIndex, Timestamp, @@ -935,18 +936,19 @@ def test_to_csv_compression(self, df, encoding, compression): with ensure_clean() as filename: df.to_csv(filename, compression=compression, encoding=encoding) - # test the round trip - to_csv -> read_csv result = read_csv(filename, compression=compression, index_col=0, encoding=encoding) + assert_frame_equal(df, result) - with open(filename, 'w') as fh: - df.to_csv(fh, compression=compression, encoding=encoding) - - result_fh = read_csv(filename, compression=compression, - index_col=0, encoding=encoding) + # test the round trip using file handle - to_csv -> read_csv + f, _handles = _get_handle(filename, 'w', compression=compression, + encoding=encoding) + with f: + df.to_csv(f, encoding=encoding) + result = pd.read_csv(filename, compression=compression, + encoding=encoding, index_col=0, squeeze=True) assert_frame_equal(df, result) - assert_frame_equal(df, result_fh) # explicitly make sure file is compressed with tm.decompress_file(filename, compression) as fh: diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index dae69a86910af..b138b79caac76 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -469,6 +469,15 @@ def test_constructor_with_non_normalized_pytz(self, tz): result = DatetimeIndex(['2010'], tz=non_norm_tz) assert pytz.timezone(tz) is result.tz + def test_constructor_timestamp_near_dst(self): + # GH 20854 + ts = [Timestamp('2016-10-30 03:00:00+0300', tz='Europe/Helsinki'), + Timestamp('2016-10-30 03:00:00+0200', tz='Europe/Helsinki')] + result = DatetimeIndex(ts) + expected = DatetimeIndex([ts[0].to_pydatetime(), + ts[1].to_pydatetime()]) + tm.assert_index_equal(result, expected) + class TestTimeSeries(object): diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 193804b66395b..ec37bbbcb6c02 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -278,6 +278,20 @@ def test_wom_len(self, periods): res = date_range(start='20110101', periods=periods, freq='WOM-1MON') assert len(res) == periods + def test_construct_over_dst(self): + # GH 20854 + pre_dst = Timestamp('2010-11-07 01:00:00').tz_localize('US/Pacific', + ambiguous=True) + pst_dst = Timestamp('2010-11-07 01:00:00').tz_localize('US/Pacific', + ambiguous=False) + expect_data = [Timestamp('2010-11-07 00:00:00', tz='US/Pacific'), + pre_dst, + pst_dst] + expected = DatetimeIndex(expect_data) + result = date_range(start='2010-11-7', periods=3, + freq='H', tz='US/Pacific') + tm.assert_index_equal(result, expected) + class TestGenRangeGeneration(object): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 1e4dd2921b3f5..a0d6907055a2e 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -419,21 +419,24 @@ def test_constructor_dtypes_timedelta(self, attr, klass): result = klass(list(values), dtype=dtype) tm.assert_index_equal(result, index) - def test_constructor_empty_gen(self): - skip_index_keys = ["repeats", "periodIndex", "rangeIndex", - "tuples"] - for key, index in self.generate_index_types(skip_index_keys): - empty = index.__class__([]) - assert isinstance(empty, index.__class__) - assert not len(empty) + @pytest.mark.parametrize("value", [[], iter([]), (x for x in [])]) + @pytest.mark.parametrize("klass", + [Index, Float64Index, Int64Index, UInt64Index, + CategoricalIndex, DatetimeIndex, TimedeltaIndex]) + def test_constructor_empty(self, value, klass): + empty = klass(value) + assert isinstance(empty, klass) + assert not len(empty) @pytest.mark.parametrize("empty,klass", [ (PeriodIndex([], freq='B'), PeriodIndex), + (PeriodIndex(iter([]), freq='B'), PeriodIndex), + (PeriodIndex((x for x in []), freq='B'), PeriodIndex), (RangeIndex(step=1), pd.RangeIndex), (MultiIndex(levels=[[1, 2], ['blue', 'red']], labels=[[], []]), MultiIndex) ]) - def test_constructor_empty(self, empty, klass): + def test_constructor_empty_special(self, empty, klass): assert isinstance(empty, klass) assert not len(empty) @@ -455,6 +458,13 @@ def test_constructor_nonhashable_name(self, indices): tm.assert_raises_regex(TypeError, message, indices.set_names, names=renamed) + def test_constructor_overflow_int64(self): + # see gh-15832 + msg = ("the elements provided in the data cannot " + "all be casted to the dtype int64") + with tm.assert_raises_regex(OverflowError, msg): + Index([np.iinfo(np.uint64).max - 1], dtype="int64") + def test_view_with_args(self): restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex', diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 182dbdf2cf4e4..df506ae9486ee 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -3295,3 +3295,20 @@ def test_duplicate_multiindex_labels(self): with pytest.raises(ValueError): ind.set_levels([['A', 'B', 'A', 'A', 'B'], [2, 1, 3, -2, 5]], inplace=True) + + def test_multiindex_compare(self): + # GH 21149 + # Ensure comparison operations for MultiIndex with nlevels == 1 + # behave consistently with those for MultiIndex with nlevels > 1 + + midx = pd.MultiIndex.from_product([[0, 1]]) + + # Equality self-test: MultiIndex object vs self + expected = pd.Series([True, True]) + result = pd.Series(midx == midx) + tm.assert_series_equal(result, expected) + + # Greater than comparison: MultiIndex object vs self + expected = pd.Series([False, False]) + result = pd.Series(midx > midx) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index dfa3751bff57a..36c4ae547ad4e 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -285,3 +285,18 @@ def test_to_csv_string_array_utf8(self): df.to_csv(path, encoding='utf-8') with open(path, 'r') as f: assert f.read() == expected_utf8 + + @tm.capture_stdout + def test_to_csv_stdout_file(self): + # GH 21561 + df = pd.DataFrame([['foo', 'bar'], ['baz', 'qux']], + columns=['name_1', 'name_2']) + expected_ascii = '''\ +,name_1,name_2 +0,foo,bar +1,baz,qux +''' + df.to_csv(sys.stdout, encoding='ascii') + output = sys.stdout.getvalue() + assert output == expected_ascii + assert not sys.stdout.closed diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 395c2c90767d3..200a853c48900 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -123,6 +123,12 @@ def test_simple_normalize_with_separator(self, deep_nested): 'country', 'states_name']).sort_values() assert result.columns.sort_values().equals(expected) + def test_value_array_record_prefix(self): + # GH 21536 + result = json_normalize({'A': [1, 2]}, 'A', record_prefix='Prefix.') + expected = DataFrame([[1], [2]], columns=['Prefix.0']) + tm.assert_frame_equal(result, expected) + def test_more_deeply_nested(self, deep_nested): result = json_normalize(deep_nested, ['states', 'cities'], diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index 2b7ff1f5a9879..b39122e5e7906 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -238,6 +238,21 @@ def test_csv_mixed_type(self): out = self.read_csv(StringIO(data)) tm.assert_frame_equal(out, expected) + def test_read_csv_low_memory_no_rows_with_index(self): + if self.engine == "c" and not self.low_memory: + pytest.skip("This is a low-memory specific test") + + # see gh-21141 + data = """A,B,C +1,1,1,2 +2,2,3,4 +3,3,4,5 +""" + out = self.read_csv(StringIO(data), low_memory=True, + index_col=0, nrows=0) + expected = DataFrame(columns=["A", "B", "C"]) + tm.assert_frame_equal(out, expected) + def test_read_csv_dataframe(self): df = self.read_csv(self.csv1, index_col=0, parse_dates=True) df2 = self.read_table(self.csv1, sep=',', index_col=0, diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py index 47cded19f5300..bb976a1e3e81c 100644 --- a/pandas/tests/plotting/test_converter.py +++ b/pandas/tests/plotting/test_converter.py @@ -1,4 +1,5 @@ import subprocess +import sys import pytest from datetime import datetime, date @@ -27,7 +28,7 @@ def test_register_by_default(self): "import pandas as pd; " "units = dict(matplotlib.units.registry); " "assert pd.Timestamp in units)'") - call = ['python', '-c', code] + call = [sys.executable, '-c', code] assert subprocess.check_call(call) == 0 def test_warns(self): diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 205fdf49d3e91..6472bd4245622 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -588,3 +588,17 @@ def test_components(self): result = s.dt.components assert not result.iloc[0].isna().all() assert result.iloc[1].isna().all() + + +@pytest.mark.parametrize('value, expected', [ + (Timedelta('10S'), True), + (Timedelta('-10S'), True), + (Timedelta(10, unit='ns'), True), + (Timedelta(0, unit='ns'), False), + (Timedelta(-10, unit='ns'), True), + (Timedelta(None), True), + (pd.NaT, True), +]) +def test_truthiness(value, expected): + # https://github.com/pandas-dev/pandas/issues/21484 + assert bool(value) is expected diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index ab87d98fca8eb..4689c7bea626f 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -528,6 +528,14 @@ def test_disallow_setting_tz(self, tz): with pytest.raises(AttributeError): ts.tz = tz + @pytest.mark.parametrize('offset', ['+0300', '+0200']) + def test_construct_timestamp_near_dst(self, offset): + # GH 20854 + expected = Timestamp('2016-10-30 03:00:00{}'.format(offset), + tz='Europe/Helsinki') + result = Timestamp(expected, tz='Europe/Helsinki') + assert result == expected + class TestTimestamp(object): diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py index 999ed5f26daee..2fdf198596ce2 100644 --- a/pandas/tests/series/indexing/test_alter_index.py +++ b/pandas/tests/series/indexing/test_alter_index.py @@ -463,54 +463,86 @@ def test_rename(): assert result.name == expected.name -def test_drop(): - # unique - s = Series([1, 2], index=['one', 'two']) - expected = Series([1], index=['one']) - result = s.drop(['two']) - assert_series_equal(result, expected) - result = s.drop('two', axis='rows') - assert_series_equal(result, expected) - - # non-unique - # GH 5248 - s = Series([1, 1, 2], index=['one', 'two', 'one']) - expected = Series([1, 2], index=['one', 'one']) - result = s.drop(['two'], axis=0) - assert_series_equal(result, expected) - result = s.drop('two') - assert_series_equal(result, expected) - - expected = Series([1], index=['two']) - result = s.drop(['one']) - assert_series_equal(result, expected) - result = s.drop('one') - assert_series_equal(result, expected) +@pytest.mark.parametrize( + 'data, index, drop_labels,' + ' axis, expected_data, expected_index', + [ + # Unique Index + ([1, 2], ['one', 'two'], ['two'], + 0, [1], ['one']), + ([1, 2], ['one', 'two'], ['two'], + 'rows', [1], ['one']), + ([1, 1, 2], ['one', 'two', 'one'], ['two'], + 0, [1, 2], ['one', 'one']), + + # GH 5248 Non-Unique Index + ([1, 1, 2], ['one', 'two', 'one'], 'two', + 0, [1, 2], ['one', 'one']), + ([1, 1, 2], ['one', 'two', 'one'], ['one'], + 0, [1], ['two']), + ([1, 1, 2], ['one', 'two', 'one'], 'one', + 0, [1], ['two'])]) +def test_drop_unique_and_non_unique_index(data, index, axis, drop_labels, + expected_data, expected_index): + + s = Series(data=data, index=index) + result = s.drop(drop_labels, axis=axis) + expected = Series(data=expected_data, index=expected_index) + tm.assert_series_equal(result, expected) - # single string/tuple-like - s = Series(range(3), index=list('abc')) - pytest.raises(KeyError, s.drop, 'bc') - pytest.raises(KeyError, s.drop, ('a',)) +@pytest.mark.parametrize( + 'data, index, drop_labels,' + ' axis, error_type, error_desc', + [ + # single string/tuple-like + (range(3), list('abc'), 'bc', + 0, KeyError, 'not found in axis'), + + # bad axis + (range(3), list('abc'), ('a',), + 0, KeyError, 'not found in axis'), + (range(3), list('abc'), 'one', + 'columns', ValueError, 'No axis named columns')]) +def test_drop_exception_raised(data, index, drop_labels, + axis, error_type, error_desc): + + with tm.assert_raises_regex(error_type, error_desc): + Series(data, index=index).drop(drop_labels, axis=axis) + + +def test_drop_with_ignore_errors(): # errors='ignore' s = Series(range(3), index=list('abc')) result = s.drop('bc', errors='ignore') - assert_series_equal(result, s) + tm.assert_series_equal(result, s) result = s.drop(['a', 'd'], errors='ignore') expected = s.iloc[1:] - assert_series_equal(result, expected) - - # bad axis - pytest.raises(ValueError, s.drop, 'one', axis='columns') + tm.assert_series_equal(result, expected) # GH 8522 s = Series([2, 3], index=[True, False]) assert s.index.is_object() result = s.drop(True) expected = Series([3], index=[False]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) + - # GH 16877 - s = Series([2, 3], index=[0, 1]) - with tm.assert_raises_regex(KeyError, 'not contained in axis'): - s.drop([False, True]) +@pytest.mark.parametrize('index', [[1, 2, 3], [1, 1, 3]]) +@pytest.mark.parametrize('drop_labels', [[], [1], [3]]) +def test_drop_empty_list(index, drop_labels): + # GH 21494 + expected_index = [i for i in index if i not in drop_labels] + series = pd.Series(index=index).drop(drop_labels) + tm.assert_series_equal(series, pd.Series(index=expected_index)) + + +@pytest.mark.parametrize('data, index, drop_labels', [ + (None, [1, 2, 3], [1, 4]), + (None, [1, 2, 2], [1, 4]), + ([2, 3], [0, 1], [False, True]) +]) +def test_drop_non_empty_list(data, index, drop_labels): + # GH 21494 and GH 16877 + with tm.assert_raises_regex(KeyError, 'not found in axis'): + pd.Series(data=data, index=index).drop(drop_labels) diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 6ea40329f4bc3..1e6ea96a5de51 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -1866,6 +1866,15 @@ def s_main_dtypes(): return df +def assert_check_nselect_boundary(vals, dtype, method): + # helper function for 'test_boundary_{dtype}' tests + s = Series(vals, dtype=dtype) + result = getattr(s, method)(3) + expected_idxr = [0, 1, 2] if method == 'nsmallest' else [3, 2, 1] + expected = s.loc[expected_idxr] + tm.assert_series_equal(result, expected) + + class TestNLargestNSmallest(object): @pytest.mark.parametrize( @@ -1950,6 +1959,32 @@ def test_n(self, n): expected = s.sort_values().head(n) assert_series_equal(result, expected) + def test_boundary_integer(self, nselect_method, any_int_dtype): + # GH 21426 + dtype_info = np.iinfo(any_int_dtype) + min_val, max_val = dtype_info.min, dtype_info.max + vals = [min_val, min_val + 1, max_val - 1, max_val] + assert_check_nselect_boundary(vals, any_int_dtype, nselect_method) + + def test_boundary_float(self, nselect_method, float_dtype): + # GH 21426 + dtype_info = np.finfo(float_dtype) + min_val, max_val = dtype_info.min, dtype_info.max + min_2nd, max_2nd = np.nextafter( + [min_val, max_val], 0, dtype=float_dtype) + vals = [min_val, min_2nd, max_2nd, max_val] + assert_check_nselect_boundary(vals, float_dtype, nselect_method) + + @pytest.mark.parametrize('dtype', ['datetime64[ns]', 'timedelta64[ns]']) + def test_boundary_datetimelike(self, nselect_method, dtype): + # GH 21426 + # use int64 bounds and +1 to min_val since true minimum is NaT + # (include min_val/NaT at end to maintain same expected_idxr) + dtype_info = np.iinfo('int64') + min_val, max_val = dtype_info.min, dtype_info.max + vals = [min_val + 1, min_val + 2, max_val - 1, max_val, min_val] + assert_check_nselect_boundary(vals, dtype, nselect_method) + class TestCategoricalSeriesAnalytics(object): diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py index 76dd4bc1f3d4a..90f37053ce17e 100644 --- a/pandas/tests/series/test_io.py +++ b/pandas/tests/series/test_io.py @@ -11,6 +11,7 @@ from pandas import Series, DataFrame from pandas.compat import StringIO, u +from pandas.io.common import _get_handle from pandas.util.testing import (assert_series_equal, assert_almost_equal, assert_frame_equal, ensure_clean) import pandas.util.testing as tm @@ -152,20 +153,19 @@ def test_to_csv_compression(self, s, encoding, compression): s.to_csv(filename, compression=compression, encoding=encoding, header=True) - # test the round trip - to_csv -> read_csv result = pd.read_csv(filename, compression=compression, encoding=encoding, index_col=0, squeeze=True) + assert_series_equal(s, result) - with open(filename, 'w') as fh: - s.to_csv(fh, compression=compression, encoding=encoding, - header=True) - - result_fh = pd.read_csv(filename, compression=compression, - encoding=encoding, index_col=0, - squeeze=True) + # test the round trip using file handle - to_csv -> read_csv + f, _handles = _get_handle(filename, 'w', compression=compression, + encoding=encoding) + with f: + s.to_csv(f, encoding=encoding, header=True) + result = pd.read_csv(filename, compression=compression, + encoding=encoding, index_col=0, squeeze=True) assert_series_equal(s, result) - assert_series_equal(s, result_fh) # explicitly ensure file was compressed with tm.decompress_file(filename, compression) as fh: diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index 97236f028b1c4..730c2b7865f1f 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -11,6 +11,7 @@ from pandas import (Index, Series, DataFrame, date_range, option_context, Categorical, period_range, timedelta_range) from pandas.core.index import MultiIndex +from pandas.core.base import StringMixin from pandas.compat import lrange, range, u from pandas import compat @@ -202,6 +203,35 @@ def test_latex_repr(self): class TestCategoricalRepr(object): + def test_categorical_repr_unicode(self): + # GH#21002 if len(index) > 60, sys.getdefaultencoding()=='ascii', + # and we are working in PY2, then rendering a Categorical could raise + # UnicodeDecodeError by trying to decode when it shouldn't + + class County(StringMixin): + name = u'San Sebastián' + state = u'PR' + + def __unicode__(self): + return self.name + u', ' + self.state + + cat = pd.Categorical([County() for n in range(61)]) + idx = pd.Index(cat) + ser = idx.to_series() + + if compat.PY3: + # no reloading of sys, just check that the default (utf8) works + # as expected + repr(ser) + str(ser) + + else: + # set sys.defaultencoding to ascii, then change it back after + # the test + with tm.set_defaultencoding('ascii'): + repr(ser) + str(ser) + def test_categorical_repr(self): a = Series(Categorical([1, 2, 3, 4])) exp = u("0 1\n1 2\n2 3\n3 4\n" + diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 3443331e3d4ba..576239e49455e 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -11,6 +11,7 @@ from pandas.compat import range, lmap import pandas.core.common as com from pandas.core import ops +from pandas.io.common import _get_handle import pandas.util.testing as tm @@ -248,19 +249,34 @@ def test_compression_size(obj, method, compression): [12.32112, 123123.2, 321321.2]], columns=['X', 'Y', 'Z']), Series(100 * [0.123456, 0.234567, 0.567567], name='X')]) -@pytest.mark.parametrize('method', ['to_csv']) +@pytest.mark.parametrize('method', ['to_csv', 'to_json']) def test_compression_size_fh(obj, method, compression_only): with tm.ensure_clean() as filename: - with open(filename, 'w') as fh: - getattr(obj, method)(fh, compression=compression_only) - assert not fh.closed - assert fh.closed + f, _handles = _get_handle(filename, 'w', compression=compression_only) + with f: + getattr(obj, method)(f) + assert not f.closed + assert f.closed compressed = os.path.getsize(filename) with tm.ensure_clean() as filename: - with open(filename, 'w') as fh: - getattr(obj, method)(fh, compression=None) - assert not fh.closed - assert fh.closed + f, _handles = _get_handle(filename, 'w', compression=None) + with f: + getattr(obj, method)(f) + assert not f.closed + assert f.closed uncompressed = os.path.getsize(filename) assert uncompressed > compressed + + +# GH 21227 +def test_compression_warning(compression_only): + df = DataFrame(100 * [[0.123456, 0.234567, 0.567567], + [12.32112, 123123.2, 321321.2]], + columns=['X', 'Y', 'Z']) + with tm.ensure_clean() as filename: + f, _handles = _get_handle(filename, 'w', compression=compression_only) + with tm.assert_produces_warning(RuntimeWarning, + check_stacklevel=False): + with f: + df.to_csv(f, compression=compression_only) diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index afd7993fefc70..cf98cff97669a 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -3,6 +3,7 @@ Testing that we work in the downstream packages """ import subprocess +import sys import pytest import numpy as np # noqa @@ -57,7 +58,7 @@ def test_xarray(df): def test_oo_optimizable(): # GH 21071 - subprocess.check_call(["python", "-OO", "-c", "import pandas"]) + subprocess.check_call([sys.executable, "-OO", "-c", "import pandas"]) @tm.network diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 233eba6490937..6384eca9849f6 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -553,6 +553,28 @@ def _valid_locales(locales, normalize): # Stdout / stderr decorators +@contextmanager +def set_defaultencoding(encoding): + """ + Set default encoding (as given by sys.getdefaultencoding()) to the given + encoding; restore on exit. + + Parameters + ---------- + encoding : str + """ + if not PY2: + raise ValueError("set_defaultencoding context is only available " + "in Python 2.") + orig = sys.getdefaultencoding() + reload(sys) # noqa:F821 + sys.setdefaultencoding(encoding) + try: + yield + finally: + sys.setdefaultencoding(orig) + + def capture_stdout(f): """ Decorator to capture stdout in a buffer so that it can be checked
https://api.github.com/repos/pandas-dev/pandas/pulls/21683
2018-06-29T15:08:23Z
2018-07-02T13:59:05Z
2018-07-02T13:59:05Z
2018-07-02T13:59:54Z
Allow merging on object / non-object column
diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index b4331aab3085f..e8ede92c32374 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -426,6 +426,7 @@ Backwards incompatible API changes - :func:`read_csv` will now raise a ``ValueError`` if a column with missing values is declared as having dtype ``bool`` (:issue:`20591`) - The column order of the resultant :class:`DataFrame` from :meth:`MultiIndex.to_frame` is now guaranteed to match the :attr:`MultiIndex.names` order. (:issue:`22420`) - :func:`pd.offsets.generate_range` argument ``time_rule`` has been removed; use ``offset`` instead (:issue:`24157`) +- In 0.23.x, pandas would raise a ``ValueError`` on a merge of a numeric column (e.g. ``int`` dtyped column) and an ``object`` dtyped column (:issue:`9780`). We have re-enabled the ability to merge ``object`` and other dtypes (:issue:`21681`) Percentage change on groupby ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 58344c0ec9ec7..130bc2b080c72 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -20,7 +20,7 @@ is_datetime64tz_dtype, is_datetimelike, is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_int64_dtype, is_integer, is_integer_dtype, is_list_like, is_number, is_numeric_dtype, - needs_i8_conversion) + is_object_dtype, needs_i8_conversion) from pandas.core.dtypes.missing import isnull, na_value_for_dtype from pandas import Categorical, DataFrame, Index, MultiIndex, Series, Timedelta @@ -901,6 +901,8 @@ def _maybe_coerce_merge_keys(self): lk_is_cat = is_categorical_dtype(lk) rk_is_cat = is_categorical_dtype(rk) + lk_is_object = is_object_dtype(lk) + rk_is_object = is_object_dtype(rk) # if either left or right is a categorical # then the must match exactly in categories & ordered @@ -925,7 +927,7 @@ def _maybe_coerce_merge_keys(self): # the same, then proceed if is_numeric_dtype(lk) and is_numeric_dtype(rk): if lk.dtype.kind == rk.dtype.kind: - pass + continue # check whether ints and floats elif is_integer_dtype(rk) and is_float_dtype(lk): @@ -934,6 +936,7 @@ def _maybe_coerce_merge_keys(self): 'columns where the float values ' 'are not equal to their int ' 'representation', UserWarning) + continue elif is_float_dtype(rk) and is_integer_dtype(lk): if not (rk == rk.astype(lk.dtype))[~np.isnan(rk)].all(): @@ -941,22 +944,41 @@ def _maybe_coerce_merge_keys(self): 'columns where the float values ' 'are not equal to their int ' 'representation', UserWarning) + continue # let's infer and see if we are ok elif lib.infer_dtype(lk) == lib.infer_dtype(rk): - pass + continue # Check if we are trying to merge on obviously # incompatible dtypes GH 9780, GH 15800 - # boolean values are considered as numeric, but are still allowed - # to be merged on object boolean values - elif ((is_numeric_dtype(lk) and not is_bool_dtype(lk)) - and not is_numeric_dtype(rk)): - raise ValueError(msg) - elif (not is_numeric_dtype(lk) - and (is_numeric_dtype(rk) and not is_bool_dtype(rk))): - raise ValueError(msg) + # bool values are coerced to object + elif ((lk_is_object and is_bool_dtype(rk)) or + (is_bool_dtype(lk) and rk_is_object)): + pass + + # object values are allowed to be merged + elif ((lk_is_object and is_numeric_dtype(rk)) or + (is_numeric_dtype(lk) and rk_is_object)): + inferred_left = lib.infer_dtype(lk) + inferred_right = lib.infer_dtype(rk) + bool_types = ['integer', 'mixed-integer', 'boolean', 'empty'] + string_types = ['string', 'unicode', 'mixed', 'bytes', 'empty'] + + # inferred bool + if (inferred_left in bool_types and + inferred_right in bool_types): + pass + + # unless we are merging non-string-like with string-like + elif ((inferred_left in string_types and + inferred_right not in string_types) or + (inferred_right in string_types and + inferred_left not in string_types)): + raise ValueError(msg) + + # datetimelikes must match exactly elif is_datetimelike(lk) and not is_datetimelike(rk): raise ValueError(msg) elif not is_datetimelike(lk) and is_datetimelike(rk): @@ -966,6 +988,9 @@ def _maybe_coerce_merge_keys(self): elif not is_datetime64tz_dtype(lk) and is_datetime64tz_dtype(rk): raise ValueError(msg) + elif lk_is_object and rk_is_object: + continue + # Houston, we have a problem! # let's coerce to object if the dtypes aren't # categorical, otherwise coerce to the category @@ -973,15 +998,14 @@ def _maybe_coerce_merge_keys(self): # then we would lose type information on some # columns, and end up trying to merge # incompatible dtypes. See GH 16900. - else: - if name in self.left.columns: - typ = lk.categories.dtype if lk_is_cat else object - self.left = self.left.assign( - **{name: self.left[name].astype(typ)}) - if name in self.right.columns: - typ = rk.categories.dtype if rk_is_cat else object - self.right = self.right.assign( - **{name: self.right[name].astype(typ)}) + if name in self.left.columns: + typ = lk.categories.dtype if lk_is_cat else object + self.left = self.left.assign( + **{name: self.left[name].astype(typ)}) + if name in self.right.columns: + typ = rk.categories.dtype if rk_is_cat else object + self.right = self.right.assign( + **{name: self.right[name].astype(typ)}) def _validate_specification(self): # Hm, any way to make this logic less complicated?? diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 970802e94662a..7839d93f5af88 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -924,10 +924,6 @@ class TestMergeDtypes(object): @pytest.mark.parametrize('right_vals', [ ['foo', 'bar'], Series(['foo', 'bar']).astype('category'), - [1, 2], - [1.0, 2.0], - Series([1, 2], dtype='uint64'), - Series([1, 2], dtype='int32') ]) def test_different(self, right_vals): @@ -942,22 +938,8 @@ def test_different(self, right_vals): # GH 9780 # We allow merging on object and categorical cols and cast # categorical cols to object - if (is_categorical_dtype(right['A'].dtype) or - is_object_dtype(right['A'].dtype)): - result = pd.merge(left, right, on='A') - assert is_object_dtype(result.A.dtype) - - # GH 9780 - # We raise for merging on object col and int/float col and - # merging on categorical col and int/float col - else: - msg = ("You are trying to merge on " - "{lk_dtype} and {rk_dtype} columns. " - "If you wish to proceed you should use " - "pd.concat".format(lk_dtype=left['A'].dtype, - rk_dtype=right['A'].dtype)) - with pytest.raises(ValueError, match=msg): - pd.merge(left, right, on='A') + result = pd.merge(left, right, on='A') + assert is_object_dtype(result.A.dtype) @pytest.mark.parametrize('d1', [np.int64, np.int32, np.int16, np.int8, np.uint8]) @@ -1056,6 +1038,33 @@ def test_merge_incompat_infer_boolean_object(self): assert_frame_equal(result, expected) @pytest.mark.parametrize('df1_vals, df2_vals', [ + + # merge on category coerces to object + ([0, 1, 2], Series(['a', 'b', 'a']).astype('category')), + ([0.0, 1.0, 2.0], Series(['a', 'b', 'a']).astype('category')), + + # no not infer + ([0, 1], pd.Series([False, True], dtype=object)), + ([0, 1], pd.Series([False, True], dtype=bool)), + ]) + def test_merge_incompat_dtypes_are_ok(self, df1_vals, df2_vals): + # these are explicity allowed incompat merges, that pass thru + # the result type is dependent on if the values on the rhs are + # inferred, otherwise these will be coereced to object + + df1 = DataFrame({'A': df1_vals}) + df2 = DataFrame({'A': df2_vals}) + + result = pd.merge(df1, df2, on=['A']) + assert is_object_dtype(result.A.dtype) + result = pd.merge(df2, df1, on=['A']) + assert is_object_dtype(result.A.dtype) + + @pytest.mark.parametrize('df1_vals, df2_vals', [ + # do not infer to numeric + + (Series([1, 2], dtype='uint64'), ["a", "b", "c"]), + (Series([1, 2], dtype='int32'), ["a", "b", "c"]), ([0, 1, 2], ["0", "1", "2"]), ([0.0, 1.0, 2.0], ["0", "1", "2"]), ([0, 1, 2], [u"0", u"1", u"2"]), @@ -1065,12 +1074,8 @@ def test_merge_incompat_infer_boolean_object(self): (pd.date_range('1/1/2011', periods=2, freq='D'), [0.0, 1.0]), (pd.date_range('20130101', periods=3), pd.date_range('20130101', periods=3, tz='US/Eastern')), - ([0, 1, 2], Series(['a', 'b', 'a']).astype('category')), - ([0.0, 1.0, 2.0], Series(['a', 'b', 'a']).astype('category')), - # TODO ([0, 1], pd.Series([False, True], dtype=bool)), - ([0, 1], pd.Series([False, True], dtype=object)) ]) - def test_merge_incompat_dtypes(self, df1_vals, df2_vals): + def test_merge_incompat_dtypes_error(self, df1_vals, df2_vals): # GH 9780, GH 15800 # Raise a ValueError when a user tries to merge on # dtypes that are incompatible (e.g., obj and int/float)
Follow-up on discussion in https://github.com/pandas-dev/pandas/pull/21310 (cc @jreback ) What this does: allow `merge` on an object and a non-object column (eg object and int, object and categorical, ..), by coercing the non-object column to object dtype. Reasoning: - object dtype can be anything, so IMO pandas should not try to be smart and think to know the merge is not valid - all other, certainly invalid dtype combinations (eg int and datetime64) keep raising an error The main disadvantage is that we no longer detect the case of merging object strings with eg integer column, but IMO we cannot avoid such cases as long as we don't have a proper string dtype but use object dtype for this (you can also mix string and ints in a column, we also don't raise for that for a similar reason). Additional option would be to issue a warning in this case. Closes https://github.com/pandas-dev/pandas/issues/23733
https://api.github.com/repos/pandas-dev/pandas/pulls/21681
2018-06-29T13:38:42Z
2019-01-03T00:45:04Z
2019-01-03T00:45:04Z
2020-04-23T17:56:57Z
ENH: Adding pd.__git_version__ to point to git sha commit (#21295)
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3b04d9937d7f2..7eb6204387337 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -180,6 +180,8 @@ Other Enhancements - :func:`~DataFrame.to_csv` and :func:`~DataFrame.to_json` now support ``compression='infer'`` to infer compression based on filename (:issue:`15008`) - :func:`to_timedelta` now supports iso-formated timedelta strings (:issue:`21877`) - :class:`Series` and :class:`DataFrame` now support :class:`Iterable` in constructor (:issue:`2193`) +- New attribute :attr:`__git_version__` will return git commit sha of current build +- .. _whatsnew_0240.api_breaking: diff --git a/pandas/__init__.py b/pandas/__init__.py index 97ae73174c09c..05b502f8b281b 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -83,6 +83,7 @@ from ._version import get_versions v = get_versions() __version__ = v.get('closest-tag', v['version']) +__git_version__ = v.get('full-revisionid') del get_versions, v # module level doc-string diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index e1c9202189972..7f41058a8c5d5 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -3,6 +3,7 @@ import pytest import os import collections +import string from functools import partial import numpy as np @@ -12,6 +13,7 @@ from pandas.core import ops from pandas.io.common import _get_handle import pandas.util.testing as tm +import pandas as pd def test_get_callable_name(): @@ -165,3 +167,10 @@ def test_compression_warning(compression_only): check_stacklevel=False): with f: df.to_csv(f, compression=compression_only) + + +def test_git_version(): + # GH 21295 + git_version = pd.__git_version__ + assert len(git_version) == 40 + assert all(c in string.hexdigits for c in git_version)
- [ ] closes #21295 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21680
2018-06-29T13:35:31Z
2018-09-18T19:35:29Z
null
2018-09-18T19:35:29Z
API: referring to duplicate level name raises ValueError
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 812ea366b704a..4bb1e9efffff6 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -229,6 +229,9 @@ Other API Changes ^^^^^^^^^^^^^^^^^ - :class:`DatetimeIndex` now accepts :class:`Int64Index` arguments as epoch timestamps (:issue:`20997`) +- Accessing a level of a ``MultiIndex`` with a duplicate name (e.g. in + :meth:~MultiIndex.get_level_values) now raises a ``ValueError`` instead of + a ``KeyError`` (:issue:`21678`). - Invalid construction of ``IntervalDtype`` will now always raise a ``TypeError`` rather than a ``ValueError`` if the subdtype is invalid (:issue:`21185`) - Trying to reindex a ``DataFrame`` with a non unique ``MultiIndex`` now raises a ``ValueError`` instead of an ``Exception`` (:issue:`21770`) - diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index e143e5fdebfb1..b3bf7abe97279 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -19,6 +19,7 @@ is_categorical_dtype, is_object_dtype, is_hashable, + is_integer, is_iterator, is_list_like, pandas_dtype, @@ -757,14 +758,14 @@ def _from_elements(values, labels=None, levels=None, names=None, return MultiIndex(levels, labels, names, sortorder=sortorder) def _get_level_number(self, level): + count = self.names.count(level) + if (count > 1) and not is_integer(level): + raise ValueError('The name %s occurs multiple times, use a ' + 'level number' % level) try: - count = self.names.count(level) - if count > 1: - raise ValueError('The name %s occurs multiple times, use a ' - 'level number' % level) level = self.names.index(level) except ValueError: - if not isinstance(level, int): + if not is_integer(level): raise KeyError('Level %s not found' % str(level)) elif level < 0: level += self.nlevels @@ -2879,13 +2880,6 @@ def isin(self, values, level=None): else: return np.lib.arraysetops.in1d(labs, sought_labels) - def _reference_duplicate_name(self, name): - """ - Returns True if the name refered to in self.names is duplicated. - """ - # count the times name equals an element in self.names. - return sum(name == n for n in self.names) > 1 - MultiIndex._add_numeric_methods_disabled() MultiIndex._add_numeric_methods_add_sub_disabled() diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 089634fb8e315..d5d2e594b8d6b 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -114,12 +114,6 @@ def __init__(self, values, index, level=-1, value_columns=None, self.index = index.remove_unused_levels() - if isinstance(self.index, MultiIndex): - if index._reference_duplicate_name(level): - msg = ("Ambiguous reference to {level}. The index " - "names are not unique.".format(level=level)) - raise ValueError(msg) - self.level = self.index._get_level_number(level) # when index includes `nan`, need to lift levels/strides by 1 @@ -533,12 +527,6 @@ def factorize(index): N, K = frame.shape - if isinstance(frame.columns, MultiIndex): - if frame.columns._reference_duplicate_name(level): - msg = ("Ambiguous reference to {level}. The column " - "names are not unique.".format(level=level)) - raise ValueError(msg) - # Will also convert negative level numbers and check if out of bounds. level_num = frame.columns._get_level_number(level) diff --git a/pandas/tests/indexes/multi/test_unique_and_duplicates.py b/pandas/tests/indexes/multi/test_unique_and_duplicates.py index a97d84ace9602..c1000e5b6e0f6 100644 --- a/pandas/tests/indexes/multi/test_unique_and_duplicates.py +++ b/pandas/tests/indexes/multi/test_unique_and_duplicates.py @@ -255,5 +255,5 @@ def test_unique_na(): def test_duplicate_level_names_access_raises(idx): idx.names = ['foo', 'foo'] - tm.assert_raises_regex(KeyError, 'Level foo not found', + tm.assert_raises_regex(ValueError, 'name foo occurs multiple times', idx._get_level_number, 'foo')
follow-up on: https://github.com/pandas-dev/pandas/pull/21423 But, this currently has a lot of failures, because of https://github.com/pandas-dev/pandas/issues/21677 that we first need to resolve.
https://api.github.com/repos/pandas-dev/pandas/pulls/21678
2018-06-29T12:07:09Z
2018-07-08T14:16:22Z
2018-07-08T14:16:22Z
2018-07-08T14:16:26Z
TST/CLN: Old timezone issues PT3
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 0ca5b9cdf1d57..cfcee79281eec 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -248,6 +248,8 @@ Timezones - Bug in :meth:`Series.truncate` with a tz-aware :class:`DatetimeIndex` which would cause a core dump (:issue:`9243`) - Bug in :class:`Series` constructor which would coerce tz-aware and tz-naive :class:`Timestamp`s to tz-aware (:issue:`13051`) - Bug in :class:`Index` with ``datetime64[ns, tz]`` dtype that did not localize integer data correctly (:issue:`20964`) +- Bug in :class:`DatetimeIndex` where constructing with an integer and tz would not localize correctly (:issue:`12619`) +- Bug in :func:`DataFrame.fillna` where a ``ValueError`` would raise when one column contained a ``datetime64[ns, tz]`` dtype (:issue:`15522`) Offsets ^^^^^^^ @@ -326,7 +328,7 @@ Sparse Reshaping ^^^^^^^^^ -- +- Bug in :func:`pandas.concat` when joining resampled DataFrames with timezone aware index (:issue:`13783`) - - diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index f1113fd6debf2..9567c08781856 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -300,6 +300,17 @@ def test_fillna(self): pd.Timestamp('2012-11-11 00:00:00+01:00')]}) assert_frame_equal(df.fillna(method='bfill'), exp) + # with timezone in another column + # GH 15522 + df = pd.DataFrame({'A': pd.date_range('20130101', periods=4, + tz='US/Eastern'), + 'B': [1, 2, np.nan, np.nan]}) + result = df.fillna(method='pad') + expected = pd.DataFrame({'A': pd.date_range('20130101', periods=4, + tz='US/Eastern'), + 'B': [1., 2., 2., 2.]}) + assert_frame_equal(result, expected) + def test_na_actions_categorical(self): cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index ae98510951845..5653943c37e37 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -496,6 +496,13 @@ def test_constructor_with_int_tz(self, klass, box, tz, dtype): expected = klass([ts]) assert result == expected + def test_construction_int_rountrip(self, tz_naive_fixture): + # GH 12619 + tz = tz_naive_fixture + result = 1293858000000000000 + expected = DatetimeIndex([1293858000000000000], tz=tz).asi8[0] + assert result == expected + class TestTimeSeries(object): diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 8d819f9926abb..d05fd689ed754 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -2351,6 +2351,15 @@ def test_concat_datetime_timezone(self): tm.assert_frame_equal(result, expected) + # GH 13783: Concat after resample + with catch_warnings(record=True): + result = pd.concat([df1.resample('H').mean(), + df2.resample('H').mean()]) + expected = pd.DataFrame({'a': [1, 2, 3] + [np.nan] * 3, + 'b': [np.nan] * 3 + [1, 2, 3]}, + index=idx1.append(idx1)) + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize('pdt', [pd.Series, pd.DataFrame, pd.Panel]) @pytest.mark.parametrize('dt', np.sctypes['float'])
- [x] closes #13783 - [x] closes #12619 - [x] closes #15522 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry xref #21612 and #21491, last of the cleanup of older timezone issues
https://api.github.com/repos/pandas-dev/pandas/pulls/21674
2018-06-29T06:14:20Z
2018-07-02T23:44:12Z
2018-07-02T23:44:11Z
2018-07-03T02:36:36Z
ENH: pivot/groupby index with nan (GH3729)
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 406ca9ba045c9..69a8be39be62c 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -9,6 +9,7 @@ New features ~~~~~~~~~~~~ - ``ExcelWriter`` now accepts ``mode`` as a keyword argument, enabling append to existing workbooks when using the ``openpyxl`` engine (:issue:`3441`) +- ``groupby`` now accepts ``group_nas`` as a keyword argument, enabling the `np.nan` as a grouping label (:issue:`3729`) .. _whatsnew_0240.enhancements.other: diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 9e34b8eb55ccb..adfe47ddd5b94 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -493,6 +493,8 @@ def _factorize_array(values, na_sentinel=-1, size_hint=None, %(values)s%(sort)s%(order)s na_sentinel : int, default -1 Value to mark "not found". + factor_nas : boolean, default False + If true, treat NaNs as a factorizable value %(size_hint)s\ Returns @@ -597,7 +599,8 @@ def _factorize_array(values, na_sentinel=-1, size_hint=None, ) @Appender(_shared_docs['factorize']) @deprecate_kwarg(old_arg_name='order', new_arg_name=None) -def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): +def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None, + factor_nas=False): # Implementation notes: This method is responsible for 3 things # 1.) coercing data to array-like (ndarray, Index, extension array) # 2.) factorizing labels and uniques @@ -642,6 +645,13 @@ def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): na_sentinel=na_sentinel, assume_unique=True) + if factor_nas and (labels == na_sentinel).any(): + new_na_sentinel = len(uniques) + # Append the np.nan + uniques = np.resize(uniques, len(uniques) + 1) + uniques[-1] = np.nan + labels = np.where(labels == na_sentinel, new_na_sentinel, labels) + uniques = _reconstruct_data(uniques, dtype, original) # return original tenor diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 8fa79a130d1f8..f523ab73730a4 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6584,7 +6584,8 @@ def clip_lower(self, threshold, axis=None, inplace=False): axis=axis, inplace=inplace) def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, - group_keys=True, squeeze=False, observed=False, **kwargs): + group_keys=True, squeeze=False, observed=False, + group_nas=False, **kwargs): """ Group series using mapper (dict or key function, apply given function to group, return result as series) or by a series of columns. @@ -6621,6 +6622,8 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, This only applies if any of the groupers are Categoricals If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. + group_nas : boolean, default False + Group the NaNs as normal values .. versionadded:: 0.23.0 @@ -6656,7 +6659,7 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, axis = self._get_axis_number(axis) return groupby(self, by=by, axis=axis, level=level, as_index=as_index, sort=sort, group_keys=group_keys, squeeze=squeeze, - observed=observed, **kwargs) + observed=observed, group_nas=group_nas, **kwargs) def asfreq(self, freq, method=None, how=None, normalize=False, fill_value=None): diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c69d7f43de8ea..763cb9e2c875c 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -567,7 +567,7 @@ class _GroupBy(PandasObject, SelectionMixin): def __init__(self, obj, keys=None, axis=0, level=None, grouper=None, exclusions=None, selection=None, as_index=True, sort=True, group_keys=True, squeeze=False, - observed=False, **kwargs): + observed=False, group_nas=False, **kwargs): self._selection = selection @@ -588,6 +588,7 @@ def __init__(self, obj, keys=None, axis=0, level=None, self.group_keys = group_keys self.squeeze = squeeze self.observed = observed + self.group_nas = group_nas self.mutated = kwargs.pop('mutated', False) if grouper is None: @@ -596,6 +597,7 @@ def __init__(self, obj, keys=None, axis=0, level=None, level=level, sort=sort, observed=observed, + group_nas=group_nas, mutated=self.mutated) self.obj = obj @@ -2922,6 +2924,8 @@ class Grouping(object): level : observed : boolean, default False If we are a Categorical, use the observed values + group_nas : boolean, default False + Should NaNs be grouped as another value in_axis : if the Grouping is a column in self.obj and hence among Groupby.exclusions list @@ -2937,7 +2941,7 @@ class Grouping(object): """ def __init__(self, index, grouper=None, obj=None, name=None, level=None, - sort=True, observed=False, in_axis=False): + sort=True, observed=False, group_nas=False, in_axis=False): self.name = name self.level = level @@ -2947,6 +2951,7 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None, self.sort = sort self.obj = obj self.observed = observed + self.group_nas = group_nas self.in_axis = in_axis # right place for this? @@ -3100,7 +3105,7 @@ def _make_labels(self): uniques = self.grouper.result_index else: labels, uniques = algorithms.factorize( - self.grouper, sort=self.sort) + self.grouper, sort=self.sort, factor_nas=self.group_nas) uniques = Index(uniques, name=self.name) self._labels = labels self._group_index = uniques @@ -3112,7 +3117,8 @@ def groups(self): def _get_grouper(obj, key=None, axis=0, level=None, sort=True, - observed=False, mutated=False, validate=True): + observed=False, group_nas=False, mutated=False, + validate=True): """ create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. @@ -3311,6 +3317,7 @@ def is_in_obj(gpr): level=level, sort=sort, observed=observed, + group_nas=group_nas, in_axis=in_axis) \ if not isinstance(gpr, Grouping) else gpr @@ -3752,7 +3759,9 @@ def nunique(self, dropna=True): except TypeError: # catches object dtypes assert val.dtype == object, \ 'val.dtype must be object, got %s' % val.dtype - val, _ = algorithms.factorize(val, sort=False) + val, _ = algorithms.factorize( + val, sort=False, factor_nas=self.group_nas + ) sorter = np.lexsort((val, ids)) _isna = lambda a: a == -1 else: diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index e05f9de5ea7f4..63923160496fb 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -276,6 +276,12 @@ def test_with_na_groups(dtype): assert_series_equal(agged, expected, check_dtype=False) + grouped_na = values.groupby(labels, group_nas=True) + agged_na = grouped_na.agg(len) + expected_na = Series([4, 2, 4], index=['bar', 'foo', np.nan]) + + assert_series_equal(agged_na, expected_na, check_dtype=False) + # assert issubclass(agged.dtype.type, np.integer) # explicitly return a float from my function @@ -288,6 +294,28 @@ def f(x): assert_series_equal(agged, expected, check_dtype=False) assert issubclass(agged.dtype.type, np.dtype(dtype).type) + agged_na = grouped_na.agg(f) + expected_na = Series([4, 2, 4], index=['bar', 'foo', np.nan]) + + assert_series_equal(agged_na, expected_na, check_dtype=False) + assert issubclass(agged_na.dtype.type, np.dtype(dtype).type) + + # Check the data frame groupby interface also handles NaNs correctly + df = pd.DataFrame({"Vals": values, "Labs": labels}) + + agged = df.groupby("Labs")["Vals"].sum() + expected = Series( + [4, 2], index=Index(['bar', 'foo'], name='Labs'), name='Vals' + ) + assert_series_equal(agged, expected, check_dtype=False) + + agged_na = df.groupby("Labs", group_nas=True)["Vals"].sum() + expected_na = Series( + [4, 2, 4], index=Index(['bar', 'foo', np.nan], name='Labs'), + name='Vals' + ) + assert_series_equal(agged_na, expected_na, check_dtype=False) + def test_indices_concatenation_order():
Adds the ability to use NaN as a grouping variable. Required allowing NA as a factorisation variable in `factorize()`. - [x] closes #3729 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21669
2018-06-29T03:17:56Z
2018-11-23T03:33:07Z
null
2018-11-23T03:33:07Z
DOC: Fixup docstring [ci skip]
diff --git a/doc/source/merging.rst b/doc/source/merging.rst index 2eb5962ead986..eb71722dd563a 100644 --- a/doc/source/merging.rst +++ b/doc/source/merging.rst @@ -494,7 +494,7 @@ You can also pass a list of dicts or Series: dicts = [{'A': 1, 'B': 2, 'C': 3, 'X': 4}, {'A': 5, 'B': 6, 'C': 7, 'Y': 8}] - result = df1.append(dicts, ignore_index=True) + result = df1.append(dicts, ignore_index=True, sort=False) .. ipython:: python :suppress: diff --git a/doc/source/text.rst b/doc/source/text.rst index 34bb1a07dfc08..dde82e3c19f82 100644 --- a/doc/source/text.rst +++ b/doc/source/text.rst @@ -270,12 +270,13 @@ For concatenation with a ``Series`` or ``DataFrame``, it is possible to align th the ``join``-keyword. .. ipython:: python + :okwarning: - u = pd.Series(['b', 'd', 'a', 'c'], index=[1, 3, 0, 2]) - s - u - s.str.cat(u) - s.str.cat(u, join='left') + u = pd.Series(['b', 'd', 'a', 'c'], index=[1, 3, 0, 2]) + s + u + s.str.cat(u) + s.str.cat(u, join='left') .. warning:: @@ -296,7 +297,7 @@ In particular, alignment also means that the different lengths do not need to co The same alignment can be used when ``others`` is a ``DataFrame``: .. ipython:: python - + f = d.loc[[3, 2, 1, 0], :] s f @@ -311,7 +312,7 @@ All one-dimensional list-likes can be arbitrarily combined in a list-like contai s u - s.str.cat([u, pd.Index(u.values), ['A', 'B', 'C', 'D'], map(str, u.index)], na_rep='-') + s.str.cat([u, u.values, ['A', 'B', 'C', 'D'], map(str, u.index)], na_rep='-') All elements must match in length to the calling ``Series`` (or ``Index``), except those having an index if ``join`` is not None: diff --git a/doc/source/whatsnew/v0.10.0.txt b/doc/source/whatsnew/v0.10.0.txt index ec4ac17c80fd7..298088a4f96b3 100644 --- a/doc/source/whatsnew/v0.10.0.txt +++ b/doc/source/whatsnew/v0.10.0.txt @@ -281,17 +281,12 @@ The old behavior of printing out summary information can be achieved via the The width of each line can be changed via 'line_width' (80 by default): -.. ipython:: python +.. code-block:: python pd.set_option('line_width', 40) wide_frame -.. ipython:: python - :suppress: - - pd.reset_option('line_width') - Updated PyTables Support ~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v0.13.1.txt b/doc/source/whatsnew/v0.13.1.txt index 51ca6116d42ce..a4807a6d61b76 100644 --- a/doc/source/whatsnew/v0.13.1.txt +++ b/doc/source/whatsnew/v0.13.1.txt @@ -119,8 +119,7 @@ API changes equal. NaNs in identical locations are treated as equal. (:issue:`5283`) See also :ref:`the docs<basics.equals>` for a motivating example. - .. ipython:: python - :okwarning: + .. code-block:: python df = DataFrame({'col':['foo', 0, np.nan]}) df2 = DataFrame({'col':[np.nan, 0, 'foo']}, index=[2,1,0]) diff --git a/doc/source/whatsnew/v0.14.1.txt b/doc/source/whatsnew/v0.14.1.txt index 5183dd24e9b34..d019cf54086c6 100644 --- a/doc/source/whatsnew/v0.14.1.txt +++ b/doc/source/whatsnew/v0.14.1.txt @@ -92,15 +92,15 @@ Enhancements ``offsets.apply``, ``rollforward`` and ``rollback`` resets the time (hour, minute, etc) or not (default ``False``, preserves time) (:issue:`7156`): - .. ipython:: python + .. code-block:: python - import pandas.tseries.offsets as offsets + import pandas.tseries.offsets as offsets - day = offsets.Day() - day.apply(Timestamp('2014-01-01 09:00')) + day = offsets.Day() + day.apply(Timestamp('2014-01-01 09:00')) - day = offsets.Day(normalize=True) - day.apply(Timestamp('2014-01-01 09:00')) + day = offsets.Day(normalize=True) + day.apply(Timestamp('2014-01-01 09:00')) - ``PeriodIndex`` is represented as the same format as ``DatetimeIndex`` (:issue:`7601`) - ``StringMethods`` now work on empty Series (:issue:`7242`) diff --git a/doc/source/whatsnew/v0.15.0.txt b/doc/source/whatsnew/v0.15.0.txt index 79003296ac165..4be6975958af5 100644 --- a/doc/source/whatsnew/v0.15.0.txt +++ b/doc/source/whatsnew/v0.15.0.txt @@ -1008,7 +1008,7 @@ Other: business_dates = date_range(start='4/1/2014', end='6/30/2014', freq='B') df = DataFrame(1, index=business_dates, columns=['a', 'b']) # get the first, 4th, and last date index for each month - df.groupby((df.index.year, df.index.month)).nth([0, 3, -1]) + df.groupby([df.index.year, df.index.month]).nth([0, 3, -1]) - ``Period`` and ``PeriodIndex`` supports addition/subtraction with ``timedelta``-likes (:issue:`7966`) diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index c5ae0d147824c..328a8193c8b13 100644 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -58,7 +58,7 @@ We can render the HTML to get the following table. :file: whatsnew_0171_html_table.html :class:`~pandas.core.style.Styler` interacts nicely with the Jupyter Notebook. -See the :doc:`documentation <style>` for more. +See the :ref:`documentation </style.ipynb>` for more. .. _whatsnew_0171.enhancements: diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1105acda067d3..ef19e5984fa3d 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -176,7 +176,7 @@ Timezones ^^^^^^^^^ - Bug in :meth:`DatetimeIndex.shift` where an ``AssertionError`` would raise when shifting across DST (:issue:`8616`) -- Bug in :class:`Timestamp` constructor where passing an invalid timezone offset designator (``Z``) would not raise a ``ValueError``(:issue:`8910`) +- Bug in :class:`Timestamp` constructor where passing an invalid timezone offset designator (``Z``) would not raise a ``ValueError`` (:issue:`8910`) - Bug in :meth:`Timestamp.replace` where replacing at a DST boundary would retain an incorrect offset (:issue:`7825`) - Bug in :meth:`Series.replace` with ``datetime64[ns, tz]`` data when replacing ``NaT`` (:issue:`11792`) - Bug in :class:`Timestamp` when passing different string date formats with a timezone offset would produce different timezone offsets (:issue:`12064`) diff --git a/doc/source/whatsnew/v0.8.0.txt b/doc/source/whatsnew/v0.8.0.txt index 29d6fe563d047..28c043e772605 100644 --- a/doc/source/whatsnew/v0.8.0.txt +++ b/doc/source/whatsnew/v0.8.0.txt @@ -178,7 +178,7 @@ types. For example, ``'kde'`` is a new option: s = Series(np.concatenate((np.random.randn(1000), np.random.randn(1000) * 0.5 + 3))) plt.figure() - s.hist(normed=True, alpha=0.2) + s.hist(density=True, alpha=0.2) s.plot(kind='kde') See :ref:`the plotting page <visualization.other>` for much more. diff --git a/pandas/core/series.py b/pandas/core/series.py index cdb901d18767c..f5aea19ee4a7b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1439,7 +1439,7 @@ def mode(self, dropna=True): Always returns Series even if only one value is returned. Parameters - ------- + ---------- dropna : boolean, default True Don't consider counts of NaN/NaT.
[ci skip]
https://api.github.com/repos/pandas-dev/pandas/pulls/21663
2018-06-28T11:15:38Z
2018-07-06T16:48:38Z
2018-07-06T16:48:38Z
2018-07-06T16:48:40Z
TST: Use fixtures in dtypes/test_cast.py
diff --git a/pandas/conftest.py b/pandas/conftest.py index 5b9c162a0a022..803b3add97052 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -245,6 +245,18 @@ def float_dtype(request): return request.param +@pytest.fixture(params=["complex64", "complex128"]) +def complex_dtype(request): + """ + Parameterized fixture for complex dtypes. + + * complex64 + * complex128 + """ + + return request.param + + UNSIGNED_INT_DTYPES = ["uint8", "uint16", "uint32", "uint64"] SIGNED_INT_DTYPES = ["int8", "int16", "int32", "int64"] ALL_INT_DTYPES = UNSIGNED_INT_DTYPES + SIGNED_INT_DTYPES diff --git a/pandas/tests/dtypes/test_cast.py b/pandas/tests/dtypes/test_cast.py index 4a19682e2c558..0d6382424ccf5 100644 --- a/pandas/tests/dtypes/test_cast.py +++ b/pandas/tests/dtypes/test_cast.py @@ -36,7 +36,7 @@ class TestMaybeDowncast(object): - def test_downcast_conv(self): + def test_downcast(self): # test downcasting arr = np.array([8.5, 8.6, 8.7, 8.8, 8.9999999999995]) @@ -53,33 +53,34 @@ def test_downcast_conv(self): expected = np.array([8, 8, 8, 8, 9], dtype=np.int64) tm.assert_numpy_array_equal(result, expected) - # GH16875 coercing of bools + # see gh-16875: coercing of booleans. ser = Series([True, True, False]) result = maybe_downcast_to_dtype(ser, np.dtype(np.float64)) expected = ser tm.assert_series_equal(result, expected) - # conversions - + @pytest.mark.parametrize("dtype", [np.float64, object, np.int64]) + def test_downcast_conversion_no_nan(self, dtype): expected = np.array([1, 2]) - for dtype in [np.float64, object, np.int64]: - arr = np.array([1.0, 2.0], dtype=dtype) - result = maybe_downcast_to_dtype(arr, 'infer') - tm.assert_almost_equal(result, expected, check_dtype=False) - - for dtype in [np.float64, object]: - expected = np.array([1.0, 2.0, np.nan], dtype=dtype) - arr = np.array([1.0, 2.0, np.nan], dtype=dtype) - result = maybe_downcast_to_dtype(arr, 'infer') - tm.assert_almost_equal(result, expected) - - # empties - for dtype in [np.int32, np.float64, np.float32, np.bool_, - np.int64, object]: - arr = np.array([], dtype=dtype) - result = maybe_downcast_to_dtype(arr, 'int64') - tm.assert_almost_equal(result, np.array([], dtype=np.int64)) - assert result.dtype == np.int64 + arr = np.array([1.0, 2.0], dtype=dtype) + + result = maybe_downcast_to_dtype(arr, "infer") + tm.assert_almost_equal(result, expected, check_dtype=False) + + @pytest.mark.parametrize("dtype", [np.float64, object]) + def test_downcast_conversion_nan(self, dtype): + expected = np.array([1.0, 2.0, np.nan], dtype=dtype) + arr = np.array([1.0, 2.0, np.nan], dtype=dtype) + + result = maybe_downcast_to_dtype(arr, "infer") + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize("dtype", [np.int32, np.float64, np.float32, + np.bool_, np.int64, object]) + def test_downcast_conversion_empty(self, dtype): + arr = np.array([], dtype=dtype) + result = maybe_downcast_to_dtype(arr, "int64") + tm.assert_numpy_array_equal(result, np.array([], dtype=np.int64)) def test_datetimelikes_nan(self): arr = np.array([1, 2, np.nan]) @@ -104,66 +105,71 @@ def test_datetime_with_timezone(self): class TestInferDtype(object): - def testinfer_dtype_from_scalar(self): - # Test that infer_dtype_from_scalar is returning correct dtype for int - # and float. + def test_infer_dtype_from_int_scalar(self, any_int_dtype): + # Test that infer_dtype_from_scalar is + # returning correct dtype for int and float. + data = np.dtype(any_int_dtype).type(12) + dtype, val = infer_dtype_from_scalar(data) + assert dtype == type(data) + + def test_infer_dtype_from_float_scalar(self, float_dtype): + float_dtype = np.dtype(float_dtype).type + data = float_dtype(12) - for dtypec in [np.uint8, np.int8, np.uint16, np.int16, np.uint32, - np.int32, np.uint64, np.int64]: - data = dtypec(12) - dtype, val = infer_dtype_from_scalar(data) - assert dtype == type(data) + dtype, val = infer_dtype_from_scalar(data) + assert dtype == float_dtype + def test_infer_dtype_from_python_scalar(self): data = 12 dtype, val = infer_dtype_from_scalar(data) assert dtype == np.int64 - for dtypec in [np.float16, np.float32, np.float64]: - data = dtypec(12) - dtype, val = infer_dtype_from_scalar(data) - assert dtype == dtypec - data = np.float(12) dtype, val = infer_dtype_from_scalar(data) assert dtype == np.float64 - for data in [True, False]: - dtype, val = infer_dtype_from_scalar(data) - assert dtype == np.bool_ + @pytest.mark.parametrize("bool_val", [True, False]) + def test_infer_dtype_from_boolean(self, bool_val): + dtype, val = infer_dtype_from_scalar(bool_val) + assert dtype == np.bool_ - for data in [np.complex64(1), np.complex128(1)]: - dtype, val = infer_dtype_from_scalar(data) - assert dtype == np.complex_ + def test_infer_dtype_from_complex(self, complex_dtype): + data = np.dtype(complex_dtype).type(1) + dtype, val = infer_dtype_from_scalar(data) + assert dtype == np.complex_ - for data in [np.datetime64(1, 'ns'), Timestamp(1), - datetime(2000, 1, 1, 0, 0)]: - dtype, val = infer_dtype_from_scalar(data) - assert dtype == 'M8[ns]' + @pytest.mark.parametrize("data", [np.datetime64(1, "ns"), Timestamp(1), + datetime(2000, 1, 1, 0, 0)]) + def test_infer_dtype_from_datetime(self, data): + dtype, val = infer_dtype_from_scalar(data) + assert dtype == "M8[ns]" - for data in [np.timedelta64(1, 'ns'), Timedelta(1), - timedelta(1)]: - dtype, val = infer_dtype_from_scalar(data) - assert dtype == 'm8[ns]' + @pytest.mark.parametrize("data", [np.timedelta64(1, "ns"), Timedelta(1), + timedelta(1)]) + def test_infer_dtype_from_timedelta(self, data): + dtype, val = infer_dtype_from_scalar(data) + assert dtype == "m8[ns]" - for freq in ['M', 'D']: - p = Period('2011-01-01', freq=freq) - dtype, val = infer_dtype_from_scalar(p, pandas_dtype=True) - assert dtype == 'period[{0}]'.format(freq) - assert val == p.ordinal + @pytest.mark.parametrize("freq", ["M", "D"]) + def test_infer_dtype_from_period(self, freq): + p = Period("2011-01-01", freq=freq) + dtype, val = infer_dtype_from_scalar(p, pandas_dtype=True) - dtype, val = infer_dtype_from_scalar(p) - dtype == np.object_ - assert val == p + assert dtype == "period[{0}]".format(freq) + assert val == p.ordinal - # misc - for data in [date(2000, 1, 1), - Timestamp(1, tz='US/Eastern'), 'foo']: + dtype, val = infer_dtype_from_scalar(p) + assert dtype == np.object_ + assert val == p - dtype, val = infer_dtype_from_scalar(data) - assert dtype == np.object_ + @pytest.mark.parametrize("data", [date(2000, 1, 1), "foo", + Timestamp(1, tz="US/Eastern")]) + def test_infer_dtype_misc(self, data): + dtype, val = infer_dtype_from_scalar(data) + assert dtype == np.object_ @pytest.mark.parametrize('tz', ['UTC', 'US/Eastern', 'Asia/Tokyo']) - def testinfer_from_scalar_tz(self, tz): + def test_infer_from_scalar_tz(self, tz): dt = Timestamp(1, tz=tz) dtype, val = infer_dtype_from_scalar(dt, pandas_dtype=True) assert dtype == 'datetime64[ns, {0}]'.format(tz) @@ -173,7 +179,7 @@ def testinfer_from_scalar_tz(self, tz): assert dtype == np.object_ assert val == dt - def testinfer_dtype_from_scalar_errors(self): + def test_infer_dtype_from_scalar_errors(self): with pytest.raises(ValueError): infer_dtype_from_scalar(np.array([1])) @@ -329,66 +335,63 @@ def test_maybe_convert_objects_copy(self): class TestCommonTypes(object): - def test_numpy_dtypes(self): - # (source_types, destination_type) - testcases = ( - # identity - ((np.int64,), np.int64), - ((np.uint64,), np.uint64), - ((np.float32,), np.float32), - ((np.object,), np.object), - - # into ints - ((np.int16, np.int64), np.int64), - ((np.int32, np.uint32), np.int64), - ((np.uint16, np.uint64), np.uint64), - - # into floats - ((np.float16, np.float32), np.float32), - ((np.float16, np.int16), np.float32), - ((np.float32, np.int16), np.float32), - ((np.uint64, np.int64), np.float64), - ((np.int16, np.float64), np.float64), - ((np.float16, np.int64), np.float64), - - # into others - ((np.complex128, np.int32), np.complex128), - ((np.object, np.float32), np.object), - ((np.object, np.int16), np.object), - - # bool with int - ((np.dtype('bool'), np.int64), np.object), - ((np.dtype('bool'), np.int32), np.object), - ((np.dtype('bool'), np.int16), np.object), - ((np.dtype('bool'), np.int8), np.object), - ((np.dtype('bool'), np.uint64), np.object), - ((np.dtype('bool'), np.uint32), np.object), - ((np.dtype('bool'), np.uint16), np.object), - ((np.dtype('bool'), np.uint8), np.object), - - # bool with float - ((np.dtype('bool'), np.float64), np.object), - ((np.dtype('bool'), np.float32), np.object), - - ((np.dtype('datetime64[ns]'), np.dtype('datetime64[ns]')), - np.dtype('datetime64[ns]')), - ((np.dtype('timedelta64[ns]'), np.dtype('timedelta64[ns]')), - np.dtype('timedelta64[ns]')), - - ((np.dtype('datetime64[ns]'), np.dtype('datetime64[ms]')), - np.dtype('datetime64[ns]')), - ((np.dtype('timedelta64[ms]'), np.dtype('timedelta64[ns]')), - np.dtype('timedelta64[ns]')), - - ((np.dtype('datetime64[ns]'), np.dtype('timedelta64[ns]')), - np.object), - ((np.dtype('datetime64[ns]'), np.int64), np.object) - ) - for src, common in testcases: - assert find_common_type(src) == common - + @pytest.mark.parametrize("source_dtypes,expected_common_dtype", [ + ((np.int64,), np.int64), + ((np.uint64,), np.uint64), + ((np.float32,), np.float32), + ((np.object,), np.object), + + # into ints + ((np.int16, np.int64), np.int64), + ((np.int32, np.uint32), np.int64), + ((np.uint16, np.uint64), np.uint64), + + # into floats + ((np.float16, np.float32), np.float32), + ((np.float16, np.int16), np.float32), + ((np.float32, np.int16), np.float32), + ((np.uint64, np.int64), np.float64), + ((np.int16, np.float64), np.float64), + ((np.float16, np.int64), np.float64), + + # into others + ((np.complex128, np.int32), np.complex128), + ((np.object, np.float32), np.object), + ((np.object, np.int16), np.object), + + # bool with int + ((np.dtype('bool'), np.int64), np.object), + ((np.dtype('bool'), np.int32), np.object), + ((np.dtype('bool'), np.int16), np.object), + ((np.dtype('bool'), np.int8), np.object), + ((np.dtype('bool'), np.uint64), np.object), + ((np.dtype('bool'), np.uint32), np.object), + ((np.dtype('bool'), np.uint16), np.object), + ((np.dtype('bool'), np.uint8), np.object), + + # bool with float + ((np.dtype('bool'), np.float64), np.object), + ((np.dtype('bool'), np.float32), np.object), + + ((np.dtype('datetime64[ns]'), np.dtype('datetime64[ns]')), + np.dtype('datetime64[ns]')), + ((np.dtype('timedelta64[ns]'), np.dtype('timedelta64[ns]')), + np.dtype('timedelta64[ns]')), + + ((np.dtype('datetime64[ns]'), np.dtype('datetime64[ms]')), + np.dtype('datetime64[ns]')), + ((np.dtype('timedelta64[ms]'), np.dtype('timedelta64[ns]')), + np.dtype('timedelta64[ns]')), + + ((np.dtype('datetime64[ns]'), np.dtype('timedelta64[ns]')), + np.object), + ((np.dtype('datetime64[ns]'), np.int64), np.object) + ]) + def test_numpy_dtypes(self, source_dtypes, expected_common_dtype): + assert find_common_type(source_dtypes) == expected_common_dtype + + def test_raises_empty_input(self): with pytest.raises(ValueError): - # empty find_common_type([]) def test_categorical_dtype(self):
Title is self-explanatory. Partially addresses #21500.
https://api.github.com/repos/pandas-dev/pandas/pulls/21661
2018-06-27T23:05:23Z
2018-06-28T10:11:49Z
2018-06-28T10:11:49Z
2018-06-28T16:58:53Z
BUG: Issues with DatetimeTZ values in where and combine_first (#21469 + #21546)
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 94257b25b11a5..dfb7a3675fdd5 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -255,7 +255,6 @@ Timezones - Bug in :class:`Series` constructor which would coerce tz-aware and tz-naive :class:`Timestamp`s to tz-aware (:issue:`13051`) - Bug in :class:`Index` with ``datetime64[ns, tz]`` dtype that did not localize integer data correctly (:issue:`20964`) - Bug in :class:`DatetimeIndex` where constructing with an integer and tz would not localize correctly (:issue:`12619`) -- Bug in :func:`DataFrame.fillna` where a ``ValueError`` would raise when one column contained a ``datetime64[ns, tz]`` dtype (:issue:`15522`) Offsets ^^^^^^^ @@ -288,13 +287,18 @@ Indexing ^^^^^^^^ - The traceback from a ``KeyError`` when asking ``.loc`` for a single missing label is now shorter and more clear (:issue:`21557`) -- When ``.ix`` is asked for a missing integer label in a :class:`MultiIndex` with a first level of integer type, it now raises a ``KeyError`` - consistently with the case of a flat :class:`Int64Index` - rather than falling back to positional indexing (:issue:`21593`) +- When ``.ix`` is asked for a missing integer label in a :class:`MultiIndex` with a first level of integer type, it now raises a ``KeyError``, consistently with the case of a flat :class:`Int64Index, rather than falling back to positional indexing (:issue:`21593`) - Bug in :meth:`DatetimeIndex.reindex` when reindexing a tz-naive and tz-aware :class:`DatetimeIndex` (:issue:`8306`) - Bug in :class:`DataFrame` when setting values with ``.loc`` and a timezone aware :class:`DatetimeIndex` (:issue:`11365`) - Bug when indexing :class:`DatetimeIndex` with nanosecond resolution dates and timezones (:issue:`11679`) - +Missing +^^^^^^^ + +- Bug in :func:`DataFrame.fillna` where a ``ValueError`` would raise when one column contained a ``datetime64[ns, tz]`` dtype (:issue:`15522`) + MultiIndex ^^^^^^^^^^ @@ -335,6 +339,8 @@ Reshaping ^^^^^^^^^ - Bug in :func:`pandas.concat` when joining resampled DataFrames with timezone aware index (:issue:`13783`) +- Bug in :meth:`Series.combine_first` with ``datetime64[ns, tz]`` dtype which would return tz-naive result (:issue:`21469`) +- Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``datetime64[ns, tz]`` dtype (:issue:`21546`) - - diff --git a/pandas/core/common.py b/pandas/core/common.py index 1de8269c9a0c6..7aa092c2354da 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -14,7 +14,7 @@ from pandas.compat import long, zip, iteritems, PY36, OrderedDict from pandas.core.config import get_option from pandas.core.dtypes.generic import ABCSeries, ABCIndex -from pandas.core.dtypes.common import _NS_DTYPE, is_integer +from pandas.core.dtypes.common import is_integer from pandas.core.dtypes.inference import _iterable_not_string from pandas.core.dtypes.missing import isna, isnull, notnull # noqa from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike @@ -410,19 +410,6 @@ def _apply_if_callable(maybe_callable, obj, **kwargs): return maybe_callable -def _where_compat(mask, arr1, arr2): - if arr1.dtype == _NS_DTYPE and arr2.dtype == _NS_DTYPE: - new_vals = np.where(mask, arr1.view('i8'), arr2.view('i8')) - return new_vals.view(_NS_DTYPE) - - if arr1.dtype == _NS_DTYPE: - arr1 = tslib.ints_to_pydatetime(arr1.view('i8')) - if arr2.dtype == _NS_DTYPE: - arr2 = tslib.ints_to_pydatetime(arr2.view('i8')) - - return np.where(mask, arr1, arr2) - - def _dict_compat(d): """ Helper function to convert datetimelike-keyed dicts to Timestamp-keyed dict diff --git a/pandas/core/internals.py b/pandas/core/internals.py index fe508dc1bb0bc..e44c0f1b8e69d 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1476,7 +1476,7 @@ def where(self, other, cond, align=True, errors='raise', if transpose: values = values.T - other = getattr(other, 'values', other) + other = getattr(other, '_values', getattr(other, 'values', other)) cond = getattr(cond, 'values', cond) # If the default broadcasting would go in the wrong direction, then @@ -1484,6 +1484,8 @@ def where(self, other, cond, align=True, errors='raise', if getattr(other, 'ndim', 0) >= 1: if values.ndim - 1 == other.ndim and axis == 1: other = other.reshape(tuple(other.shape + (1, ))) + elif transpose and values.ndim == self.ndim - 1: + cond = cond.T if not hasattr(cond, 'shape'): raise ValueError("where must have a condition that is ndarray " @@ -2888,8 +2890,8 @@ def _try_coerce_args(self, values, other): elif isinstance(other, self._holder): if other.tz != self.values.tz: raise ValueError("incompatible or non tz-aware value") - other = other.asi8 - other_mask = isna(other) + other_mask = _block_shape(isna(other), ndim=self.ndim) + other = _block_shape(other.asi8, ndim=self.ndim) elif isinstance(other, (np.datetime64, datetime, date)): other = tslib.Timestamp(other) tz = getattr(other, 'tz', None) diff --git a/pandas/core/series.py b/pandas/core/series.py index cdb901d18767c..eb333d6b451ee 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -22,6 +22,7 @@ is_float_dtype, is_extension_type, is_extension_array_dtype, + is_datetimelike, is_datetime64tz_dtype, is_timedelta64_dtype, is_object_dtype, @@ -78,6 +79,7 @@ from pandas._libs import index as libindex, tslib as libts, lib, iNaT from pandas.core.config import get_option from pandas.core.strings import StringMethods +from pandas.core.tools.datetimes import to_datetime import pandas.plotting._core as gfx @@ -2303,10 +2305,10 @@ def combine_first(self, other): new_index = self.index.union(other.index) this = self.reindex(new_index, copy=False) other = other.reindex(new_index, copy=False) - # TODO: do we need name? - name = ops.get_op_result_name(self, other) # noqa - rs_vals = com._where_compat(isna(this), other._values, this._values) - return self._constructor(rs_vals, index=new_index).__finalize__(self) + if is_datetimelike(this) and not is_datetimelike(other): + other = to_datetime(other) + + return this.where(notna(this), other) def update(self, other): """ diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index c7aaf900b17fa..90f3bede482c6 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -2936,6 +2936,20 @@ def test_where_callable(self): tm.assert_frame_equal(result, (df + 2).where((df + 2) > 8, (df + 2) + 10)) + def test_where_tz_values(self, tz_naive_fixture): + df1 = DataFrame(DatetimeIndex(['20150101', '20150102', '20150103'], + tz=tz_naive_fixture), + columns=['date']) + df2 = DataFrame(DatetimeIndex(['20150103', '20150104', '20150105'], + tz=tz_naive_fixture), + columns=['date']) + mask = DataFrame([True, True, False], columns=['date']) + exp = DataFrame(DatetimeIndex(['20150101', '20150102', '20150105'], + tz=tz_naive_fixture), + columns=['date']) + result = df1.where(mask, df2) + assert_frame_equal(exp, result) + def test_mask(self): df = DataFrame(np.random.randn(5, 3)) cond = df > 0 diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index de756375db8cb..e7daefffe5f6f 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -580,12 +580,11 @@ def test_where_series_datetime64(self, fill_val, exp_dtype): values = pd.Series(pd.date_range(fill_val, periods=4)) if fill_val.tz: exp = pd.Series([pd.Timestamp('2011-01-01'), - pd.Timestamp('2012-01-02 05:00'), + pd.Timestamp('2012-01-02 00:00', tz='US/Eastern'), pd.Timestamp('2011-01-03'), - pd.Timestamp('2012-01-04 05:00')]) - self._assert_where_conversion(obj, cond, values, exp, - 'datetime64[ns]') - pytest.xfail("ToDo: do not coerce to UTC, must be object") + pd.Timestamp('2012-01-04 00:00', + tz='US/Eastern')]) + self._assert_where_conversion(obj, cond, values, exp, exp_dtype) exp = pd.Series([pd.Timestamp('2011-01-01'), values[1], pd.Timestamp('2011-01-03'), values[3]]) diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index 2aef0df5349cb..5cfb9b1ff4292 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -551,6 +551,18 @@ def test_where_datetime_conversion(): assert_series_equal(rs, expected) +def test_where_dt_tz_values(tz_naive_fixture): + ser1 = pd.Series(pd.DatetimeIndex(['20150101', '20150102', '20150103'], + tz=tz_naive_fixture)) + ser2 = pd.Series(pd.DatetimeIndex(['20160514', '20160515', '20160516'], + tz=tz_naive_fixture)) + mask = pd.Series([True, True, False]) + result = ser1.where(mask, ser2) + exp = pd.Series(pd.DatetimeIndex(['20150101', '20150102', '20160516'], + tz=tz_naive_fixture)) + assert_series_equal(exp, result) + + def test_mask(): # compare with tested results in test_where s = Series(np.random.randn(5)) diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py index f35cce6ac9d71..c1891430683da 100644 --- a/pandas/tests/series/test_combine_concat.py +++ b/pandas/tests/series/test_combine_concat.py @@ -170,6 +170,20 @@ def get_result_type(dtype, dtype2): ]).dtype assert result.kind == expected + def test_combine_first_dt_tz_values(self, tz_naive_fixture): + ser1 = pd.Series(pd.DatetimeIndex(['20150101', '20150102', '20150103'], + tz=tz_naive_fixture), + name='ser1') + ser2 = pd.Series(pd.DatetimeIndex(['20160514', '20160515', '20160516'], + tz=tz_naive_fixture), + index=[2, 3, 4], name='ser2') + result = ser1.combine_first(ser2) + exp_vals = pd.DatetimeIndex(['20150101', '20150102', '20150103', + '20160515', '20160516'], + tz=tz_naive_fixture) + exp = pd.Series(exp_vals, name='ser1') + assert_series_equal(exp, result) + def test_concat_empty_series_dtypes(self): # booleans
- [ ] closes #21469 - [ ] closes #21546 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry CC: @jreback. Replacement for PR #21544; fixes for #21469 (`Series.combine_first` fails on tz values input) and #21546 (`where` fails on tz values input). Series.combine_first now delegates to `where` for the bulk of its operations.
https://api.github.com/repos/pandas-dev/pandas/pulls/21660
2018-06-27T20:20:46Z
2018-07-02T23:54:23Z
2018-07-02T23:54:22Z
2018-07-02T23:54:36Z
PERF: avoid unneeded recoding of categoricals and reuse CategoricalDtypes for greater slicing speed
diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index 73e3933122628..2a7717378c280 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -210,3 +210,38 @@ def time_categorical_index_contains(self): def time_categorical_contains(self): self.key in self.c + + +class CategoricalSlicing(object): + + goal_time = 0.2 + params = ['monotonic_incr', 'monotonic_decr', 'non_monotonic'] + param_names = ['index'] + + def setup(self, index): + N = 10**6 + values = list('a' * N + 'b' * N + 'c' * N) + indices = { + 'monotonic_incr': pd.Categorical(values), + 'monotonic_decr': pd.Categorical(reversed(values)), + 'non_monotonic': pd.Categorical(list('abc' * N))} + self.data = indices[index] + + self.scalar = 10000 + self.list = list(range(10000)) + self.cat_scalar = 'b' + + def time_getitem_scalar(self, index): + self.data[self.scalar] + + def time_getitem_slice(self, index): + self.data[:self.scalar] + + def time_getitem_list_like(self, index): + self.data[[self.scalar]] + + def time_getitem_list(self, index): + self.data[self.list] + + def time_getitem_bool_array(self, index): + self.data[self.data == self.cat_scalar] diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 77e013e1e4fb0..739ad6a3d278b 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -3,7 +3,8 @@ import numpy as np import pandas.util.testing as tm from pandas import (Series, DataFrame, MultiIndex, Int64Index, Float64Index, - IntervalIndex, IndexSlice, concat, date_range) + IntervalIndex, CategoricalIndex, + IndexSlice, concat, date_range) from .pandas_vb_common import setup, Panel # noqa @@ -230,6 +231,49 @@ def time_loc_list(self, monotonic): monotonic.loc[80000:] +class CategoricalIndexIndexing(object): + + goal_time = 0.2 + params = ['monotonic_incr', 'monotonic_decr', 'non_monotonic'] + param_names = ['index'] + + def setup(self, index): + N = 10**5 + values = list('a' * N + 'b' * N + 'c' * N) + indices = { + 'monotonic_incr': CategoricalIndex(values), + 'monotonic_decr': CategoricalIndex(reversed(values)), + 'non_monotonic': CategoricalIndex(list('abc' * N))} + self.data = indices[index] + + self.int_scalar = 10000 + self.int_list = list(range(10000)) + + self.cat_scalar = 'b' + self.cat_list = ['a', 'c'] + + def time_getitem_scalar(self, index): + self.data[self.int_scalar] + + def time_getitem_slice(self, index): + self.data[:self.int_scalar] + + def time_getitem_list_like(self, index): + self.data[[self.int_scalar]] + + def time_getitem_list(self, index): + self.data[self.int_list] + + def time_getitem_bool_array(self, index): + self.data[self.data == self.cat_scalar] + + def time_get_loc_scalar(self, index): + self.data.get_loc(self.cat_scalar) + + def time_get_indexer_list(self, index): + self.data.get_indexer(self.cat_list) + + class PanelIndexing(object): goal_time = 0.2 diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 406ca9ba045c9..14d9c03b477ed 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -134,6 +134,9 @@ Removal of prior version deprecations/changes Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ +- Very large improvement in performance of slicing when the index is a :class:`CategoricalIndex`, + both when indexing by label (using .loc) and position(.iloc). + Likewise, slicing a ``CategoricalIndex`` itself (i.e. ``ci[100:200]``) shows similar speed improvements (:issue:`21659`) - Improved performance of :func:`Series.describe` in case of numeric dtpyes (:issue:`21274`) - Improved performance of :func:`pandas.core.groupby.GroupBy.rank` when dealing with tied rankings (:issue:`21237`) - Improved performance of :func:`DataFrame.set_index` with columns consisting of :class:`Period` objects (:issue:`21582`,:issue:`21606`) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 7b3cce0f2585d..0252b5b52ae94 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2009,8 +2009,7 @@ def __getitem__(self, key): return self.categories[i] else: return self._constructor(values=self._codes[key], - categories=self.categories, - ordered=self.ordered, fastpath=True) + dtype=self.dtype, fastpath=True) def __setitem__(self, key, value): """ Item assignment. diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 708f54f5ca75b..1e762c2be92a6 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -184,18 +184,20 @@ def __eq__(self, other): """ Rules for CDT equality: 1) Any CDT is equal to the string 'category' - 2) Any CDT is equal to a CDT with categories=None regardless of ordered - 3) A CDT with ordered=True is only equal to another CDT with + 2) Any CDT is equal to itself + 3) Any CDT is equal to a CDT with categories=None regardless of ordered + 4) A CDT with ordered=True is only equal to another CDT with ordered=True and identical categories in the same order - 4) A CDT with ordered={False, None} is only equal to another CDT with + 5) A CDT with ordered={False, None} is only equal to another CDT with ordered={False, None} and identical categories, but same order is not required. There is no distinction between False/None. - 5) Any other comparison returns False + 6) Any other comparison returns False """ if isinstance(other, compat.string_types): return other == self.name - - if not (hasattr(other, 'ordered') and hasattr(other, 'categories')): + elif other is self: + return True + elif not (hasattr(other, 'ordered') and hasattr(other, 'categories')): return False elif self.categories is None or other.categories is None: # We're forced into a suboptimal corner thanks to math and @@ -348,6 +350,8 @@ def update_dtype(self, dtype): msg = ('a CategoricalDtype must be passed to perform an update, ' 'got {dtype!r}').format(dtype=dtype) raise ValueError(msg) + elif dtype.categories is not None and dtype.ordered is self.ordered: + return dtype # dtype is CDT: keep current categories/ordered if None new_categories = dtype.categories diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index a2efe2c49c747..8472d5fd49bd9 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -169,7 +169,7 @@ def _create_categorical(cls, data, categories=None, ordered=None, data = data.set_categories(categories, ordered=ordered) elif ordered is not None and ordered != data.ordered: data = data.set_ordered(ordered) - if isinstance(dtype, CategoricalDtype): + if isinstance(dtype, CategoricalDtype) and dtype != data.dtype: # we want to silently ignore dtype='category' data = data._set_dtype(dtype) return data @@ -236,7 +236,7 @@ def _is_dtype_compat(self, other): if not is_list_like(values): values = [values] other = CategoricalIndex(self._create_categorical( - other, categories=self.categories, ordered=self.ordered)) + other, dtype=self.dtype)) if not other.isin(values).all(): raise TypeError("cannot append a non-category item to a " "CategoricalIndex") @@ -798,8 +798,7 @@ def _evaluate_compare(self, other): other = other._values elif isinstance(other, Index): other = self._create_categorical( - other._values, categories=self.categories, - ordered=self.ordered) + other._values, dtype=self.dtype) if isinstance(other, (ABCCategorical, np.ndarray, ABCSeries)):
- [x] progress towards #20395 - [x] ASVs added - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Currently, a lot of indexing/slicing ops on CategoricalIndexes goes through ``CategoricalIndex._create_categorical``, which can be a slow operation, because calling ``data._set_dtype`` there is slow. This PR improves performance by avoiding calling ``data._set_dtype`` as often, specifically when the new and the old dtypes are equal. An complicating issue was that comparisons of ``CategoricalDtype`` was quite slow, so the improvements I saw in #20395 were offset by slowdowns in other places. To avoid this, ``CategoricalDtype.__equal__`` needed to become smarter and pandas has to pass round existing dtypes rather than only ``categories`` and ``ordered``. This is ok, as CategoricalDtype is immutable. This minimizes the need to call the expensive ``CategoricalDtype.__hash__`` method in ``CategoricalDtype.__equal__`` and makes comparisons much faster. ### Some notable results First setup: ```python >>> n = 100_000 >>> c = pd.Categorical(list('a' * n + 'b' * n + 'c' * n)) >>> ci = pd.CategoricalIndex(c) >>> df = pd.DataFrame({'A': range(n * 3)}, index=ci) >>> sl = slice(n, n * 2) ``` Results: ```python >>> %timeit c[sl] 13.9 µs # master 4.43 µs # this PR >>> %timeit ci[sl] 740 µs # master 12.7 µs # this PR >>> %timeit df.iloc[sl] 855 µs # master 72.2 µs # this PR >>> %timeit df.loc['b'] 3.23 ms # master 1.62 ms # this PR ``` ### Benchmarks benchmarks/indexing.py: ``` before after ratio [36422a88] [e0c62df0] + 53.4±0μs 61.1±0μs 1.14 indexing.NumericSeriesIndexing.time_iloc_slice(<class 'pandas.core.indexes.numeric.Int64Index'>) - 477±4ms 414±4ms 0.87 indexing.CategoricalIndexIndexing.time_get_indexer_list('monotonic_incr') - 476±40ns 381±20ns 0.80 indexing.MethodLookup.time_lookup_iloc - 1.23±0.2ms 367±0μs 0.30 indexing.CategoricalIndexIndexing.time_getitem_bool_array('monotonic_decr') - 1.29±0.2ms 344±5μs 0.27 indexing.CategoricalIndexIndexing.time_getitem_bool_array('monotonic_incr') - 115±8μs 19.5±2μs 0.17 indexing.CategoricalIndexIndexing.time_getitem_list_like('monotonic_decr') - 122±2μs 19.5±0μs 0.16 indexing.CategoricalIndexIndexing.time_getitem_list_like('non_monotonic') - 125±8μs 19.8±2μs 0.16 indexing.CategoricalIndexIndexing.time_getitem_list_like('monotonic_incr') - 121±2μs 13.4±0μs 0.11 indexing.CategoricalIndexIndexing.time_getitem_slice('non_monotonic') - 129±2μs 12.5±0μs 0.10 indexing.CategoricalIndexIndexing.time_getitem_slice('monotonic_incr') - 195±20μs 13.4±0.2μs 0.07 indexing.CategoricalIndexIndexing.time_getitem_slice('monotonic_decr') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. ``` benchmarks/categoricals.py: ``` before after ratio [a620e725] [04667f67] + 10.4±0ms 11.7±0.5ms 1.12 categoricals.Concat.time_union + 3.42μs 3.76μs 1.10 categoricals.CategoricalSlicing.time_getitem_scalar('non_monotonic') - 3.66μs 3.20μs 0.87 categoricals.CategoricalSlicing.time_getitem_scalar('monotonic_incr') - 20.8±0.7ms 13.9±0ms 0.67 categoricals.ValueCounts.time_value_counts(False) - 23.4±0ms 12.2±0ms 0.52 categoricals.ValueCounts.time_value_counts(True) - 13.3μs 5.86μs 0.44 categoricals.CategoricalSlicing.time_getitem_slice('monotonic_decr') - 13.3μs 4.88μs 0.37 categoricals.CategoricalSlicing.time_getitem_slice('non_monotonic') - 17.1μs 6.12μs 0.36 categoricals.CategoricalSlicing.time_getitem_list_like('monotonic_incr') - 17.1μs 6.11μs 0.36 categoricals.CategoricalSlicing.time_getitem_list_like('non_monotonic') - 15.5μs 4.39μs 0.28 categoricals.CategoricalSlicing.time_getitem_slice('monotonic_incr') - 22.0μs 6.11μs 0.28 categoricals.CategoricalSlicing.time_getitem_list_like('monotonic_decr') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. ``` I haven't run the whole test suite, as that takes a long time (4-5 hours?) for me. Would appreciate input first and, if I need to run the whole suite, if there is a smarter way to do it.
https://api.github.com/repos/pandas-dev/pandas/pulls/21659
2018-06-27T20:09:49Z
2018-06-29T00:36:06Z
2018-06-29T00:36:06Z
2018-07-24T23:50:41Z
BUG: fix reindexing MultiIndex with categorical datetime-like level
diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index 987f171878d0b..c9b6fa6827367 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -55,6 +55,8 @@ Fixed Regressions - Fixed regression in :meth:`to_csv` when handling file-like object incorrectly (:issue:`21471`) - Re-allowed duplicate level names of a ``MultiIndex``. Accessing a level that has a duplicate name by name still raises an error (:issue:`19029`). - Bug in both :meth:`DataFrame.first_valid_index` and :meth:`Series.first_valid_index` raised for a row index having duplicate values (:issue:`21441`) +- Fixed regression in :meth:`~DataFrame.reindex` and :meth:`~DataFrame.groupby` + with a MultiIndex or multiple keys that contains categorical datetime-like values (:issue:`21390`). - Fixed regression in unary negative operations with object dtype (:issue:`21380`) - Bug in :meth:`Timestamp.ceil` and :meth:`Timestamp.floor` when timestamp is a multiple of the rounding frequency (:issue:`21262`) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index a2322348e1caa..ab1a5783a4045 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -11,6 +11,8 @@ from pandas.compat.numpy import function as nv from pandas import compat +from pandas.core.dtypes.dtypes import ( + ExtensionDtype, PandasExtensionDtype) from pandas.core.dtypes.common import ( _ensure_int64, _ensure_platform_int, @@ -807,20 +809,16 @@ def values(self): return self._tuples values = [] - for lev, lab in zip(self.levels, self.labels): - # Need to box timestamps, etc. - box = hasattr(lev, '_box_values') - # Try to minimize boxing. - if box and len(lev) > len(lab): - taken = lev._box_values(algos.take_1d(lev._ndarray_values, - lab)) - elif box: - taken = algos.take_1d(lev._box_values(lev._ndarray_values), - lab, - fill_value=lev._na_value) - else: - taken = algos.take_1d(np.asarray(lev._values), lab) - values.append(taken) + + for i in range(self.nlevels): + vals = self._get_level_values(i) + if is_categorical_dtype(vals): + vals = vals.get_values() + if (isinstance(vals.dtype, (PandasExtensionDtype, ExtensionDtype)) + or hasattr(vals, '_box_values')): + vals = vals.astype(object) + vals = np.array(vals, copy=False) + values.append(vals) self._tuples = lib.fast_zip(values) return self._tuples diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 0e0d6598f5101..004fb4eb0c128 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -10,7 +10,7 @@ import numpy as np from pandas.compat import lrange, lzip, u -from pandas import (compat, DataFrame, Series, Index, MultiIndex, +from pandas import (compat, DataFrame, Series, Index, MultiIndex, Categorical, date_range, isna) import pandas as pd @@ -1129,6 +1129,19 @@ def test_reindex_multi(self): assert_frame_equal(result, expected) + def test_reindex_multi_categorical_time(self): + # https://github.com/pandas-dev/pandas/issues/21390 + midx = pd.MultiIndex.from_product( + [Categorical(['a', 'b', 'c']), + Categorical(date_range("2012-01-01", periods=3, freq='H'))]) + df = pd.DataFrame({'a': range(len(midx))}, index=midx) + df2 = df.iloc[[0, 1, 2, 3, 4, 5, 6, 8]] + + result = df2.reindex(midx) + expected = pd.DataFrame( + {'a': [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx) + assert_frame_equal(result, expected) + data = [[1, 2, 3], [1, 2, 3]] @pytest.mark.parametrize('actual', [ diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index cb76195eacf40..d021396a7acb3 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -850,3 +850,23 @@ def test_empty_prod(): result = df.groupby("A", observed=False).B.prod(min_count=1) expected = pd.Series([2, 1, np.nan], expected_idx, name='B') tm.assert_series_equal(result, expected) + + +def test_groupby_multiindex_categorical_datetime(): + # https://github.com/pandas-dev/pandas/issues/21390 + + df = pd.DataFrame({ + 'key1': pd.Categorical(list('abcbabcba')), + 'key2': pd.Categorical( + list(pd.date_range('2018-06-01 00', freq='1T', periods=3)) * 3), + 'values': np.arange(9), + }) + result = df.groupby(['key1', 'key2']).mean() + + idx = pd.MultiIndex.from_product( + [pd.Categorical(['a', 'b', 'c']), + pd.Categorical(pd.date_range('2018-06-01 00', freq='1T', periods=3))], + names=['key1', 'key2']) + expected = pd.DataFrame( + {'values': [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx) + assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 1dc44677ab3ad..b1fb5f01862ae 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -12,8 +12,8 @@ import pandas as pd -from pandas import (CategoricalIndex, DataFrame, Index, MultiIndex, - compat, date_range, period_range) +from pandas import (CategoricalIndex, Categorical, DataFrame, Index, + MultiIndex, compat, date_range, period_range) from pandas.compat import PY3, long, lrange, lzip, range, u, PYPY from pandas.errors import PerformanceWarning, UnsortedIndexError from pandas.core.dtypes.dtypes import CategoricalDtype @@ -1596,6 +1596,14 @@ def test_get_indexer_nearest(self): with pytest.raises(NotImplementedError): midx.get_indexer(['a'], method='pad', tolerance=2) + def test_get_indexer_categorical_time(self): + # https://github.com/pandas-dev/pandas/issues/21390 + midx = MultiIndex.from_product( + [Categorical(['a', 'b', 'c']), + Categorical(date_range("2012-01-01", periods=3, freq='H'))]) + result = midx.get_indexer(midx) + tm.assert_numpy_array_equal(result, np.arange(9, dtype=np.intp)) + def test_hash_collisions(self): # non-smoke test that we don't get hash collisions
closes #21390 This fixes the bug, but is not really a general solution. However, I would like to keep that for another PR (won't have time for this before 0.23.2), also because the underlying reason is more widely present than in just the MultiIndex.values (will open a separate issue about this -> https://github.com/pandas-dev/pandas/issues/21658). I added some tests of the bug at several levels where it surfaces (groupby, reindex, index.get_indexer)
https://api.github.com/repos/pandas-dev/pandas/pulls/21657
2018-06-27T15:46:20Z
2018-07-02T15:26:44Z
2018-07-02T15:26:44Z
2018-07-02T15:44:50Z
BUG: Fix MI repr with long names
diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index 70443f999ba31..69a1100b161b4 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -55,6 +55,7 @@ Fixed Regressions - Fixed regression in :meth:`to_csv` when handling file-like object incorrectly (:issue:`21471`) - Re-allowed duplicate level names of a ``MultiIndex``. Accessing a level that has a duplicate name by name still raises an error (:issue:`19029`). - Bug in both :meth:`DataFrame.first_valid_index` and :meth:`Series.first_valid_index` raised for a row index having duplicate values (:issue:`21441`) +- Fixed printing of DataFrames with hierarchical columns with long names (:issue:`21180`) - Fixed regression in :meth:`~DataFrame.reindex` and :meth:`~DataFrame.groupby` with a MultiIndex or multiple keys that contains categorical datetime-like values (:issue:`21390`). - Fixed regression in unary negative operations with object dtype (:issue:`21380`) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 12201f62946ac..c46f4b5ad9c18 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -636,10 +636,14 @@ def to_string(self): mid = int(round(n_cols / 2.)) mid_ix = col_lens.index[mid] col_len = col_lens[mid_ix] - adj_dif -= (col_len + 1) # adjoin adds one + # adjoin adds one + adj_dif -= (col_len + 1) col_lens = col_lens.drop(mid_ix) n_cols = len(col_lens) - max_cols_adj = n_cols - self.index # subtract index column + # subtract index column + max_cols_adj = n_cols - self.index + # GH-21180. Ensure that we print at least two. + max_cols_adj = max(max_cols_adj, 2) self.max_cols_adj = max_cols_adj # Call again _chk_truncate to cut frame appropriately @@ -778,7 +782,7 @@ def space_format(x, y): str_columns = list(zip(*[[space_format(x, y) for y in x] for x in fmt_columns])) - if self.sparsify: + if self.sparsify and len(str_columns): str_columns = _sparsify(str_columns) str_columns = [list(x) for x in zip(*str_columns)] diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 63b7cb3459069..191e3f37f1c37 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -305,6 +305,44 @@ def test_repr_non_interactive(self): assert not has_truncated_repr(df) assert not has_expanded_repr(df) + def test_repr_truncates_terminal_size(self): + # https://github.com/pandas-dev/pandas/issues/21180 + # TODO: use mock fixutre. + # This is being backported, so doing it directly here. + try: + from unittest import mock + except ImportError: + mock = pytest.importorskip("mock") + + terminal_size = (118, 96) + p1 = mock.patch('pandas.io.formats.console.get_terminal_size', + return_value=terminal_size) + p2 = mock.patch('pandas.io.formats.format.get_terminal_size', + return_value=terminal_size) + + index = range(5) + columns = pd.MultiIndex.from_tuples([ + ('This is a long title with > 37 chars.', 'cat'), + ('This is a loooooonger title with > 43 chars.', 'dog'), + ]) + df = pd.DataFrame(1, index=index, columns=columns) + + with p1, p2: + result = repr(df) + + h1, h2 = result.split('\n')[:2] + assert 'long' in h1 + assert 'loooooonger' in h1 + assert 'cat' in h2 + assert 'dog' in h2 + + # regular columns + df2 = pd.DataFrame({"A" * 41: [1, 2], 'B' * 41: [1, 2]}) + with p1, p2: + result = repr(df2) + + assert df2.columns[0] in result.split('\n')[0] + def test_repr_max_columns_max_rows(self): term_width, term_height = get_terminal_size() if term_width < 10 or term_height < 10:
Closes #21180 ```python In [4]: try: ...: from unittest import mock ...: except ImportError: ...: mock = pytest.importorskip("mock") ...: ...: terminal_size = os.terminal_size((118, 96)) ...: p1 = mock.patch('pandas.io.formats.console.get_terminal_size', ...: return_value=terminal_size) ...: p2 = mock.patch('pandas.io.formats.format.get_terminal_size', ...: return_value=terminal_size) ...: ...: index = range(5) ...: columns = pd.MultiIndex.from_tuples([ ...: ('This is a long title with > 37 chars.', 'cat'), ...: ('This is a loooooonger title with > 43 chars.', 'dog'), ...: ]) ...: df = pd.DataFrame(1, index=index, columns=columns) ...: ...: In [5]: with p1, p2: ...: print('-' * 80) ...: print(repr(df)) ...: print('-' * 80) ...: ``` output: ``` -------------------------------------------------------------------------------- ... ... 0 ... 1 ... 2 ... 3 ... 4 ... [5 rows x 2 columns] -------------------------------------------------------------------------------- ``` This matches the repr for non-hierarchical ```python In [6]: s = pd.DataFrame({"A" * 41: [1, 2], 'B' * 41: [1, 2]}) In [7]: with p1, p2: ...: print('-' * 80) ...: print(repr(s)) ...: print('-' * 80) ...: ``` output: ``` -------------------------------------------------------------------------------- ... 0 ... 1 ... [2 rows x 2 columns] -------------------------------------------------------------------------------- ``` These can certainly be improved, though I'm not sure we'll (I'll) get to it for 0.23.2.
https://api.github.com/repos/pandas-dev/pandas/pulls/21655
2018-06-27T13:40:08Z
2018-07-02T15:28:20Z
2018-07-02T15:28:19Z
2018-07-02T15:45:26Z
DOC: update DataFrame.dropna's axis argument docs
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b553cfdc72c92..42a68de52a3c4 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4186,6 +4186,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None, .. deprecated:: 0.23.0 Pass tuple or list to drop on multiple axes. + Only a single axis is allowed. how : {'any', 'all'}, default 'any' Determine if row or column is removed from DataFrame, when we have
Make `DataFrame.dropna`'s axis argument type deprecated warning in documentation easier to understand.
https://api.github.com/repos/pandas-dev/pandas/pulls/21652
2018-06-27T10:07:34Z
2018-06-27T12:00:00Z
2018-06-27T12:00:00Z
2018-06-27T12:00:04Z
ENH: Allow keep='all' for nlargest/nsmallest
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 12e4824b2dd2a..1819cfa2725db 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -501,7 +501,7 @@ def time_info(self): class NSort(object): goal_time = 0.2 - params = ['first', 'last'] + params = ['first', 'last', 'all'] param_names = ['keep'] def setup(self, keep): diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 3f6522c3403d9..a5ccf5c32b876 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -41,7 +41,7 @@ def time_isin(self, dtypes): class NSort(object): goal_time = 0.2 - params = ['last', 'first'] + params = ['first', 'last', 'all'] param_names = ['keep'] def setup(self, keep): diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1105acda067d3..1ab67bd80a5e8 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -24,6 +24,7 @@ Other Enhancements <https://pandas-gbq.readthedocs.io/en/latest/changelog.html#changelog-0-5-0>`__. (:issue:`21627`) - New method :meth:`HDFStore.walk` will recursively walk the group hierarchy of an HDF5 file (:issue:`10932`) +- :meth:`Series.nlargest`, :meth:`Series.nsmallest`, :meth:`DataFrame.nlargest`, and :meth:`DataFrame.nsmallest` now accept the value ``"all"`` for the ``keep` argument. This keeps all ties for the nth largest/smallest value (:issue:`16818`) - .. _whatsnew_0240.api_breaking: diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 9e34b8eb55ccb..dc726a736d34f 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1076,8 +1076,8 @@ def __init__(self, obj, n, keep): self.n = n self.keep = keep - if self.keep not in ('first', 'last'): - raise ValueError('keep must be either "first", "last"') + if self.keep not in ('first', 'last', 'all'): + raise ValueError('keep must be either "first", "last" or "all"') def nlargest(self): return self.compute('nlargest') @@ -1148,7 +1148,11 @@ def compute(self, method): kth_val = algos.kth_smallest(arr.copy(), n - 1) ns, = np.nonzero(arr <= kth_val) - inds = ns[arr[ns].argsort(kind='mergesort')][:n] + inds = ns[arr[ns].argsort(kind='mergesort')] + + if self.keep != 'all': + inds = inds[:n] + if self.keep == 'last': # reverse indices inds = narr - 1 - inds diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 42a68de52a3c4..a420266561c5a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4559,11 +4559,15 @@ def nlargest(self, n, columns, keep='first'): Number of rows to return. columns : label or list of labels Column label(s) to order by. - keep : {'first', 'last'}, default 'first' + keep : {'first', 'last', 'all'}, default 'first' Where there are duplicate values: - `first` : prioritize the first occurrence(s) - `last` : prioritize the last occurrence(s) + - ``all`` : do not drop any duplicates, even it means + selecting more than `n` items. + + .. versionadded:: 0.24.0 Returns ------- @@ -4586,47 +4590,58 @@ def nlargest(self, n, columns, keep='first'): Examples -------- - >>> df = pd.DataFrame({'a': [1, 10, 8, 10, -1], - ... 'b': list('abdce'), - ... 'c': [1.0, 2.0, np.nan, 3.0, 4.0]}) + >>> df = pd.DataFrame({'a': [1, 10, 8, 11, 8, 2], + ... 'b': list('abdcef'), + ... 'c': [1.0, 2.0, np.nan, 3.0, 4.0, 9.0]}) >>> df a b c 0 1 a 1.0 1 10 b 2.0 2 8 d NaN - 3 10 c 3.0 - 4 -1 e 4.0 + 3 11 c 3.0 + 4 8 e 4.0 + 5 2 f 9.0 In the following example, we will use ``nlargest`` to select the three rows having the largest values in column "a". >>> df.nlargest(3, 'a') a b c + 3 11 c 3.0 1 10 b 2.0 - 3 10 c 3.0 2 8 d NaN When using ``keep='last'``, ties are resolved in reverse order: >>> df.nlargest(3, 'a', keep='last') a b c - 3 10 c 3.0 + 3 11 c 3.0 + 1 10 b 2.0 + 4 8 e 4.0 + + When using ``keep='all'``, all duplicate items are maintained: + + >>> df.nlargest(3, 'a', keep='all') + a b c + 3 11 c 3.0 1 10 b 2.0 2 8 d NaN + 4 8 e 4.0 To order by the largest values in column "a" and then "c", we can specify multiple columns like in the next example. >>> df.nlargest(3, ['a', 'c']) a b c - 3 10 c 3.0 + 4 8 e 4.0 + 3 11 c 3.0 1 10 b 2.0 - 2 8 d NaN Attempting to use ``nlargest`` on non-numeric dtypes will raise a ``TypeError``: >>> df.nlargest(3, 'b') + Traceback (most recent call last): TypeError: Column 'b' has dtype object, cannot use method 'nlargest' """ @@ -4645,10 +4660,14 @@ def nsmallest(self, n, columns, keep='first'): Number of items to retrieve columns : list or str Column name or names to order by - keep : {'first', 'last'}, default 'first' + keep : {'first', 'last', 'all'}, default 'first' Where there are duplicate values: - ``first`` : take the first occurrence. - ``last`` : take the last occurrence. + - ``all`` : do not drop any duplicates, even it means + selecting more than `n` items. + + .. versionadded:: 0.24.0 Returns ------- @@ -4656,14 +4675,60 @@ def nsmallest(self, n, columns, keep='first'): Examples -------- - >>> df = pd.DataFrame({'a': [1, 10, 8, 11, -1], - ... 'b': list('abdce'), - ... 'c': [1.0, 2.0, np.nan, 3.0, 4.0]}) + >>> df = pd.DataFrame({'a': [1, 10, 8, 11, 8, 2], + ... 'b': list('abdcef'), + ... 'c': [1.0, 2.0, np.nan, 3.0, 4.0, 9.0]}) + >>> df + a b c + 0 1 a 1.0 + 1 10 b 2.0 + 2 8 d NaN + 3 11 c 3.0 + 4 8 e 4.0 + 5 2 f 9.0 + + In the following example, we will use ``nsmallest`` to select the + three rows having the smallest values in column "a". + >>> df.nsmallest(3, 'a') - a b c - 4 -1 e 4 - 0 1 a 1 - 2 8 d NaN + a b c + 0 1 a 1.0 + 5 2 f 9.0 + 2 8 d NaN + + When using ``keep='last'``, ties are resolved in reverse order: + + >>> df.nsmallest(3, 'a', keep='last') + a b c + 0 1 a 1.0 + 5 2 f 9.0 + 4 8 e 4.0 + + When using ``keep='all'``, all duplicate items are maintained: + + >>> df.nsmallest(3, 'a', keep='all') + a b c + 0 1 a 1.0 + 5 2 f 9.0 + 2 8 d NaN + 4 8 e 4.0 + + To order by the largest values in column "a" and then "c", we can + specify multiple columns like in the next example. + + >>> df.nsmallest(3, ['a', 'c']) + a b c + 0 1 a 1.0 + 5 2 f 9.0 + 4 8 e 4.0 + + Attempting to use ``nsmallest`` on non-numeric dtypes will raise a + ``TypeError``: + + >>> df.nsmallest(3, 'b') + + Traceback (most recent call last): + TypeError: Column 'b' has dtype object, cannot use method 'nsmallest' """ return algorithms.SelectNFrame(self, n=n, diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 84873659ac931..d357208813dd8 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -2461,6 +2461,22 @@ def test_n_duplicate_index(self, df_duplicates, n, order): expected = df.sort_values(order, ascending=False).head(n) tm.assert_frame_equal(result, expected) + def test_duplicate_keep_all_ties(self): + # see gh-16818 + df = pd.DataFrame({'a': [5, 4, 4, 2, 3, 3, 3, 3], + 'b': [10, 9, 8, 7, 5, 50, 10, 20]}) + result = df.nlargest(4, 'a', keep='all') + expected = pd.DataFrame({'a': {0: 5, 1: 4, 2: 4, 4: 3, + 5: 3, 6: 3, 7: 3}, + 'b': {0: 10, 1: 9, 2: 8, 4: 5, + 5: 50, 6: 10, 7: 20}}) + tm.assert_frame_equal(result, expected) + + result = df.nsmallest(2, 'a', keep='all') + expected = pd.DataFrame({'a': {3: 2, 4: 3, 5: 3, 6: 3, 7: 3}, + 'b': {3: 7, 4: 5, 5: 50, 6: 10, 7: 20}}) + tm.assert_frame_equal(result, expected) + def test_series_broadcasting(self): # smoke test for numpy warnings # GH 16378, GH 16306 diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 36342b5ba4ee1..fcfaff9b11002 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -2082,6 +2082,17 @@ def test_boundary_datetimelike(self, nselect_method, dtype): vals = [min_val + 1, min_val + 2, max_val - 1, max_val, min_val] assert_check_nselect_boundary(vals, dtype, nselect_method) + def test_duplicate_keep_all_ties(self): + # see gh-16818 + s = Series([10, 9, 8, 7, 7, 7, 7, 6]) + result = s.nlargest(4, keep='all') + expected = Series([10, 9, 8, 7, 7, 7, 7]) + assert_series_equal(result, expected) + + result = s.nsmallest(2, keep='all') + expected = Series([6, 7, 7, 7, 7], index=[7, 3, 4, 5, 6]) + assert_series_equal(result, expected) + class TestCategoricalSeriesAnalytics(object):
Title is self-explanatory. Closes #16818. Closes #18656.
https://api.github.com/repos/pandas-dev/pandas/pulls/21650
2018-06-27T07:14:39Z
2018-06-28T21:20:32Z
2018-06-28T21:20:32Z
2018-06-28T21:20:59Z
DOC: Fix versionadded directive typos in IntervalIndex
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index eb9d7efc06c27..23a655b9a51ee 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -160,7 +160,7 @@ class IntervalIndex(IntervalMixin, Index): dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Attributes ---------- @@ -438,7 +438,7 @@ def from_breaks(cls, breaks, closed='right', name=None, copy=False, dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples -------- @@ -568,7 +568,7 @@ def from_intervals(cls, data, closed=None, name=None, copy=False, dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples -------- @@ -619,7 +619,7 @@ def from_tuples(cls, data, closed='right', name=None, copy=False, dtype : dtype or None, default None If None, dtype will be inferred - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples -------- @@ -671,7 +671,7 @@ def to_tuples(self, na_tuple=True): Returns NA as a tuple if True, ``(nan, nan)``, or just as the NA value itself if False, ``nan``. - ..versionadded:: 0.23.0 + .. versionadded:: 0.23.0 Examples --------
There needs to be a space between the `..` and `versionadded::`. Currently being rendered as plaintext, which doesn't look too great: ![image](https://user-images.githubusercontent.com/5332445/41943354-50072132-7960-11e8-814e-5fd8ef559a86.png) Couldn't find any other instances of this in the codebase for `versionadded` or any other commonly used directives. Pretty minor so tagging this as 0.23.2.
https://api.github.com/repos/pandas-dev/pandas/pulls/21649
2018-06-27T00:12:10Z
2018-06-27T09:57:56Z
2018-06-27T09:57:56Z
2018-09-24T17:22:43Z
addresses GH #21646
diff --git a/pandas/conftest.py b/pandas/conftest.py index 82d860b091b82..5b9c162a0a022 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -153,8 +153,10 @@ def datapath(request): ValueError If the path doesn't exist and the --strict-data-files option is set. """ + BASE_PATH = os.path.join(os.path.dirname(__file__), 'tests') + def deco(*args): - path = os.path.join('pandas', 'tests', *args) + path = os.path.join(BASE_PATH, *args) if not os.path.exists(path): if request.config.getoption("--strict-data-files"): msg = "Could not find file {} and --strict-data-files is set." diff --git a/pandas/tests/util/test_testing.py b/pandas/tests/util/test_testing.py index 4d34987e14f75..95ea4658212e9 100644 --- a/pandas/tests/util/test_testing.py +++ b/pandas/tests/util/test_testing.py @@ -852,5 +852,10 @@ def test_datapath_missing(datapath, request): datapath('not_a_file') result = datapath('data', 'iris.csv') - expected = os.path.join('pandas', 'tests', 'data', 'iris.csv') + expected = os.path.join( + os.path.dirname(os.path.dirname(__file__)), + 'data', + 'iris.csv' + ) + assert result == expected
- [x] closes #21646 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21647
2018-06-26T22:40:02Z
2018-06-27T11:23:23Z
2018-06-27T11:23:23Z
2018-06-27T11:36:33Z
ENH: add return_inverse to duplicated for DataFrame/Series/Index/MultiIndex
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 1819cfa2725db..50789d64edda1 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -412,21 +412,35 @@ def time_frame_nunique(self): class Duplicated(object): goal_time = 0.2 + params = (['first', 'last', False], [True, False]) + param_names = ['keep', 'return_inverse'] + + def setup(self, keep, return_inverse): + if keep is False and return_inverse: + raise NotImplementedError - def setup(self): n = (1 << 20) t = date_range('2015-01-01', freq='S', periods=(n // 64)) xs = np.random.randn(n // 64).round(2) self.df = DataFrame({'a': np.random.randint(-1 << 8, 1 << 8, n), 'b': np.random.choice(t, n), 'c': np.random.choice(xs, n)}) - self.df2 = DataFrame(np.random.randn(1000, 100).astype(str)).T + # df2 will not have any duplicates + self.df2 = DataFrame(np.random.randn(100, 1000).astype(str)) + + df3 = DataFrame(np.random.randint(0, 10, (2 ** 18, 5)), + columns=list('ABCDE')) + df3.loc[:, 'F'] = Series('', index=df3.index).str.cat(df3.astype(str)) + self.df3 = df3 + + def time_frame_duplicated(self, keep, return_inverse): + self.df.duplicated(keep=keep, return_inverse=return_inverse) - def time_frame_duplicated(self): - self.df.duplicated() + def time_frame_duplicated_wide(self, keep, return_inverse): + self.df2.duplicated(keep=keep, return_inverse=return_inverse) - def time_frame_duplicated_wide(self): - self.df2.duplicated() + def time_frame_duplicated_mixed(self, keep, return_inverse): + self.df3.duplicated(keep=keep, return_inverse=return_inverse) class XS(object): diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py index f1703e163917a..a3a7f7f17d332 100644 --- a/asv_bench/benchmarks/index_object.py +++ b/asv_bench/benchmarks/index_object.py @@ -84,6 +84,24 @@ def time_modulo(self, dtype): self.index % 2 +class Duplicated(object): + + goal_time = 0.2 + params = (['first', 'last', False], [True, False]) + param_names = ['keep', 'return_inverse'] + + def setup(self, keep, return_inverse): + if keep is False and return_inverse: + raise NotImplementedError + + n, k = 200, 1000 + base = tm.makeStringIndex(n) + self.idx = Index(base[np.random.choice(n, k * n)]) + + def time_duplicated(self, keep, return_inverse): + self.idx.duplicated(keep=keep, return_inverse=return_inverse) + + class Range(object): goal_time = 0.2 diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py index 0c92214795557..ac73c2d9c72dc 100644 --- a/asv_bench/benchmarks/multiindex_object.py +++ b/asv_bench/benchmarks/multiindex_object.py @@ -83,17 +83,22 @@ def time_is_monotonic(self): class Duplicated(object): goal_time = 0.2 + params = (['first', 'last', False], [True, False]) + param_names = ['keep', 'return_inverse'] - def setup(self): - n, k = 200, 5000 + def setup(self, keep, return_inverse): + if keep is False and return_inverse: + raise NotImplementedError + + n, k = 200, 1000 levels = [np.arange(n), tm.makeStringIndex(n).values, 1000 + np.arange(n)] labels = [np.random.choice(n, (k * n)) for lev in levels] self.mi = MultiIndex(levels=levels, labels=labels) - def time_duplicated(self): - self.mi.duplicated() + def time_duplicated(self, keep, return_inverse): + self.mi.duplicated(keep=keep, return_inverse=return_inverse) class Sortlevel(object): diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index a26c5d89bc483..cc08355b61e88 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -192,3 +192,21 @@ def setup(self): def time_series_datetimeindex_repr(self): getattr(self.s, 'a', None) + + +class Duplicated(object): + + goal_time = 0.2 + params = (['first', 'last', False], [True, False]) + param_names = ['keep', 'return_inverse'] + + def setup(self, keep, return_inverse): + if keep is False and return_inverse: + raise NotImplementedError + + n, k = 200, 1000 + base = tm.makeStringIndex(n) + self.s = Series(base[np.random.choice(n, k * n)]) + + def time_series_duplicated(self, keep, return_inverse): + self.s.duplicated(keep=keep, return_inverse=return_inverse) diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 618d7454c67fe..c477c66604993 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -163,6 +163,52 @@ This is the same behavior as ``Series.values`` for categorical data. See :ref:`whatsnew_0240.api_breaking.interval_values` for more. +.. _whatsnew_0240.enhancements.duplicated_inverse: + +The `duplicated`-method has gained the `return_inverse` kwarg +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :meth:`~DataFrame.duplicated`-method for ``Series``, ``DataFrame`` and all flavors of ``Index`` has gained a ``return_inverse`` keyword, +which is ``False`` by default. Specifying ``return_inverse=True`` will add an object to the output (which therefore becomes a tuple) +that allows reconstructing the original object from the deduplicated, unique subset (:issue:`21357`). + +For ``Index`` objects, the inverse is an ``np.ndarray``: + +.. ipython:: python + + idx = pd.Index(['a', 'b', 'b', 'c', 'a']) + isduplicate, inverse = idx.duplicated(return_inverse=True) # default: keep='first' + isduplicate + inverse + +This allows to reconstruct the original ``Index`` as follows: + +.. ipython:: python + + unique = idx[~isduplicate] # same as idx.drop_duplicates() + unique + + reconstruct = unique[inverse] + reconstruct.equals(idx) + +For ``DataFrame`` and ``Series`` the inverse needs to take into account the original index as well, and is therefore a ``Series``, +which contains the mapping from the index of the deduplicated, unique subset back to the original index. + +.. ipython:: python + + df = pd.DataFrame({'A': [0, 1, 1, 2, 0], 'B': ['a', 'b', 'b', 'c', 'a']}, + index=[1, 4, 9, 16, 25]) + df + isduplicate, inverse = df.duplicated(keep='last', return_inverse=True) + isduplicate + inverse + + unique = df.loc[~isduplicate] # same as df.drop_duplicates(keep='last') + unique + reconstruct = unique.reindex(inverse.values).set_index(inverse.index) + reconstruct.equals(df) + + .. _whatsnew_0240.enhancements.other: Other Enhancements diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index d39e9e08e2947..4c8dbb8dafdb2 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -771,7 +771,7 @@ def _value_counts_arraylike(values, dropna): return keys, counts -def duplicated(values, keep='first'): +def duplicated(values, keep='first', return_inverse=False): """ Return boolean ndarray denoting duplicate values. @@ -786,16 +786,69 @@ def duplicated(values, keep='first'): occurrence. - ``last`` : Mark duplicates as ``True`` except for the last occurrence. - - False : Mark all duplicates as ``True``. + - False : Mark all duplicates as ``True``. This option is not + compatible with ``return_inverse``. + return_inverse : boolean, default False + If True, also return the selection of (integer) indices from the array + of unique values (created e.g. by selecting the boolean complement of + the first output, or by using `.drop_duplicates` with the same + `keep`-parameter) that can be used to reconstruct "values". + + .. versionadded:: 0.24.0 Returns ------- - duplicated : ndarray + duplicated : ndarray or tuple of ndarray if ``return_inverse`` is True """ + if return_inverse and keep is False: + raise ValueError("The parameters return_inverse=True and " + "keep=False cannot be used together (impossible " + "to calculate an inverse when discarding all " + "instances of a duplicate).") + values, dtype, ndtype = _ensure_data(values) f = getattr(htable, "duplicated_{dtype}".format(dtype=ndtype)) - return f(values, keep=keep) + isduplicate = f(values, keep=keep) + if not return_inverse: + return isduplicate + elif not isduplicate.any(): + # no need to calculate inverse if no duplicates + inverse = np.arange(len(values)) + return isduplicate, inverse + + if keep == 'first': + # values2unique: original indices to indices of ARRAY of unique values + # unique2values: reduplication from array of uniques to original array + # this fits together in the way that values[values2unique] are the + # unique values and values[values2unique][unique2values] == values + _, values2unique, unique2values = np.unique(values, return_index=True, + return_inverse=True) + elif keep == 'last': + # np.unique takes first occurrence per unique value, + # so we flip values that first becomes last + values = values[::-1] + _, values2unique, unique2values = np.unique(values, return_index=True, + return_inverse=True) + # the values in "values" correspond(ed) to the index of "values", + # which is simply np.arange(len(values)). + # By flipping "values" around, we need to do the same for the index, + # _because values2unique and unique2values are relative to that order_. + # Finally, to fit with the original order again, we need to flip the + # result around one last time. + values2unique = np.arange(len(values))[::-1][values2unique] + unique2values = unique2values[::-1] + + # np.unique yields a ___sorted___ list of uniques, and values2unique resp. + # unique2values are relative to this order. To restore the original order, + # we argsort values2unique, because values2unique would be ordered if + # np.unique had not sorted implicitly. + # The first argsort gives the permutation from values2unique to its sorted + # form, but we need the inverse permutation (the map from the unsorted + # uniques to values2unique, from which we can continue with unique2values). + # This inversion (as a permutation) is achieved by the second argsort. + inverse = np.argsort(np.argsort(values2unique))[unique2values] + return isduplicate, inverse def mode(values, dropna=True): diff --git a/pandas/core/base.py b/pandas/core/base.py index 26fea89b45ae1..e9ae6004be5a0 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1259,16 +1259,40 @@ def drop_duplicates(self, keep='first', inplace=False): else: return result - def duplicated(self, keep='first'): + def duplicated(self, keep='first', return_inverse=False): from pandas.core.algorithms import duplicated + + if return_inverse and keep is False: + raise ValueError("The parameters return_inverse=True and " + "keep=False cannot be used together (impossible " + "to calculate an inverse when discarding all " + "instances of a duplicate).") + if isinstance(self, ABCIndexClass): if self.is_unique: - return np.zeros(len(self), dtype=np.bool) - return duplicated(self, keep=keep) - else: + isduplicate = np.zeros(len(self), dtype=np.bool) + if not return_inverse: + return isduplicate + return isduplicate, np.arange(len(self)) + # core.algorithms.duplicated has the same output signature as + # Index.duplicated -> no need to distinguish cases here + return duplicated(self, keep=keep, return_inverse=return_inverse) + + # Series case + if not return_inverse: return self._constructor(duplicated(self, keep=keep), index=self.index).__finalize__(self) + # return_inverse = True + isduplicate_array, inverse_array = duplicated(self, keep=keep, + return_inverse=True) + isduplicate = self._constructor(isduplicate_array, + index=self.index).__finalize__(self) + inverse = self._constructor( + self.loc[~isduplicate_array].index[inverse_array], + index=self.index) + return isduplicate, inverse + # ---------------------------------------------------------------------- # abstracts diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 81d5c112885ec..d4ff421d4793a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4384,7 +4384,7 @@ def drop_duplicates(self, subset=None, keep='first', inplace=False): else: return self[-duplicated] - def duplicated(self, subset=None, keep='first'): + def duplicated(self, subset=None, keep='first', return_inverse=False): """ Return boolean Series denoting duplicate rows, optionally only considering certain columns @@ -4399,14 +4399,156 @@ def duplicated(self, subset=None, keep='first'): first occurrence. - ``last`` : Mark duplicates as ``True`` except for the last occurrence. - - False : Mark all duplicates as ``True``. + - False : Mark all duplicates as ``True``. This option is not + compatible with ``return_inverse``. + return_inverse : boolean, default False + If True, also return a Series mapping the index of the current + DataFrame to the index after deduplication (created e.g. by using + `.drop_duplicates` or by selecting everything that is not + duplicate). This allows to reconstruct the original DataFrame from + the subset of deduplicated (=unique) values, see example below. + + .. versionadded:: 0.24.0 Returns ------- - duplicated : Series + duplicated : Series or tuple of Series if return_inverse is True + + Notes + ----- + The `return_inverse`-keyword works as expected for + ``keep='first'|'last'``, but cannot be used together with + ``keep=False`` (since discarding all duplicates makes it impossible to + construct an inverse). + + Examples + -------- + By default, for each set of duplicated values, the first occurrence is + set on False and all others on True: + + >>> data = {'species': ['lama', 'cow', 'lama', 'ant', 'lama', 'bee'], + ... 'type': ['mammal'] * 3 + ['insect', 'mammal', 'insect']} + >>> animals = pd.DataFrame(data, index=[1, 4, 9, 16, 25, 36]) + >>> animals + species type + 1 lama mammal + 4 cow mammal + 9 lama mammal + 16 ant insect + 25 lama mammal + 36 bee insect + >>> + >>> animals.duplicated() # default: keep='first' + 1 False + 4 False + 9 True + 16 False + 25 True + 36 False + dtype: bool + + By using `'last'`, the last occurrence of each set of duplicated values + is set to False and all others to True: + + >>> animals.duplicated(keep='last') + 1 True + 4 False + 9 True + 16 False + 25 False + 36 False + dtype: bool + + By specifying `keep=False`, all duplicates are set to True: + + >>> animals.duplicated(keep=False) + 1 True + 4 False + 9 True + 16 False + 25 True + 36 False + dtype: bool + + By specifying the `subset`-keyword, the duplicates will be calculated + based on just the subset of columns given + + >>> animals.duplicated(subset=['type']) # default: keep='first' + 1 False + 4 True + 9 True + 16 False + 25 True + 36 True + dtype: bool + + Using the keyword `return_inverse=True`, the output becomes a tuple of + `Series`: + + >>> isduplicate, inverse = animals.duplicated(return_inverse=True) + >>> inverse + 1 1 + 4 4 + 9 1 + 16 16 + 25 1 + 36 36 + dtype: int64 + + This can be used to reconstruct the original object from its unique + elements as follows: + + >>> # same as animals.drop_duplicates() + >>> animals_unique = animals.loc[~isduplicate] + >>> animals_unique + species type + 1 lama mammal + 4 cow mammal + 16 ant insect + 36 bee insect + >>> + >>> reconstruct = animals_unique.reindex(inverse) + >>> reconstruct + species type + 1 lama mammal + 4 cow mammal + 1 lama mammal + 16 ant insect + 1 lama mammal + 36 bee insect + + We see that the values of `animals` get reconstructed correctly, but + the index does not match yet -- consequently, the last step is to + correctly set the index. + + >>> reconstruct = reconstruct.set_index(inverse.index) + >>> reconstruct + species type + 1 lama mammal + 4 cow mammal + 9 lama mammal + 16 ant insect + 25 lama mammal + 36 bee insect + >>> + >>> reconstruct.equals(animals) + True + + See Also + -------- + pandas.Index.duplicated : Equivalent method on pandas.Index + pandas.Series.duplicated : Equivalent method on pandas.Series + pandas.DataFrame.drop_duplicates : Remove duplicate values """ from pandas.core.sorting import get_group_index - from pandas._libs.hashtable import duplicated_int64, _SIZE_HINT_LIMIT + from pandas._libs.hashtable import _SIZE_HINT_LIMIT + from pandas.core.algorithms import duplicated + + if return_inverse and keep is False: + raise ValueError("The parameters return_inverse=True and " + "keep=False cannot be used together (impossible " + "to calculate an inverse when discarding all " + "instances of a duplicate).") if self.empty: return Series() @@ -4435,7 +4577,16 @@ def f(vals): labels, shape = map(list, zip(*map(f, vals))) ids = get_group_index(labels, shape, sort=False, xnull=False) - return Series(duplicated_int64(ids, keep), index=self.index) + if not return_inverse: + return Series(duplicated(ids, keep=keep), index=self.index) + + # return_inverse = True + isduplicated_array, inverse_array = duplicated(ids, keep=keep, + return_inverse=True) + isduplicated = Series(isduplicated_array, index=self.index) + inverse = Series(self.loc[~isduplicated_array].index[inverse_array], + index=self.index) + return isduplicated, inverse # ---------------------------------------------------------------------- # Sorting diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b42bbdafcab45..0a9ad8098f2e7 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4587,7 +4587,7 @@ def drop_duplicates(self, keep='first'): """ return super(Index, self).drop_duplicates(keep=keep) - def duplicated(self, keep='first'): + def duplicated(self, keep='first', return_inverse=False): """ Indicate duplicate index values. @@ -4604,7 +4604,27 @@ def duplicated(self, keep='first'): occurrence. - 'last' : Mark duplicates as ``True`` except for the last occurrence. - - ``False`` : Mark all duplicates as ``True``. + - ``False`` : Mark all duplicates as ``True``. This option is not + compatible with ``return_inverse``. + return_inverse : boolean, default False + If True, also return the selection of (integer) indices from the + Index with unique values (created e.g. by selecting the boolean + complement of the first output, or by using `.drop_duplicates` with + the same `keep`-parameter). This allows to reconstruct the original + Index from the subset of unique values, see example below. + + .. versionadded:: 0.24.0 + + Returns + ------- + duplicated : ndarray or or tuple of ndarray if return_inverse is True + + Notes + ----- + The `return_inverse`-keyword works as expected for + ``keep='first'|'last'``, but cannot be used together with + ``keep=False`` (since discarding all duplicates makes it impossible to + construct an inverse). Examples -------- @@ -4620,20 +4640,37 @@ def duplicated(self, keep='first'): >>> idx.duplicated(keep='first') array([False, False, True, False, True]) - By using 'last', the last occurrence of each set of duplicated values - is set on False and all others on True: + By using `'last'`, the last occurrence of each set of duplicated values + is set to False and all others to True: >>> idx.duplicated(keep='last') array([ True, False, True, False, False]) - By setting keep on ``False``, all duplicates are True: + By specifying `keep=False`, all duplicates are set to True: >>> idx.duplicated(keep=False) array([ True, False, True, False, True]) - Returns - ------- - numpy.ndarray + Using the keyword `return_inverse=True`, the output becomes a tuple of + `np.ndarray`: + + >>> isduplicate, inverse = idx.duplicated(return_inverse=True) + >>> inverse + array([0, 1, 0, 2, 0], dtype=int64) + + This can be used to reconstruct the original object from its unique + elements as follows: + + >>> idx_unique = idx[~isduplicate] # same as idx.drop_duplicates() + >>> idx_unique + Index(['lama', 'cow', 'beetle'], dtype='object') + >>> + >>> reconstruct = idx_unique[inverse] + >>> reconstruct + Index(['lama', 'cow', 'lama', 'beetle', 'lama'], dtype='object') + >>> + >>> reconstruct.equals(idx) + True See Also -------- @@ -4641,7 +4678,8 @@ def duplicated(self, keep='first'): pandas.DataFrame.duplicated : Equivalent method on pandas.DataFrame pandas.Index.drop_duplicates : Remove duplicate values from Index """ - return super(Index, self).duplicated(keep=keep) + return super(Index, self).duplicated(keep=keep, + return_inverse=return_inverse) _index_shared_docs['fillna'] = """ Fill NA/NaN values with the specified value diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 45703c220a4be..28f67b4d21fdb 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -403,10 +403,10 @@ def unique(self, level=None): ordered=result.ordered) @Appender(Index.duplicated.__doc__) - def duplicated(self, keep='first'): - from pandas._libs.hashtable import duplicated_int64 + def duplicated(self, keep='first', return_inverse=False): + from pandas.core.algorithms import duplicated codes = self.codes.astype('i8') - return duplicated_int64(codes, keep) + return duplicated(codes, keep=keep, return_inverse=return_inverse) def _to_safe_for_reshape(self): """ convert to object if we are a categorical """ diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index ad38f037b6578..a333208a6f632 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -923,14 +923,19 @@ def f(k, stringify): return hash_tuple(key) @Appender(Index.duplicated.__doc__) - def duplicated(self, keep='first'): + def duplicated(self, keep='first', return_inverse=False): from pandas.core.sorting import get_group_index - from pandas._libs.hashtable import duplicated_int64 + from pandas.core.algorithms import duplicated + + if return_inverse and keep is False: + raise ValueError("The parameters return_inverse=True and " + "keep=False cannot be used together (impossible " + "to calculate an inverse when discarding all " + "instances of a duplicate).") shape = map(len, self.levels) ids = get_group_index(self.labels, shape, sort=False, xnull=False) - - return duplicated_int64(ids, keep) + return duplicated(ids, keep=keep, return_inverse=return_inverse) def fillna(self, value=None, downcast=None): """ diff --git a/pandas/core/series.py b/pandas/core/series.py index fdb9ef59c1d3e..c5cc536496dd8 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1585,7 +1585,7 @@ def drop_duplicates(self, keep='first', inplace=False): """ return super(Series, self).drop_duplicates(keep=keep, inplace=inplace) - def duplicated(self, keep='first'): + def duplicated(self, keep='first', return_inverse=False): """ Indicate duplicate Series values. @@ -1600,56 +1600,122 @@ def duplicated(self, keep='first'): occurrence. - 'last' : Mark duplicates as ``True`` except for the last occurrence. - - ``False`` : Mark all duplicates as ``True``. + - ``False`` : Mark all duplicates as ``True``. This option is not + compatible with ``return_inverse``. + return_inverse : boolean, default False + If True, also return the selection from the index from the Series + of unique values (created e.g. by selecting the boolean complement + of the first output, or by using `.drop_duplicates` with the same + `keep`-parameter) and how they relate to the index of the current + Series. This allows to reconstruct the original Series from the + subset of unique values, see example below. + + .. versionadded:: 0.24.0 + + Returns + ------- + duplicated : Series or or tuple of Series if return_inverse is True + + Notes + ----- + The `return_inverse`-keyword works as expected for + ``keep='first'|'last'``, but cannot be used together with + ``keep=False`` (since discarding all duplicates makes it impossible to + construct an inverse). Examples -------- By default, for each set of duplicated values, the first occurrence is set on False and all others on True: - >>> animals = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama']) + >>> animals = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama'], + ... index=[1, 4, 9, 16, 25]) >>> animals.duplicated() - 0 False - 1 False - 2 True - 3 False - 4 True + 1 False + 4 False + 9 True + 16 False + 25 True dtype: bool which is equivalent to >>> animals.duplicated(keep='first') - 0 False - 1 False - 2 True - 3 False - 4 True + 1 False + 4 False + 9 True + 16 False + 25 True dtype: bool - By using 'last', the last occurrence of each set of duplicated values - is set on False and all others on True: + By using `'last'`, the last occurrence of each set of duplicated values + is set to False and all others to True: >>> animals.duplicated(keep='last') - 0 True - 1 False - 2 True - 3 False - 4 False + 1 True + 4 False + 9 True + 16 False + 25 False dtype: bool - By setting keep on ``False``, all duplicates are True: + By specifying `keep=False`, all duplicates are set to True: >>> animals.duplicated(keep=False) - 0 True - 1 False - 2 True - 3 False - 4 True + 1 True + 4 False + 9 True + 16 False + 25 True dtype: bool - Returns - ------- - pandas.core.series.Series + Using the keyword `return_inverse=True`, the output becomes a tuple of + `Series`: + + >>> isduplicate, inverse = animals.duplicated(return_inverse=True) + >>> inverse + 1 1 + 4 4 + 9 1 + 16 16 + 25 1 + dtype: int64 + + This can be used to reconstruct the original object from its unique + elements as follows: + + >>> # same as animals.drop_duplicates() + >>> animals_unique = animals.loc[~isduplicate] + >>> animals_unique + 1 lama + 4 cow + 16 beetle + dtype: object + >>> + >>> reconstruct = animals_unique.reindex(inverse) + >>> reconstruct + 1 lama + 4 cow + 1 lama + 16 beetle + 1 lama + dtype: object + + We see that the values of `animals` get reconstructed correctly, but + the index does not match yet -- consequently, the last step is to + correctly set the index. + + >>> reconstruct.index = inverse.index + >>> reconstruct + 1 lama + 4 cow + 9 lama + 16 beetle + 25 lama + dtype: object + >>> + >>> reconstruct.equals(animals) + True See Also -------- @@ -1657,7 +1723,8 @@ def duplicated(self, keep='first'): pandas.DataFrame.duplicated : Equivalent method on pandas.DataFrame pandas.Series.drop_duplicates : Remove duplicate values from Series """ - return super(Series, self).duplicated(keep=keep) + return super(Series, self).duplicated(keep=keep, + return_inverse=return_inverse) def idxmin(self, axis=0, skipna=True, *args, **kwargs): """ diff --git a/pandas/tests/frame/test_duplicates.py b/pandas/tests/frame/test_duplicates.py index 3478d66b919a6..9e1521a4cfff6 100644 --- a/pandas/tests/frame/test_duplicates.py +++ b/pandas/tests/frame/test_duplicates.py @@ -88,6 +88,70 @@ def test_duplicated_subset(subset, keep): tm.assert_series_equal(result, expected) +@pytest.mark.parametrize('keep, expected_inv_values', [ + ('first', [1, 4, 4, 16, 1]), + ('last', [25, 9, 9, 16, 25]) +]) +def test_duplicated_inverse(keep, expected_inv_values): + # GH 21357 + # check that return_inverse kwarg does not affect outcome; + # index of inverse must be correctly transformed as well + idx = [1, 4, 9, 16, 25] + df = DataFrame({'A': [0, 1, 1, 2, 0], 'B': ['a', 'b', 'b', 'c', 'a']}, + index=idx) + + expected_isdup = df.duplicated(keep=keep) + expected_inv = Series(expected_inv_values, index=idx) + result_isdup, result_inv = df.duplicated(keep=keep, + return_inverse=True) + tm.assert_series_equal(result_isdup, expected_isdup) + tm.assert_series_equal(result_inv, expected_inv) + + # test that result_inv works (and fits together with expected_isdup) + unique = df.loc[~expected_isdup] + reconstr = unique.reindex(result_inv).set_index(result_inv.index) + tm.assert_frame_equal(reconstr, df) + + +def test_duplicated_inverse_raises(): + df = DataFrame({'A': [0, 1, 1, 2, 0], 'B': ['a', 'b', 'b', 'c', 'a']}) + + rgx = 'The parameters return_inverse=True and keep=False cannot be.*' + with tm.assert_raises_regex(ValueError, rgx): + df.duplicated(keep=False, return_inverse=True) + + +@pytest.mark.parametrize('keep', ['first', 'last']) +@pytest.mark.parametrize('subset', [['A', 'B', 'C'], ['A', 'B'], ['A']]) +def test_duplicated_inverse_large(subset, keep): + # unsorted index (through .sample); important to check correct + # 'first'/'last' functionality of return_inverse + df = DataFrame(np.random.randint(0, 10, (10000, 3)), + columns=list('ABC')).sample(5000) + + expected_isdup = df.duplicated(keep=keep, subset=subset) + result_isdup, result_inv = df.duplicated(keep=keep, subset=subset, + return_inverse=True) + tm.assert_series_equal(result_isdup, expected_isdup) + + unique = df.loc[~expected_isdup, subset] + reconstr = unique.reindex(result_inv).set_index(result_inv.index) + tm.assert_frame_equal(reconstr, df[subset]) + + +@pytest.mark.parametrize('keep', ['first', 'last']) +def test_duplicated_inverse_fastpath(keep): + df = DataFrame({'A': range(10)}) # no duplicates + + expected_isdup = df.duplicated(keep=keep) + result_isdup, result_inv = df.duplicated(keep=keep, + return_inverse=True) + tm.assert_series_equal(result_isdup, expected_isdup) + + expected_inv = Series(range(10)) + tm.assert_series_equal(result_inv, expected_inv) + + def test_drop_duplicates(): df = DataFrame({'AAA': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'bar', 'foo'], diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 49a247608ab0b..f8a9538f8416c 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -383,6 +383,71 @@ def test_duplicated(self, indices, keep): result = idx.duplicated(keep=keep) tm.assert_numpy_array_equal(result, expected) + @pytest.mark.parametrize('keep', ['first', 'last']) + def test_duplicated_inverse(self, indices, keep): + # GH 21357 + # check that return_inverse kwarg does not affect outcome + if type(indices) is not self._holder: + pytest.skip('Can only check if we have the correct type') + if not len(indices) or isinstance(indices, MultiIndex): + # MultiIndex tested separately in: + # tests/indexes/multi/test_unique_and_duplicates + pytest.skip('Skip check for empty Index and MultiIndex') + + idx = self._holder(indices) + if idx.has_duplicates: + # We need to be able to control creation of duplicates here + # This is slightly circular, as drop_duplicates depends on + # duplicated, but in the end, it all works out because we + # cross-check with Series.duplicated + idx = idx.drop_duplicates() + + n, k = len(idx), 10 + duplicated_selection = np.random.choice(n, k * n) + idx = self._holder(idx.values[duplicated_selection]) + + expected_isdup = idx.duplicated(keep=keep) + result_isdup, result_inv = idx.duplicated(keep=keep, + return_inverse=True) + tm.assert_numpy_array_equal(result_isdup, expected_isdup) + + # the following tests the correctness of result_inv in two ways: + # - it needs to fit together with expected_isdup + # - it needs to correctly reconstruct the object + unique = idx[~expected_isdup] + reconstr = unique[result_inv] + tm.assert_index_equal(reconstr, idx) + + def test_duplicated_inverse_raises(self, indices): + if type(indices) is not self._holder: + pytest.skip('Can only check if we have the correct type') + + rgx = 'The parameters return_inverse=True and keep=False cannot be.*' + with tm.assert_raises_regex(ValueError, rgx): + self._holder(indices).duplicated(keep=False, return_inverse=True) + + @pytest.mark.parametrize('keep', ['first', 'last']) + def test_duplicated_inverse_fastpath(self, indices, keep): + if type(indices) is not self._holder: + pytest.skip('Can only check if we have the correct type') + if not len(indices) or isinstance(indices, MultiIndex): + # MultiIndex tested separately in: + # tests/indexes/multi/test_unique_and_duplicates + pytest.skip('Skip check for empty Index and MultiIndex') + + idx = self._holder(indices) + if idx.has_duplicates: + # fastpath only possible if no duplicates + idx = idx.drop_duplicates() + + expected_isdup = idx.duplicated(keep=keep) + result_isdup, result_inv = idx.duplicated(keep=keep, + return_inverse=True) + tm.assert_numpy_array_equal(result_isdup, expected_isdup) + + expected_inv = np.arange(len(idx)) + tm.assert_numpy_array_equal(result_inv, expected_inv) + def test_unique(self, indices): # don't test a MultiIndex here (as its tested separated) # don't test a CategoricalIndex because categories change (GH 18291) diff --git a/pandas/tests/indexes/multi/test_duplicates.py b/pandas/tests/indexes/multi/test_duplicates.py index 54a12137c9457..7065c65e40127 100644 --- a/pandas/tests/indexes/multi/test_duplicates.py +++ b/pandas/tests/indexes/multi/test_duplicates.py @@ -211,29 +211,6 @@ def f(a): check(8, True) -@pytest.mark.parametrize('keep, expected', [ - ('first', np.array([False, False, False, True, True, False])), - ('last', np.array([False, True, True, False, False, False])), - (False, np.array([False, True, True, True, True, False])) -]) -def test_duplicated(idx_dup, keep, expected): - result = idx_dup.duplicated(keep=keep) - tm.assert_numpy_array_equal(result, expected) - - -@pytest.mark.parametrize('keep', ['first', 'last', False]) -def test_duplicated_large(keep): - # GH 9125 - n, k = 200, 5000 - levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)] - labels = [np.random.choice(n, k * n) for lev in levels] - mi = MultiIndex(levels=levels, labels=labels) - - result = mi.duplicated(keep=keep) - expected = hashtable.duplicated_object(mi.values, keep=keep) - tm.assert_numpy_array_equal(result, expected) - - def test_get_duplicates(): # GH5873 for a in [101, 102]: @@ -263,3 +240,85 @@ def test_get_duplicates(): tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(len(mi), dtype='bool')) + + +@pytest.mark.parametrize('keep, expected', [ + ('first', np.array([False, False, False, True, True, False])), + ('last', np.array([False, True, True, False, False, False])), + (False, np.array([False, True, True, True, True, False])) +]) +def test_duplicated(idx_dup, keep, expected): + result = idx_dup.duplicated(keep=keep) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize('keep', ['first', 'last', False]) +def test_duplicated_large(keep): + # GH 9125 + n, k = 200, 5000 + levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)] + labels = [np.random.choice(n, k * n) for lev in levels] + mi = MultiIndex(levels=levels, labels=labels) + + result = mi.duplicated(keep=keep) + expected = hashtable.duplicated_object(mi.values, keep=keep) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize('keep', ['first', 'last']) +def test_duplicated_inverse(idx_dup, keep): + # GH 21357 + # check that return_inverse kwarg does not affect outcome; + # index of inverse must be correctly transformed as well + + expected_isdup = idx_dup.duplicated(keep=keep) + expected_inv = np.array([0, 1, 2, 1, 2, 3], dtype='int64') + result_isdup, result_inv = idx_dup.duplicated(keep=keep, + return_inverse=True) + tm.assert_numpy_array_equal(result_isdup, expected_isdup) + tm.assert_numpy_array_equal(result_inv, expected_inv) + + # test that result_inv works (and fits together with expected_isdup) + unique = MultiIndex.from_tuples(idx_dup.values[~expected_isdup]) + reconstr = MultiIndex.from_tuples(unique.values[result_inv], + names=idx_dup.names) + tm.assert_index_equal(reconstr, idx_dup) + + +def test_duplicated_inverse_raises(idx_dup): + rgx = 'The parameters return_inverse=True and keep=False cannot be.*' + with tm.assert_raises_regex(ValueError, rgx): + idx_dup.duplicated(keep=False, return_inverse=True) + + +@pytest.mark.parametrize('keep', ['first', 'last']) +def test_duplicated_inverse_large(keep): + n, k = 200, 5000 + levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)] + labels = [np.random.choice(n, k * n) for lev in levels] + mi = MultiIndex(levels=levels, labels=labels) + + expected_isdup = mi.duplicated(keep=keep) + result_isdup, result_inv = mi.duplicated(keep=keep, + return_inverse=True) + tm.assert_numpy_array_equal(result_isdup, expected_isdup) + + # test that result_inv works (and fits together with expected_isdup) + unique = MultiIndex.from_tuples(mi.values[~expected_isdup]) + reconstr = MultiIndex.from_tuples(unique.values[result_inv], + names=mi.names) + tm.assert_index_equal(reconstr, mi) + + +@pytest.mark.parametrize('keep', ['first', 'last']) +def test_duplicated_inverse_fastpath(idx_dup, keep): + # fastpath is only taken if there are no duplicates + mi = idx_dup.drop_duplicates() + + expected_isdup = mi.duplicated(keep=keep) + result_isdup, result_inv = mi.duplicated(keep=keep, + return_inverse=True) + tm.assert_numpy_array_equal(result_isdup, expected_isdup) + + expected_inv = np.arange(4) + tm.assert_numpy_array_equal(result_inv, expected_inv) diff --git a/pandas/tests/series/test_duplicates.py b/pandas/tests/series/test_duplicates.py index 2e4d64188307c..61a628081702d 100644 --- a/pandas/tests/series/test_duplicates.py +++ b/pandas/tests/series/test_duplicates.py @@ -138,3 +138,67 @@ def test_duplicated_nan_none(keep, expected): result = s.duplicated(keep=keep) tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize('keep, expected_inv_values', [ + ('first', [1, 4, 4, 16, 1]), + ('last', [25, 9, 9, 16, 25]) +]) +def test_duplicated_inverse(keep, expected_inv_values): + # GH 21357 + # check that return_inverse kwarg does not affect outcome; + # index of inverse must be correctly transformed as well + idx = [1, 4, 9, 16, 25] + s = Series(['a', 'b', 'b', 'c', 'a'], index=idx) + + expected_isdup = s.duplicated(keep=keep) + expected_inv = Series(expected_inv_values, index=idx) + result_isdup, result_inv = s.duplicated(keep=keep, + return_inverse=True) + tm.assert_series_equal(result_isdup, expected_isdup) + tm.assert_series_equal(result_inv, expected_inv) + + # test that result_inv works (and fits together with expected_isdup) + unique = s.loc[~expected_isdup] + reconstr = unique.reindex(result_inv) + # Series has no set_index (GH21684) + reconstr.index = result_inv.index + tm.assert_series_equal(reconstr, s) + + +def test_duplicated_inverse_raises(): + s = Series(['a', 'b', 'b', 'c', 'a']) + + rgx = 'The parameters return_inverse=True and keep=False cannot be.*' + with tm.assert_raises_regex(ValueError, rgx): + s.duplicated(keep=False, return_inverse=True) + + +@pytest.mark.parametrize('keep', ['first', 'last']) +def test_duplicated_inverse_large(keep): + # unsorted index important to check 'first'/'last' functionality + s = Series(np.random.randint(0, 1000, 10000)).sample(5000) + + expected_isdup = s.duplicated(keep=keep) + result_isdup, result_inv = s.duplicated(keep=keep, return_inverse=True) + tm.assert_series_equal(result_isdup, expected_isdup) + + # test that result_inv works (and fits together with expected_isdup) + unique = s.loc[~expected_isdup] + reconstr = unique.reindex(result_inv) + # Series has no set_index (GH21684) + reconstr.index = result_inv.index + tm.assert_series_equal(reconstr, s) + + +@pytest.mark.parametrize('keep', ['first', 'last']) +def test_duplicated_inverse_fastpath(keep): + s = Series(range(10)) # no duplicates + + expected_isdup = s.duplicated(keep=keep) + result_isdup, result_inv = s.duplicated(keep=keep, + return_inverse=True) + tm.assert_series_equal(result_isdup, expected_isdup) + + expected_inv = Series(range(10)) + tm.assert_series_equal(result_inv, expected_inv)
Closes #21357 I followed the recommendation of @jreback there to change `duplicated`, and to make the output a tuple if `return_inverse=True`. I didn't find a test for the behavior of `DataFrame.duplicated()` -- there's a test of `Index.duplicated()` and `Series.duplicated()` in `tests/test_base.py`, but nothing I could find in `tests/frame/`. So I added a file to test to test current behavior, as well as the new kwarg. Notably, the backend between the different Series in the output tuple is different (`pandas._libs.hashtable.duplicated_int64` vs. `np.unique`), and so I also added several tests that these results are exactly compatible.
https://api.github.com/repos/pandas-dev/pandas/pulls/21645
2018-06-26T21:20:23Z
2018-12-03T17:37:51Z
null
2018-12-03T17:37:51Z
DOC: minor correction to v0.23.2.txt
diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index a41a6c31b0678..9c4b408a1d24b 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -61,8 +61,8 @@ Fixed Regressions Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- Improved performance of membership checks in :class:`CategoricalIndex` - (i.e. ``x in ci``-style checks are much faster). :meth:`CategoricalIndex.contains` +- Improved performance of membership checks in :class:`Categorical` and :class:`CategoricalIndex` + (i.e. ``x in cat``-style checks are much faster). :meth:`CategoricalIndex.contains` is likewise much faster (:issue:`21369`, :issue:`21508`) - Improved performance of :meth:`HDFStore.groups` (and dependent functions like :meth:`~HDFStore.keys`. (i.e. ``x in store`` checks are much faster)
- [x] xref #21508 - [x] whatsnew entry Small clairification that ``pd.Categorical.__contains__`` has gotten faster.
https://api.github.com/repos/pandas-dev/pandas/pulls/21644
2018-06-26T20:45:56Z
2018-06-26T21:30:42Z
2018-06-26T21:30:42Z
2018-06-26T21:39:54Z
TST: xfail flaky 3.7 test, xref #21636
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index e0793b8e1bd64..0fec6a8f96a24 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -6,6 +6,7 @@ import numpy as np import pandas as pd +from pandas.compat import PY37 from pandas import (Index, MultiIndex, CategoricalIndex, DataFrame, Categorical, Series, qcut) from pandas.util.testing import assert_frame_equal, assert_series_equal @@ -205,6 +206,7 @@ def test_level_get_group(observed): assert_frame_equal(result, expected) +@pytest.mark.xfail(PY37, reason="flaky on 3.7, xref gh-21636") @pytest.mark.parametrize('ordered', [True, False]) def test_apply(ordered): # GH 10138
e.g. https://travis-ci.org/pandas-dev/pandas/jobs/396806967 xref #21636
https://api.github.com/repos/pandas-dev/pandas/pulls/21637
2018-06-26T11:57:07Z
2018-06-26T12:26:22Z
2018-06-26T12:26:22Z
2018-07-02T15:37:07Z
DOC: fix typo in cookbook.rst
diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index fdc3b38cfdebc..f6fa9e9f86143 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -132,7 +132,7 @@ Building Criteria .. ipython:: python - newseries = df.loc[(df['BBB'] > 25) | (df['CCC'] >= -40), 'AAA']; newseries; + newseries = df.loc[(df['BBB'] > 25) | (df['CCC'] >= -40), 'AAA']; newseries ...or (with assignment modifies the DataFrame.)
Removing the semicolon delimiter at the end of the modified line of code allows the line's output to be displayed. - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21635
2018-06-26T09:13:46Z
2018-06-26T20:26:40Z
2018-06-26T20:26:40Z
2018-06-26T20:26:46Z
DOC: fixup old whatsnew for dtype coercing change (#21456)
diff --git a/doc/source/whatsnew/v0.11.0.txt b/doc/source/whatsnew/v0.11.0.txt index 3c9cfda49aebd..f39e6c9ff459b 100644 --- a/doc/source/whatsnew/v0.11.0.txt +++ b/doc/source/whatsnew/v0.11.0.txt @@ -76,7 +76,7 @@ Numeric dtypes will propagate and can coexist in DataFrames. If a dtype is passe df1.dtypes df2 = DataFrame(dict( A = Series(randn(8),dtype='float16'), B = Series(randn(8)), - C = Series(randn(8),dtype='uint8') )) + C = Series(range(8),dtype='uint8') )) df2 df2.dtypes
xref https://github.com/pandas-dev/pandas/pull/21456 cc @gfyoung
https://api.github.com/repos/pandas-dev/pandas/pulls/21634
2018-06-26T08:38:15Z
2018-06-26T10:01:11Z
2018-06-26T10:01:10Z
2018-06-26T10:01:17Z