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
BUG: fix MultiIndex.remove_unused_levels() when index contains NaNs
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 4f403ff8053a7..df8d786cfe598 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -119,7 +119,7 @@ Indexing - Bug in :func:`Series.truncate` which raises ``TypeError`` with a monotonic ``PeriodIndex`` (:issue:`17717`) - Bug in :func:`DataFrame.groupby` where tuples were interpreted as lists of keys rather than as keys (:issue:`17979`, :issue:`18249`) -- +- Bug in :func:`MultiIndex.remove_unused_levels`` which would fill nan values (:issue:`18417`) - I/O diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index ec506d7a67118..cc99505b53bf5 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1365,25 +1365,31 @@ def remove_unused_levels(self): new_labels = [] changed = False - for lev, lab in zip(self.levels, self.labels): + for idx, (lev, lab) in enumerate(zip(self.levels, self.labels)): + na_idxs = np.where(lab == -1)[0] + + if len(na_idxs): + lab = np.delete(lab, na_idxs) uniques = algos.unique(lab) # nothing unused - if len(uniques) == len(lev): - new_levels.append(lev) - new_labels.append(lab) - continue + if len(uniques) != len(lev): + changed = True + + # labels get mapped from uniques to 0:len(uniques) + label_mapping = np.zeros(len(lev)) + label_mapping[uniques] = np.arange(len(uniques)) - changed = True + lab = label_mapping[lab] - # labels get mapped from uniques to 0:len(uniques) - label_mapping = np.zeros(len(lev)) - label_mapping[uniques] = np.arange(len(uniques)) - lab = label_mapping[lab] + # new levels are simple + lev = lev.take(uniques) - # new levels are simple - lev = lev.take(uniques) + if len(na_idxs): + lab = np.insert(lab, na_idxs - np.arange(len(na_idxs)), -1) + else: + lab = self.labels[idx] new_levels.append(lev) new_labels.append(lab) diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 9d81cfef04e87..506a9e1c64b10 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -2629,6 +2629,20 @@ def test_reconstruct_remove_unused(self): tm.assert_index_equal(result2, expected) assert result2.is_(result) + @pytest.mark.parametrize('level0', [['a', 'd', 'b'], + ['a', 'd', 'b', 'unused']]) + @pytest.mark.parametrize('level1', [['w', 'x', 'y', 'z'], + ['w', 'x', 'y', 'z', 'unused']]) + def test_remove_unused_nan(self, level0, level1): + # GH 18417 + mi = pd.MultiIndex(levels=[level0, level1], + labels=[[0, 2, -1, 1, -1], [0, 1, 2, 3, 2]]) + + result = mi.remove_unused_levels() + tm.assert_index_equal(result, mi) + for level in 0, 1: + assert('unused' not in result.levels[level]) + @pytest.mark.parametrize('first_type,second_type', [ ('int64', 'int64'), ('datetime64[D]', 'str')])
- [x] closes #18417 - [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/18426
2017-11-22T12:21:11Z
2017-11-22T22:50:42Z
2017-11-22T22:50:41Z
2017-11-22T22:54:27Z
BUG: Fix IntervalIndex constructor inconsistencies
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 4a4d60b4dfbb2..5b07caf8cc902 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -74,6 +74,7 @@ Other API Changes - `tseries.frequencies.get_freq_group()` and `tseries.frequencies.DAYS` are removed from the public API (:issue:`18034`) - :func:`Series.truncate` and :func:`DataFrame.truncate` will raise a ``ValueError`` if the index is not sorted instead of an unhelpful ``KeyError`` (:issue:`17935`) - :func:`Dataframe.unstack` will now default to filling with ``np.nan`` for ``object`` columns. (:issue:`12815`) +- :class:`IntervalIndex` constructor will raise if the ``closed`` parameter conflicts with how the input data is inferred to be closed (:issue:`18421`) .. _whatsnew_0220.deprecations: @@ -137,6 +138,7 @@ Indexing - Bug in :func:`Series.truncate` which raises ``TypeError`` with a monotonic ``PeriodIndex`` (:issue:`17717`) - Bug in :func:`DataFrame.groupby` where tuples were interpreted as lists of keys rather than as keys (:issue:`17979`, :issue:`18249`) - Bug in :func:`MultiIndex.remove_unused_levels`` which would fill nan values (:issue:`18417`) +- Bug in :class:`IntervalIndex` where empty and purely NA data was constructed inconsistently depending on the construction method (:issue:`18421`) - I/O diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index c09642511207a..39b26c61172ed 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -211,8 +211,8 @@ cpdef intervals_to_interval_bounds(ndarray intervals): int64_t n = len(intervals) ndarray left, right - left = np.empty(n, dtype=object) - right = np.empty(n, dtype=object) + left = np.empty(n, dtype=intervals.dtype) + right = np.empty(n, dtype=intervals.dtype) for i in range(len(intervals)): interval = intervals[i] diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index c9bb8748abe7b..cca7a06a2d44b 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -5,6 +5,7 @@ from pandas.core.dtypes.missing import notna, isna from pandas.core.dtypes.generic import ABCPeriodIndex from pandas.core.dtypes.dtypes import IntervalDtype +from pandas.core.dtypes.cast import maybe_convert_platform from pandas.core.dtypes.common import ( _ensure_platform_int, is_list_like, @@ -31,7 +32,9 @@ from pandas.core.indexes.timedeltas import timedelta_range from pandas.core.indexes.multi import MultiIndex from pandas.compat.numpy import function as nv -from pandas.core import common as com +from pandas.core.common import ( + _all_not_none, _any_none, _asarray_tuplesafe, _count_not_none, + is_bool_indexer, _maybe_box_datetimelike, _not_none) from pandas.util._decorators import cache_readonly, Appender from pandas.core.config import get_option from pandas.tseries.frequencies import to_offset @@ -176,7 +179,7 @@ class IntervalIndex(IntervalMixin, Index): _mask = None - def __new__(cls, data, closed='right', + def __new__(cls, data, closed=None, name=None, copy=False, dtype=None, fastpath=False, verify_integrity=True): @@ -197,8 +200,17 @@ def __new__(cls, data, closed='right', if is_scalar(data): cls._scalar_data_error(data) - data = IntervalIndex.from_intervals(data, name=name) - left, right, closed = data.left, data.right, data.closed + data = maybe_convert_platform(data) + left, right, infer_closed = intervals_to_interval_bounds(data) + + if _all_not_none(closed, infer_closed) and closed != infer_closed: + # GH 18421 + msg = ("conflicting values for closed: constructor got " + "'{closed}', inferred from data '{infer_closed}'" + .format(closed=closed, infer_closed=infer_closed)) + raise ValueError(msg) + + closed = closed or infer_closed return cls._simple_new(left, right, closed, name, copy=copy, verify_integrity=verify_integrity) @@ -376,7 +388,8 @@ def from_breaks(cls, breaks, closed='right', name=None, copy=False): IntervalIndex.from_tuples : Construct an IntervalIndex from a list/array of tuples """ - breaks = np.asarray(breaks) + breaks = maybe_convert_platform(breaks) + return cls.from_arrays(breaks[:-1], breaks[1:], closed, name=name, copy=copy) @@ -416,8 +429,9 @@ def from_arrays(cls, left, right, closed='right', name=None, copy=False): IntervalIndex.from_tuples : Construct an IntervalIndex from a list/array of tuples """ - left = np.asarray(left) - right = np.asarray(right) + left = maybe_convert_platform(left) + right = maybe_convert_platform(right) + return cls._simple_new(left, right, closed, name=name, copy=copy, verify_integrity=True) @@ -460,8 +474,12 @@ def from_intervals(cls, data, name=None, copy=False): IntervalIndex.from_tuples : Construct an IntervalIndex from a list/array of tuples """ - data = np.asarray(data) - left, right, closed = intervals_to_interval_bounds(data) + if isinstance(data, IntervalIndex): + left, right, closed = data.left, data.right, data.closed + name = name or data.name + else: + data = maybe_convert_platform(data) + left, right, closed = intervals_to_interval_bounds(data) return cls.from_arrays(left, right, closed, name=name, copy=False) @classmethod @@ -497,8 +515,11 @@ def from_tuples(cls, data, closed='right', name=None, copy=False): IntervalIndex.from_intervals : Construct an IntervalIndex from an array of Interval objects """ - left = [] - right = [] + if len(data): + left, right = [], [] + else: + left = right = data + for d in data: if isna(d): @@ -517,7 +538,7 @@ def from_tuples(cls, data, closed='right', name=None, copy=False): return cls.from_arrays(left, right, closed, name=name, copy=False) def to_tuples(self): - return Index(com._asarray_tuplesafe(zip(self.left, self.right))) + return Index(_asarray_tuplesafe(zip(self.left, self.right))) @cache_readonly def _multiindex(self): @@ -838,7 +859,7 @@ def get_loc(self, key, method=None): return self._engine.get_loc(key) def get_value(self, series, key): - if com.is_bool_indexer(key): + if is_bool_indexer(key): loc = key elif is_list_like(key): loc = self.get_indexer(key) @@ -1166,7 +1187,7 @@ def _is_type_compatible(a, b): return ((is_number(a) and is_number(b)) or (is_ts_compat(a) and is_ts_compat(b)) or (is_td_compat(a) and is_td_compat(b)) or - com._any_none(a, b)) + _any_none(a, b)) def interval_range(start=None, end=None, periods=None, freq=None, @@ -1244,13 +1265,13 @@ def interval_range(start=None, end=None, periods=None, freq=None, -------- IntervalIndex : an Index of intervals that are all closed on the same side. """ - if com._count_not_none(start, end, periods) != 2: + if _count_not_none(start, end, periods) != 2: raise ValueError('Of the three parameters: start, end, and periods, ' 'exactly two must be specified') - start = com._maybe_box_datetimelike(start) - end = com._maybe_box_datetimelike(end) - endpoint = next(com._not_none(start, end)) + start = _maybe_box_datetimelike(start) + end = _maybe_box_datetimelike(end) + endpoint = next(_not_none(start, end)) if not _is_valid_endpoint(start): msg = 'start must be numeric or datetime-like, got {start}' diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index 399d88309072e..b98359ea0ec4d 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -6,7 +6,7 @@ from pandas import (Interval, IntervalIndex, Index, isna, interval_range, Timestamp, Timedelta, compat, date_range, timedelta_range, DateOffset) -from pandas.compat import zip +from pandas.compat import lzip from pandas.tseries.offsets import Day from pandas._libs.interval import IntervalTree from pandas.tests.indexes.common import Base @@ -38,7 +38,7 @@ def create_index_with_nan(self, closed='right'): @pytest.mark.parametrize('name', [None, 'foo']) def test_constructors(self, closed, name): left, right = Index([0, 1, 2, 3]), Index([1, 2, 3, 4]) - ivs = [Interval(l, r, closed=closed) for l, r in zip(left, right)] + ivs = [Interval(l, r, closed=closed) for l, r in lzip(left, right)] expected = IntervalIndex._simple_new( left=left, right=right, closed=closed, name=name) @@ -57,7 +57,7 @@ def test_constructors(self, closed, name): tm.assert_index_equal(result, expected) result = IntervalIndex.from_tuples( - zip(left, right), closed=closed, name=name) + lzip(left, right), closed=closed, name=name) tm.assert_index_equal(result, expected) result = Index(ivs, name=name) @@ -68,6 +68,9 @@ def test_constructors(self, closed, name): tm.assert_index_equal(Index(expected), expected) tm.assert_index_equal(IntervalIndex(expected), expected) + result = IntervalIndex.from_intervals(expected) + tm.assert_index_equal(result, expected) + result = IntervalIndex.from_intervals( expected.values, name=expected.name) tm.assert_index_equal(result, expected) @@ -86,63 +89,118 @@ def test_constructors(self, closed, name): breaks, closed=expected.closed, name=expected.name) tm.assert_index_equal(result, expected) - def test_constructors_other(self): - - # all-nan - result = IntervalIndex.from_intervals([np.nan]) - expected = np.array([np.nan], dtype=object) - tm.assert_numpy_array_equal(result.values, expected) - - # empty - result = IntervalIndex.from_intervals([]) - expected = np.array([], dtype=object) - tm.assert_numpy_array_equal(result.values, expected) + @pytest.mark.parametrize('data', [[np.nan], [np.nan] * 2, [np.nan] * 50]) + def test_constructors_nan(self, closed, data): + # GH 18421 + expected_values = np.array(data, dtype=object) + expected_idx = IntervalIndex(data, closed=closed) + + # validate the expected index + assert expected_idx.closed == closed + tm.assert_numpy_array_equal(expected_idx.values, expected_values) + + result = IntervalIndex.from_tuples(data, closed=closed) + tm.assert_index_equal(result, expected_idx) + tm.assert_numpy_array_equal(result.values, expected_values) + + result = IntervalIndex.from_breaks([np.nan] + data, closed=closed) + tm.assert_index_equal(result, expected_idx) + tm.assert_numpy_array_equal(result.values, expected_values) + + result = IntervalIndex.from_arrays(data, data, closed=closed) + tm.assert_index_equal(result, expected_idx) + tm.assert_numpy_array_equal(result.values, expected_values) + + if closed == 'right': + # Can't specify closed for IntervalIndex.from_intervals + result = IntervalIndex.from_intervals(data) + tm.assert_index_equal(result, expected_idx) + tm.assert_numpy_array_equal(result.values, expected_values) + + @pytest.mark.parametrize('data', [ + [], + np.array([], dtype='int64'), + np.array([], dtype='float64'), + np.array([], dtype=object)]) + def test_constructors_empty(self, data, closed): + # GH 18421 + expected_dtype = data.dtype if isinstance(data, np.ndarray) else object + expected_values = np.array([], dtype=object) + expected_index = IntervalIndex(data, closed=closed) + + # validate the expected index + assert expected_index.empty + assert expected_index.closed == closed + assert expected_index.dtype.subtype == expected_dtype + tm.assert_numpy_array_equal(expected_index.values, expected_values) + + result = IntervalIndex.from_tuples(data, closed=closed) + tm.assert_index_equal(result, expected_index) + tm.assert_numpy_array_equal(result.values, expected_values) + + result = IntervalIndex.from_breaks(data, closed=closed) + tm.assert_index_equal(result, expected_index) + tm.assert_numpy_array_equal(result.values, expected_values) + + result = IntervalIndex.from_arrays(data, data, closed=closed) + tm.assert_index_equal(result, expected_index) + tm.assert_numpy_array_equal(result.values, expected_values) + + if closed == 'right': + # Can't specify closed for IntervalIndex.from_intervals + result = IntervalIndex.from_intervals(data) + tm.assert_index_equal(result, expected_index) + tm.assert_numpy_array_equal(result.values, expected_values) def test_constructors_errors(self): # scalar - msg = ('IntervalIndex(...) must be called with a collection of ' + msg = ('IntervalIndex\(...\) must be called with a collection of ' 'some kind, 5 was passed') - with pytest.raises(TypeError, message=msg): + with tm.assert_raises_regex(TypeError, msg): IntervalIndex(5) # not an interval - msg = "type <class 'numpy.int32'> with value 0 is not an interval" - with pytest.raises(TypeError, message=msg): + msg = ("type <(class|type) 'numpy.int64'> with value 0 " + "is not an interval") + with tm.assert_raises_regex(TypeError, msg): IntervalIndex([0, 1]) - with pytest.raises(TypeError, message=msg): + with tm.assert_raises_regex(TypeError, msg): IntervalIndex.from_intervals([0, 1]) # invalid closed msg = "invalid options for 'closed': invalid" - with pytest.raises(ValueError, message=msg): + with tm.assert_raises_regex(ValueError, msg): IntervalIndex.from_arrays([0, 1], [1, 2], closed='invalid') - # mismatched closed + # mismatched closed within intervals msg = 'intervals must all be closed on the same side' - with pytest.raises(ValueError, message=msg): + with tm.assert_raises_regex(ValueError, msg): IntervalIndex.from_intervals([Interval(0, 1), Interval(1, 2, closed='left')]) - with pytest.raises(ValueError, message=msg): - IntervalIndex.from_arrays([0, 10], [3, 5]) - - with pytest.raises(ValueError, message=msg): + with tm.assert_raises_regex(ValueError, msg): Index([Interval(0, 1), Interval(2, 3, closed='left')]) + # mismatched closed inferred from intervals vs constructor. + msg = 'conflicting values for closed' + with tm.assert_raises_regex(ValueError, msg): + iv = [Interval(0, 1, closed='both'), Interval(1, 2, closed='both')] + IntervalIndex(iv, closed='neither') + # no point in nesting periods in an IntervalIndex msg = 'Period dtypes are not supported, use a PeriodIndex instead' - with pytest.raises(ValueError, message=msg): + with tm.assert_raises_regex(ValueError, msg): IntervalIndex.from_breaks( pd.period_range('2000-01-01', periods=3)) # decreasing breaks/arrays msg = 'left side of interval must be <= right side' - with pytest.raises(ValueError, message=msg): + with tm.assert_raises_regex(ValueError, msg): IntervalIndex.from_breaks(range(10, -1, -1)) - with pytest.raises(ValueError, message=msg): + with tm.assert_raises_regex(ValueError, msg): IntervalIndex.from_arrays(range(10, -1, -1), range(9, -2, -1)) def test_constructors_datetimelike(self, closed): @@ -865,7 +923,7 @@ def test_is_non_overlapping_monotonic(self, closed): idx = IntervalIndex.from_tuples(tpls, closed=closed) assert idx.is_non_overlapping_monotonic is True - idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) + idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed) assert idx.is_non_overlapping_monotonic is True # Should be False in all cases (overlapping) @@ -873,7 +931,7 @@ def test_is_non_overlapping_monotonic(self, closed): idx = IntervalIndex.from_tuples(tpls, closed=closed) assert idx.is_non_overlapping_monotonic is False - idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) + idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed) assert idx.is_non_overlapping_monotonic is False # Should be False in all cases (non-monotonic) @@ -881,7 +939,7 @@ def test_is_non_overlapping_monotonic(self, closed): idx = IntervalIndex.from_tuples(tpls, closed=closed) assert idx.is_non_overlapping_monotonic is False - idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) + idx = IntervalIndex.from_tuples(tpls[::-1], closed=closed) assert idx.is_non_overlapping_monotonic is False # Should be False for closed='both', overwise True (GH16560) @@ -1054,10 +1112,6 @@ def test_constructor_coverage(self): end=end.to_pydatetime()) tm.assert_index_equal(result, expected) - result = pd.interval_range(start=start.tz_localize('UTC'), - end=end.tz_localize('UTC')) - tm.assert_index_equal(result, expected) - result = pd.interval_range(start=start.asm8, end=end.asm8) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexing/test_interval.py b/pandas/tests/indexing/test_interval.py index 3792293f48b99..e29dc627a5d94 100644 --- a/pandas/tests/indexing/test_interval.py +++ b/pandas/tests/indexing/test_interval.py @@ -54,7 +54,7 @@ def test_getitem_with_scalar(self): def test_nonoverlapping_monotonic(self, direction, closed): tpls = [(0, 1), (2, 3), (4, 5)] if direction == 'decreasing': - tpls = reversed(tpls) + tpls = tpls[::-1] idx = IntervalIndex.from_tuples(tpls, closed=closed) s = Series(list('abc'), idx)
- [X] closes #18421 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry Regarding item 3) in the issue, which deals with the dtype of `IntervalIndex([])`: I implemented this so that the default behavior is to have `object` dtype. However, if the empty data has a specific dtype, e.g. `np.array([], dtype='int64')`, it will use that dtype instead.
https://api.github.com/repos/pandas-dev/pandas/pulls/18424
2017-11-22T09:12:20Z
2017-11-24T16:55:14Z
2017-11-24T16:55:14Z
2017-11-24T18:58:06Z
CLN: ASV Algorithms benchmark
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py index 40cfec1bcd4c7..7ffb180b49e09 100644 --- a/asv_bench/benchmarks/algorithms.py +++ b/asv_bench/benchmarks/algorithms.py @@ -1,7 +1,6 @@ from importlib import import_module import numpy as np - import pandas as pd from pandas.util import testing as tm @@ -12,113 +11,118 @@ except: pass -class Algorithms(object): + +class Factorize(object): + goal_time = 0.2 - def setup(self): - N = 100000 - np.random.seed(1234) + params = [True, False] + param_names = ['sort'] - self.int_unique = pd.Int64Index(np.arange(N * 5)) - # cache is_unique - self.int_unique.is_unique + def setup(self, sort): + N = 10**5 + np.random.seed(1234) + self.int_idx = pd.Int64Index(np.arange(N).repeat(5)) + self.float_idx = pd.Float64Index(np.random.randn(N).repeat(5)) + self.string_idx = tm.makeStringIndex(N) - self.int = pd.Int64Index(np.arange(N).repeat(5)) - self.float = pd.Float64Index(np.random.randn(N).repeat(5)) + def time_factorize_int(self, sort): + self.int_idx.factorize(sort=sort) - # Convenience naming. - self.checked_add = pd.core.algorithms.checked_add_with_arr + def time_factorize_float(self, sort): + self.float_idx.factorize(sort=sort) - self.arr = np.arange(1000000) - self.arrpos = np.arange(1000000) - self.arrneg = np.arange(-1000000, 0) - self.arrmixed = np.array([1, -1]).repeat(500000) - self.strings = tm.makeStringIndex(100000) + def time_factorize_string(self, sort): + self.string_idx.factorize(sort=sort) - self.arr_nan = np.random.choice([True, False], size=1000000) - self.arrmixed_nan = np.random.choice([True, False], size=1000000) - # match - self.uniques = tm.makeStringIndex(1000).values - self.all = self.uniques.repeat(10) +class Duplicated(object): - def time_factorize_string(self): - self.strings.factorize() + goal_time = 0.2 - def time_factorize_int(self): - self.int.factorize() + params = ['first', 'last', False] + param_names = ['keep'] - def time_factorize_float(self): - self.int.factorize() + def setup(self, keep): + N = 10**5 + np.random.seed(1234) + self.int_idx = pd.Int64Index(np.arange(N).repeat(5)) + self.float_idx = pd.Float64Index(np.random.randn(N).repeat(5)) + self.string_idx = tm.makeStringIndex(N) - def time_duplicated_int_unique(self): - self.int_unique.duplicated() + def time_duplicated_int(self, keep): + self.int_idx.duplicated(keep=keep) - def time_duplicated_int(self): - self.int.duplicated() + def time_duplicated_float(self, keep): + self.float_idx.duplicated(keep=keep) - def time_duplicated_float(self): - self.float.duplicated() + def time_duplicated_string(self, keep): + self.string_idx.duplicated(keep=keep) - def time_match_strings(self): - pd.match(self.all, self.uniques) - def time_add_overflow_pos_scalar(self): - self.checked_add(self.arr, 1) +class DuplicatedUniqueIndex(object): - def time_add_overflow_neg_scalar(self): - self.checked_add(self.arr, -1) + goal_time = 0.2 - def time_add_overflow_zero_scalar(self): - self.checked_add(self.arr, 0) + def setup(self): + N = 10**5 + self.idx_int_dup = pd.Int64Index(np.arange(N * 5)) + # cache is_unique + self.idx_int_dup.is_unique - def time_add_overflow_pos_arr(self): - self.checked_add(self.arr, self.arrpos) + def time_duplicated_unique_int(self): + self.idx_int_dup.duplicated() - def time_add_overflow_neg_arr(self): - self.checked_add(self.arr, self.arrneg) - def time_add_overflow_mixed_arr(self): - self.checked_add(self.arr, self.arrmixed) +class Match(object): - def time_add_overflow_first_arg_nan(self): - self.checked_add(self.arr, self.arrmixed, arr_mask=self.arr_nan) + goal_time = 0.2 - def time_add_overflow_second_arg_nan(self): - self.checked_add(self.arr, self.arrmixed, b_mask=self.arrmixed_nan) + def setup(self): + np.random.seed(1234) + self.uniques = tm.makeStringIndex(1000).values + self.all = self.uniques.repeat(10) - def time_add_overflow_both_arg_nan(self): - self.checked_add(self.arr, self.arrmixed, arr_mask=self.arr_nan, - b_mask=self.arrmixed_nan) + def time_match_string(self): + pd.match(self.all, self.uniques) class Hashing(object): + goal_time = 0.2 - def setup(self): - N = 100000 - - self.df = pd.DataFrame( - {'A': pd.Series(tm.makeStringIndex(100).take( - np.random.randint(0, 100, size=N))), - 'B': pd.Series(tm.makeStringIndex(10000).take( - np.random.randint(0, 10000, size=N))), - 'D': np.random.randn(N), - 'E': np.arange(N), - 'F': pd.date_range('20110101', freq='s', periods=N), - 'G': pd.timedelta_range('1 day', freq='s', periods=N), - }) - self.df['C'] = self.df['B'].astype('category') - self.df.iloc[10:20] = np.nan - - def time_frame(self): - hashing.hash_pandas_object(self.df) - - def time_series_int(self): - hashing.hash_pandas_object(self.df.E) - - def time_series_string(self): - hashing.hash_pandas_object(self.df.B) - - def time_series_categorical(self): - hashing.hash_pandas_object(self.df.C) + def setup_cache(self): + np.random.seed(1234) + N = 10**5 + + df = pd.DataFrame( + {'strings': pd.Series(tm.makeStringIndex(10000).take( + np.random.randint(0, 10000, size=N))), + 'floats': np.random.randn(N), + 'ints': np.arange(N), + 'dates': pd.date_range('20110101', freq='s', periods=N), + 'timedeltas': pd.timedelta_range('1 day', freq='s', periods=N)}) + df['categories'] = df['strings'].astype('category') + df.iloc[10:20] = np.nan + return df + + def time_frame(self, df): + hashing.hash_pandas_object(df) + + def time_series_int(self, df): + hashing.hash_pandas_object(df['ints']) + + def time_series_string(self, df): + hashing.hash_pandas_object(df['strings']) + + def time_series_float(self, df): + hashing.hash_pandas_object(df['floats']) + + def time_series_categorical(self, df): + hashing.hash_pandas_object(df['categories']) + + def time_series_timedeltas(self, df): + hashing.hash_pandas_object(df['timedeltas']) + + def time_series_dates(self, df): + hashing.hash_pandas_object(df['dates']) diff --git a/asv_bench/benchmarks/binary_ops.py b/asv_bench/benchmarks/binary_ops.py index 429965c06cb48..14169ced4b71f 100644 --- a/asv_bench/benchmarks/binary_ops.py +++ b/asv_bench/benchmarks/binary_ops.py @@ -1,5 +1,6 @@ import numpy as np from pandas import DataFrame, Series, date_range +from pandas.core.algorithms import checked_add_with_arr try: import pandas.core.computation.expressions as expr except ImportError: @@ -108,3 +109,46 @@ def time_timestamp_ops_diff(self, tz): def time_timestamp_ops_diff_with_shift(self, tz): self.s - self.s.shift() + + +class AddOverflowScalar(object): + + goal_time = 0.2 + + params = [1, -1, 0] + param_names = ['scalar'] + + def setup(self, scalar): + N = 10**6 + self.arr = np.arange(N) + + def time_add_overflow_scalar(self, scalar): + checked_add_with_arr(self.arr, scalar) + + +class AddOverflowArray(object): + + goal_time = 0.2 + + def setup(self): + np.random.seed(1234) + N = 10**6 + self.arr = np.arange(N) + self.arr_rev = np.arange(-N, 0) + self.arr_mixed = np.array([1, -1]).repeat(N / 2) + self.arr_nan_1 = np.random.choice([True, False], size=N) + self.arr_nan_2 = np.random.choice([True, False], size=N) + + def time_add_overflow_arr_rev(self): + checked_add_with_arr(self.arr, self.arr_rev) + + def time_add_overflow_arr_mask_nan(self): + checked_add_with_arr(self.arr, self.arr_mixed, arr_mask=self.arr_nan_1) + + def time_add_overflow_b_mask_nan(self): + checked_add_with_arr(self.arr, self.arr_mixed, + b_mask=self.arr_nan_1) + + def time_add_overflow_both_arg_nan(self): + checked_add_with_arr(self.arr, self.arr_mixed, arr_mask=self.arr_nan_1, + b_mask=self.arr_nan_2)
High Level changes: - The `Algorithms` class benchmark was getting large so I broke it into several smaller classes, avoiding creating data structures in each `setup` call that would only be used for 1 benchmark. - Added `np.random.seed(1234)` in `setup` classes where random data is created xref #8144 - Utilized `params` and `setup_cache` where applicable. - Added additional hashing benchmarks The benchmarks should be equivalent to what existed before. If the diff is too large I can break it up into smaller PRs. You can find 3 asv runs below. <details> ``` $ asv run -b ^algorithms -q [ 5.26%] ··· Running algorithms.Hashing.time_frame 58.8ms [ 10.53%] ··· Running algorithms.Hashing.time_series_categorical 15.6ms [ 15.79%] ··· Running algorithms.Hashing.time_series_dates 10.3ms [ 21.05%] ··· Running algorithms.Hashing.time_series_float 13.7ms [ 26.32%] ··· Running algorithms.Hashing.time_series_int 11.0ms [ 31.58%] ··· Running algorithms.Hashing.time_series_string 29.7ms [ 36.84%] ··· Running algorithms.Hashing.time_series_timedeltas 13.4ms [ 42.11%] ··· Running algorithms.AddOverflowArray.time_add_overflow_arr_mask_nan 45.8ms [ 47.37%] ··· Running algorithms.AddOverflowArray.time_add_overflow_arr_rev 32.5ms [ 52.63%] ··· Running algorithms.AddOverflowArray.time_add_overflow_b_mask_nan 43.2ms [ 57.89%] ··· Running algorithms.AddOverflowArray.time_add_overflow_both_arg_nan 40.2ms [ 63.16%] ··· Running algorithms.AddOverflowScalar.time_add_overflow_scalar 25.8ms;... [ 68.42%] ··· Running algorithms.Duplicated.time_duplicated_float 40.1ms [ 73.68%] ··· Running algorithms.Duplicated.time_duplicated_int 26.3ms [ 78.95%] ··· Running algorithms.DuplicatedUniqueIndex.time_duplicated_unique_int 374μs [ 84.21%] ··· Running algorithms.Factorize.time_factorize_float 27.8ms [ 89.47%] ··· Running algorithms.Factorize.time_factorize_int 18.3ms [ 94.74%] ··· Running algorithms.Factorize.time_factorize_string 52.3ms [100.00%] ··· Running algorithms.Match.time_match_string 902μs asv run -b ^algorithms -q [ 5.26%] ··· Running algorithms.Hashing.time_frame 58.7ms [ 10.53%] ··· Running algorithms.Hashing.time_series_categorical 12.4ms [ 15.79%] ··· Running algorithms.Hashing.time_series_dates 9.24ms [ 21.05%] ··· Running algorithms.Hashing.time_series_float 9.53ms [ 26.32%] ··· Running algorithms.Hashing.time_series_int 9.53ms [ 31.58%] ··· Running algorithms.Hashing.time_series_string 29.1ms [ 36.84%] ··· Running algorithms.Hashing.time_series_timedeltas 9.57ms [ 42.11%] ··· Running algorithms.AddOverflowArray.time_add_overflow_arr_mask_nan 47.3ms [ 47.37%] ··· Running algorithms.AddOverflowArray.time_add_overflow_arr_rev 26.5ms [ 52.63%] ··· Running algorithms.AddOverflowArray.time_add_overflow_b_mask_nan 38.9ms [ 57.89%] ··· Running algorithms.AddOverflowArray.time_add_overflow_both_arg_nan 39.6ms [ 63.16%] ··· Running algorithms.AddOverflowScalar.time_add_overflow_scalar 24.2ms;... [ 68.42%] ··· Running algorithms.Duplicated.time_duplicated_float 40.1ms [ 73.68%] ··· Running algorithms.Duplicated.time_duplicated_int 28.5ms [ 78.95%] ··· Running algorithms.DuplicatedUniqueIndex.time_duplicated_unique_int 450μs [ 84.21%] ··· Running algorithms.Factorize.time_factorize_float 31.6ms [ 89.47%] ··· Running algorithms.Factorize.time_factorize_int 18.6ms [ 94.74%] ··· Running algorithms.Factorize.time_factorize_string 56.0ms [100.00%] ··· Running algorithms.Match.time_match_string 788μs asv run -b ^algorithms -q [ 5.26%] ··· Running algorithms.Hashing.time_frame 57.4ms [ 10.53%] ··· Running algorithms.Hashing.time_series_categorical 13.3ms [ 15.79%] ··· Running algorithms.Hashing.time_series_dates 12.5ms [ 21.05%] ··· Running algorithms.Hashing.time_series_float 9.70ms [ 26.32%] ··· Running algorithms.Hashing.time_series_int 9.27ms [ 31.58%] ··· Running algorithms.Hashing.time_series_string 30.0ms [ 36.84%] ··· Running algorithms.Hashing.time_series_timedeltas 15.8ms [ 42.11%] ··· Running algorithms.AddOverflowArray.time_add_overflow_arr_mask_nan 40.5ms [ 47.37%] ··· Running algorithms.AddOverflowArray.time_add_overflow_arr_rev 25.5ms [ 52.63%] ··· Running algorithms.AddOverflowArray.time_add_overflow_b_mask_nan 38.7ms [ 57.89%] ··· Running algorithms.AddOverflowArray.time_add_overflow_both_arg_nan 44.5ms [ 63.16%] ··· Running algorithms.AddOverflowScalar.time_add_overflow_scalar 20.3ms;... [ 68.42%] ··· Running algorithms.Duplicated.time_duplicated_float 45.3ms [ 73.68%] ··· Running algorithms.Duplicated.time_duplicated_int 33.3ms [ 78.95%] ··· Running algorithms.DuplicatedUniqueIndex.time_duplicated_unique_int 332μs [ 84.21%] ··· Running algorithms.Factorize.time_factorize_float 26.2ms [ 89.47%] ··· Running algorithms.Factorize.time_factorize_int 18.5ms [ 94.74%] ··· Running algorithms.Factorize.time_factorize_string 55.5ms [100.00%] ··· Running algorithms.Match.time_match_string 800μs ``` </details>
https://api.github.com/repos/pandas-dev/pandas/pulls/18423
2017-11-22T08:17:52Z
2017-11-25T21:26:13Z
2017-11-25T21:26:13Z
2017-11-25T23:23:50Z
simplify skiplist inclusion/cimport to be more cythonize-friendly
diff --git a/pandas/_libs/skiplist.pxd b/pandas/_libs/skiplist.pxd new file mode 100644 index 0000000000000..82a0862112199 --- /dev/null +++ b/pandas/_libs/skiplist.pxd @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# cython: profile=False + +from cython cimport Py_ssize_t + +from numpy cimport double_t + + +cdef extern from "src/skiplist.h": + ctypedef struct node_t: + node_t **next + int *width + double value + int is_nil + int levels + int ref_count + + ctypedef struct skiplist_t: + node_t *head + node_t **tmp_chain + int *tmp_steps + int size + int maxlevels + + skiplist_t* skiplist_init(int) nogil + void skiplist_destroy(skiplist_t*) nogil + double skiplist_get(skiplist_t*, int, int*) nogil + int skiplist_insert(skiplist_t*, double) nogil + int skiplist_remove(skiplist_t*, double) nogil + + +# Note: Node is declared here so that IndexableSkiplist can be exposed; +# Node itself not intended to be exposed. +cdef class Node: + cdef public: + double_t value + list next + list width + + +cdef class IndexableSkiplist: + cdef: + Py_ssize_t size, maxlevels + Node head + + cpdef get(self, Py_ssize_t i) + cpdef insert(self, double value) + cpdef remove(self, double value) diff --git a/pandas/_libs/src/skiplist.pyx b/pandas/_libs/skiplist.pyx similarity index 95% rename from pandas/_libs/src/skiplist.pyx rename to pandas/_libs/skiplist.pyx index 1524dca38d0e0..c96413edfb0f2 100644 --- a/pandas/_libs/src/skiplist.pyx +++ b/pandas/_libs/skiplist.pyx @@ -6,8 +6,7 @@ # Cython version: Wes McKinney -cdef extern from "math.h": - double log(double x) +from libc.math cimport log # MSVC does not have log2! @@ -16,6 +15,7 @@ cdef double Log2(double x): cimport numpy as np import numpy as np +from numpy cimport double_t from random import random @@ -25,10 +25,10 @@ np.import_array() # TODO: optimize this, make less messy cdef class Node: - cdef public: - double_t value - list next - list width + # cdef public: + # double_t value + # list next + # list width def __init__(self, double_t value, list next, list width): self.value = value @@ -43,9 +43,9 @@ cdef class IndexableSkiplist: Sorted collection supporting O(lg n) insertion, removal, and lookup by rank. """ - cdef: - Py_ssize_t size, maxlevels - Node head + # cdef: + # Py_ssize_t size, maxlevels + # Node head def __init__(self, expected_size=100): self.size = 0 diff --git a/pandas/_libs/src/skiplist.pxd b/pandas/_libs/src/skiplist.pxd deleted file mode 100644 index 214aa1c7aeaf0..0000000000000 --- a/pandas/_libs/src/skiplist.pxd +++ /dev/null @@ -1,22 +0,0 @@ -cdef extern from "skiplist.h": - ctypedef struct node_t: - node_t **next - int *width - double value - int is_nil - int levels - int ref_count - - ctypedef struct skiplist_t: - node_t *head - node_t **tmp_chain - int *tmp_steps - int size - int maxlevels - - skiplist_t* skiplist_init(int) nogil - void skiplist_destroy(skiplist_t*) nogil - double skiplist_get(skiplist_t*, int, int*) nogil - int skiplist_insert(skiplist_t*, double) nogil - int skiplist_remove(skiplist_t*, double) nogil - diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index 95df5a07a390b..ecce45742afa7 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -14,9 +14,13 @@ cimport util from libc.stdlib cimport malloc, free - from numpy cimport ndarray, double_t, int64_t, float64_t +from skiplist cimport (IndexableSkiplist, + node_t, skiplist_t, + skiplist_init, skiplist_destroy, + skiplist_get, skiplist_insert, skiplist_remove) + cdef np.float32_t MINfloat32 = np.NINF cdef np.float64_t MINfloat64 = np.NINF @@ -30,19 +34,10 @@ cdef inline int int_min(int a, int b): return a if a <= b else b from util cimport numeric -from skiplist cimport ( - skiplist_t, - skiplist_init, - skiplist_destroy, - skiplist_get, - skiplist_insert, - skiplist_remove) - cdef extern from "../src/headers/math.h": - double sqrt(double x) nogil int signbit(double) nogil + double sqrt(double x) nogil -include "skiplist.pyx" # Cython implementations of rolling sum, mean, variance, skewness, # other statistical moment functions diff --git a/setup.py b/setup.py index 7e56298d1b20b..37be0b696503d 100755 --- a/setup.py +++ b/setup.py @@ -341,6 +341,7 @@ class CheckSDist(sdist_class): 'pandas/_libs/missing.pyx', 'pandas/_libs/testing.pyx', 'pandas/_libs/window.pyx', + 'pandas/_libs/skiplist.pyx', 'pandas/_libs/sparse.pyx', 'pandas/_libs/parsers.pyx', 'pandas/_libs/tslibs/strptime.pyx', @@ -544,6 +545,9 @@ def pxd(name): '_libs.reshape': { 'pyxfile': '_libs/reshape', 'depends': _pxi_dep['reshape']}, + '_libs.skiplist': { + 'pyxfile': '_libs/skiplist', + 'depends': ['pandas/_libs/src/skiplist.h']}, '_libs.sparse': { 'pyxfile': '_libs/sparse', 'depends': _pxi_dep['sparse']}, @@ -629,9 +633,7 @@ def pxd(name): 'pyxfile': '_libs/testing'}, '_libs.window': { 'pyxfile': '_libs/window', - 'pxdfiles': ['_libs/src/skiplist', '_libs/src/util'], - 'depends': ['pandas/_libs/src/skiplist.pyx', - 'pandas/_libs/src/skiplist.h']}, + 'pxdfiles': ['_libs/skiplist', '_libs/src/util']}, 'io.sas._sas': { 'pyxfile': 'io/sas/sas'}}
Next up in the moving-towards-`cythonize` parade... `_libs.window` has both `include "skiplist.pyx"` and `from skiplist cimport`. The cimport refers to `src/skiplist.pxd`, which is just passing through declarations from `src/skiplist.h`. This PR removes skiplist.pxd and moves its contents into src/skiplist.pyx. Background on motivation: when `cythonize` is used in setup.py it chokes on cimports from the src/ directory. After some troubleshooting to avoid this choking, I decided to take the alternate route of just avoiding cimporting from there. This is the first of four cimports to remove. - [ ] 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/18420
2017-11-22T01:49:06Z
2017-11-27T00:35:42Z
2017-11-27T00:35:42Z
2017-12-02T11:41:36Z
STYLE: fix flake8=3.4.1
diff --git a/ci/install_travis.sh b/ci/install_travis.sh index 4d8a371ba2994..dac3625cba4ba 100755 --- a/ci/install_travis.sh +++ b/ci/install_travis.sh @@ -107,7 +107,7 @@ time conda install -n pandas pytest>=3.1.0 time pip install pytest-xdist moto if [ "$LINT" ]; then - conda install flake8 + conda install flake8=3.4.1 pip install cpplint fi
https://api.github.com/repos/pandas-dev/pandas/pulls/18418
2017-11-22T01:37:01Z
2017-11-22T01:54:51Z
2017-11-22T01:54:51Z
2017-11-22T02:06:02Z
Fix: DataFrame created with tzinfo cannot use to_dict(orient="records)
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 7c5dc66ce4587..ef25393c41a9b 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -63,7 +63,7 @@ Conversion - Bug in :class:`TimedeltaIndex` subtraction could incorrectly overflow when ``NaT`` is present (:issue:`17791`) - Bug in :class:`DatetimeIndex` subtracting datetimelike from DatetimeIndex could fail to overflow (:issue:`18020`) - Bug in :meth:`IntervalIndex.copy` when copying and ``IntervalIndex`` with non-default ``closed`` (:issue:`18339`) -- +- Bug in :func:`DataFrame.to_dict` where columns of datetime that are tz-aware were not converted to required arrays when used with ``orient='records'``, raising``TypeError` (:issue:`18372`) - - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7145fa709c345..b05cfe41fd9d1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -993,7 +993,7 @@ def to_dict(self, orient='dict', into=dict): for k, v in compat.iteritems(self)) elif orient.lower().startswith('r'): return [into_c((k, _maybe_box_datetimelike(v)) - for k, v in zip(self.columns, row)) + for k, v in zip(self.columns, np.atleast_1d(row))) for row in self.values] elif orient.lower().startswith('i'): return into_c((k, v.to_dict(into)) for k, v in self.iterrows()) diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 5bdb76494f4c8..7d2d18db8d41c 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -1,6 +1,9 @@ # -*- coding: utf-8 -*- +from datetime import datetime + import pytest +import pytz import collections import numpy as np @@ -249,3 +252,18 @@ def test_to_dict_box_scalars(self): result = DataFrame(d).to_dict(orient='records') assert isinstance(result[0]['a'], (int, long)) + + def test_frame_to_dict_tz(self): + # GH18372 When converting to dict with orient='records' columns of + # datetime that are tz-aware were not converted to required arrays + data = [(datetime(2017, 11, 18, 21, 53, 0, 219225, tzinfo=pytz.utc),), + (datetime(2017, 11, 18, 22, 6, 30, 61810, tzinfo=pytz.utc,),)] + df = DataFrame(list(data), columns=["d", ]) + + result = df.to_dict(orient='records') + expected = [ + {'d': Timestamp('2017-11-18 21:53:00.219225+0000', tz=pytz.utc)}, + {'d': Timestamp('2017-11-18 22:06:30.061810+0000', tz=pytz.utc)}, + ] + tm.assert_dict_equal(result[0], expected[0]) + tm.assert_dict_equal(result[1], expected[1])
Columns with datetimez are not returning arrays. Closes #18372 - [X] closes #18372 - [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/18416
2017-11-21T19:39:25Z
2017-11-23T15:35:41Z
2017-11-23T15:35:40Z
2017-12-11T20:22:58Z
DOC: escaping code examples properly in read_csv docstring
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index c15b878822522..558a1f6d76868 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -246,8 +246,8 @@ of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as ``skip_blank_lines=True``), fully commented lines are ignored by the parameter `header` but not by - `skiprows`. For example, if comment='#', parsing '#empty\\na,b,c\\n1,2,3' - with `header=0` will result in 'a,b,c' being + `skiprows`. For example, if ``comment='#'``, parsing + ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in 'a,b,c' being treated as the header. encoding : str, default None Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
- [x] closes #18411 ~~- [ ] tests added / passed~~ ~~- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`~~ ~~- [ ] whatsnew entry~~
https://api.github.com/repos/pandas-dev/pandas/pulls/18412
2017-11-21T15:28:06Z
2017-11-22T10:25:47Z
2017-11-22T10:25:47Z
2017-11-22T15:03:18Z
DOC: clean up whatsnew 0.21.1
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 0645cb265e5d9..7c5dc66ce4587 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -56,19 +56,13 @@ Documentation Changes Bug Fixes ~~~~~~~~~ -- Bug in ``DataFrame.resample(...).apply(...)`` when there is a callable that returns different columns (:issue:`15169`) -- Bug in :class:`TimedeltaIndex` subtraction could incorrectly overflow when ``NaT`` is present (:issue:`17791`) -- Bug in :class:`DatetimeIndex` subtracting datetimelike from DatetimeIndex could fail to overflow (:issue:`18020`) -- Bug in ``pd.Series.rolling.skew()`` and ``rolling.kurt()`` with all equal values has floating issue (:issue:`18044`) -- Bug in ``pd.DataFrameGroupBy.count()`` when counting over a datetimelike column (:issue:`13393`) -- Bug in ``pd.concat`` when empty and non-empty DataFrames or Series are concatenated (:issue:`18178` :issue:`18187`) -- Bug in ``DataFrame.resample(...)`` when there is a time change (DST) and resampling frequecy is 12h or higher (:issue:`15549`) -- Bug in :class:`IntervalIndex` constructor when a list of intervals is passed with non-default ``closed`` (:issue:`18334`) -- Bug in :meth:`IntervalIndex.copy` when copying and ``IntervalIndex`` with non-default ``closed`` (:issue:`18339`) Conversion ^^^^^^^^^^ +- Bug in :class:`TimedeltaIndex` subtraction could incorrectly overflow when ``NaT`` is present (:issue:`17791`) +- Bug in :class:`DatetimeIndex` subtracting datetimelike from DatetimeIndex could fail to overflow (:issue:`18020`) +- Bug in :meth:`IntervalIndex.copy` when copying and ``IntervalIndex`` with non-default ``closed`` (:issue:`18339`) - - - @@ -78,6 +72,7 @@ Indexing - Bug in a boolean comparison of a ``datetime.datetime`` and a ``datetime64[ns]`` dtype Series (:issue:`17965`) - Bug where a ``MultiIndex`` with more than a million records was not raising ``AttributeError`` when trying to access a missing attribute (:issue:`18165`) +- Bug in :class:`IntervalIndex` constructor when a list of intervals is passed with non-default ``closed`` (:issue:`18334`) - - @@ -101,6 +96,9 @@ Plotting Groupby/Resample/Rolling ^^^^^^^^^^^^^^^^^^^^^^^^ +- Bug in ``DataFrame.resample(...).apply(...)`` when there is a callable that returns different columns (:issue:`15169`) +- Bug in ``DataFrame.resample(...)`` when there is a time change (DST) and resampling frequecy is 12h or higher (:issue:`15549`) +- Bug in ``pd.DataFrameGroupBy.count()`` when counting over a datetimelike column (:issue:`13393`) - - - @@ -116,12 +114,14 @@ Reshaping ^^^^^^^^^ - Error message in ``pd.merge_asof()`` for key datatype mismatch now includes datatype of left and right key (:issue:`18068`) +- Bug in ``pd.concat`` when empty and non-empty DataFrames or Series are concatenated (:issue:`18178` :issue:`18187`) - - Numeric ^^^^^^^ +- Bug in ``pd.Series.rolling.skew()`` and ``rolling.kurt()`` with all equal values has floating issue (:issue:`18044`) - - - @@ -130,8 +130,7 @@ Categorical ^^^^^^^^^^^ - Bug in :meth:`DataFrame.astype` where casting to 'category' on an empty ``DataFrame`` causes a segmentation fault (:issue:`18004`) -- Error messages in the testing module have been improved when items have - different ``CategoricalDtype`` (:issue:`18069`) +- Error messages in the testing module have been improved when items have different ``CategoricalDtype`` (:issue:`18069`) - ``CategoricalIndex`` can now correctly take a ``pd.api.types.CategoricalDtype`` as its dtype (:issue:`18116`) Other
https://api.github.com/repos/pandas-dev/pandas/pulls/18408
2017-11-21T13:18:13Z
2017-11-21T13:18:19Z
2017-11-21T13:18:19Z
2017-12-11T20:23:27Z
BUG: Fix Index.putmask makes stack overflow with an invalid mask
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 637ccf0603e0f..51fd3b1076ade 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -73,7 +73,7 @@ Indexing - Bug in a boolean comparison of a ``datetime.datetime`` and a ``datetime64[ns]`` dtype Series (:issue:`17965`) - Bug where a ``MultiIndex`` with more than a million records was not raising ``AttributeError`` when trying to access a missing attribute (:issue:`18165`) - Bug in :class:`IntervalIndex` constructor when a list of intervals is passed with non-default ``closed`` (:issue:`18334`) -- +- Bug in ``Index.putmask`` when an invalid mask passed (:issue:`18368`) - I/O diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index b5d912f4201b5..2696f9f94375d 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1939,7 +1939,10 @@ def putmask(self, mask, value): try: np.putmask(values, mask, self._convert_for_op(value)) return self._shallow_copy(values) - except (ValueError, TypeError): + except (ValueError, TypeError) as err: + if is_object_dtype(self): + raise err + # coerces to object return self.astype(object).putmask(mask, value) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index ee6434431bcfc..ba7795d005721 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -1032,3 +1032,16 @@ def test_map(self): dict_map = {} tm.assert_index_equal(index.map(dict_map), nan_index) + + def test_putmask_with_wrong_mask(self): + # GH18368 + index = self.create_index() + + with pytest.raises(ValueError): + index.putmask(np.ones(len(index) + 1, np.bool), 1) + + with pytest.raises(ValueError): + index.putmask(np.ones(len(index) - 1, np.bool), 1) + + with pytest.raises(ValueError): + index.putmask('foo', 1)
- [x] closes #18368 - [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/18407
2017-11-21T12:32:59Z
2017-11-25T21:01:22Z
2017-11-25T21:01:22Z
2017-12-11T20:22:49Z
CLN: replace %s syntax with .format in tslibs/timedeltas
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 3a1e9de2a6cf6..6ea30642625fe 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -150,7 +150,7 @@ cpdef convert_to_timedelta64(object ts, object unit): ts = np.timedelta64(delta_to_nanoseconds(ts), 'ns') elif not is_timedelta64_object(ts): raise ValueError("Invalid type for timedelta " - "scalar: %s" % type(ts)) + "scalar: {ts_type}".format(ts_type=type(ts))) return ts.astype('timedelta64[ns]') @@ -526,7 +526,7 @@ cdef class _Timedelta(timedelta): int64_t value # nanoseconds object freq # frequency reference bint is_populated # are my components populated - int64_t _sign, _d, _h, _m, _s, _ms, _us, _ns + int64_t _d, _h, _m, _s, _ms, _us, _ns # higher than np.ndarray and np.matrix __array_priority__ = 100 @@ -560,9 +560,9 @@ cdef class _Timedelta(timedelta): return True # only allow ==, != ops - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, - type(other).__name__)) + raise TypeError('Cannot compare type {!r} with type ' \ + '{!r}'.format(type(self).__name__, + type(other).__name__)) if util.is_array(other): return PyObject_RichCompare(np.array([self]), other, op) return PyObject_RichCompare(other, self, reverse_ops[op]) @@ -571,8 +571,9 @@ cdef class _Timedelta(timedelta): return False elif op == Py_NE: return True - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, type(other).__name__)) + raise TypeError('Cannot compare type {!r} with type ' \ + '{!r}'.format(type(self).__name__, + type(other).__name__)) return cmp_scalar(self.value, ots.value, op) @@ -591,10 +592,6 @@ cdef class _Timedelta(timedelta): td64_to_tdstruct(self.value, &tds) self._d = tds.days - if self._d < 0: - self._sign = -1 - else: - self._sign = 1 self._h = tds.hrs self._m = tds.min self._s = tds.sec @@ -680,60 +677,47 @@ cdef class _Timedelta(timedelta): Parameters ---------- - format : None|all|even_day|sub_day|long + format : None|all|sub_day|long Returns ------- converted : string of a Timedelta """ - cdef object sign_pretty, sign2_pretty, seconds_pretty, subs + cdef object sign, seconds_pretty, subs, fmt, comp_dict self._ensure_components() - if self._sign < 0: - sign_pretty = "-" - sign2_pretty = " +" + if self._d < 0: + sign = " +" else: - sign_pretty = "" - sign2_pretty = " " + sign = " " - # show everything if format == 'all': - seconds_pretty = "%02d.%03d%03d%03d" % ( - self._s, self._ms, self._us, self._ns) - return "%d days%s%02d:%02d:%s" % (self._d, - sign2_pretty, self._h, - self._m, seconds_pretty) - - # by default not showing nano - if self._ms or self._us or self._ns: - seconds_pretty = "%02d.%03d%03d" % (self._s, self._ms, self._us) + fmt = "{days} days{sign}{hours:02}:{minutes:02}:{seconds:02}." \ + "{milliseconds:03}{microseconds:03}{nanoseconds:03}" else: - seconds_pretty = "%02d" % self._s - - # if we have a partial day - subs = (self._h or self._m or self._s or - self._ms or self._us or self._ns) - - if format == 'even_day': - if not subs: - return "%d days" % (self._d) - - elif format == 'sub_day': - if not self._d: - - # degenerate, don't need the extra space - if self._sign > 0: - sign2_pretty = "" - return "%s%s%02d:%02d:%s" % (sign_pretty, sign2_pretty, - self._h, self._m, seconds_pretty) - - if subs or format=='long': - return "%d days%s%02d:%02d:%s" % (self._d, - sign2_pretty, self._h, - self._m, seconds_pretty) - return "%d days" % (self._d) + # if we have a partial day + subs = (self._h or self._m or self._s or + self._ms or self._us or self._ns) + + # by default not showing nano + if self._ms or self._us or self._ns: + seconds_fmt = "{seconds:02}.{milliseconds:03}{microseconds:03}" + else: + seconds_fmt = "{seconds:02}" + + if format == 'sub_day' and not self._d: + fmt = "{hours:02}:{minutes:02}:" + seconds_fmt + elif subs or format == 'long': + fmt = "{days} days{sign}{hours:02}:{minutes:02}:" + seconds_fmt + else: + fmt = "{days} days" + + comp_dict = self.components._asdict() + comp_dict['sign'] = sign + + return fmt.format(**comp_dict) def __repr__(self): return "Timedelta('{0}')".format(self._repr_base(format='long')) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 09d6b37bae772..ca3b1cfb18b18 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -2274,7 +2274,7 @@ def _get_format_timedelta64(values, nat_rep='NaT', box=False): consider_values, np.abs(values_int) >= one_day_nanos).sum() == 0 if even_days: - format = 'even_day' + format = None elif all_sub_day: format = 'sub_day' else: diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index bfaa47bf39f83..47632b1399991 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2281,22 +2281,9 @@ def test_none(self): assert drepr(delta_1s) == "0 days 00:00:01" assert drepr(delta_500ms) == "0 days 00:00:00.500000" assert drepr(delta_1d + delta_1s) == "1 days 00:00:01" + assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01" assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000" - - def test_even_day(self): - delta_1d = pd.to_timedelta(1, unit='D') - delta_0d = pd.to_timedelta(0, unit='D') - delta_1s = pd.to_timedelta(1, unit='s') - delta_500ms = pd.to_timedelta(500, unit='ms') - - drepr = lambda x: x._repr_base(format='even_day') - assert drepr(delta_1d) == "1 days" - assert drepr(-delta_1d) == "-1 days" - assert drepr(delta_0d) == "0 days" - assert drepr(delta_1s) == "0 days 00:00:01" - assert drepr(delta_500ms) == "0 days 00:00:00.500000" - assert drepr(delta_1d + delta_1s) == "1 days 00:00:01" - assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000" + assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000" def test_sub_day(self): delta_1d = pd.to_timedelta(1, unit='D') @@ -2311,7 +2298,9 @@ def test_sub_day(self): assert drepr(delta_1s) == "00:00:01" assert drepr(delta_500ms) == "00:00:00.500000" assert drepr(delta_1d + delta_1s) == "1 days 00:00:01" + assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01" assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000" + assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000" def test_long(self): delta_1d = pd.to_timedelta(1, unit='D') @@ -2326,7 +2315,9 @@ def test_long(self): assert drepr(delta_1s) == "0 days 00:00:01" assert drepr(delta_500ms) == "0 days 00:00:00.500000" assert drepr(delta_1d + delta_1s) == "1 days 00:00:01" + assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01" assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000" + assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000" def test_all(self): delta_1d = pd.to_timedelta(1, unit='D') @@ -2335,8 +2326,10 @@ def test_all(self): drepr = lambda x: x._repr_base(format='all') assert drepr(delta_1d) == "1 days 00:00:00.000000000" + assert drepr(-delta_1d) == "-1 days +00:00:00.000000000" assert drepr(delta_0d) == "0 days 00:00:00.000000000" assert drepr(delta_1ns) == "0 days 00:00:00.000000001" + assert drepr(-delta_1d + delta_1ns) == "-1 days +00:00:00.000000001" class TestTimedelta64Formatter(object):
- [X] Progress towards #16130 - [X] tests passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/18405
2017-11-21T11:08:18Z
2017-11-22T00:19:20Z
2017-11-22T00:19:20Z
2017-11-22T00:28:31Z
Read csv category fix
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 86dcc9dcefa09..558dd14f24b4f 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -82,6 +82,7 @@ I/O - Bug in class:`~pandas.io.stata.StataReader` not converting date/time columns with display formatting addressed (:issue:`17990`). Previously columns with display formatting were normally left as ordinal numbers and not converted to datetime objects. - Bug in :func:`read_csv` when reading a compressed UTF-16 encoded file (:issue:`18071`) - Bug in :func:`read_csv` for handling null values in index columns when specifying ``na_filter=False`` (:issue:`5239`) +- Bug in :func:`read_csv` when reading numeric category fields with high cardinality (:issue:`18186`) - Bug in :meth:`DataFrame.to_csv` when the table had ``MultiIndex`` columns, and a list of strings was passed in for ``header`` (:issue:`5539`) - :func:`read_parquet` now allows to specify the columns to read from a parquet file (:issue:`18154`) - :func:`read_parquet` now allows to specify kwargs which are passed to the respective engine (:issue:`18216`) diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 546f08d651eea..f1bd03a097cd0 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -2227,9 +2227,10 @@ def _concatenate_chunks(list chunks): for name in names: arrs = [chunk.pop(name) for chunk in chunks] # Check each arr for consistent types. - dtypes = set(a.dtype for a in arrs) - if len(dtypes) > 1: - common_type = np.find_common_type(dtypes, []) + dtypes = {a.dtype for a in arrs} + numpy_dtypes = {x for x in dtypes if not is_categorical_dtype(x)} + if len(numpy_dtypes) > 1: + common_type = np.find_common_type(numpy_dtypes, []) if common_type == np.object: warning_columns.append(str(name)) diff --git a/pandas/tests/io/parser/dtypes.py b/pandas/tests/io/parser/dtypes.py index 7d3df6201a390..b91ce04673e29 100644 --- a/pandas/tests/io/parser/dtypes.py +++ b/pandas/tests/io/parser/dtypes.py @@ -114,6 +114,17 @@ def test_categorical_dtype(self): actual = self.read_csv(StringIO(data), dtype='category') tm.assert_frame_equal(actual, expected) + @pytest.mark.slow + def test_categorical_dtype_high_cardinality_numeric(self): + # GH 18186 + data = np.sort([str(i) for i in range(524289)]) + expected = DataFrame({'a': Categorical(data, ordered=True)}) + actual = self.read_csv(StringIO('a\n' + '\n'.join(data)), + dtype='category') + actual["a"] = actual["a"].cat.reorder_categories( + np.sort(actual.a.cat.categories), ordered=True) + tm.assert_frame_equal(actual, expected) + def test_categorical_dtype_encoding(self): # GH 10153 pth = tm.get_data_path('unicode_series.csv')
- [x] closes #18186 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whats new entry Summary: - Fix the bug as suggested by @TomAugspurger in issue #18186 - Added a unit test which ensures fix is working.
https://api.github.com/repos/pandas-dev/pandas/pulls/18402
2017-11-21T03:15:53Z
2017-11-22T11:28:42Z
2017-11-22T11:28:41Z
2017-12-11T20:23:18Z
Change UInt64Index._na_value from 0 to np.nan
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 90032a692fd15..ff710cc899ac7 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -52,6 +52,7 @@ Backwards incompatible API changes - :func:`Series.fillna` now raises a ``TypeError`` instead of a ``ValueError`` when passed a list, tuple or DataFrame as a ``value`` (:issue:`18293`) - :func:`pandas.DataFrame.merge` no longer casts a ``float`` column to ``object`` when merging on ``int`` and ``float`` columns (:issue:`16572`) +- The default NA value for :class:`UInt64Index` has changed from 0 to ``NaN``, which impacts methods that mask with NA, such as ``UInt64Index.where()`` (:issue:`18398`) - @@ -127,7 +128,7 @@ Bug Fixes Conversion ^^^^^^^^^^ -- +- Bug in :class:`Index` constructor with `dtype='uint64'` where int-like floats were not coerced to :class:`UInt64Index` (:issue:`18400`) - - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7a34e64724245..c1423fab91a0d 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -251,7 +251,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, # then coerce to integer. try: return cls._try_convert_to_int_index( - data, copy, name) + data, copy, name, dtype) except ValueError: pass @@ -307,7 +307,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, if inferred == 'integer': try: return cls._try_convert_to_int_index( - subarr, copy, name) + subarr, copy, name, dtype) except ValueError: pass @@ -664,7 +664,7 @@ def ravel(self, order='C'): # construction helpers @classmethod - def _try_convert_to_int_index(cls, data, copy, name): + def _try_convert_to_int_index(cls, data, copy, name, dtype): """ Attempt to convert an array of data into an integer index. @@ -685,15 +685,18 @@ def _try_convert_to_int_index(cls, data, copy, name): """ from .numeric import Int64Index, UInt64Index - try: - res = data.astype('i8', copy=False) - if (res == data).all(): - return Int64Index(res, copy=copy, name=name) - except (OverflowError, TypeError, ValueError): - pass + if not is_unsigned_integer_dtype(dtype): + # skip int64 conversion attempt if uint-like dtype is passed, as + # this could return Int64Index when UInt64Index is what's desrired + try: + res = data.astype('i8', copy=False) + if (res == data).all(): + return Int64Index(res, copy=copy, name=name) + except (OverflowError, TypeError, ValueError): + pass - # Conversion to int64 failed (possibly due to - # overflow), so let's try now with uint64. + # Conversion to int64 failed (possibly due to overflow) or was skipped, + # so let's try now with uint64. try: res = data.astype('u8', copy=False) if (res == data).all(): diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index ae6a810ece510..fddbb2de83dca 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -216,7 +216,6 @@ class UInt64Index(NumericIndex): _inner_indexer = libjoin.inner_join_indexer_uint64 _outer_indexer = libjoin.outer_join_indexer_uint64 _can_hold_na = False - _na_value = 0 _engine_type = libindex.UInt64Engine _default_dtype = np.uint64 diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 81360bc0c13f9..43b20f420eb48 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -9,8 +9,7 @@ from pandas import (Series, Index, Float64Index, Int64Index, UInt64Index, RangeIndex, MultiIndex, CategoricalIndex, DatetimeIndex, - TimedeltaIndex, PeriodIndex, IntervalIndex, - notna, isna) + TimedeltaIndex, PeriodIndex, IntervalIndex, isna) from pandas.core.indexes.base import InvalidIndexError from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin from pandas.core.dtypes.common import needs_i8_conversion @@ -529,31 +528,20 @@ def test_numpy_repeat(self): tm.assert_raises_regex(ValueError, msg, np.repeat, i, rep, axis=0) - def test_where(self): + @pytest.mark.parametrize('klass', [list, tuple, np.array, Series]) + def test_where(self, klass): i = self.create_index() - result = i.where(notna(i)) + + cond = [True] * len(i) + result = i.where(klass(cond)) expected = i tm.assert_index_equal(result, expected) - _nan = i._na_value cond = [False] + [True] * len(i[1:]) - expected = pd.Index([_nan] + i[1:].tolist(), dtype=i.dtype) - - result = i.where(cond) + expected = pd.Index([i._na_value] + i[1:].tolist(), dtype=i.dtype) + result = i.where(klass(cond)) tm.assert_index_equal(result, expected) - def test_where_array_like(self): - i = self.create_index() - - _nan = i._na_value - cond = [False] + [True] * (len(i) - 1) - klasses = [list, tuple, np.array, pd.Series] - expected = pd.Index([_nan] + i[1:].tolist(), dtype=i.dtype) - - for klass in klasses: - result = i.where(klass(cond)) - tm.assert_index_equal(result, expected) - def test_setops_errorcases(self): for name, idx in compat.iteritems(self.indices): # # non-iterable input diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 7fefcc859d447..52558c27ce707 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -61,27 +61,18 @@ def test_pickle_round_trip(self): result = tm.round_trip_pickle(idx) tm.assert_index_equal(result, idx) - def test_where(self): + @pytest.mark.parametrize('klass', [list, tuple, np.array, Series]) + def test_where(self, klass): i = self.create_index() - result = i.where(notna(i)) + cond = [True] * len(i) expected = i + result = i.where(klass(cond)) tm.assert_index_equal(result, expected) - i2 = pd.PeriodIndex([pd.NaT, pd.NaT] + i[2:].tolist(), - freq='D') - result = i.where(notna(i2)) - expected = i2 - tm.assert_index_equal(result, expected) - - def test_where_array_like(self): - i = self.create_index() cond = [False] + [True] * (len(i) - 1) - klasses = [list, tuple, np.array, Series] - expected = pd.PeriodIndex([pd.NaT] + i[1:].tolist(), freq='D') - - for klass in klasses: - result = i.where(klass(cond)) - tm.assert_index_equal(result, expected) + expected = PeriodIndex([NaT] + i[1:].tolist(), freq='D') + result = i.where(klass(cond)) + tm.assert_index_equal(result, expected) def test_where_other(self): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index c55f53601848c..99a99cc5cc3eb 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -5,6 +5,7 @@ from datetime import datetime, timedelta import pandas.util.testing as tm +from pandas.core.dtypes.common import is_unsigned_integer_dtype from pandas.core.indexes.api import Index, MultiIndex from pandas.tests.indexes.common import Base @@ -14,7 +15,7 @@ import numpy as np from pandas import (period_range, date_range, Series, - DataFrame, Float64Index, Int64Index, + DataFrame, Float64Index, Int64Index, UInt64Index, CategoricalIndex, DatetimeIndex, TimedeltaIndex, PeriodIndex, isna) from pandas.core.index import _get_combined_index, _ensure_index_from_sequences @@ -201,6 +202,20 @@ def __array__(self, dtype=None): result = pd.Index(ArrayLike(array)) tm.assert_index_equal(result, expected) + @pytest.mark.parametrize('dtype', [ + int, 'int64', 'int32', 'int16', 'int8', 'uint64', 'uint32', + 'uint16', 'uint8']) + def test_constructor_int_dtype_float(self, dtype): + # GH 18400 + if is_unsigned_integer_dtype(dtype): + index_type = UInt64Index + else: + index_type = Int64Index + + expected = index_type([0, 1, 2, 3]) + result = Index([0., 1., 2., 3.], dtype=dtype) + tm.assert_index_equal(result, expected) + def test_constructor_int_dtype_nan(self): # see gh-15187 data = [np.nan] diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index 5e40e06d57413..5e6898f9c8711 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -11,7 +11,7 @@ import numpy as np -from pandas import Categorical, IntervalIndex, compat, notna +from pandas import Categorical, IntervalIndex, compat from pandas.util.testing import assert_almost_equal import pandas.core.config as cf import pandas as pd @@ -269,28 +269,19 @@ def f(x): ordered=False) tm.assert_index_equal(result, exp) - def test_where(self): + @pytest.mark.parametrize('klass', [list, tuple, np.array, pd.Series]) + def test_where(self, klass): i = self.create_index() - result = i.where(notna(i)) + cond = [True] * len(i) expected = i + result = i.where(klass(cond)) tm.assert_index_equal(result, expected) - i2 = pd.CategoricalIndex([np.nan, np.nan] + i[2:].tolist(), - categories=i.categories) - result = i.where(notna(i2)) - expected = i2 - tm.assert_index_equal(result, expected) - - def test_where_array_like(self): - i = self.create_index() cond = [False] + [True] * (len(i) - 1) - klasses = [list, tuple, np.array, pd.Series] - expected = pd.CategoricalIndex([np.nan] + i[1:].tolist(), - categories=i.categories) - - for klass in klasses: - result = i.where(klass(cond)) - tm.assert_index_equal(result, expected) + expected = CategoricalIndex([np.nan] + i[1:].tolist(), + categories=i.categories) + result = i.where(klass(cond)) + tm.assert_index_equal(result, expected) def test_append(self): diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index 399d88309072e..3876fa4f9939d 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -290,20 +290,19 @@ def test_astype(self, closed): expected = pd.Categorical(idx, ordered=True) tm.assert_categorical_equal(result, expected) - def test_where(self, closed): - expected = self.create_index(closed=closed) - result = expected.where(expected.notna()) + @pytest.mark.parametrize('klass', [list, tuple, np.array, pd.Series]) + def test_where(self, closed, klass): + idx = self.create_index(closed=closed) + cond = [True] * len(idx) + expected = idx + result = expected.where(klass(cond)) tm.assert_index_equal(result, expected) - idx = IntervalIndex.from_breaks([1, 2], closed=closed) - result = idx.where([True, False]) - expected = IntervalIndex.from_intervals( - [Interval(1.0, 2.0, closed=closed), np.nan]) + cond = [False] + [True] * len(idx[1:]) + expected = IntervalIndex([np.nan] + idx[1:].tolist()) + result = idx.where(klass(cond)) tm.assert_index_equal(result, expected) - def test_where_array_like(self): - pass - def test_delete(self, closed): expected = IntervalIndex.from_breaks([1, 2], closed=closed) result = self.create_index(closed=closed).delete(0) diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index a96c677852339..030d688f510b0 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -7,7 +7,7 @@ import numpy as np -from pandas import (date_range, notna, Series, Index, Float64Index, +from pandas import (date_range, Series, Index, Float64Index, Int64Index, UInt64Index, RangeIndex) import pandas.util.testing as tm @@ -175,6 +175,18 @@ def test_modulo(self): expected = Index(index.values % 2) tm.assert_index_equal(index % 2, expected) + @pytest.mark.parametrize('klass', [list, tuple, np.array, Series]) + def test_where(self, klass): + i = self.create_index() + cond = [True] * len(i) + expected = i + result = i.where(klass(cond)) + + cond = [False] + [True] * (len(i) - 1) + expected = Float64Index([i._na_value] + i[1:].tolist()) + result = i.where(klass(cond)) + tm.assert_index_equal(result, expected) + class TestFloat64Index(Numeric): _holder = Float64Index @@ -726,31 +738,6 @@ def test_coerce_list(self): arr = Index([1, 2, 3, 4], dtype=object) assert isinstance(arr, Index) - def test_where(self): - i = self.create_index() - result = i.where(notna(i)) - expected = i - tm.assert_index_equal(result, expected) - - _nan = i._na_value - cond = [False] + [True] * len(i[1:]) - expected = pd.Index([_nan] + i[1:].tolist()) - - result = i.where(cond) - tm.assert_index_equal(result, expected) - - def test_where_array_like(self): - i = self.create_index() - - _nan = i._na_value - cond = [False] + [True] * (len(i) - 1) - klasses = [list, tuple, np.array, pd.Series] - expected = pd.Index([_nan] + i[1:].tolist()) - - for klass in klasses: - result = i.where(klass(cond)) - tm.assert_index_equal(result, expected) - def test_get_indexer(self): target = Int64Index(np.arange(10)) indexer = self.index.get_indexer(target) diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index 7d88b547746f6..b4d1c3760f25a 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -10,7 +10,7 @@ import numpy as np -from pandas import (isna, notna, Series, Index, Float64Index, +from pandas import (isna, Series, Index, Float64Index, Int64Index, RangeIndex) import pandas.util.testing as tm @@ -934,31 +934,6 @@ def test_len_specialised(self): i = RangeIndex(0, 5, step) assert len(i) == 0 - def test_where(self): - i = self.create_index() - result = i.where(notna(i)) - expected = i - tm.assert_index_equal(result, expected) - - _nan = i._na_value - cond = [False] + [True] * len(i[1:]) - expected = pd.Index([_nan] + i[1:].tolist()) - - result = i.where(cond) - tm.assert_index_equal(result, expected) - - def test_where_array_like(self): - i = self.create_index() - - _nan = i._na_value - cond = [False] + [True] * (len(i) - 1) - klasses = [list, tuple, np.array, pd.Series] - expected = pd.Index([_nan] + i[1:].tolist()) - - for klass in klasses: - result = i.where(klass(cond)) - tm.assert_index_equal(result, expected) - def test_append(self): # GH16212 RI = RangeIndex
Prerequisite for #18300 - [X] closes #18398 - [X] closes #18400 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry Summary: - Changed `UInt64Index._na_value` from 0 to `np.nan` - Added a `dtype` parameter to `_try_convert_to_int_index` to skip the initial attempt to coerce to `Int64Index` in cases where we really want `UInt64Index` (fix for #18400). - Moved `test_where` and `test_where_array_like` from `TestInt64Index` to the `NumericInt` base class for more generic coverage, and forced it to check that things get coerced to `Float64Index`. The way it was originally written raised a ValueError due to the 0 -> `np.nan` change.
https://api.github.com/repos/pandas-dev/pandas/pulls/18401
2017-11-21T01:14:40Z
2017-11-24T20:18:04Z
2017-11-24T20:18:04Z
2017-12-04T20:43:19Z
Pin correct names to wrapped Index comparison methods
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1359a938e652d..944a2aadfeb3b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -9,7 +9,7 @@ from pandas._libs.lib import is_datetime_array from pandas._libs.tslibs import parsing -from pandas.compat import range, u +from pandas.compat import range, u, set_function_name from pandas.compat.numpy import function as nv from pandas import compat @@ -3890,7 +3890,8 @@ def _evaluate_compare(self, other): except TypeError: return result - return _evaluate_compare + name = '__{name}__'.format(name=op.__name__) + return set_function_name(_evaluate_compare, name, cls) cls.__eq__ = _make_compare(operator.eq) cls.__ne__ = _make_compare(operator.ne) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 84d4585f0a56c..d09e5447431ce 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -722,7 +722,7 @@ def _codes_for_groupby(self, sort): def _add_comparison_methods(cls): """ add in comparison methods """ - def _make_compare(op): + def _make_compare(opname): def _evaluate_compare(self, other): # if we have a Categorical type, then must have the same @@ -745,9 +745,9 @@ def _evaluate_compare(self, other): "have the same categories and ordered " "attributes") - return getattr(self.values, op)(other) + return getattr(self.values, opname)(other) - return _evaluate_compare + return compat.set_function_name(_evaluate_compare, opname, cls) cls.__eq__ = _make_compare('__eq__') cls.__ne__ = _make_compare('__ne__') diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 64b5b9f958880..4f706c3b29a07 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -98,7 +98,7 @@ def f(self): return property(f) -def _dt_index_cmp(opname, nat_result=False): +def _dt_index_cmp(opname, cls, nat_result=False): """ Wrap comparison operations to convert datetime-like to datetime64 """ @@ -135,7 +135,7 @@ def wrapper(self, other): return result return Index(result) - return wrapper + return compat.set_function_name(wrapper, opname, cls) def _ensure_datetime64(other): @@ -277,12 +277,15 @@ def _join_i8_wrapper(joinf, **kwargs): libjoin.left_join_indexer_unique_int64, with_indexers=False) _arrmap = None - __eq__ = _dt_index_cmp('__eq__') - __ne__ = _dt_index_cmp('__ne__', nat_result=True) - __lt__ = _dt_index_cmp('__lt__') - __gt__ = _dt_index_cmp('__gt__') - __le__ = _dt_index_cmp('__le__') - __ge__ = _dt_index_cmp('__ge__') + @classmethod + def _add_comparison_methods(cls): + """ add in comparison methods """ + cls.__eq__ = _dt_index_cmp('__eq__', cls) + cls.__ne__ = _dt_index_cmp('__ne__', cls, nat_result=True) + cls.__lt__ = _dt_index_cmp('__lt__', cls) + cls.__gt__ = _dt_index_cmp('__gt__', cls) + cls.__le__ = _dt_index_cmp('__le__', cls) + cls.__ge__ = _dt_index_cmp('__ge__', cls) _engine_type = libindex.DatetimeEngine @@ -1596,14 +1599,15 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None): else: raise - # alias to offset - def _get_freq(self): + @property + def freq(self): + """get/set the frequency of the Index""" return self.offset - def _set_freq(self, value): + @freq.setter + def freq(self, value): + """get/set the frequency of the Index""" self.offset = value - freq = property(fget=_get_freq, fset=_set_freq, - doc="get/set the frequency of the Index") year = _field_accessor('year', 'Y', "The year of the datetime") month = _field_accessor('month', 'M', @@ -2011,6 +2015,7 @@ def to_julian_date(self): ) / 24.0) +DatetimeIndex._add_comparison_methods() DatetimeIndex._add_numeric_methods_disabled() DatetimeIndex._add_logical_methods_disabled() DatetimeIndex._add_datetimelike_methods() diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 85e3300913000..43522257bd047 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -77,7 +77,7 @@ def dt64arr_to_periodarr(data, freq, tz): _DIFFERENT_FREQ_INDEX = period._DIFFERENT_FREQ_INDEX -def _period_index_cmp(opname, nat_result=False): +def _period_index_cmp(opname, cls, nat_result=False): """ Wrap comparison operations to convert datetime-like to datetime64 """ @@ -115,7 +115,8 @@ def wrapper(self, other): result[self._isnan] = nat_result return result - return wrapper + + return compat.set_function_name(wrapper, opname, cls) def _new_PeriodIndex(cls, **d): @@ -227,12 +228,15 @@ class PeriodIndex(DatelikeOps, DatetimeIndexOpsMixin, Int64Index): _engine_type = libindex.PeriodEngine - __eq__ = _period_index_cmp('__eq__') - __ne__ = _period_index_cmp('__ne__', nat_result=True) - __lt__ = _period_index_cmp('__lt__') - __gt__ = _period_index_cmp('__gt__') - __le__ = _period_index_cmp('__le__') - __ge__ = _period_index_cmp('__ge__') + @classmethod + def _add_comparison_methods(cls): + """ add in comparison methods """ + cls.__eq__ = _period_index_cmp('__eq__', cls) + cls.__ne__ = _period_index_cmp('__ne__', cls, nat_result=True) + 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, copy=False, name=None, tz=None, dtype=None, @@ -1102,6 +1106,7 @@ def tz_localize(self, tz, infer_dst=False): raise NotImplementedError("Not yet implemented for PeriodIndex") +PeriodIndex._add_comparison_methods() PeriodIndex._add_numeric_methods_disabled() PeriodIndex._add_logical_methods_disabled() PeriodIndex._add_datetimelike_methods() diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index c592aa9608d97..93329f4b4e65a 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -52,7 +52,7 @@ def f(self): return property(f) -def _td_index_cmp(opname, nat_result=False): +def _td_index_cmp(opname, cls, nat_result=False): """ Wrap comparison operations to convert timedelta-like to timedelta64 """ @@ -93,7 +93,7 @@ def wrapper(self, other): return result return Index(result) - return wrapper + return compat.set_function_name(wrapper, opname, cls) class TimedeltaIndex(DatetimeIndexOpsMixin, TimelikeOps, Int64Index): @@ -180,12 +180,15 @@ def _join_i8_wrapper(joinf, **kwargs): _datetimelike_methods = ["to_pytimedelta", "total_seconds", "round", "floor", "ceil"] - __eq__ = _td_index_cmp('__eq__') - __ne__ = _td_index_cmp('__ne__', nat_result=True) - __lt__ = _td_index_cmp('__lt__') - __gt__ = _td_index_cmp('__gt__') - __le__ = _td_index_cmp('__le__') - __ge__ = _td_index_cmp('__ge__') + @classmethod + def _add_comparison_methods(cls): + """ add in comparison methods """ + cls.__eq__ = _td_index_cmp('__eq__', cls) + cls.__ne__ = _td_index_cmp('__ne__', cls, nat_result=True) + cls.__lt__ = _td_index_cmp('__lt__', cls) + cls.__gt__ = _td_index_cmp('__gt__', cls) + cls.__le__ = _td_index_cmp('__le__', cls) + cls.__ge__ = _td_index_cmp('__ge__', cls) _engine_type = libindex.TimedeltaEngine @@ -912,6 +915,7 @@ def delete(self, loc): return TimedeltaIndex(new_tds, name=self.name, freq=freq) +TimedeltaIndex._add_comparison_methods() TimedeltaIndex._add_numeric_methods() TimedeltaIndex._add_logical_methods_disabled() TimedeltaIndex._add_datetimelike_methods() diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 307cda7f2d1cb..c55f53601848c 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2174,3 +2174,11 @@ class TestIndexUtils(object): def test_ensure_index_from_sequences(self, data, names, expected): result = _ensure_index_from_sequences(data, names) tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize('opname', ['eq', 'ne', 'le', 'lt', 'ge', 'gt']) +def test_generated_op_names(opname, indices): + index = indices + opname = '__{name}__'.format(name=opname) + method = getattr(index, opname) + assert method.__name__ == opname
Currently: ``` >>> pd.Index.__eq__.__name__ '_evaluate_compare' ``` PR: ``` >>> pd.Index.__eq__.__name__ '__eq__' ``` Same for subclasses and other comparison methods. On the side: use property decorator for `DatetimeIndex.freq` to avoid leaving `_get_freq` and `_set_freq` in the namespace. - [ ] closes #xxxx - [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/18397
2017-11-20T23:39:04Z
2017-11-22T02:22:11Z
2017-11-22T02:22:11Z
2017-11-22T05:57:01Z
Numpy bool msgpack bugfix
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 5829481cdb731..ab7ffecaebc4f 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -87,6 +87,7 @@ I/O - :func:`read_parquet` now allows to specify the columns to read from a parquet file (:issue:`18154`) - :func:`read_parquet` now allows to specify kwargs which are passed to the respective engine (:issue:`18216`) - Bug in parsing integer datetime-like columns with specified format in ``read_sql`` (:issue:`17855`). +- Bug in :meth:`DataFrame.to_msgpack` when serializing data of the numpy.bool_ datatype (:issue:`18390`) Plotting diff --git a/pandas/io/msgpack/_packer.pyx b/pandas/io/msgpack/_packer.pyx index f6383b42d4975..c81069c8e04c0 100644 --- a/pandas/io/msgpack/_packer.pyx +++ b/pandas/io/msgpack/_packer.pyx @@ -8,6 +8,7 @@ from libc.limits cimport * from pandas.io.msgpack.exceptions import PackValueError from pandas.io.msgpack import ExtType +import numpy as np cdef extern from "../../src/msgpack/pack.h": @@ -133,7 +134,7 @@ cdef class Packer(object): while True: if o is None: ret = msgpack_pack_nil(&self.pk) - elif isinstance(o, bool): + elif isinstance(o, (bool, np.bool_)): if o: ret = msgpack_pack_true(&self.pk) else: diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index a28adcf1ee771..bc58ea1c7c228 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -180,6 +180,15 @@ def test_scalar_float(self): x_rec = self.encode_decode(x) tm.assert_almost_equal(x, x_rec) + def test_scalar_bool(self): + x = np.bool_(1) + x_rec = self.encode_decode(x) + tm.assert_almost_equal(x, x_rec) + + x = np.bool_(0) + x_rec = self.encode_decode(x) + tm.assert_almost_equal(x, x_rec) + def test_scalar_complex(self): x = np.random.rand() + 1j * np.random.rand() x_rec = self.encode_decode(x) @@ -263,7 +272,7 @@ def test_numpy_array_complex(self): x.dtype == x_rec.dtype) def test_list_mixed(self): - x = [1.0, np.float32(3.5), np.complex128(4.25), u('foo')] + x = [1.0, np.float32(3.5), np.complex128(4.25), u('foo'), np.bool_(1)] x_rec = self.encode_decode(x) # current msgpack cannot distinguish list/tuple tm.assert_almost_equal(tuple(x), x_rec) @@ -401,6 +410,7 @@ def setup_method(self, method): 'G': [Timestamp('20130102', tz='US/Eastern')] * 5, 'H': Categorical([1, 2, 3, 4, 5]), 'I': Categorical([1, 2, 3, 4, 5], ordered=True), + 'J': (np.bool_(1), 2, 3, 4, 5), } self.d['float'] = Series(data['A']) @@ -410,6 +420,7 @@ def setup_method(self, method): self.d['dt_tz'] = Series(data['G']) self.d['cat_ordered'] = Series(data['H']) self.d['cat_unordered'] = Series(data['I']) + self.d['numpy_bool_mixed'] = Series(data['J']) def test_basic(self):
This fixes issue #18390. It allows for running DataFrame.to_msgpack() with dataframes containing fields of the numpy.bool_ datatype. - [x] closes #18390 - [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/18395
2017-11-20T22:23:54Z
2017-11-23T15:29:02Z
2017-11-23T15:29:02Z
2017-12-11T20:11:37Z
Inclusion of new NAMED_COLORS for MS Excel
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 2fc648d2952c4..81e8881f3f06b 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -277,7 +277,9 @@ def build_font(self, props): NAMED_COLORS = { 'maroon': '800000', + 'brown': 'A52A2A', 'red': 'FF0000', + 'pink': 'FFC0CB', 'orange': 'FFA500', 'yellow': 'FFFF00', 'olive': '808000', @@ -291,6 +293,7 @@ def build_font(self, props): 'navy': '000080', 'black': '000000', 'gray': '808080', + 'grey': '808080', 'silver': 'C0C0C0', 'white': 'FFFFFF', } diff --git a/pandas/tests/io/formats/test_to_excel.py b/pandas/tests/io/formats/test_to_excel.py index 26a9bb018f30a..2d691bf2c5d8e 100644 --- a/pandas/tests/io/formats/test_to_excel.py +++ b/pandas/tests/io/formats/test_to_excel.py @@ -4,7 +4,9 @@ """ import pytest +import pandas.util.testing as tm +from warnings import catch_warnings from pandas.io.formats.excel import CSSToExcelConverter @@ -212,3 +214,61 @@ def test_css_to_excel_multiple(): def test_css_to_excel_inherited(css, inherited, expected): convert = CSSToExcelConverter(inherited) assert expected == convert(css) + + +@pytest.mark.parametrize("input_color,output_color", ( + [(name, rgb) for name, rgb in CSSToExcelConverter.NAMED_COLORS.items()] + + [("#" + rgb, rgb) for rgb in CSSToExcelConverter.NAMED_COLORS.values()] + + [("#F0F", "FF00FF"), ("#ABC", "AABBCC")]) +) +def test_css_to_excel_good_colors(input_color, output_color): + # see gh-18392 + css = ("border-top-color: {color}; " + "border-right-color: {color}; " + "border-bottom-color: {color}; " + "border-left-color: {color}; " + "background-color: {color}; " + "color: {color}").format(color=input_color) + + expected = dict() + + expected["fill"] = { + "patternType": "solid", + "fgColor": output_color + } + + expected["font"] = { + "color": output_color + } + + expected["border"] = { + k: { + "color": output_color, + } for k in ("top", "right", "bottom", "left") + } + + with tm.assert_produces_warning(None): + convert = CSSToExcelConverter() + assert expected == convert(css) + + +@pytest.mark.parametrize("input_color", [None, "not-a-color"]) +def test_css_to_excel_bad_colors(input_color): + # see gh-18392 + css = ("border-top-color: {color}; " + "border-right-color: {color}; " + "border-bottom-color: {color}; " + "border-left-color: {color}; " + "background-color: {color}; " + "color: {color}").format(color=input_color) + + expected = dict() + + if input_color is not None: + expected["fill"] = { + "patternType": "solid" + } + + with catch_warnings(record=True): + convert = CSSToExcelConverter() + assert expected == convert(css)
- [ ] 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/18392
2017-11-20T19:46:40Z
2018-01-24T01:35:20Z
2018-01-24T01:35:20Z
2018-01-24T01:35:22Z
CLN/PERF: simplify tslib.get_time_micros
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index ea4f4728a0741..2c43bed4ad053 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -730,29 +730,6 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', return oresult -# ---------------------------------------------------------------------- -# Accessors - - -def get_time_micros(ndarray[int64_t] dtindex): - """ - Datetime as int64 representation to a structured array of fields - """ - cdef: - Py_ssize_t i, n = len(dtindex) - pandas_datetimestruct dts - ndarray[int64_t] micros - - micros = np.empty(n, dtype=np.int64) - - for i in range(n): - dt64_to_dtstruct(dtindex[i], &dts) - micros[i] = 1000000LL * (dts.hour * 60 * 60 + - 60 * dts.min + dts.sec) + dts.us - - return micros - - # ---------------------------------------------------------------------- # Some general helper functions diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index e813fad1d3fa7..3de361c511fbf 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -23,6 +23,26 @@ from np_datetime cimport (pandas_datetimestruct, pandas_timedeltastruct, from nattype cimport NPY_NAT +def get_time_micros(ndarray[int64_t] dtindex): + """ + Return the number of microseconds in the time component of a + nanosecond timestamp. + + Parameters + ---------- + dtindex : ndarray[int64_t] + + Returns + ------- + micros : ndarray[int64_t] + """ + cdef: + ndarray[int64_t] micros + + micros = np.mod(dtindex, 86400000000000, dtype=np.int64) // 1000LL + return micros + + def build_field_sarray(ndarray[int64_t] dtindex): """ Datetime as int64 representation to a structured array of fields diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e08bf4a625bce..111ba0c92aa9b 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -926,7 +926,7 @@ def _get_time_micros(self): values = self.asi8 if self.tz is not None and self.tz is not utc: values = self._local_timestamps() - return libts.get_time_micros(values) + return fields.get_time_micros(values) def to_series(self, keep_tz=False): """
`tslib.get_time_micros` implementation is way more complicated than it needs to be. Instead of calling `dt64_to_dtstruct` in a loop, this changes the function to one call to `np.mod`. AFAIK the `np.mod` call is to the python function, not sure if numpy exposes a cython version of mod. Then again, the function is only used once in `indexes.datetimes` and isn't all that perf sensitive. It might not need to be in cython in the first place. Re-wrote inaccurate docstring.
https://api.github.com/repos/pandas-dev/pandas/pulls/18389
2017-11-20T16:28:16Z
2017-11-24T16:59:13Z
2017-11-24T16:59:13Z
2017-11-24T19:06:13Z
CLN: Add teardowns for some benchmarks (#17616)
diff --git a/asv_bench/benchmarks/hdfstore_bench.py b/asv_bench/benchmarks/hdfstore_bench.py index 7d490180e8af6..5aa8f76917797 100644 --- a/asv_bench/benchmarks/hdfstore_bench.py +++ b/asv_bench/benchmarks/hdfstore_bench.py @@ -40,10 +40,11 @@ def setup(self): def teardown(self): self.store.close() + self.remove(self.f) def remove(self, f): try: - os.remove(self.f) + os.remove(f) except: pass @@ -115,10 +116,11 @@ def setup(self): def teardown(self): self.store.close() + self.remove(self.f) def remove(self, f): try: - os.remove(self.f) + os.remove(f) except: pass diff --git a/asv_bench/benchmarks/io_bench.py b/asv_bench/benchmarks/io_bench.py index d5eedf63dfe8a..c718b13912e73 100644 --- a/asv_bench/benchmarks/io_bench.py +++ b/asv_bench/benchmarks/io_bench.py @@ -8,18 +8,36 @@ import timeit -class frame_to_csv(object): +class _BenchTeardown(object): + """ + base class for teardown method implementation + """ + fname = None + + def remove(self, f): + try: + os.remove(f) + except: + pass + + def teardown(self): + self.remove(self.fname) + + +class frame_to_csv(_BenchTeardown): goal_time = 0.2 + fname = '__test__.csv' def setup(self): self.df = DataFrame(np.random.randn(3000, 30)) def time_frame_to_csv(self): - self.df.to_csv('__test__.csv') + self.df.to_csv(self.fname) -class frame_to_csv2(object): +class frame_to_csv2(_BenchTeardown): goal_time = 0.2 + fname = '__test__.csv' def setup(self): self.df = DataFrame({'A': range(50000), }) @@ -28,22 +46,24 @@ def setup(self): self.df['D'] = (self.df.A + 3.0) def time_frame_to_csv2(self): - self.df.to_csv('__test__.csv') + self.df.to_csv(self.fname) -class frame_to_csv_date_formatting(object): +class frame_to_csv_date_formatting(_BenchTeardown): goal_time = 0.2 + fname = '__test__.csv' def setup(self): self.rng = date_range('1/1/2000', periods=1000) self.data = DataFrame(self.rng, index=self.rng) def time_frame_to_csv_date_formatting(self): - self.data.to_csv('__test__.csv', date_format='%Y%m%d') + self.data.to_csv(self.fname, date_format='%Y%m%d') -class frame_to_csv_mixed(object): +class frame_to_csv_mixed(_BenchTeardown): goal_time = 0.2 + fname = '__test__.csv' def setup(self): self.df_float = DataFrame(np.random.randn(5000, 5), dtype='float64', columns=self.create_cols('float')) @@ -55,7 +75,7 @@ def setup(self): self.df = concat([self.df_float, self.df_int, self.df_bool, self.df_object, self.df_dt], axis=1) def time_frame_to_csv_mixed(self): - self.df.to_csv('__test__.csv') + self.df.to_csv(self.fname) def create_cols(self, name): return [('%s%03d' % (name, i)) for i in range(5)] @@ -94,28 +114,30 @@ def time_read_csv_infer_datetime_format_ymd(self): read_csv(StringIO(self.data), header=None, names=['foo'], parse_dates=['foo'], infer_datetime_format=True) -class read_csv_skiprows(object): +class read_csv_skiprows(_BenchTeardown): goal_time = 0.2 + fname = '__test__.csv' def setup(self): self.index = tm.makeStringIndex(20000) self.df = DataFrame({'float1': randn(20000), 'float2': randn(20000), 'string1': (['foo'] * 20000), 'bool1': ([True] * 20000), 'int1': np.random.randint(0, 200000, size=20000), }, index=self.index) - self.df.to_csv('__test__.csv') + self.df.to_csv(self.fname) def time_read_csv_skiprows(self): - read_csv('__test__.csv', skiprows=10000) + read_csv(self.fname, skiprows=10000) -class read_csv_standard(object): +class read_csv_standard(_BenchTeardown): goal_time = 0.2 + fname = '__test__.csv' def setup(self): self.index = tm.makeStringIndex(10000) self.df = DataFrame({'float1': randn(10000), 'float2': randn(10000), 'string1': (['foo'] * 10000), 'bool1': ([True] * 10000), 'int1': np.random.randint(0, 100000, size=10000), }, index=self.index) - self.df.to_csv('__test__.csv') + self.df.to_csv(self.fname) def time_read_csv_standard(self): - read_csv('__test__.csv') + read_csv(self.fname) class read_parse_dates_iso8601(object): @@ -152,15 +174,16 @@ def time_read_uint64_na_values(self): read_csv(StringIO(self.data1), header=None, na_values=self.na_values) -class write_csv_standard(object): +class write_csv_standard(_BenchTeardown): goal_time = 0.2 + fname = '__test__.csv' def setup(self): self.index = tm.makeStringIndex(10000) self.df = DataFrame({'float1': randn(10000), 'float2': randn(10000), 'string1': (['foo'] * 10000), 'bool1': ([True] * 10000), 'int1': np.random.randint(0, 100000, size=10000), }, index=self.index) def time_write_csv_standard(self): - self.df.to_csv('__test__.csv') + self.df.to_csv(self.fname) class read_csv_from_s3(object): @@ -195,7 +218,7 @@ def time_read_nrows(self, compression, engine): compression=compression, engine=engine) -class read_json_lines(object): +class read_json_lines(_BenchTeardown): goal_time = 0.2 fname = "__test__.json" @@ -205,12 +228,6 @@ def setup(self): self.df = DataFrame({('float{0}'.format(i), randn(self.N)) for i in range(self.C)}) self.df.to_json(self.fname,orient="records",lines=True) - def teardown(self): - try: - os.remove(self.fname) - except: - pass - def time_read_json_lines(self): pd.read_json(self.fname, lines=True) diff --git a/asv_bench/benchmarks/packers.py b/asv_bench/benchmarks/packers.py index e3d95aa3586c5..927f1505e85c6 100644 --- a/asv_bench/benchmarks/packers.py +++ b/asv_bench/benchmarks/packers.py @@ -9,6 +9,7 @@ import numpy as np from random import randrange + class _Packers(object): goal_time = 0.2 @@ -24,12 +25,15 @@ def _setup(self): def remove(self, f): try: - os.remove(self.f) + os.remove(f) except: pass + def teardown(self): + self.remove(self.f) + + class Packers(_Packers): - goal_time = 0.2 def setup(self): self._setup() @@ -38,8 +42,8 @@ def setup(self): def time_packers_read_csv(self): pd.read_csv(self.f) + class packers_read_excel(_Packers): - goal_time = 0.2 def setup(self): self._setup() @@ -54,7 +58,6 @@ def time_packers_read_excel(self): class packers_read_hdf_store(_Packers): - goal_time = 0.2 def setup(self): self._setup() @@ -115,6 +118,7 @@ def setup(self): def time_packers_read_pickle(self): pd.read_pickle(self.f) + class packers_read_sql(_Packers): def setup(self): @@ -177,9 +181,6 @@ def setup(self): def time_write_csv(self): self.df.to_csv(self.f) - def teardown(self): - self.remove(self.f) - class Excel(_Packers): @@ -217,8 +218,6 @@ def time_write_hdf_store(self): def time_write_hdf_table(self): self.df2.to_hdf(self.f, 'df', table=True) - def teardown(self): - self.remove(self.f) class JSON(_Packers): @@ -259,9 +258,6 @@ def time_write_json_mixed_float_int_str(self): def time_write_json_lines(self): self.df.to_json(self.f, orient="records", lines=True) - def teardown(self): - self.remove(self.f) - class MsgPack(_Packers): @@ -271,9 +267,6 @@ def setup(self): def time_write_msgpack(self): self.df2.to_msgpack(self.f) - def teardown(self): - self.remove(self.f) - class Pickle(_Packers): @@ -283,9 +276,6 @@ def setup(self): def time_write_pickle(self): self.df2.to_pickle(self.f) - def teardown(self): - self.remove(self.f) - class SQL(_Packers): @@ -313,6 +303,3 @@ def time_write_stata(self): def time_write_stata_with_validation(self): self.df3.to_stata(self.f, {'index': 'tc', }) - - def teardown(self): - self.remove(self.f)
Added teardown functions for hdfstore, io and packers asv benchmarks. - [x] closes #17616 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/18388
2017-11-20T15:29:21Z
2017-11-23T19:41:04Z
2017-11-23T19:41:04Z
2017-11-23T19:43:02Z
CLN: Remove unused cimports of float16
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index e9ef9c4ffe24b..bb7f69f04b32d 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -20,7 +20,7 @@ from numpy cimport (ndarray, NPY_FLOAT32, NPY_FLOAT64, NPY_OBJECT, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, - uint32_t, uint64_t, float16_t, float32_t, float64_t, + uint32_t, uint64_t, float32_t, float64_t, double_t) diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index e1312a40971f0..dc0fdcf123c32 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -11,7 +11,7 @@ cnp.import_array() from numpy cimport (ndarray, double_t, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, - uint32_t, uint64_t, float16_t, float32_t, float64_t) + uint32_t, uint64_t, float32_t, float64_t) from libc.stdlib cimport malloc, free diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx index 8dbc70a0bdbe9..6befc5e60f5f6 100644 --- a/pandas/_libs/join.pyx +++ b/pandas/_libs/join.pyx @@ -10,7 +10,7 @@ np.import_array() from numpy cimport (ndarray, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, - uint32_t, uint64_t, float16_t, float32_t, float64_t) + uint32_t, uint64_t, float32_t, float64_t) cdef double NaN = <double> np.NaN cdef double nan = NaN diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx index db2e8b43d1ead..c4104b66e009f 100644 --- a/pandas/_libs/reshape.pyx +++ b/pandas/_libs/reshape.pyx @@ -10,7 +10,7 @@ np.import_array() from numpy cimport (ndarray, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, - uint32_t, uint64_t, float16_t, float32_t, float64_t) + uint32_t, uint64_t, float32_t, float64_t) cdef double NaN = <double> np.NaN cdef double nan = NaN diff --git a/pandas/_libs/sparse.pyx b/pandas/_libs/sparse.pyx index 5484cbda5bdf9..bbdd5f0d8334c 100644 --- a/pandas/_libs/sparse.pyx +++ b/pandas/_libs/sparse.pyx @@ -1,5 +1,5 @@ from numpy cimport (ndarray, uint8_t, int64_t, int32_t, int16_t, int8_t, - float64_t, float32_t, float16_t) + float64_t, float32_t) cimport numpy as np cimport cython
Part of the "move towards cythonize" sequence. - [ ] 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/18387
2017-11-20T15:06:11Z
2017-11-22T02:05:09Z
2017-11-22T02:05:09Z
2017-12-08T19:40:10Z
API: change datetimelike Index to raise IndexError instead ValueError
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 4a27bf54de695..d43d5bec7175f 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -150,6 +150,8 @@ Indexing - Bug in :class:`Index`` construction from list of mixed type tuples (:issue:`18505`) - Bug in :class:`IntervalIndex` where empty and purely NA data was constructed inconsistently depending on the construction method (:issue:`18421`) - Bug in ``IntervalIndex.symmetric_difference()`` where the symmetric difference with a non-``IntervalIndex`` did not raise (:issue:`18475`) +- Bug in indexing a datetimelike ``Index`` that raised ``ValueError`` instead of ``IndexError`` (:issue:`18386`). + I/O ^^^ diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 5643d886a4fec..c15727c247e1e 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -263,7 +263,9 @@ def __getitem__(self, key): is_int = is_integer(key) if is_scalar(key) and not is_int: - raise ValueError + raise IndexError("only integers, slices (`:`), ellipsis (`...`), " + "numpy.newaxis (`None`) and integer or boolean " + "arrays are valid indices") getitem = self._data.__getitem__ if is_int: diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 0b71f6bb3fb01..0b782e600822a 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -623,12 +623,13 @@ def test_empty_fancy(self): # Index. pytest.raises(IndexError, idx.__getitem__, empty_farr) - def test_getitem(self): - arr = np.array(self.dateIndex) - exp = self.dateIndex[5] - exp = _to_m8(exp) + def test_getitem_error(self, indices): - assert exp == arr[5] + with pytest.raises(IndexError): + indices[101] + + with pytest.raises(IndexError): + indices['no_int'] def test_intersection(self): first = self.strIndex[:20]
I noticed this in the plotting PR that DatetimeIndex et al behave a bit strange on an invalid index: ``` In [41]: pd.Index([1, 2, 3])['no_int'] ... IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices In [42]: pd.DatetimeIndex([1, 2, 3])['no_int'] ... ValueError: ``` I think this should be consistent IndexError ?
https://api.github.com/repos/pandas-dev/pandas/pulls/18386
2017-11-20T14:53:11Z
2017-12-01T01:06:59Z
2017-12-01T01:06:59Z
2017-12-01T01:07:03Z
BUG: fillna maximum recursion depth exceeded in cmp (GH18159).
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index a9608594be547..73962efad61e7 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -56,6 +56,8 @@ Documentation Changes Bug Fixes ~~~~~~~~~ +- + Conversion ^^^^^^^^^^ @@ -65,6 +67,7 @@ Conversion - Bug in :meth:`IntervalIndex.copy` when copying and ``IntervalIndex`` with non-default ``closed`` (:issue:`18339`) - Bug in :func:`DataFrame.to_dict` where columns of datetime that are tz-aware were not converted to required arrays when used with ``orient='records'``, raising``TypeError` (:issue:`18372`) - Bug in :class:`DateTimeIndex` and :meth:`date_range` where mismatching tz-aware ``start`` and ``end`` timezones would not raise an err if ``end.tzinfo`` is None (:issue:`18431`) +- Bug in :meth:`Series.fillna` which raised when passed a long integer on Python 2 (:issue:`18159`). - Indexing diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e5db5679c43f6..4169a001655cb 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -1847,8 +1847,10 @@ def _can_hold_element(self, element): if tipo is not None: return (issubclass(tipo.type, (np.floating, np.integer)) and not issubclass(tipo.type, (np.datetime64, np.timedelta64))) - return (isinstance(element, (float, int, np.floating, np.int_)) and - not isinstance(element, (bool, np.bool_, datetime, timedelta, + return ( + isinstance( + element, (float, int, np.floating, np.int_, compat.long)) + and not isinstance(element, (bool, np.bool_, datetime, timedelta, np.datetime64, np.timedelta64))) def to_native_types(self, slicer=None, na_rep='', float_format=None, @@ -1896,9 +1898,11 @@ def _can_hold_element(self, element): if tipo is not None: return issubclass(tipo.type, (np.floating, np.integer, np.complexfloating)) - return (isinstance(element, - (float, int, complex, np.float_, np.int_)) and - not isinstance(element, (bool, np.bool_))) + return ( + isinstance( + element, + (float, int, complex, np.float_, np.int_, compat.long)) + and not isinstance(element, (bool, np.bool_))) def should_store(self, value): return issubclass(value.dtype.type, np.complexfloating) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index a22d0174947e1..08f769e02e267 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -1222,7 +1222,9 @@ class TestCanHoldElement(object): @pytest.mark.parametrize('value, dtype', [ (1, 'i8'), (1.0, 'f8'), + (2**63, 'f8'), (1j, 'complex128'), + (2**63, 'complex128'), (True, 'bool'), (np.timedelta64(20, 'ns'), '<m8[ns]'), (np.datetime64(20, 'ns'), '<M8[ns]'),
- [x] closes #18159 - [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/18385
2017-11-20T13:08:57Z
2017-12-09T00:27:05Z
2017-12-09T00:27:05Z
2017-12-12T02:38:30Z
doc: fix typo in doc
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 38d9baee834b3..c15b878822522 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -63,7 +63,7 @@ object with a read() method (such as a file handle or StringIO) The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could - be file ://localhost/path/to/table.csv + be file://localhost/path/to/table.csv %s delim_whitespace : boolean, default False Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be
- [ ] 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/18384
2017-11-20T09:56:32Z
2017-11-20T11:09:02Z
2017-11-20T11:09:02Z
2017-11-20T11:09:08Z
CLN: Replace comprehensions list/set/dict functions with corresponding symbols
diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index 7f95e8d06eb72..2ee5f5da7a84a 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -23,9 +23,9 @@ def setup(self): self.some_dict = list(self.data.values())[0] self.dict_list = [dict(zip(self.columns, row)) for row in self.frame.values] - self.data2 = dict( - ((i, dict(((j, float(j)) for j in range(100)))) for i in - range(2000))) + self.data2 = {i: {j: float(j) for j in range(100)} + for i in range(2000)} + def time_frame_ctor_list_of_dict(self): DataFrame(self.dict_list) diff --git a/asv_bench/benchmarks/packers.py b/asv_bench/benchmarks/packers.py index 927f1505e85c6..758162f000e8d 100644 --- a/asv_bench/benchmarks/packers.py +++ b/asv_bench/benchmarks/packers.py @@ -18,7 +18,7 @@ def _setup(self): self.N = 100000 self.C = 5 self.index = date_range('20000101', periods=self.N, freq='H') - self.df = DataFrame(dict(('float{0}'.format(i), randn(self.N)) for i in range(self.C)), index=self.index) + self.df = DataFrame({'float{0}'.format(i): randn(self.N) for i in range(self.C)}, index=self.index) self.df2 = self.df.copy() self.df2['object'] = [('%08x' % randrange((16 ** 8))) for _ in range(self.N)] self.remove(self.f) diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py index 63562f90eab2b..157d5fe1e3948 100644 --- a/asv_bench/benchmarks/replace.py +++ b/asv_bench/benchmarks/replace.py @@ -23,7 +23,7 @@ class replace_large_dict(object): def setup(self): self.n = (10 ** 6) self.start_value = (10 ** 5) - self.to_rep = dict(((i, (self.start_value + i)) for i in range(self.n))) + self.to_rep = {i: self.start_value + i for i in range(self.n)} self.s = Series(np.random.randint(self.n, size=(10 ** 3))) def time_replace_large_dict(self): @@ -35,8 +35,8 @@ class replace_convert(object): def setup(self): self.n = (10 ** 3) - self.to_ts = dict(((i, pd.Timestamp(i)) for i in range(self.n))) - self.to_td = dict(((i, pd.Timedelta(i)) for i in range(self.n))) + self.to_ts = {i: pd.Timestamp(i) for i in range(self.n)} + self.to_td = {i: pd.Timedelta(i) for i in range(self.n)} self.s = Series(np.random.randint(self.n, size=(10 ** 3))) self.df = DataFrame({'A': np.random.randint(self.n, size=(10 ** 3)), 'B': np.random.randint(self.n, size=(10 ** 3))}) diff --git a/doc/sphinxext/numpydoc/phantom_import.py b/doc/sphinxext/numpydoc/phantom_import.py index e0bd645f5db76..f33dd838e8bb3 100755 --- a/doc/sphinxext/numpydoc/phantom_import.py +++ b/doc/sphinxext/numpydoc/phantom_import.py @@ -60,8 +60,8 @@ def import_phantom_module(xml_file): # Sort items so that # - Base classes come before classes inherited from them # - Modules come before their contents - all_nodes = dict((n.attrib['id'], n) for n in root) - + all_nodes = {n.attrib['id']: n for n in root} + def _get_bases(node, recurse=False): bases = [x.attrib['ref'] for x in node.findall('base')] if recurse: diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 526595e3a2eda..b03d48bba1649 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -33,7 +33,7 @@ from np_datetime cimport (pandas_datetimestruct, _MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] _int_to_month = {(k + 1): v for k, v in enumerate(_MONTHS)} -_month_to_int = dict((v, k) for k, v in _int_to_month.items()) +_month_to_int = {v: k for k, v in _int_to_month.items()} class WeekDay(object): diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 388075903a8ba..0692d985b4877 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -53,7 +53,7 @@ _ONE_HOUR = 60 * _ONE_MINUTE _ONE_DAY = 24 * _ONE_HOUR DAYS = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] -_weekday_rule_aliases = dict((k, v) for k, v in enumerate(DAYS)) +_weekday_rule_aliases = {k: v for k, v in enumerate(DAYS)} _MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] diff --git a/pandas/_version.py b/pandas/_version.py index 4a469ebb8630e..624c7b5cd63a1 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -141,11 +141,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set(r.strip() for r in refnames.strip("()").split(",")) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -154,7 +154,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set(r for r in refs if re.search(r'\d', r)) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '{}', no digits".format(",".join(refs - tags))) if verbose: diff --git a/pandas/core/common.py b/pandas/core/common.py index 8e12ce3647340..76a69030463ec 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -347,7 +347,7 @@ def map_indices_py(arr): Returns a dictionary with (element, index) pairs for each element in the given array/list """ - return dict((x, i) for i, x in enumerate(arr)) + return {x: i for i, x in enumerate(arr)} def union(*seqs): diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 7f9245bb31530..c1ba018adbcec 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -459,7 +459,7 @@ def _concat_datetimetz(to_concat, name=None): it is used in DatetimeIndex.append also """ # do not pass tz to set because tzlocal cannot be hashed - if len(set(str(x.dtype) for x in to_concat)) != 1: + if len({str(x.dtype) for x in to_concat}) != 1: raise ValueError('to_concat must have the same tz') tz = to_concat[0].tz # no need to localize because internal repr will not be changed @@ -525,7 +525,7 @@ def convert_sparse(x, axis): if len(typs) == 1: # concat input as it is if all inputs are sparse # and have the same fill_value - fill_values = set(c.fill_value for c in to_concat) + fill_values = {c.fill_value for c in to_concat} if len(fill_values) == 1: sp_values = [c.sp_values for c in to_concat] indexes = [c.sp_index.to_int_index() for c in to_concat] diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b05cfe41fd9d1..ae1bbd89df9b2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -347,7 +347,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None, elif isinstance(data, (np.ndarray, Series, Index)): if data.dtype.names: data_columns = list(data.dtype.names) - data = dict((k, data[k]) for k in data_columns) + data = {k: data[k] for k in data_columns} if columns is None: columns = data_columns mgr = self._init_dict(data, index, columns, dtype=dtype) @@ -417,8 +417,7 @@ def _init_dict(self, data, index, columns, dtype=None): extract_index(list(data.values())) # prefilter if columns passed - data = dict((k, v) for k, v in compat.iteritems(data) - if k in columns) + data = {k: v for k, v in compat.iteritems(data) if k in columns} if index is None: index = extract_index(list(data.values())) @@ -3895,7 +3894,7 @@ def f(col): return self._constructor_sliced(r, index=new_index, dtype=r.dtype) - result = dict((col, f(col)) for col in this) + result = {col: f(col) for col in this} # non-unique else: @@ -3906,7 +3905,7 @@ def f(i): return self._constructor_sliced(r, index=new_index, dtype=r.dtype) - result = dict((i, f(i)) for i, col in enumerate(this.columns)) + result = {i: f(i) for i, col in enumerate(this.columns)} result = self._constructor(result, index=new_index, copy=False) result.columns = new_columns return result @@ -3984,7 +3983,7 @@ def _compare_frame_evaluate(self, other, func, str_rep, try_cast=True): if self.columns.is_unique: def _compare(a, b): - return dict((col, func(a[col], b[col])) for col in a.columns) + return {col: func(a[col], b[col]) for col in a.columns} new_data = expressions.evaluate(_compare, str_rep, self, other) return self._constructor(data=new_data, index=self.index, @@ -3993,8 +3992,8 @@ def _compare(a, b): else: def _compare(a, b): - return dict((i, func(a.iloc[:, i], b.iloc[:, i])) - for i, col in enumerate(a.columns)) + return {i: func(a.iloc[:, i], b.iloc[:, i]) + for i, col in enumerate(a.columns)} new_data = expressions.evaluate(_compare, str_rep, self, other) result = self._constructor(data=new_data, index=self.index, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 782971a742b54..548f228cdd96b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -235,10 +235,10 @@ def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None, """ cls._AXIS_ORDERS = axes - cls._AXIS_NUMBERS = dict((a, i) for i, a in enumerate(axes)) + cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)} cls._AXIS_LEN = len(axes) cls._AXIS_ALIASES = aliases or dict() - cls._AXIS_IALIASES = dict((v, k) for k, v in cls._AXIS_ALIASES.items()) + cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()} cls._AXIS_NAMES = dict(enumerate(axes)) cls._AXIS_SLICEMAP = slicers or None cls._AXIS_REVERSED = axes_are_reversed @@ -279,21 +279,21 @@ def set_axis(a, i): def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" - d = dict((a, self._get_axis(a)) for a in (axes or self._AXIS_ORDERS)) + d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d @staticmethod def _construct_axes_dict_from(self, axes, **kwargs): """Return an axes dictionary for the passed axes.""" - d = dict((a, ax) for a, ax in zip(self._AXIS_ORDERS, axes)) + d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)} d.update(kwargs) return d def _construct_axes_dict_for_slice(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" - d = dict((self._AXIS_SLICEMAP[a], self._get_axis(a)) - for a in (axes or self._AXIS_ORDERS)) + d = {self._AXIS_SLICEMAP[a]: self._get_axis(a) + for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d @@ -329,7 +329,7 @@ def _construct_axes_from_arguments(self, args, kwargs, require_all=False): raise TypeError("not enough/duplicate arguments " "specified!") - axes = dict((a, kwargs.pop(a, None)) for a in self._AXIS_ORDERS) + axes = {a: kwargs.pop(a, None) for a in self._AXIS_ORDERS} return axes, kwargs @classmethod @@ -1172,7 +1172,7 @@ def to_dense(self): # Picklability def __getstate__(self): - meta = dict((k, getattr(self, k, None)) for k in self._metadata) + meta = {k: getattr(self, k, None) for k in self._metadata} return dict(_data=self._data, _typ=self._typ, _metadata=self._metadata, **meta) @@ -4277,8 +4277,8 @@ def fillna(self, value=None, method=None, axis=None, inplace=False, elif self.ndim == 3: # fill in 2d chunks - result = dict((col, s.fillna(method=method, value=value)) - for col, s in self.iteritems()) + result = {col: s.fillna(method=method, value=value) + for col, s in self.iteritems()} new_obj = self._constructor.\ from_dict(result).__finalize__(self) new_data = new_obj._data @@ -5681,7 +5681,7 @@ def align(self, other, join='outer', axis=None, level=None, copy=True, # this means other is a DataFrame, and we need to broadcast # self cons = self._constructor_expanddim - df = cons(dict((c, self) for c in other.columns), + df = cons({c: self for c in other.columns}, **other._construct_axes_dict()) return df._align_frame(other, join=join, axis=axis, level=level, copy=copy, @@ -5691,7 +5691,7 @@ def align(self, other, join='outer', axis=None, level=None, copy=True, # this means self is a DataFrame, and we need to broadcast # other cons = other._constructor_expanddim - df = cons(dict((c, other) for c in self.columns), + df = cons({c: other for c in self.columns}, **self._construct_axes_dict()) return self._align_frame(df, join=join, axis=axis, level=level, copy=copy, fill_value=fill_value, diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 8338df33f5cde..ba180cc98cb08 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -3840,7 +3840,7 @@ def first_not_none(values): # if all series have a consistent name. If the # series do not have a consistent name, do # nothing. - names = set(v.name for v in values) + names = {v.name for v in values} if len(names) == 1: index.name = list(names)[0] diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7a34e64724245..1cb40b3ecf255 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -732,7 +732,7 @@ def _coerce_to_ndarray(cls, data): def _get_attributes_dict(self): """ return an attributes dict for my class """ - return dict((k, getattr(self, k, None)) for k in self._attributes) + return {k: getattr(self, k, None) for k in self._attributes} def view(self, cls=None): @@ -1784,7 +1784,7 @@ def append(self, other): if not isinstance(obj, Index): raise TypeError('all inputs must be Index') - names = set(obj.name for obj in to_concat) + names = {obj.name for obj in to_concat} name = None if len(names) > 1 else self.name return self._concat(to_concat, name) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index c9bb8748abe7b..20b6c15781535 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1003,7 +1003,7 @@ def _concat_same_dtype(self, to_concat, name): assert that we all have the same .closed we allow a 0-len index here as well """ - if not len(set(i.closed for i in to_concat if len(i))) == 1: + if not len({i.closed for i in to_concat if len(i)}) == 1: msg = ('can only append two IntervalIndex objects ' 'that are closed on the same side') raise ValueError(msg) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index ca4984cc16673..e537cb2edc1c4 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3377,7 +3377,7 @@ def reduction(self, f, axis=0, consolidate=True, transposed=False, blocks.append(block) # note that some DatetimeTZ, Categorical are always ndim==1 - ndim = set(b.ndim for b in blocks) + ndim = {b.ndim for b in blocks} if 2 in ndim: @@ -3891,7 +3891,7 @@ def get_scalar(self, tup): """ Retrieve single item """ - full_loc = list(ax.get_loc(x) for ax, x in zip(self.axes, tup)) + full_loc = [ax.get_loc(x) for ax, x in zip(self.axes, tup)] blk = self.blocks[self._blknos[full_loc[0]]] values = blk.values @@ -4871,7 +4871,7 @@ def _merge_blocks(blocks, dtype=None, _can_consolidate=True): if _can_consolidate: if dtype is None: - if len(set(b.dtype for b in blocks)) != 1: + if len({b.dtype for b in blocks}) != 1: raise AssertionError("_merge_blocks are invalid!") dtype = blocks[0].dtype diff --git a/pandas/core/ops.py b/pandas/core/ops.py index fa50036b6eb95..934570602c99d 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -146,7 +146,7 @@ def names(x): construct_result=_construct_divmod_result, ) - new_methods = dict((names(k), v) for k, v in new_methods.items()) + new_methods = {names(k): v for k, v in new_methods.items()} return new_methods diff --git a/pandas/core/panelnd.py b/pandas/core/panelnd.py index 691787125043d..80ee680d2b9d2 100644 --- a/pandas/core/panelnd.py +++ b/pandas/core/panelnd.py @@ -105,7 +105,7 @@ def _combine_with_constructor(self, other, func): new_axes.append(getattr(self, a).union(getattr(other, a))) # reindex: could check that everything's the same size, but forget it - d = dict((a, ax) for a, ax in zip(self._AXIS_ORDERS, new_axes)) + d = {a: ax for a, ax in zip(self._AXIS_ORDERS, new_axes)} d['copy'] = False this = self.reindex(**d) other = other.reindex(**d) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 6139f093202fe..9bd5abb2cd476 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -568,7 +568,7 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None): names = list(names) else: # make sure that all of the passed indices have the same nlevels - if not len(set(idx.nlevels for idx in indexes)) == 1: + if not len({idx.nlevels for idx in indexes}) == 1: raise AssertionError("Cannot concat indices that do" " not have the same number of levels") diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 36e52f1472f82..16439b30d5bb4 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -149,7 +149,7 @@ def lreshape(data, groups, dropna=True, label=None): for c in pivot_cols: mask &= notna(mdata[c]) if not mask.all(): - mdata = dict((k, v[mask]) for k, v in compat.iteritems(mdata)) + mdata = {k: v[mask] for k, v in compat.iteritems(mdata)} from pandas import DataFrame return DataFrame(mdata, columns=id_cols + pivot_cols) diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index 0c9a55e0c9acd..36a18d8f8b4a0 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -131,8 +131,7 @@ def _init_dict(self, data, index, columns, dtype=None): # pre-filter out columns if we passed it if columns is not None: columns = _ensure_index(columns) - data = dict((k, v) for k, v in compat.iteritems(data) - if k in columns) + data = {k: v for k, v in compat.iteritems(data) if k in columns} else: columns = Index(_try_sort(list(data.keys()))) @@ -173,7 +172,7 @@ def _init_matrix(self, data, index, columns, dtype=None): """ Init self from ndarray or list of lists """ data = _prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) - data = dict((idx, data[:, i]) for i, idx in enumerate(columns)) + data = {idx: data[:, i] for i, idx in enumerate(columns)} return self._init_dict(data, index, columns, dtype) def _init_spmatrix(self, data, index, columns, dtype=None, @@ -307,7 +306,7 @@ def to_dense(self): ------- df : DataFrame """ - data = dict((k, v.to_dense()) for k, v in compat.iteritems(self)) + data = {k: v.to_dense() for k, v in compat.iteritems(self)} return DataFrame(data, index=self.index, columns=self.columns) def _apply_columns(self, func): @@ -697,7 +696,7 @@ def _reindex_columns(self, columns, method, copy, level, fill_value=None, raise NotImplementedError("'method' argument is not supported") # TODO: fill value handling - sdict = dict((k, v) for k, v in compat.iteritems(self) if k in columns) + sdict = {k: v for k, v in compat.iteritems(self) if k in columns} return self._constructor( sdict, index=self.index, columns=columns, default_fill_value=self._default_fill_value).__finalize__(self) diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py index 117c96d00171c..8e9b5497083f6 100644 --- a/pandas/io/clipboards.py +++ b/pandas/io/clipboards.py @@ -53,7 +53,7 @@ def read_clipboard(sep='\s+', **kwargs): # pragma: no cover # 0 1 2 # 1 3 4 - counts = set(x.lstrip().count('\t') for x in lines) + counts = {x.lstrip().count('\t') for x in lines} if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0: sep = '\t' diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py index 32bab09a0c4ac..11bf3a9363953 100644 --- a/pandas/io/json/json.py +++ b/pandas/io/json/json.py @@ -715,10 +715,8 @@ def _parse_no_numpy(self): json = self.json orient = self.orient if orient == "split": - decoded = dict((str(k), v) - for k, v in compat.iteritems(loads( - json, - precise_float=self.precise_float))) + decoded = {str(k): v for k, v in compat.iteritems( + loads(json, precise_float=self.precise_float))} self.check_keys_split(decoded) self.obj = Series(dtype=None, **decoded) else: @@ -732,7 +730,7 @@ def _parse_numpy(self): if orient == "split": decoded = loads(json, dtype=None, numpy=True, precise_float=self.precise_float) - decoded = dict((str(k), v) for k, v in compat.iteritems(decoded)) + decoded = {str(k): v for k, v in compat.iteritems(decoded)} self.check_keys_split(decoded) self.obj = Series(**decoded) elif orient == "columns" or orient == "index": @@ -770,7 +768,7 @@ def _parse_numpy(self): elif orient == "split": decoded = loads(json, dtype=None, numpy=True, precise_float=self.precise_float) - decoded = dict((str(k), v) for k, v in compat.iteritems(decoded)) + decoded = {str(k): v for k, v in compat.iteritems(decoded)} self.check_keys_split(decoded) self.obj = DataFrame(**decoded) elif orient == "values": @@ -790,10 +788,8 @@ def _parse_no_numpy(self): self.obj = DataFrame( loads(json, precise_float=self.precise_float), dtype=None) elif orient == "split": - decoded = dict((str(k), v) - for k, v in compat.iteritems(loads( - json, - precise_float=self.precise_float))) + decoded = {str(k): v for k, v in compat.iteritems( + loads(json, precise_float=self.precise_float))} self.check_keys_split(decoded) self.obj = DataFrame(dtype=None, **decoded) elif orient == "index": diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 558a1f6d76868..8f6b013558396 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1133,8 +1133,7 @@ def _evaluate_usecols(usecols, names): If not a callable, returns 'usecols'. """ if callable(usecols): - return set(i for i, name in enumerate(names) - if usecols(name)) + return {i for i, name in enumerate(names) if usecols(name)} return usecols @@ -1906,7 +1905,7 @@ def read(self, nrows=None): # rename dict keys data = sorted(data.items()) - data = dict((k, v) for k, (i, v) in zip(names, data)) + data = {k: v for k, (i, v) in zip(names, data)} names, data = self._do_date_conversions(names, data) @@ -1924,7 +1923,7 @@ def read(self, nrows=None): # columns as list alldata = [x[1] for x in data] - data = dict((k, v) for k, (i, v) in zip(names, data)) + data = {k: v for k, (i, v) in zip(names, data)} names, data = self._do_date_conversions(names, data) index, names = self._make_index(data, alldata, names) @@ -2300,7 +2299,7 @@ def _exclude_implicit_index(self, alldata): offset += 1 data[col] = alldata[i + offset] else: - data = dict((k, v) for k, v in zip(names, alldata)) + data = {k: v for k, v in zip(names, alldata)} return data @@ -3233,9 +3232,8 @@ def _get_empty_meta(columns, index_col, index_names, dtype=None): for i, n in enumerate(index_col): columns.pop(n - i) - col_dict = dict((col_name, - Series([], dtype=dtype[col_name])) - for col_name in columns) + col_dict = {col_name: Series([], dtype=dtype[col_name]) + for col_name in columns} return index, columns, col_dict diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index b9cddce55c096..2a66aea88f6d9 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -815,7 +815,7 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, "all tables must have exactly the same nrows!") # axis is the concentation axes - axis = list(set(t.non_index_axes[0][0] for t in tbls))[0] + axis = list({t.non_index_axes[0][0] for t in tbls})[0] def func(_start, _stop, _where): @@ -2374,8 +2374,7 @@ class GenericFixed(Fixed): """ a generified fixed version """ _index_type_map = {DatetimeIndex: 'datetime', PeriodIndex: 'period'} - _reverse_index_map = dict((v, k) - for k, v in compat.iteritems(_index_type_map)) + _reverse_index_map = {v: k for k, v in compat.iteritems(_index_type_map)} attributes = [] # indexer helpders @@ -3510,8 +3509,8 @@ def get_blk_items(mgr, blocks): # reorder the blocks in the same order as the existing_table if we can if existing_table is not None: - by_items = dict((tuple(b_items.tolist()), (b, b_items)) - for b, b_items in zip(blocks, blk_items)) + by_items = {tuple(b_items.tolist()): (b, b_items) + for b, b_items in zip(blocks, blk_items)} new_blocks = [] new_blk_items = [] for ea in existing_table.values_axes: @@ -3659,7 +3658,7 @@ def create_description(self, complib=None, complevel=None, d = dict(name='table', expectedrows=expectedrows) # description from the axes & values - d['description'] = dict((a.cname, a.typ) for a in self.axes) + d['description'] = {a.cname: a.typ for a in self.axes} if complib: if complevel is None: diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 401a9c11a774d..975ad1e4ff368 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -641,7 +641,7 @@ def insert_data(self): return column_names, data_list def _execute_insert(self, conn, keys, data_iter): - data = [dict((k, v) for k, v in zip(keys, row)) for row in data_iter] + data = [{k: v for k, v in zip(keys, row)} for row in data_iter] conn.execute(self.insert_statement(), data) def insert(self, chunksize=None): diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index 0f06d87726905..9daee918b9f30 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -994,7 +994,7 @@ def _set_default_format(self, vmin, vmax): info) else: format = np.compress(info['maj'], info) - self.formatdict = dict((x, f) for (x, _, _, f) in format) + self.formatdict = {x: f for (x, _, _, f) in format} return self.formatdict def set_locs(self, locs): diff --git a/pandas/tests/frame/common.py b/pandas/tests/frame/common.py index 3786facdd4ebd..c85fea3c3d71b 100644 --- a/pandas/tests/frame/common.py +++ b/pandas/tests/frame/common.py @@ -10,8 +10,8 @@ _frame = pd.DataFrame(_seriesd) _frame2 = pd.DataFrame(_seriesd, columns=['D', 'C', 'B', 'A']) -_intframe = pd.DataFrame(dict((k, v.astype(int)) - for k, v in compat.iteritems(_seriesd))) +_intframe = pd.DataFrame({k: v.astype(int) + for k, v in compat.iteritems(_seriesd)}) _tsframe = pd.DataFrame(_tsd) @@ -32,8 +32,7 @@ def frame2(self): @cache_readonly def intframe(self): # force these all to int64 to avoid platform testing issues - return pd.DataFrame(dict((c, s) for c, s in - compat.iteritems(_intframe)), + return pd.DataFrame({c: s for c, s in compat.iteritems(_intframe)}, dtype=np.int64) @cache_readonly @@ -112,7 +111,7 @@ def _check_mixed_float(df, dtype=None): # float16 are most likely to be upcasted to float32 dtypes = dict(A='float32', B='float32', C='float16', D='float64') if isinstance(dtype, compat.string_types): - dtypes = dict((k, dtype) for k, v in dtypes.items()) + dtypes = {k: dtype for k, v in dtypes.items()} elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): @@ -128,7 +127,7 @@ def _check_mixed_float(df, dtype=None): def _check_mixed_int(df, dtype=None): dtypes = dict(A='int32', B='uint64', C='uint8', D='int64') if isinstance(dtype, compat.string_types): - dtypes = dict((k, dtype) for k, v in dtypes.items()) + dtypes = {k: dtype for k, v in dtypes.items()} elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index c50aa858a15b5..e81e31b718498 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -234,7 +234,7 @@ def test_itertuples(self): if sys.version >= LooseVersion('2.7'): assert tup2._fields == ('Index', '_1', '_2') - df3 = DataFrame(dict(('f' + str(i), [i]) for i in range(1024))) + df3 = DataFrame({'f' + str(i): [i] for i in range(1024)}) # will raise SyntaxError if trying to create namedtuple tup3 = next(df3.itertuples()) assert not hasattr(tup3, '_fields') diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 6ca90d715cb0b..2f947527ce95b 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -120,7 +120,7 @@ def _make_mixed_dtypes_df(typ, ad=None): assert(a.dtype == d) if ad is None: ad = dict() - ad.update(dict((d, a) for d, a in zipper)) + ad.update({d: a for d, a in zipper}) return DataFrame(ad) def _check_mixed_dtypes(df, dtypes=None): @@ -349,8 +349,8 @@ def test_constructor_subclass_dict(self): data = {'col1': tm.TestSubDict((x, 10.0 * x) for x in range(10)), 'col2': tm.TestSubDict((x, 20.0 * x) for x in range(10))} df = DataFrame(data) - refdf = DataFrame(dict((col, dict(compat.iteritems(val))) - for col, val in compat.iteritems(data))) + refdf = DataFrame({col: dict(compat.iteritems(val)) + for col, val in compat.iteritems(data)}) tm.assert_frame_equal(refdf, df) data = tm.TestSubDict(compat.iteritems(data)) @@ -413,8 +413,7 @@ def test_constructor_dict_of_tuples(self): data = {'a': (1, 2, 3), 'b': (4, 5, 6)} result = DataFrame(data) - expected = DataFrame(dict((k, list(v)) - for k, v in compat.iteritems(data))) + expected = DataFrame({k: list(v) for k, v in compat.iteritems(data)}) tm.assert_frame_equal(result, expected, check_dtype=False) def test_constructor_dict_multiindex(self): @@ -447,8 +446,8 @@ def test_constructor_dict_datetime64_index(self): dates_as_str = ['1984-02-19', '1988-11-06', '1989-12-03', '1990-03-15'] def create_data(constructor): - return dict((i, {constructor(s): 2 * i}) - for i, s in enumerate(dates_as_str)) + return {i: {constructor(s): 2 * i} + for i, s in enumerate(dates_as_str)} data_datetime64 = create_data(np.datetime64) data_datetime = create_data(lambda x: datetime.strptime(x, '%Y-%m-%d')) @@ -472,8 +471,8 @@ def test_constructor_dict_timedelta64_index(self): td_as_int = [1, 2, 3, 4] def create_data(constructor): - return dict((i, {constructor(s): 2 * i}) - for i, s in enumerate(td_as_int)) + return {i: {constructor(s): 2 * i} + for i, s in enumerate(td_as_int)} data_timedelta64 = create_data(lambda x: np.timedelta64(x, 'D')) data_timedelta = create_data(lambda x: timedelta(days=x)) @@ -696,8 +695,8 @@ def test_constructor_mrecarray(self): mrecs = mrecords.fromarrays(data, names=names) # fill the comb - comb = dict((k, v.filled()) if hasattr( - v, 'filled') else (k, v) for k, v in comb) + comb = {k: (v.filled() if hasattr(v, 'filled') else v) + for k, v in comb} expected = DataFrame(comb, columns=names) result = DataFrame(mrecs) @@ -1854,8 +1853,8 @@ def test_from_records_dictlike(self): for dtype, b in compat.iteritems(blocks): columns.extend(b.columns) - asdict = dict((x, y) for x, y in compat.iteritems(df)) - asdict2 = dict((x, y.values) for x, y in compat.iteritems(df)) + asdict = {x: y for x, y in compat.iteritems(df)} + asdict2 = {x: y.values for x, y in compat.iteritems(df)} # dict of series & dict of ndarrays (have dtype info) results = [] diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 91a5569b352e9..81153e83471cd 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -257,7 +257,7 @@ def test_len(self): assert len(grouped) == len(df) grouped = df.groupby([lambda x: x.year, lambda x: x.month]) - expected = len(set((x.year, x.month) for x in df.index)) + expected = len({(x.year, x.month) for x in df.index}) assert len(grouped) == expected # issue 11016 diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index 977c639d79711..de0deb442e516 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -238,7 +238,7 @@ def test_groupby_blacklist(df_letters): def test_tab_completion(mframe): grp = mframe.groupby(level='second') - results = set(v for v in dir(grp) if not v.startswith('_')) + results = {v for v in dir(grp) if not v.startswith('_')} expected = { 'A', 'B', 'C', 'agg', 'aggregate', 'apply', 'boxplot', 'filter', 'first', 'get_group', 'groups', 'hist', 'indices', 'last', 'max', diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 506a9e1c64b10..2f8c27f1abb7d 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -2178,7 +2178,7 @@ def check(nlevels, with_nulls): if with_nulls: # inject some null values labels[500] = -1 # common nan value - labels = list(labels.copy() for i in range(nlevels)) + labels = [labels.copy() for i in range(nlevels)] for i in range(nlevels): labels[i][500 + i - nlevels // 2] = -1 @@ -2773,7 +2773,7 @@ def test_groupby(self): # GH5620 groups = self.index.groupby(self.index) - exp = dict((key, [key]) for key in self.index) + exp = {key: [key] for key in self.index} tm.assert_dict_equal(groups, exp) def test_index_name_retained(self): diff --git a/pandas/tests/indexing/test_panel.py b/pandas/tests/indexing/test_panel.py index 4d7768c9e8083..c4f7bd28e4d90 100644 --- a/pandas/tests/indexing/test_panel.py +++ b/pandas/tests/indexing/test_panel.py @@ -119,7 +119,7 @@ def test_panel_getitem(self): df = DataFrame( np.random.randn( len(ind), 5), index=ind, columns=list('ABCDE')) - panel = Panel(dict(('frame_' + c, df) for c in list('ABC'))) + panel = Panel({'frame_' + c: df for c in list('ABC')}) test2 = panel.loc[:, "2002":"2002-12-31"] test1 = panel.loc[:, "2002"] diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 47632b1399991..6553dd66cba5f 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1505,11 +1505,11 @@ def test_repr_html_long_and_wide(self): max_rows = get_option('display.max_rows') h, w = max_rows - 1, max_cols - 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert '...' not in df._repr_html_() h, w = max_rows + 1, max_cols + 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert '...' in df._repr_html_() def test_info_repr(self): @@ -1517,14 +1517,14 @@ def test_info_repr(self): max_cols = get_option('display.max_columns') # Long h, w = max_rows + 1, max_cols - 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert has_vertically_truncated_repr(df) with option_context('display.large_repr', 'info'): assert has_info_repr(df) # Wide h, w = max_rows - 1, max_cols + 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert has_horizontally_truncated_repr(df) with option_context('display.large_repr', 'info'): assert has_info_repr(df) @@ -1550,14 +1550,14 @@ def test_info_repr_html(self): max_cols = get_option('display.max_columns') # Long h, w = max_rows + 1, max_cols - 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert r'&lt;class' not in df._repr_html_() with option_context('display.large_repr', 'info'): assert r'&lt;class' in df._repr_html_() # Wide h, w = max_rows - 1, max_cols + 1 - df = DataFrame(dict((k, np.arange(1, 1 + h)) for k in np.arange(w))) + df = DataFrame({k: np.arange(1, 1 + h) for k in np.arange(w)}) assert '<class' not in df._repr_html_() with option_context('display.large_repr', 'info'): assert '&lt;class' in df._repr_html_() @@ -2058,7 +2058,7 @@ def chck_ncols(self, s): lines = res.split('\n') lines = [line for line in repr(s).split('\n') if not re.match(r'[^\.]*\.+', line)][:-1] - ncolsizes = len(set(len(line.strip()) for line in lines)) + ncolsizes = len({len(line.strip()) for line in lines}) assert ncolsizes == 1 def test_format_explicit(self): diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 639c11a3d3fbb..35ef5a1cf5c72 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -146,11 +146,11 @@ def test_to_latex_multiindex(self): assert result == expected df = DataFrame.from_dict({ - ('c1', 0): pd.Series(dict((x, x) for x in range(4))), - ('c1', 1): pd.Series(dict((x, x + 4) for x in range(4))), - ('c2', 0): pd.Series(dict((x, x) for x in range(4))), - ('c2', 1): pd.Series(dict((x, x + 4) for x in range(4))), - ('c3', 0): pd.Series(dict((x, x) for x in range(4))), + ('c1', 0): pd.Series({x: x for x in range(4)}), + ('c1', 1): pd.Series({x: x + 4 for x in range(4)}), + ('c2', 0): pd.Series({x: x for x in range(4)}), + ('c2', 1): pd.Series({x: x + 4 for x in range(4)}), + ('c3', 0): pd.Series({x: x for x in range(4)}), }).T result = df.to_latex() expected = r"""\begin{tabular}{llrrrr} @@ -223,11 +223,11 @@ def test_to_latex_multiindex(self): def test_to_latex_multicolumnrow(self): df = pd.DataFrame({ - ('c1', 0): dict((x, x) for x in range(5)), - ('c1', 1): dict((x, x + 5) for x in range(5)), - ('c2', 0): dict((x, x) for x in range(5)), - ('c2', 1): dict((x, x + 5) for x in range(5)), - ('c3', 0): dict((x, x) for x in range(5)) + ('c1', 0): {x: x for x in range(5)}, + ('c1', 1): {x: x + 5 for x in range(5)}, + ('c2', 0): {x: x for x in range(5)}, + ('c2', 1): {x: x + 5 for x in range(5)}, + ('c3', 0): {x: x for x in range(5)} }) result = df.to_latex() expected = r"""\begin{tabular}{lrrrrr} diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 18b91bb3d9324..a1c0ec3bc1a0a 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -1643,4 +1643,4 @@ def test_encodeSet(self): def _clean_dict(d): - return dict((str(k), v) for k, v in compat.iteritems(d)) + return {str(k): v for k, v in compat.iteritems(d)} diff --git a/pandas/tests/io/msgpack/test_case.py b/pandas/tests/io/msgpack/test_case.py index 9bb34a70e2593..c0e76b37ee46d 100644 --- a/pandas/tests/io/msgpack/test_case.py +++ b/pandas/tests/io/msgpack/test_case.py @@ -98,10 +98,10 @@ def test_match(): (tuple(range(16)), (b"\xdc\x00\x10\x00\x01\x02\x03\x04\x05\x06\x07" b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")), ({}, b'\x80'), - (dict((x, x) for x in range(15)), + ({x: x for x in range(15)}, (b'\x8f\x00\x00\x01\x01\x02\x02\x03\x03\x04\x04\x05\x05\x06\x06\x07' b'\x07\x08\x08\t\t\n\n\x0b\x0b\x0c\x0c\r\r\x0e\x0e')), - (dict((x, x) for x in range(16)), + ({x: x for x in range(16)}, (b'\xde\x00\x10\x00\x00\x01\x01\x02\x02\x03\x03\x04\x04\x05\x05\x06' b'\x06\x07\x07\x08\x08\t\t\n\n\x0b\x0b\x0c\x0c\r\r\x0e\x0e' b'\x0f\x0f')), diff --git a/pandas/tests/io/msgpack/test_pack.py b/pandas/tests/io/msgpack/test_pack.py index c0b3e1b24674f..3afd1fc086b33 100644 --- a/pandas/tests/io/msgpack/test_pack.py +++ b/pandas/tests/io/msgpack/test_pack.py @@ -132,7 +132,7 @@ def testMapSize(self, sizes=[0, 5, 50, 1000]): bio.seek(0) unpacker = Unpacker(bio) for size in sizes: - assert unpacker.unpack() == dict((i, i * 2) for i in range(size)) + assert unpacker.unpack() == {i: i * 2 for i in range(size)} def test_odict(self): seq = [(b'one', 1), (b'two', 2), (b'three', 3), (b'four', 4)] diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index bc58ea1c7c228..2d1671840ce8f 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -618,8 +618,8 @@ def setup_method(self, method): 'E': [datetime.timedelta(days=x) for x in range(1000)], } self.frame = { - 'float': DataFrame(dict((k, data[k]) for k in ['A', 'A'])), - 'int': DataFrame(dict((k, data[k]) for k in ['B', 'B'])), + 'float': DataFrame({k: data[k] for k in ['A', 'A']}), + 'int': DataFrame({k: data[k] for k in ['B', 'B']}), 'mixed': DataFrame(data), } @@ -805,8 +805,8 @@ def setup_method(self, method): 'G': [400] * 1000 } self.frame = { - 'float': DataFrame(dict((k, data[k]) for k in ['A', 'A'])), - 'int': DataFrame(dict((k, data[k]) for k in ['B', 'B'])), + 'float': DataFrame({k: data[k] for k in ['A', 'A']}), + 'int': DataFrame({k: data[k] for k in ['B', 'B']}), 'mixed': DataFrame(data), } self.utf_encodings = ['utf8', 'utf16', 'utf32'] diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index ca20d089ee5f7..5e5fc6e7eac62 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -1391,7 +1391,7 @@ def test_append_with_strings(self): with catch_warnings(record=True): wp = tm.makePanel() wp2 = wp.rename_axis( - dict((x, "%s_extra" % x) for x in wp.minor_axis), axis=2) + {x: "%s_extra" % x for x in wp.minor_axis}, axis=2) def check_col(key, name, size): assert getattr(store.get_storer(key) diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 78b47960e1a04..b3ead7d9c8333 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -590,7 +590,7 @@ def test_105(self): def test_date_export_formats(self): columns = ['tc', 'td', 'tw', 'tm', 'tq', 'th', 'ty'] - conversions = dict(((c, c) for c in columns)) + conversions = {c: c for c in columns} data = [datetime(2006, 11, 20, 23, 13, 20)] * len(columns) original = DataFrame([data], columns=columns) original.index.name = 'index' @@ -774,7 +774,7 @@ def test_big_dates(self): tm.assert_frame_equal(expected, parsed_117, check_datetimelike_compat=True) - date_conversion = dict((c, c[-2:]) for c in columns) + date_conversion = {c: c[-2:] for c in columns} # {c : c[-2:] for c in columns} with tm.ensure_clean() as path: expected.index.name = 'index' diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index d04065ee34339..fdfd87d1e898c 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -3,7 +3,7 @@ """ Test cases for Series.plot """ -import itertools +from itertools import chain import pytest from datetime import datetime @@ -333,8 +333,7 @@ def test_pie_series(self): autopct='%.2f', fontsize=7) pcts = ['{0:.2f}'.format(s * 100) for s in series.values / float(series.sum())] - iters = [iter(series.index), iter(pcts)] - expected_texts = list(next(it) for it in itertools.cycle(iters)) + expected_texts = list(chain.from_iterable(zip(series.index, pcts))) self._check_text_labels(ax.texts, expected_texts) for t in ax.texts: assert t.get_fontsize() == 7 diff --git a/pandas/tests/reshape/test_join.py b/pandas/tests/reshape/test_join.py index 75c01fabea8f6..76791b08a26be 100644 --- a/pandas/tests/reshape/test_join.py +++ b/pandas/tests/reshape/test_join.py @@ -788,7 +788,7 @@ def _assert_same_contents(join_chunk, source): jvalues = join_chunk.fillna(NA_SENTINEL).drop_duplicates().values svalues = source.fillna(NA_SENTINEL).drop_duplicates().values - rows = set(tuple(row) for row in jvalues) + rows = {tuple(row) for row in jvalues} assert(len(rows) == len(source)) assert(all(tuple(row) in rows for row in svalues)) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 86e5cc54bd490..7ffda3a58ac1c 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -251,7 +251,7 @@ def test_constructor_maskedarray(self): def test_series_ctor_plus_datetimeindex(self): rng = date_range('20090415', '20090519', freq='B') - data = dict((k, 1) for k in rng) + data = {k: 1 for k in rng} result = Series(data, index=rng) assert result.index is rng diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index d141b378fe214..c0ef5a3694bf3 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -1734,7 +1734,7 @@ def test_timedelta_assignment(self): def test_underlying_data_conversion(self): # GH 4080 - df = DataFrame(dict((c, [1, 2, 3]) for c in ['a', 'b', 'c'])) + df = DataFrame({c: [1, 2, 3] for c in ['a', 'b', 'c']}) df.set_index(['a', 'b', 'c'], inplace=True) s = Series([1], index=[(2, 2, 2)]) df['val'] = 0 diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 0e783d67517ac..f51bf0c4e476a 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1094,21 +1094,21 @@ def test_ctor_dict(self): assert_panel_equal(Panel(d4), Panel(items=['A', 'B'])) # cast - dcasted = dict((k, v.reindex(wp.major_axis).fillna(0)) - for k, v in compat.iteritems(d)) + dcasted = {k: v.reindex(wp.major_axis).fillna(0) + for k, v in compat.iteritems(d)} result = Panel(dcasted, dtype=int) - expected = Panel(dict((k, v.astype(int)) - for k, v in compat.iteritems(dcasted))) + expected = Panel({k: v.astype(int) + for k, v in compat.iteritems(dcasted)}) assert_panel_equal(result, expected) result = Panel(dcasted, dtype=np.int32) - expected = Panel(dict((k, v.astype(np.int32)) - for k, v in compat.iteritems(dcasted))) + expected = Panel({k: v.astype(np.int32) + for k, v in compat.iteritems(dcasted)}) assert_panel_equal(result, expected) def test_constructor_dict_mixed(self): with catch_warnings(record=True): - data = dict((k, v.values) for k, v in self.panel.iteritems()) + data = {k: v.values for k, v in self.panel.iteritems()} result = Panel(data) exp_major = Index(np.arange(len(self.panel.major_axis))) tm.assert_index_equal(result.major_axis, exp_major) @@ -1350,18 +1350,18 @@ def test_apply_slabs(self): # make sure that we don't trigger any warnings result = self.panel.apply(f, axis=['items', 'major_axis']) - expected = Panel(dict((ax, f(self.panel.loc[:, :, ax])) - for ax in self.panel.minor_axis)) + expected = Panel({ax: f(self.panel.loc[:, :, ax]) + for ax in self.panel.minor_axis}) assert_panel_equal(result, expected) result = self.panel.apply(f, axis=['major_axis', 'minor_axis']) - expected = Panel(dict((ax, f(self.panel.loc[ax])) - for ax in self.panel.items)) + expected = Panel({ax: f(self.panel.loc[ax]) + for ax in self.panel.items}) assert_panel_equal(result, expected) result = self.panel.apply(f, axis=['minor_axis', 'items']) - expected = Panel(dict((ax, f(self.panel.loc[:, ax])) - for ax in self.panel.major_axis)) + expected = Panel({ax: f(self.panel.loc[:, ax]) + for ax in self.panel.major_axis}) assert_panel_equal(result, expected) # with multi-indexes @@ -1994,8 +1994,8 @@ def test_shift(self): # negative numbers, #2164 result = self.panel.shift(-1) - expected = Panel(dict((i, f.shift(-1)[:-1]) - for i, f in self.panel.iteritems())) + expected = Panel({i: f.shift(-1)[:-1] + for i, f in self.panel.iteritems()}) assert_panel_equal(result, expected) # mixed dtypes #6959 diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index c0e8770dff8b8..c42bedebe2f23 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -689,7 +689,7 @@ def test_ctor_dict(self): def test_constructor_dict_mixed(self): with catch_warnings(record=True): - data = dict((k, v.values) for k, v in self.panel4d.iteritems()) + data = {k: v.values for k, v in self.panel4d.iteritems()} result = Panel4D(data) exp_major = Index(np.arange(len(self.panel4d.major_axis))) diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index 957352d9ff13f..0e6cbea21493c 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -430,7 +430,7 @@ def merge_class(base, other): if not isinstance(other, list): other = [other] - other_holidays = dict((holiday.name, holiday) for holiday in other) + other_holidays = {holiday.name: holiday for holiday in other} try: base = base.rules @@ -439,7 +439,7 @@ def merge_class(base, other): if not isinstance(base, list): base = [base] - base_holidays = dict((holiday.name, holiday) for holiday in base) + base_holidays = {holiday.name: holiday for holiday in base} other_holidays.update(base_holidays) return list(other_holidays.values()) diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 2097fb22b3ec5..fb03af9953b8a 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -237,9 +237,9 @@ def apply_index(self, i): i = (i.to_period('W') + weeks).to_timestamp() + \ i.to_perioddelta('W') - timedelta_kwds = dict((k, v) for k, v in self.kwds.items() - if k in ['days', 'hours', 'minutes', - 'seconds', 'microseconds']) + timedelta_kwds = {k: v for k, v in self.kwds.items() + if k in ['days', 'hours', 'minutes', + 'seconds', 'microseconds']} if timedelta_kwds: delta = Timedelta(**timedelta_kwds) i = i + (self.n * delta) @@ -1639,7 +1639,7 @@ def onOffset(self, dt): _int_to_month = tslib._MONTH_ALIASES -_month_to_int = dict((v, k) for k, v in _int_to_month.items()) +_month_to_int = {v: k for k, v in _int_to_month.items()} # TODO: This is basically the same as BQuarterEnd diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 1c4c63acb436a..0da59ba5f958e 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1741,7 +1741,7 @@ def makeObjectSeries(name=None): def getSeriesData(): index = makeStringIndex(N) - return dict((c, Series(randn(N), index=index)) for c in getCols(K)) + return {c: Series(randn(N), index=index) for c in getCols(K)} def makeTimeSeries(nper=None, freq='B', name=None): @@ -1757,11 +1757,11 @@ def makePeriodSeries(nper=None, name=None): def getTimeSeriesData(nper=None, freq='B'): - return dict((c, makeTimeSeries(nper, freq)) for c in getCols(K)) + return {c: makeTimeSeries(nper, freq) for c in getCols(K)} def getPeriodData(nper=None): - return dict((c, makePeriodSeries(nper)) for c in getCols(K)) + return {c: makePeriodSeries(nper) for c in getCols(K)} # make frame @@ -1800,14 +1800,14 @@ def makePeriodFrame(nper=None): def makePanel(nper=None): with warnings.catch_warnings(record=True): cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]] - data = dict((c, makeTimeDataFrame(nper)) for c in cols) + data = {c: makeTimeDataFrame(nper) for c in cols} return Panel.fromDict(data) def makePeriodPanel(nper=None): with warnings.catch_warnings(record=True): cols = ['Item' + c for c in string.ascii_uppercase[:K - 1]] - data = dict((c, makePeriodFrame(nper)) for c in cols) + data = {c: makePeriodFrame(nper) for c in cols} return Panel.fromDict(data) diff --git a/versioneer.py b/versioneer.py index 59228ec63c136..b0ae4fa2dc8e8 100644 --- a/versioneer.py +++ b/versioneer.py @@ -606,11 +606,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set(r.strip() for r in refnames.strip("()").split(",")) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d @@ -619,7 +619,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set(r for r in refs if re.search(r'\d', r)) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs-tags)) if verbose: @@ -960,11 +960,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set(r.strip() for r in refnames.strip("()").split(",")) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -973,7 +973,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set(r for r in refs if re.search(r'\d', r)) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose:
- [x] tests passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` xref @jreback's [comment](https://github.com/pandas-dev/pandas/pull/18335#discussion_r151851542) and @maxim-lian [comment](https://github.com/pandas-dev/pandas/pull/18335#discussion_r151843012), replace the following where appropriate: `list(x for x in iterator)` --> `[x for x in iterator]` `set(x for x in iterator)` --> `{x for x in iterator}` `dict((x,x) for x in iterator)` --> `{x: x for x in iterator}`
https://api.github.com/repos/pandas-dev/pandas/pulls/18383
2017-11-20T08:18:28Z
2017-11-24T19:27:14Z
2017-11-24T19:27:14Z
2017-11-25T00:15:56Z
14350
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 6dc730cae37f7..73ec9e0d5391a 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -26,6 +26,7 @@ Other Enhancements - :func:`pandas.tseries.frequencies.to_offset` now accepts leading '+' signs e.g. '+1h'. (:issue:`18171`) - :class:`pandas.io.formats.style.Styler` now has method ``hide_index()`` to determine whether the index will be rendered in ouptut (:issue:`14194`) - :class:`pandas.io.formats.style.Styler` now has method ``hide_columns()`` to determine whether columns will be hidden in output (:issue:`14194`) +- Improved wording of ValueError raised in :func:`Timestamp.tz_localize` function .. _whatsnew_0220.api_breaking: diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index e4c065202a6ef..63fc84c9d7972 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -1445,10 +1445,8 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'): else: if is_raise: - raise ValueError("non convertible value {0}" - "with the unit '{1}'".format( - val, - unit)) + raise ValueError("unit='{0}' not valid with non-numerical " + "val='{1}'".format(unit, val)) if is_ignore: raise AssertionError
- [x] closes #14350 - [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/18380
2017-11-20T04:00:49Z
2017-11-20T11:10:06Z
2017-11-20T11:10:06Z
2017-11-20T11:42:59Z
move a small set of non-scalar tests out of scalar.test_timestamp
diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index d35b67b52d16a..33a3495dcd71e 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -594,6 +594,16 @@ def test_setitem_boolean_column(self): assert_frame_equal(self.frame, expected) + def test_frame_setitem_timestamp(self): + # GH#2155 + columns = DatetimeIndex(start='1/1/2012', end='2/1/2012', freq=BDay()) + index = lrange(10) + data = DataFrame(columns=columns, index=index) + t = datetime(2012, 11, 1) + ts = Timestamp(t) + data[ts] = np.nan # works, mostly a smoke-test + assert np.isnan(data[ts]).all() + def test_setitem_corner(self): # corner case df = DataFrame({'B': [1., 2., 3.], diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 1fca0445de5c4..edcee0479827f 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -5,6 +5,7 @@ import pytest import numpy as np +import pytz from pytz import timezone from datetime import datetime, timedelta, time @@ -20,6 +21,61 @@ START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) +class TestTimestampEquivDateRange(object): + # Older tests in TestTimeSeries constructed their `stamp` objects + # using `date_range` instead of the `Timestamp` constructor. + # TestTimestampEquivDateRange checks that these are equivalent in the + # pertinent cases. + + def test_date_range_timestamp_equiv(self): + rng = date_range('20090415', '20090519', tz='US/Eastern') + stamp = rng[0] + + ts = Timestamp('20090415', tz='US/Eastern', freq='D') + assert ts == stamp + + def test_date_range_timestamp_equiv_dateutil(self): + rng = date_range('20090415', '20090519', tz='dateutil/US/Eastern') + stamp = rng[0] + + ts = Timestamp('20090415', tz='dateutil/US/Eastern', freq='D') + assert ts == stamp + + def test_date_range_timestamp_equiv_explicit_pytz(self): + rng = date_range('20090415', '20090519', + tz=pytz.timezone('US/Eastern')) + stamp = rng[0] + + ts = Timestamp('20090415', tz=pytz.timezone('US/Eastern'), freq='D') + assert ts == stamp + + def test_date_range_timestamp_equiv_explicit_dateutil(self): + tm._skip_if_windows_python_3() + from pandas._libs.tslibs.timezones import dateutil_gettz as gettz + + rng = date_range('20090415', '20090519', tz=gettz('US/Eastern')) + stamp = rng[0] + + ts = Timestamp('20090415', tz=gettz('US/Eastern'), freq='D') + assert ts == stamp + + def test_date_range_timestamp_equiv_from_datetime_instance(self): + datetime_instance = datetime(2014, 3, 4) + # build a timestamp with a frequency, since then it supports + # addition/subtraction of integers + timestamp_instance = date_range(datetime_instance, periods=1, + freq='D')[0] + + ts = Timestamp(datetime_instance, freq='D') + assert ts == timestamp_instance + + def test_date_range_timestamp_equiv_preserve_frequency(self): + timestamp_instance = date_range('2014-03-05', periods=1, freq='D')[0] + ts = Timestamp('2014-03-05', freq='D') + + assert timestamp_instance == ts + + class TestDateRanges(TestData): def test_date_range_gen_error(self): diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 36f691903d233..076c3d6f25a89 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -1,7 +1,7 @@ import pytest import numpy as np -from datetime import date, timedelta, time +from datetime import date, timedelta, time, datetime import dateutil import pandas as pd @@ -9,13 +9,38 @@ from pandas.compat import lrange from pandas.compat.numpy import np_datetime64_compat from pandas import (DatetimeIndex, Index, date_range, DataFrame, - Timestamp, datetime, offsets) + Timestamp, offsets) from pandas.util.testing import assert_almost_equal randn = np.random.randn +class TestDatetimeIndexLikeTimestamp(object): + # Tests for DatetimeIndex behaving like a vectorized Timestamp + + def test_dti_date_out_of_range(self): + # see gh-1475 + pytest.raises(ValueError, DatetimeIndex, ['1400-01-01']) + pytest.raises(ValueError, DatetimeIndex, [datetime(1400, 1, 1)]) + + def test_timestamp_fields(self): + # extra fields from DatetimeIndex like quarter and week + idx = tm.makeDateIndex(100) + + fields = ['dayofweek', 'dayofyear', 'week', 'weekofyear', 'quarter', + 'days_in_month', 'is_month_start', 'is_month_end', + 'is_quarter_start', 'is_quarter_end', 'is_year_start', + 'is_year_end', 'weekday_name'] + for f in fields: + expected = getattr(idx, f)[-1] + result = getattr(Timestamp(idx[-1]), f) + assert result == expected + + assert idx.freq == Timestamp(idx[-1], idx.freq).freq + assert idx.freqstr == Timestamp(idx[-1], idx.freq).freqstr + + class TestDatetimeIndex(object): def test_get_loc(self): diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index a9c26ebb90359..6bb4229883525 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -13,6 +13,21 @@ class TestSlicing(object): + def test_dti_slicing(self): + dti = DatetimeIndex(start='1/1/2005', end='12/1/2005', freq='M') + dti2 = dti[[1, 3, 5]] + + v1 = dti2[0] + v2 = dti2[1] + v3 = dti2[2] + + assert v1 == Timestamp('2/28/2005') + assert v2 == Timestamp('4/30/2005') + assert v3 == Timestamp('6/30/2005') + + # don't carry freq through irregular slicing + assert dti2.freq is None + def test_slice_keeps_name(self): # GH4226 st = pd.Timestamp('2013-07-01 00:00:00', tz='America/Los_Angeles') diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index a79fb554f9454..545ed7f1ebbf3 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -20,11 +20,11 @@ from pandas._libs.tslibs.timezones import get_timezone from pandas._libs.tslibs import conversion -from pandas.compat import lrange, long, PY3 +from pandas.compat import long, PY3 from pandas.util.testing import assert_series_equal from pandas.compat.numpy import np_datetime64_compat from pandas import (Timestamp, date_range, Period, Timedelta, compat, - Series, NaT, DataFrame, DatetimeIndex) + Series, NaT, DataFrame) from pandas.tseries.frequencies import (RESO_DAY, RESO_HR, RESO_MIN, RESO_US, RESO_MS, RESO_SEC) @@ -1227,8 +1227,7 @@ def test_addition_subtraction_types(self): timedelta_instance = timedelta(seconds=1) # build a timestamp with a frequency, since then it supports # addition/subtraction of integers - timestamp_instance = date_range(datetime_instance, periods=1, - freq='D')[0] + timestamp_instance = Timestamp(datetime_instance, freq='D') assert type(timestamp_instance + 1) == Timestamp assert type(timestamp_instance - 1) == Timestamp @@ -1246,7 +1245,7 @@ def test_addition_subtraction_types(self): assert type(timestamp_instance - timedelta64_instance) == Timestamp def test_addition_subtraction_preserve_frequency(self): - timestamp_instance = date_range('2014-03-05', periods=1, freq='D')[0] + timestamp_instance = Timestamp('2014-03-05', freq='D') timedelta_instance = timedelta(days=1) original_freq = timestamp_instance.freq @@ -1330,30 +1329,10 @@ def test_timestamp_to_datetime_explicit_dateutil(self): assert stamp == dtval assert stamp.tzinfo == dtval.tzinfo - def test_timestamp_fields(self): - # extra fields from DatetimeIndex like quarter and week - idx = tm.makeDateIndex(100) - - fields = ['dayofweek', 'dayofyear', 'week', 'weekofyear', 'quarter', - 'days_in_month', 'is_month_start', 'is_month_end', - 'is_quarter_start', 'is_quarter_end', 'is_year_start', - 'is_year_end', 'weekday_name'] - for f in fields: - expected = getattr(idx, f)[-1] - result = getattr(Timestamp(idx[-1]), f) - assert result == expected - - assert idx.freq == Timestamp(idx[-1], idx.freq).freq - assert idx.freqstr == Timestamp(idx[-1], idx.freq).freqstr - def test_timestamp_date_out_of_range(self): pytest.raises(ValueError, Timestamp, '1676-01-01') pytest.raises(ValueError, Timestamp, '2263-01-01') - # see gh-1475 - pytest.raises(ValueError, DatetimeIndex, ['1400-01-01']) - pytest.raises(ValueError, DatetimeIndex, [datetime(1400, 1, 1)]) - def test_timestamp_repr(self): # pre-1900 stamp = Timestamp('1850-01-01', tz='US/Eastern') @@ -1422,16 +1401,6 @@ def test_series_box_timestamp(self): assert isinstance(s.iat[5], Timestamp) - def test_frame_setitem_timestamp(self): - # 2155 - columns = DatetimeIndex(start='1/1/2012', end='2/1/2012', - freq=offsets.BDay()) - index = lrange(10) - data = DataFrame(columns=columns, index=index) - t = datetime(2012, 11, 1) - ts = Timestamp(t) - data[ts] = np.nan # works - def test_to_html_timestamp(self): rng = date_range('2000-01-01', periods=10) df = DataFrame(np.random.randn(10, 4), index=rng) @@ -1451,21 +1420,6 @@ def f(x): s.apply(f) DataFrame(s).applymap(f) - def test_dti_slicing(self): - dti = DatetimeIndex(start='1/1/2005', end='12/1/2005', freq='M') - dti2 = dti[[1, 3, 5]] - - v1 = dti2[0] - v2 = dti2[1] - v3 = dti2[2] - - assert v1 == Timestamp('2/28/2005') - assert v2 == Timestamp('4/30/2005') - assert v3 == Timestamp('6/30/2005') - - # don't carry freq through irregular slicing - assert dti2.freq is None - def test_woy_boundary(self): # make sure weeks at year boundaries are correct d = datetime(2013, 12, 31) @@ -1521,58 +1475,3 @@ def test_to_datetime_bijective(self): with tm.assert_produces_warning(exp_warning, check_stacklevel=False): assert (Timestamp(Timestamp.min.to_pydatetime()).value / 1000 == Timestamp.min.value / 1000) - - -class TestTimestampEquivDateRange(object): - # Older tests in TestTimeSeries constructed their `stamp` objects - # using `date_range` instead of the `Timestamp` constructor. - # TestTimestampEquivDateRange checks that these are equivalent in the - # pertinent cases. - - def test_date_range_timestamp_equiv(self): - rng = date_range('20090415', '20090519', tz='US/Eastern') - stamp = rng[0] - - ts = Timestamp('20090415', tz='US/Eastern', freq='D') - assert ts == stamp - - def test_date_range_timestamp_equiv_dateutil(self): - rng = date_range('20090415', '20090519', tz='dateutil/US/Eastern') - stamp = rng[0] - - ts = Timestamp('20090415', tz='dateutil/US/Eastern', freq='D') - assert ts == stamp - - def test_date_range_timestamp_equiv_explicit_pytz(self): - rng = date_range('20090415', '20090519', - tz=pytz.timezone('US/Eastern')) - stamp = rng[0] - - ts = Timestamp('20090415', tz=pytz.timezone('US/Eastern'), freq='D') - assert ts == stamp - - def test_date_range_timestamp_equiv_explicit_dateutil(self): - tm._skip_if_windows_python_3() - from pandas._libs.tslibs.timezones import dateutil_gettz as gettz - - rng = date_range('20090415', '20090519', tz=gettz('US/Eastern')) - stamp = rng[0] - - ts = Timestamp('20090415', tz=gettz('US/Eastern'), freq='D') - assert ts == stamp - - def test_date_range_timestamp_equiv_from_datetime_instance(self): - datetime_instance = datetime(2014, 3, 4) - # build a timestamp with a frequency, since then it supports - # addition/subtraction of integers - timestamp_instance = date_range(datetime_instance, periods=1, - freq='D')[0] - - ts = Timestamp(datetime_instance, freq='D') - assert ts == timestamp_instance - - def test_date_range_timestamp_equiv_preserve_frequency(self): - timestamp_instance = date_range('2014-03-05', periods=1, freq='D')[0] - ts = Timestamp('2014-03-05', freq='D') - - assert timestamp_instance == ts
Taking over from #18142 where scope got out of hand. This PR is part of a series intended to separate non-scalar tests out of `tests.scalars`.
https://api.github.com/repos/pandas-dev/pandas/pulls/18377
2017-11-20T00:42:42Z
2017-11-22T01:59:45Z
2017-11-22T01:59:45Z
2017-12-08T19:40:07Z
implement assert_tzawareness_compat for DatetimeIndex
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 77de1851490b2..ea083cfb1cb15 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -342,6 +342,7 @@ Conversion - Bug in :class:`Series`` with ``dtype='timedelta64[ns]`` where addition or subtraction of ``TimedeltaIndex`` had results cast to ``dtype='int64'`` (:issue:`17250`) - Bug in :class:`TimedeltaIndex` where division by a ``Series`` would return a ``TimedeltaIndex`` instead of a ``Series`` (issue:`19042`) - Bug in :class:`Series` with ``dtype='timedelta64[ns]`` where addition or subtraction of ``TimedeltaIndex`` could return a ``Series`` with an incorrect name (issue:`19043`) +- Fixed bug where comparing :class:`DatetimeIndex` failed to raise ``TypeError`` when attempting to compare timezone-aware and timezone-naive datetimelike objects (:issue:`18162`) - Indexing diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index ef0406a4b9f9d..d83d2d2c93ec8 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -13,14 +13,14 @@ _INT64_DTYPE, _NS_DTYPE, is_object_dtype, - is_datetime64_dtype, + is_datetime64_dtype, is_datetime64tz_dtype, is_datetimetz, is_dtype_equal, is_timedelta64_dtype, is_integer, is_float, is_integer_dtype, - is_datetime64_ns_dtype, + is_datetime64_ns_dtype, is_datetimelike, is_period_dtype, is_bool_dtype, is_string_like, @@ -106,8 +106,12 @@ def _dt_index_cmp(opname, cls, nat_result=False): def wrapper(self, other): func = getattr(super(DatetimeIndex, self), opname) - if (isinstance(other, datetime) or - isinstance(other, compat.string_types)): + + if isinstance(other, (datetime, compat.string_types)): + if isinstance(other, datetime): + # GH#18435 strings get a pass from tzawareness compat + self._assert_tzawareness_compat(other) + other = _to_m8(other, tz=self.tz) result = func(other) if isna(other): @@ -117,6 +121,10 @@ def wrapper(self, other): other = DatetimeIndex(other) elif not isinstance(other, (np.ndarray, Index, ABCSeries)): other = _ensure_datetime64(other) + + if is_datetimelike(other): + self._assert_tzawareness_compat(other) + result = func(np.asarray(other)) result = _values_from_object(result) @@ -652,6 +660,20 @@ def _simple_new(cls, values, name=None, freq=None, tz=None, result._reset_identity() return result + def _assert_tzawareness_compat(self, other): + # adapted from _Timestamp._assert_tzawareness_compat + other_tz = getattr(other, 'tzinfo', None) + if is_datetime64tz_dtype(other): + # Get tzinfo from Series dtype + other_tz = other.dtype.tz + if self.tz is None: + if other_tz is not None: + raise TypeError('Cannot compare tz-naive and tz-aware ' + 'datetime-like objects.') + elif other_tz is None: + raise TypeError('Cannot compare tz-naive and tz-aware ' + 'datetime-like objects') + @property def tzinfo(self): """ diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 076c3d6f25a89..41cd654cf22b9 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -1,3 +1,5 @@ +import operator + import pytest import numpy as np @@ -248,6 +250,42 @@ def test_append_join_nondatetimeindex(self): # it works rng.join(idx, how='outer') + @pytest.mark.parametrize('op', [operator.eq, operator.ne, + operator.gt, operator.ge, + operator.lt, operator.le]) + def test_comparison_tzawareness_compat(self, op): + # GH#18162 + dr = pd.date_range('2016-01-01', periods=6) + dz = dr.tz_localize('US/Pacific') + + with pytest.raises(TypeError): + op(dr, dz) + with pytest.raises(TypeError): + op(dr, list(dz)) + with pytest.raises(TypeError): + op(dz, dr) + with pytest.raises(TypeError): + op(dz, list(dr)) + + # Check that there isn't a problem aware-aware and naive-naive do not + # raise + assert (dr == dr).all() + assert (dr == list(dr)).all() + assert (dz == dz).all() + assert (dz == list(dz)).all() + + # Check comparisons against scalar Timestamps + ts = pd.Timestamp('2000-03-14 01:59') + ts_tz = pd.Timestamp('2000-03-14 01:59', tz='Europe/Amsterdam') + + assert (dr > ts).all() + with pytest.raises(TypeError): + op(dr, ts_tz) + + assert (dz > ts_tz).all() + with pytest.raises(TypeError): + op(dz, ts) + def test_comparisons_coverage(self): rng = date_range('1/1/2000', periods=10) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 5109542403b43..c4e8682934369 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2262,6 +2262,26 @@ def test_intersect_str_dates(self): assert len(res) == 0 + @pytest.mark.parametrize('op', [operator.eq, operator.ne, + operator.gt, operator.ge, + operator.lt, operator.le]) + def test_comparison_tzawareness_compat(self, op): + # GH#18162 + dr = pd.date_range('2016-01-01', periods=6) + dz = dr.tz_localize('US/Pacific') + + # Check that there isn't a problem aware-aware and naive-naive do not + # raise + naive_series = Series(dr) + aware_series = Series(dz) + with pytest.raises(TypeError): + op(dz, naive_series) + with pytest.raises(TypeError): + op(dr, aware_series) + + # TODO: implement _assert_tzawareness_compat for the reverse + # comparison with the Series on the left-hand side + class TestIndexUtils(object): diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 52b2d7205c849..de756375db8cb 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -821,6 +821,9 @@ def test_replace_series(self, how, to_key, from_key): if (from_key.startswith('datetime') and to_key.startswith('datetime')): # tested below return + elif from_key in ['datetime64[ns, US/Eastern]', 'datetime64[ns, UTC]']: + # tested below + return if how == 'dict': replacer = dict(zip(self.rep[from_key], self.rep[to_key])) @@ -849,6 +852,37 @@ def test_replace_series(self, how, to_key, from_key): tm.assert_series_equal(result, exp) + # TODO(jbrockmendel) commented out to only have a single xfail printed + @pytest.mark.xfail(reason='GH #18376, tzawareness-compat bug ' + 'in BlockManager.replace_list') + # @pytest.mark.parametrize('how', ['dict', 'series']) + # @pytest.mark.parametrize('to_key', ['timedelta64[ns]', 'bool', 'object', + # 'complex128', 'float64', 'int64']) + # @pytest.mark.parametrize('from_key', ['datetime64[ns, UTC]', + # 'datetime64[ns, US/Eastern]']) + # def test_replace_series_datetime_tz(self, how, to_key, from_key): + def test_replace_series_datetime_tz(self): + how = 'series' + from_key = 'datetime64[ns, US/Eastern]' + to_key = 'timedelta64[ns]' + + index = pd.Index([3, 4], name='xxx') + obj = pd.Series(self.rep[from_key], index=index, name='yyy') + assert obj.dtype == from_key + + if how == 'dict': + replacer = dict(zip(self.rep[from_key], self.rep[to_key])) + elif how == 'series': + replacer = pd.Series(self.rep[to_key], index=self.rep[from_key]) + else: + raise ValueError + + result = obj.replace(replacer) + exp = pd.Series(self.rep[to_key], index=index, name='yyy') + assert exp.dtype == to_key + + tm.assert_series_equal(result, exp) + # TODO(jreback) commented out to only have a single xfail printed @pytest.mark.xfail(reason="different tz, " "currently mask_missing raises SystemError") diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 0503a7b30e91c..29b4363ec70b9 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -450,6 +450,13 @@ def test_getitem_setitem_datetimeindex(self): lb = "1990-01-01 04:00:00" rb = "1990-01-01 07:00:00" + # GH#18435 strings get a pass from tzawareness compat + result = ts[(ts.index >= lb) & (ts.index <= rb)] + expected = ts[4:8] + assert_series_equal(result, expected) + + lb = "1990-01-01 04:00:00-0500" + rb = "1990-01-01 07:00:00-0500" result = ts[(ts.index >= lb) & (ts.index <= rb)] expected = ts[4:8] assert_series_equal(result, expected) @@ -475,6 +482,13 @@ def test_getitem_setitem_datetimeindex(self): lb = datetime(1990, 1, 1, 4) rb = datetime(1990, 1, 1, 7) + with pytest.raises(TypeError): + # tznaive vs tzaware comparison is invalid + # see GH#18376, GH#18162 + ts[(ts.index >= lb) & (ts.index <= rb)] + + lb = pd.Timestamp(datetime(1990, 1, 1, 4)).tz_localize(rng.tzinfo) + rb = pd.Timestamp(datetime(1990, 1, 1, 7)).tz_localize(rng.tzinfo) result = ts[(ts.index >= lb) & (ts.index <= rb)] expected = ts[4:8] assert_series_equal(result, expected) diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index cb905d8186ea9..c468908db5449 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -114,7 +114,7 @@ def __init__(self, obj): def setup_method(self, method): pass - def test_invalida_delgation(self): + def test_invalid_delegation(self): # these show that in order for the delegation to work # the _delegate_* methods need to be overridden to not raise # a TypeError
closes #18162 ATM comparing tzaware `DatetimeIndex` with tznaive DTI fails to raise. This PR implements `_assert_tzawareness_compa`t (which currently exists in `_Timestamp`) in `DatetimeIndex` to fix that. That in turn causes breakage in `Series.replace`. There's a small edit in `core.internals` to fix that, but I'm not sure that's the best way to make that work. There is still one remaining test error in `tests.series.test_indexing.TestSeriesIndexing.test_getitem_setitem_datetimeindex`, which may either represent a bug or a case where tznaive/tzaware rules are relaxed. ``` N = 50 rng = date_range('1/1/1990', periods=N, freq='H', tz='US/Eastern') ts = Series(np.random.randn(N), index=rng) lb = "1990-01-01 04:00:00" rb = "1990-01-01 07:00:00" >>> result = ts[(ts.index >= lb) & (ts.index <= rb)] TypeError: Cannot compare tz-naive and tz-aware datetime-like objects ``` Later in the same tests it tries to compare `ts.index` to naive `datetime` objects. Is this a special case where we are intentionally less strict?
https://api.github.com/repos/pandas-dev/pandas/pulls/18376
2017-11-20T00:21:05Z
2018-01-06T17:12:40Z
2018-01-06T17:12:40Z
2018-02-11T21:59:20Z
move shift_months to liboffsets, unify implementations of Q/M/Y offsets,
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index e4c065202a6ef..cabd792d69477 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -1761,10 +1761,6 @@ def monthrange(int64_t year, int64_t month): return (dayofweek(year, month, 1), days) -cdef inline int days_in_month(pandas_datetimestruct dts) nogil: - return days_per_month_table[is_leapyear(dts.year)][dts.month - 1] - - cpdef normalize_date(object dt): """ Normalize datetime.datetime value to midnight. Returns datetime.date as a @@ -1783,104 +1779,3 @@ cpdef normalize_date(object dt): return datetime(dt.year, dt.month, dt.day) else: raise TypeError('Unrecognized type: %s' % type(dt)) - - -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 - - -cdef inline int _month_add_months(pandas_datetimestruct dts, int months) nogil: - """ - New month number after shifting pandas_datetimestruct - number of months. - """ - cdef int new_month = (dts.month + months) % 12 - return 12 if new_month == 0 else new_month - - -@cython.wraparound(False) -@cython.boundscheck(False) -def shift_months(int64_t[:] dtindex, int months, object day=None): - """ - Given an int64-based datetime index, shift all elements - specified number of months using DateOffset semantics - - day: {None, 'start', 'end'} - * None: day of month - * 'start' 1st day of month - * 'end' last day of month - """ - cdef: - Py_ssize_t i - pandas_datetimestruct dts - int count = len(dtindex) - int months_to_roll - bint roll_check - int64_t[:] out = np.empty(count, dtype='int64') - - if day is None: - with nogil: - for i in range(count): - if dtindex[i] == NPY_NAT: - out[i] = NPY_NAT - continue - - dt64_to_dtstruct(dtindex[i], &dts) - dts.year = _year_add_months(dts, months) - dts.month = _month_add_months(dts, months) - - dts.day = min(dts.day, days_in_month(dts)) - out[i] = dtstruct_to_dt64(&dts) - elif day == 'start': - roll_check = False - if months <= 0: - months += 1 - roll_check = True - with nogil: - for i in range(count): - if dtindex[i] == NPY_NAT: - out[i] = NPY_NAT - continue - - dt64_to_dtstruct(dtindex[i], &dts) - months_to_roll = months - - # offset semantics - if on the anchor point and going backwards - # shift to next - if roll_check and dts.day == 1: - months_to_roll -= 1 - - dts.year = _year_add_months(dts, months_to_roll) - dts.month = _month_add_months(dts, months_to_roll) - dts.day = 1 - - out[i] = dtstruct_to_dt64(&dts) - elif day == 'end': - roll_check = False - if months > 0: - months -= 1 - roll_check = True - with nogil: - for i in range(count): - if dtindex[i] == NPY_NAT: - out[i] = NPY_NAT - continue - - dt64_to_dtstruct(dtindex[i], &dts) - months_to_roll = months - - # similar semantics - when adding shift forward by one - # month if already at an end of month - if roll_check and dts.day == days_in_month(dts): - months_to_roll += 1 - - dts.year = _year_add_months(dts, months_to_roll) - dts.month = _month_add_months(dts, months_to_roll) - - dts.day = days_in_month(dts) - out[i] = dtstruct_to_dt64(&dts) - else: - raise ValueError("day must be None, 'start' or 'end'") - - return np.asarray(out) diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index f38aca21a0438..526595e3a2eda 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -2,6 +2,7 @@ # cython: profile=False cimport cython +from cython cimport Py_ssize_t import time from cpython.datetime cimport datetime, timedelta, time as dt_time @@ -10,6 +11,7 @@ from dateutil.relativedelta import relativedelta import numpy as np cimport numpy as np +from numpy cimport int64_t np.import_array() @@ -19,6 +21,10 @@ from pandas._libs.tslib import monthrange from conversion cimport tz_convert_single, pydt_to_i8 from frequencies cimport get_freq_code +from nattype cimport NPY_NAT +from np_datetime cimport (pandas_datetimestruct, + dtstruct_to_dt64, dt64_to_dtstruct, + is_leapyear, days_per_month_table) # --------------------------------------------------------------------- # Constants @@ -419,13 +425,121 @@ class BaseOffset(_BaseOffset): # ---------------------------------------------------------------------- # RelativeDelta Arithmetic +@cython.wraparound(False) +@cython.boundscheck(False) +cdef inline int get_days_in_month(int year, int month) nogil: + return days_per_month_table[is_leapyear(year)][month - 1] + + +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 + + +cdef inline int month_add_months(pandas_datetimestruct dts, int months) nogil: + """ + New month number after shifting pandas_datetimestruct + number of months. + """ + cdef int new_month = (dts.month + months) % 12 + return 12 if new_month == 0 else new_month + + +@cython.wraparound(False) +@cython.boundscheck(False) +def shift_months(int64_t[:] dtindex, int months, object day=None): + """ + Given an int64-based datetime index, shift all elements + specified number of months using DateOffset semantics + + day: {None, 'start', 'end'} + * None: day of month + * 'start' 1st day of month + * 'end' last day of month + """ + cdef: + Py_ssize_t i + pandas_datetimestruct dts + int count = len(dtindex) + int months_to_roll + bint roll_check + int64_t[:] out = np.empty(count, dtype='int64') + + if day is None: + with nogil: + for i in range(count): + if dtindex[i] == NPY_NAT: + out[i] = NPY_NAT + continue + + dt64_to_dtstruct(dtindex[i], &dts) + dts.year = year_add_months(dts, months) + dts.month = month_add_months(dts, months) + + dts.day = min(dts.day, get_days_in_month(dts.year, dts.month)) + out[i] = dtstruct_to_dt64(&dts) + elif day == 'start': + roll_check = False + if months <= 0: + months += 1 + roll_check = True + with nogil: + for i in range(count): + if dtindex[i] == NPY_NAT: + out[i] = NPY_NAT + continue + + dt64_to_dtstruct(dtindex[i], &dts) + months_to_roll = months + + # offset semantics - if on the anchor point and going backwards + # shift to next + if roll_check and dts.day == 1: + months_to_roll -= 1 + + dts.year = year_add_months(dts, months_to_roll) + dts.month = month_add_months(dts, months_to_roll) + dts.day = 1 + + out[i] = dtstruct_to_dt64(&dts) + elif day == 'end': + roll_check = False + if months > 0: + months -= 1 + roll_check = True + with nogil: + for i in range(count): + if dtindex[i] == NPY_NAT: + out[i] = NPY_NAT + continue + + dt64_to_dtstruct(dtindex[i], &dts) + months_to_roll = months + + # similar semantics - when adding shift forward by one + # month if already at an end of month + if roll_check and dts.day == get_days_in_month(dts.year, + dts.month): + months_to_roll += 1 + + dts.year = year_add_months(dts, months_to_roll) + dts.month = month_add_months(dts, months_to_roll) + + dts.day = get_days_in_month(dts.year, dts.month) + out[i] = dtstruct_to_dt64(&dts) + else: + raise ValueError("day must be None, 'start' or 'end'") + + return np.asarray(out) + + cpdef datetime shift_month(datetime stamp, int months, object day_opt=None): """ Given a datetime (or Timestamp) `stamp`, an integer `months` and an option `day_opt`, return a new datetimelike that many months later, with day determined by `day_opt` using relativedelta semantics. - Scalar analogue of tslib.shift_months + Scalar analogue of shift_months Parameters ---------- diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 9e4f8d979ca99..0db26652eb191 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -8,6 +8,7 @@ from itertools import product import pandas as pd import pandas._libs.tslib as tslib +from pandas._libs.tslibs.offsets import shift_months import pandas.util.testing as tm from pandas import (DatetimeIndex, PeriodIndex, Series, Timestamp, date_range, _np_version_under1p10, Index, @@ -668,8 +669,7 @@ def test_shift_months(years, months): Timestamp('2000-01-01'), Timestamp('2000-02-29'), Timestamp('2000-12-31')]) - actual = DatetimeIndex(tslib.shift_months(s.asi8, years * 12 + - months)) + actual = DatetimeIndex(shift_months(s.asi8, years * 12 + months)) expected = DatetimeIndex([x + pd.offsets.DateOffset( years=years, months=months) for x in s]) tm.assert_index_equal(actual, expected) diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index c9c4d1b1e7119..021d636042954 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -230,7 +230,7 @@ def apply_index(self, i): months = ((self.kwds.get('years', 0) * 12 + self.kwds.get('months', 0)) * self.n) if months: - shifted = tslib.shift_months(i.asi8, months) + shifted = liboffsets.shift_months(i.asi8, months) i = i._shallow_copy(shifted) weeks = (self.kwds.get('weeks', 0)) * self.n @@ -928,58 +928,57 @@ def name(self): return "{code}-{month}".format(code=self.rule_code, month=_int_to_month[self.n]) - -class MonthEnd(MonthOffset): - """DateOffset of one month end""" - _prefix = 'M' - _day_opt = 'end' + def onOffset(self, dt): + if self.normalize and not _is_normalized(dt): + return False + return dt.day == self._get_offset_day(dt) @apply_wraps def apply(self, other): n = self.n compare_day = self._get_offset_day(other) - if other.day < compare_day: - other = shift_month(other, -1, self._day_opt) - if n <= 0: - n = n + 1 - other = shift_month(other, n, self._day_opt) - return other + + if n > 0 and other.day < compare_day: + n -= 1 + elif n <= 0 and other.day > compare_day: + # as if rolled forward already + n += 1 + + return shift_month(other, n, self._day_opt) + + +class MonthEnd(MonthOffset): + """DateOffset of one month end""" + _prefix = 'M' + _day_opt = 'end' @apply_index_wraps def apply_index(self, i): - shifted = tslib.shift_months(i.asi8, self.n, self._day_opt) + shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt) return i._shallow_copy(shifted) - def onOffset(self, dt): - if self.normalize and not _is_normalized(dt): - return False - return dt.day == self._get_offset_day(dt) - class MonthBegin(MonthOffset): """DateOffset of one month at beginning""" _prefix = 'MS' _day_opt = 'start' - @apply_wraps - def apply(self, other): - n = self.n - compare_day = self._get_offset_day(other) - - if other.day > compare_day and n <= 0: # then roll forward if n<=0 - n += 1 - - return shift_month(other, n, self._day_opt) - @apply_index_wraps def apply_index(self, i): - shifted = tslib.shift_months(i.asi8, self.n, self._day_opt) + shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt) return i._shallow_copy(shifted) - def onOffset(self, dt): - if self.normalize and not _is_normalized(dt): - return False - return dt.day == self._get_offset_day(dt) + +class BusinessMonthEnd(MonthOffset): + """DateOffset increments between business EOM dates""" + _prefix = 'BM' + _day_opt = 'business_end' + + +class BusinessMonthBegin(MonthOffset): + """DateOffset of one business month at beginning""" + _prefix = 'BMS' + _day_opt = 'business_start' class SemiMonthOffset(DateOffset): @@ -1181,48 +1180,6 @@ def _apply_index_days(self, i, roll): return i + (roll % 2) * Timedelta(days=self.day_of_month - 1).value -class BusinessMonthEnd(MonthOffset): - """DateOffset increments between business EOM dates""" - _prefix = 'BM' - _day_opt = 'business_end' - - @apply_wraps - def apply(self, other): - n = self.n - compare_day = self._get_offset_day(other) - - if n > 0 and not other.day >= compare_day: - n = n - 1 - elif n <= 0 and other.day > compare_day: - n = n + 1 - - return shift_month(other, n, self._day_opt) - - -class BusinessMonthBegin(MonthOffset): - """DateOffset of one business month at beginning""" - _prefix = 'BMS' - _day_opt = 'business_start' - - @apply_wraps - def apply(self, other): - n = self.n - compare_day = self._get_offset_day(other) - - if other.day > compare_day and n <= 0: - # as if rolled forward already - n += 1 - elif other.day < compare_day and n > 0: - n -= 1 - - return shift_month(other, n, self._day_opt) - - def onOffset(self, dt): - if self.normalize and not _is_normalized(dt): - return False - return dt.day == self._get_offset_day(dt) - - class CustomBusinessMonthEnd(BusinessMixin, MonthOffset): """ DateOffset subclass representing one custom business month, incrementing @@ -1245,6 +1202,8 @@ class CustomBusinessMonthEnd(BusinessMixin, MonthOffset): _cacheable = False _prefix = 'CBM' + onOffset = DateOffset.onOffset # override MonthOffset method + def __init__(self, n=1, normalize=False, weekmask='Mon Tue Wed Thu Fri', holidays=None, calendar=None, offset=timedelta(0)): self.n = int(n) @@ -1316,6 +1275,8 @@ class CustomBusinessMonthBegin(BusinessMixin, MonthOffset): _cacheable = False _prefix = 'CBMS' + onOffset = DateOffset.onOffset # override MonthOffset method + def __init__(self, n=1, normalize=False, weekmask='Mon Tue Wed Thu Fri', holidays=None, calendar=None, offset=timedelta(0)): self.n = int(n) @@ -1641,6 +1602,23 @@ def rule_code(self): month = _int_to_month[self.startingMonth] return '{prefix}-{month}'.format(prefix=self._prefix, month=month) + @apply_wraps + def apply(self, other): + n = self.n + compare_day = self._get_offset_day(other) + + months_since = (other.month - self.startingMonth) % 3 + + if n <= 0 and (months_since != 0 or + (months_since == 0 and other.day > compare_day)): + # make sure to roll forward, so negate + n += 1 + elif n > 0 and (months_since == 0 and other.day < compare_day): + # pretend to roll back if on same month but before compare_day + n -= 1 + + return shift_month(other, 3 * n - months_since, self._day_opt) + class BQuarterEnd(QuarterOffset): """DateOffset increments between business Quarter dates @@ -1654,27 +1632,11 @@ class BQuarterEnd(QuarterOffset): _prefix = 'BQ' _day_opt = 'business_end' - @apply_wraps - def apply(self, other): - n = self.n - compare_day = self._get_offset_day(other) - - monthsToGo = 3 - ((other.month - self.startingMonth) % 3) - if monthsToGo == 3: - monthsToGo = 0 - - if n > 0 and not (other.day >= compare_day and monthsToGo == 0): - n = n - 1 - elif n <= 0 and other.day > compare_day and monthsToGo == 0: - n = n + 1 - - return shift_month(other, monthsToGo + 3 * n, self._day_opt) - def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False modMonth = (dt.month - self.startingMonth) % 3 - return BMonthEnd().onOffset(dt) and modMonth == 0 + return modMonth == 0 and dt.day == self._get_offset_day(dt) _int_to_month = tslib._MONTH_ALIASES @@ -1690,26 +1652,6 @@ class BQuarterBegin(QuarterOffset): _prefix = 'BQS' _day_opt = 'business_start' - @apply_wraps - def apply(self, other): - n = self.n - - compare_day = self._get_offset_day(other) - - monthsSince = (other.month - self.startingMonth) % 3 - - if n <= 0 and monthsSince != 0: # make sure to roll forward so negate - monthsSince = monthsSince - 3 - - # roll forward if on same month later than first bday - if n <= 0 and (monthsSince == 0 and other.day > compare_day): - n = n + 1 - # pretend to roll back if on same month but before firstbday - elif n > 0 and (monthsSince == 0 and other.day < compare_day): - n = n - 1 - - return shift_month(other, 3 * n - monthsSince, self._day_opt) - class QuarterEnd(EndMixin, QuarterOffset): """DateOffset increments between business Quarter dates @@ -1722,24 +1664,6 @@ class QuarterEnd(EndMixin, QuarterOffset): _prefix = 'Q' _day_opt = 'end' - @apply_wraps - def apply(self, other): - n = self.n - other = datetime(other.year, other.month, other.day, - other.hour, other.minute, other.second, - other.microsecond) - compare_day = self._get_offset_day(other) - - monthsToGo = 3 - ((other.month - self.startingMonth) % 3) - if monthsToGo == 3: - monthsToGo = 0 - - if n > 0 and not (other.day >= compare_day and monthsToGo == 0): - n = n - 1 - - other = shift_month(other, monthsToGo + 3 * n, self._day_opt) - return other - @apply_index_wraps def apply_index(self, i): return self._end_apply_index(i, self.freqstr) @@ -1748,7 +1672,7 @@ def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False modMonth = (dt.month - self.startingMonth) % 3 - return MonthEnd().onOffset(dt) and modMonth == 0 + return modMonth == 0 and dt.day == self._get_offset_day(dt) class QuarterBegin(BeginMixin, QuarterOffset): @@ -1758,24 +1682,6 @@ class QuarterBegin(BeginMixin, QuarterOffset): _prefix = 'QS' _day_opt = 'start' - @apply_wraps - def apply(self, other): - n = self.n - compare_day = self._get_offset_day(other) - - monthsSince = (other.month - self.startingMonth) % 3 - - if n <= 0 and monthsSince != 0: - # make sure you roll forward, so negate - monthsSince = monthsSince - 3 - - if n <= 0 and (monthsSince == 0 and other.day > compare_day): - # after start, so come back an extra period as if rolled forward - n = n + 1 - - other = shift_month(other, 3 * n - monthsSince, self._day_opt) - return other - @apply_index_wraps def apply_index(self, i): freq_month = 12 if self.startingMonth == 1 else self.startingMonth - 1 @@ -1796,6 +1702,17 @@ def _get_offset_day(self, other): return liboffsets.get_day_of_month(other.replace(month=self.month), self._day_opt) + @apply_wraps + def apply(self, other): + years = roll_yearday(other, self.n, self.month, self._day_opt) + months = years * 12 + (self.month - other.month) + return shift_month(other, months, self._day_opt) + + def onOffset(self, dt): + if self.normalize and not _is_normalized(dt): + return False + return dt.month == self.month and dt.day == self._get_offset_day(dt) + def __init__(self, n=1, normalize=False, month=None): month = month if month is not None else self._default_month self.month = month @@ -1825,24 +1742,6 @@ class BYearEnd(YearOffset): _prefix = 'BA' _day_opt = 'business_end' - @apply_wraps - def apply(self, other): - n = self.n - compare_day = self._get_offset_day(other) - - years = n - if n > 0: - if (other.month < self.month or - (other.month == self.month and other.day < compare_day)): - years -= 1 - elif n <= 0: - if (other.month > self.month or - (other.month == self.month and other.day > compare_day)): - years += 1 - - months = years * 12 + (self.month - other.month) - return shift_month(other, months, self._day_opt) - class BYearBegin(YearOffset): """DateOffset increments between business year begin dates""" @@ -1851,26 +1750,6 @@ class BYearBegin(YearOffset): _prefix = 'BAS' _day_opt = 'business_start' - @apply_wraps - def apply(self, other): - n = self.n - compare_day = self._get_offset_day(other) - - years = n - - if n > 0: # roll back first for positive n - if (other.month < self.month or - (other.month == self.month and other.day < compare_day)): - years -= 1 - elif n <= 0: # roll forward - if (other.month > self.month or - (other.month == self.month and other.day > compare_day)): - years += 1 - - # set first bday for result - months = years * 12 + (self.month - other.month) - return shift_month(other, months, self._day_opt) - class YearEnd(EndMixin, YearOffset): """DateOffset increments between calendar year ends""" @@ -1878,25 +1757,11 @@ class YearEnd(EndMixin, YearOffset): _prefix = 'A' _day_opt = 'end' - @apply_wraps - def apply(self, other): - n = roll_yearday(other, self.n, self.month, self._day_opt) - year = other.year + n - days_in_month = tslib.monthrange(year, self.month)[1] - return datetime(year, self.month, days_in_month, - other.hour, other.minute, other.second, - other.microsecond) - @apply_index_wraps def apply_index(self, i): # convert month anchor to annual period tuple return self._end_apply_index(i, self.freqstr) - def onOffset(self, dt): - if self.normalize and not _is_normalized(dt): - return False - return self.month == dt.month and dt.day == self._get_offset_day(dt) - class YearBegin(BeginMixin, YearOffset): """DateOffset increments between calendar year begin dates""" @@ -1904,23 +1769,12 @@ class YearBegin(BeginMixin, YearOffset): _prefix = 'AS' _day_opt = 'start' - @apply_wraps - def apply(self, other): - n = roll_yearday(other, self.n, self.month, self._day_opt) - year = other.year + n - return other.replace(year=year, month=self.month, day=1) - @apply_index_wraps def apply_index(self, i): freq_month = 12 if self.month == 1 else self.month - 1 freqstr = 'A-{month}'.format(month=_int_to_month[freq_month]) return self._beg_apply_index(i, freqstr) - def onOffset(self, dt): - if self.normalize and not _is_normalized(dt): - return False - return dt.month == self.month and dt.day == self._get_offset_day(dt) - # --------------------------------------------------------------------- # Special Offset Classes diff --git a/setup.py b/setup.py index 76847e66b8bd5..44e7de1665bf0 100755 --- a/setup.py +++ b/setup.py @@ -577,7 +577,10 @@ def pxd(name): 'pyxfile': '_libs/tslibs/offsets', 'pxdfiles': ['_libs/src/util', '_libs/tslibs/conversion', - '_libs/tslibs/frequencies']}, + '_libs/tslibs/frequencies', + '_libs/tslibs/nattype'], + 'depends': tseries_depends, + 'sources': np_datetime_sources}, '_libs.tslibs.parsing': { 'pyxfile': '_libs/tslibs/parsing', 'pxdfiles': ['_libs/src/util',
This moves `tslib.shift_months` to liboffsets. After several algebra-simplifing PRs, here's the payoff. Nearly all of the logic in M/Q/Y offset subclasses is now identical, so can be moved into the parent classes. `BusinessMonthEnd` gains an `onOffset` method (instead of inheriting from `DateOffset`) The Year and Day algebra is simple enough that the diff should be obvious. The `QuarterFoo.apply` methods are require a few steps of simplification before they become identical. I decided just to push the whole thing rather than drag it out.
https://api.github.com/repos/pandas-dev/pandas/pulls/18375
2017-11-19T22:07:33Z
2017-11-20T11:20:57Z
2017-11-20T11:20:57Z
2017-12-08T19:40:14Z
CLN: Removed overridden Timedelta properties (#18242)
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 6dc730cae37f7..171db4a5a6bc4 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -77,7 +77,7 @@ Performance Improvements - Added a keyword argument, ``cache``, to :func:`to_datetime` that improved the performance of converting duplicate datetime arguments (:issue:`11665`) - :class`DateOffset` arithmetic performance is improved (:issue:`18218`) - Converting a ``Series`` of ``Timedelta`` objects to days, seconds, etc... sped up through vectorization of underlying methods (:issue:`18092`) -- +- The overriden ``Timedelta`` properties of days, seconds and microseconds have been removed, leveraging their built-in Python versions instead (:issue:`18242`) .. _whatsnew_0220.docs: diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 4d55c8add6757..3a1e9de2a6cf6 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -665,36 +665,6 @@ cdef class _Timedelta(timedelta): else: return "D" - @property - def days(self): - """ - Number of Days - - .components will return the shown components - """ - self._ensure_components() - return self._d - - @property - def seconds(self): - """ - Number of seconds (>= 0 and less than 1 day). - - .components will return the shown components - """ - self._ensure_components() - return self._seconds - - @property - def microseconds(self): - """ - Number of microseconds (>= 0 and less than 1 second). - - .components will return the shown components - """ - self._ensure_components() - return self._microseconds - @property def nanoseconds(self): """
- [X] closes #18242 - [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/18374
2017-11-19T21:09:57Z
2017-11-20T11:12:35Z
2017-11-20T11:12:35Z
2017-11-20T13:07:22Z
PERF: improve plotting performance by not stringifying all x data
diff --git a/asv_bench/benchmarks/plotting.py b/asv_bench/benchmarks/plotting.py index dda684b35e301..16889b2f19e89 100644 --- a/asv_bench/benchmarks/plotting.py +++ b/asv_bench/benchmarks/plotting.py @@ -10,15 +10,37 @@ def date_range(start=None, end=None, periods=None, freq=None): from pandas.tools.plotting import andrews_curves +class Plotting(object): + goal_time = 0.2 + + def setup(self): + import matplotlib + matplotlib.use('Agg') + self.s = Series(np.random.randn(1000000)) + self.df = DataFrame({'col': self.s}) + + def time_series_plot(self): + self.s.plot() + + def time_frame_plot(self): + self.df.plot() + + class TimeseriesPlotting(object): goal_time = 0.2 def setup(self): import matplotlib matplotlib.use('Agg') - self.N = 2000 - self.M = 5 - self.df = DataFrame(np.random.randn(self.N, self.M), index=date_range('1/1/1975', periods=self.N)) + N = 2000 + M = 5 + idx = date_range('1/1/1975', periods=N) + self.df = DataFrame(np.random.randn(N, M), index=idx) + + idx_irregular = pd.DatetimeIndex(np.concatenate((idx.values[0:10], + idx.values[12:]))) + self.df2 = DataFrame(np.random.randn(len(idx_irregular), M), + index=idx_irregular) def time_plot_regular(self): self.df.plot() @@ -26,6 +48,9 @@ def time_plot_regular(self): def time_plot_regular_compat(self): self.df.plot(x_compat=True) + def time_plot_irregular(self): + self.df2.plot() + class Misc(object): goal_time = 0.6 diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 0ab536f2898c7..8179d66ac71fd 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -39,7 +39,7 @@ Deprecations Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- +- Improved performance of plotting large series/dataframes (:issue:`18236`). - - diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index c934648a1d111..090e8f7f648a9 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -383,12 +383,16 @@ def _add_table(self): def _post_plot_logic_common(self, ax, data): """Common post process for each axes""" - labels = [pprint_thing(key) for key in data.index] - labels = dict(zip(range(len(data.index)), labels)) + + def get_label(i): + try: + return pprint_thing(data.index[i]) + except Exception: + return '' if self.orientation == 'vertical' or self.orientation is None: if self._need_to_set_index: - xticklabels = [labels.get(x, '') for x in ax.get_xticks()] + xticklabels = [get_label(x) for x in ax.get_xticks()] ax.set_xticklabels(xticklabels) self._apply_axis_properties(ax.xaxis, rot=self.rot, fontsize=self.fontsize) @@ -400,7 +404,7 @@ def _post_plot_logic_common(self, ax, data): elif self.orientation == 'horizontal': if self._need_to_set_index: - yticklabels = [labels.get(y, '') for y in ax.get_yticks()] + yticklabels = [get_label(y) for y in ax.get_yticks()] ax.set_yticklabels(yticklabels) self._apply_axis_properties(ax.yaxis, rot=self.rot, fontsize=self.fontsize)
Closes #18236 Currently when plotting all x / index data are converted to strings, while you typically only need a few tick labels. So when you have a lot of data, this cause the pandas plotter to be hugely slower than needed (and than a pure matplotlib one) On master: ``` [ 33.33%] ··· Running plotting.Plotting.time_frame_plot 4.43s [ 50.00%] ··· Running plotting.Plotting.time_series_plot 4.19s [ 66.67%] ··· Running plotting.TimeseriesPlotting.time_plot_irregular 72.2±0.2ms [ 83.33%] ··· Running plotting.TimeseriesPlotting.time_plot_regular 108±0.5ms [100.00%] ··· Running plotting.TimeseriesPlotting.time_plot_regular_compat 71.5±0.8ms ``` with this branch: ``` [ 33.33%] ··· Running plotting.Plotting.time_frame_plot 132±20ms [ 50.00%] ··· Running plotting.Plotting.time_series_plot 71.4±30ms [ 66.67%] ··· Running plotting.TimeseriesPlotting.time_plot_irregular 58.7±0.5ms [ 83.33%] ··· Running plotting.TimeseriesPlotting.time_plot_regular 96.9±2ms [100.00%] ··· Running plotting.TimeseriesPlotting.time_plot_regular_compat 57.4±0.8ms ``` So for very simple plot when from 4s to ca 100ms (which is much closer to the pure matplotlib performance)
https://api.github.com/repos/pandas-dev/pandas/pulls/18373
2017-11-19T20:52:05Z
2017-11-20T18:21:04Z
2017-11-20T18:21:04Z
2017-11-20T18:21:07Z
remove get_value_box since it is redundant with libindex.get_value_at
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index d74673b17c8d9..f20a665578e00 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -47,6 +47,31 @@ def get_value_at(ndarray arr, object loc): return util.get_value_at(arr, loc) +cpdef object get_value_box(ndarray arr, object loc): + cdef: + Py_ssize_t i, sz + + if util.is_float_object(loc): + casted = int(loc) + if casted == loc: + loc = casted + i = <Py_ssize_t> loc + sz = cnp.PyArray_SIZE(arr) + + if i < 0 and sz > 0: + i += sz + + if i >= sz or sz == 0 or i < 0: + raise IndexError('index out of bounds') + + if arr.descr.type_num == NPY_DATETIME: + return Timestamp(util.get_value_1d(arr, i)) + elif arr.descr.type_num == NPY_TIMEDELTA: + return Timedelta(util.get_value_1d(arr, i)) + else: + return util.get_value_1d(arr, i) + + def set_value_at(ndarray arr, object loc, object val): return util.set_value_at(arr, loc, val) diff --git a/pandas/_libs/src/util.pxd b/pandas/_libs/src/util.pxd index 84d6dddf338a5..7361aa36144c5 100644 --- a/pandas/_libs/src/util.pxd +++ b/pandas/_libs/src/util.pxd @@ -53,7 +53,8 @@ cdef extern from "headers/stdint.h": cdef inline object get_value_at(ndarray arr, object loc): cdef: Py_ssize_t i, sz - void* data_ptr + int casted + if is_float_object(loc): casted = int(loc) if casted == loc: diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index e43fddad413a5..65e074625cad7 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -6,7 +6,7 @@ cimport numpy as np from numpy cimport (int32_t, int64_t, import_array, ndarray, - float64_t, NPY_DATETIME, NPY_TIMEDELTA) + float64_t) import numpy as np import sys @@ -848,31 +848,6 @@ cdef inline bint _check_all_nulls(object val): return res -cpdef object get_value_box(ndarray arr, object loc): - cdef: - Py_ssize_t i, sz - - if is_float_object(loc): - casted = int(loc) - if casted == loc: - loc = casted - i = <Py_ssize_t> loc - sz = np.PyArray_SIZE(arr) - - if i < 0 and sz > 0: - i += sz - - if i >= sz or sz == 0 or i < 0: - raise IndexError('index out of bounds') - - if arr.descr.type_num == NPY_DATETIME: - return Timestamp(util.get_value_1d(arr, i)) - elif arr.descr.type_num == NPY_TIMEDELTA: - return Timedelta(util.get_value_1d(arr, i)) - else: - return util.get_value_1d(arr, i) - - # Add the min and max fields at the class level cdef int64_t _NS_UPPER_BOUND = INT64_MAX # the smallest value we could actually represent is diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 121bf6a66dee5..36fe6d55f71eb 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2559,7 +2559,7 @@ def get_value(self, series, key): raise try: - return libts.get_value_box(s, key) + return libindex.get_value_box(s, key) except IndexError: raise except TypeError:
`tslib.get_value_box` is effectively identical to `index.get_value_at` (figuring this out requires looking at `util.get_value_at`). Since the only use of `get_value_box` is in `core.index.base`, just get rid of it and use `libindex.get_value_at` there instead. Fixup type declarations in `util.get_value_at`. - [x] closes #18299 - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/18371
2017-11-19T18:37:02Z
2017-11-20T11:15:27Z
2017-11-20T11:15:27Z
2017-12-08T19:40:14Z
CLN: remove tseries.util.pivot_annual/isleapyear
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 6dc730cae37f7..419ce108e110d 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -66,7 +66,8 @@ Removal of prior version deprecations/changes - Warnings against the obsolete usage ``Categorical(codes, categories)``, which were emitted for instance when the first two arguments to ``Categorical()`` had different dtypes, and recommended the use of ``Categorical.from_codes``, have now been removed (:issue:`8074`) - The ``levels`` and ``labels`` attributes of a ``MultiIndex`` can no longer be set directly (:issue:`4039`). -- +- ``pd.tseries.util.pivot_annual`` has been removed (deprecated since v0.19). Use ``pivot_table`` instead (:issue:`18370`) +- ``pd.tseries.util.isleapyear`` has been removed (deprecated since v0.19). Use ``.is_leap_year`` property in Datetime-likes instead (:issue:`18370`) .. _whatsnew_0220.performance: diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index e3951634baca9..857116c8f8f78 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -13,7 +13,6 @@ from pandas.core.reshape.pivot import pivot_table, crosstab from pandas.compat import range, product import pandas.util.testing as tm -from pandas.tseries.util import pivot_annual, isleapyear from pandas.api.types import CategoricalDtype as CDT @@ -891,6 +890,40 @@ def test_pivot_dtaccessor(self): index=['X', 'Y'], columns=exp_col) tm.assert_frame_equal(result, expected) + def test_daily(self): + rng = date_range('1/1/2000', '12/31/2004', freq='D') + ts = Series(np.random.randn(len(rng)), index=rng) + + annual = pivot_table(DataFrame(ts), index=ts.index.year, + columns=ts.index.dayofyear) + annual.columns = annual.columns.droplevel(0) + + doy = np.asarray(ts.index.dayofyear) + + for i in range(1, 367): + subset = ts[doy == i] + subset.index = subset.index.year + + result = annual[i].dropna() + tm.assert_series_equal(result, subset, check_names=False) + assert result.name == i + + def test_monthly(self): + rng = date_range('1/1/2000', '12/31/2004', freq='M') + ts = Series(np.random.randn(len(rng)), index=rng) + + annual = pivot_table(pd.DataFrame(ts), index=ts.index.year, + columns=ts.index.month) + annual.columns = annual.columns.droplevel(0) + + month = ts.index.month + for i in range(1, 13): + subset = ts[month == i] + subset.index = subset.index.year + result = annual[i].dropna() + tm.assert_series_equal(result, subset, check_names=False) + assert result.name == i + def test_pivot_table_with_iterator_values(self): # GH 12017 aggs = {'D': 'sum', 'E': 'mean'} @@ -1048,6 +1081,16 @@ def test_pivot_table_not_series(self): tm.assert_frame_equal(result, expected) + def test_pivot_margins_name_unicode(self): + # issue #13292 + greek = u'\u0394\u03bf\u03ba\u03b9\u03bc\u03ae' + frame = pd.DataFrame({'foo': [1, 2, 3]}) + table = pd.pivot_table(frame, index=['foo'], aggfunc=len, margins=True, + margins_name=greek) + index = pd.Index([1, 2, 3, greek], dtype='object', name='foo') + expected = pd.DataFrame(index=index) + tm.assert_frame_equal(table, expected) + class TestCrosstab(object): @@ -1525,116 +1568,3 @@ def test_crosstab_dup_index_names(self): index=expected_index, columns=expected_index) tm.assert_frame_equal(result, expected) - - -class TestPivotAnnual(object): - """ - New pandas of scikits.timeseries pivot_annual - """ - - def test_daily(self): - rng = date_range('1/1/2000', '12/31/2004', freq='D') - ts = Series(np.random.randn(len(rng)), index=rng) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - annual = pivot_annual(ts, 'D') - - doy = np.asarray(ts.index.dayofyear) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - doy[(~isleapyear(ts.index.year)) & (doy >= 60)] += 1 - - for i in range(1, 367): - subset = ts[doy == i] - subset.index = [x.year for x in subset.index] - - result = annual[i].dropna() - tm.assert_series_equal(result, subset, check_names=False) - assert result.name == i - - # check leap days - leaps = ts[(ts.index.month == 2) & (ts.index.day == 29)] - day = leaps.index.dayofyear[0] - leaps.index = leaps.index.year - leaps.name = 60 - tm.assert_series_equal(annual[day].dropna(), leaps) - - def test_hourly(self): - rng_hourly = date_range('1/1/1994', periods=(18 * 8760 + 4 * 24), - freq='H') - data_hourly = np.random.randint(100, 350, rng_hourly.size) - ts_hourly = Series(data_hourly, index=rng_hourly) - - grouped = ts_hourly.groupby(ts_hourly.index.year) - hoy = grouped.apply(lambda x: x.reset_index(drop=True)) - hoy = hoy.index.droplevel(0).values - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - hoy[~isleapyear(ts_hourly.index.year) & (hoy >= 1416)] += 24 - hoy += 1 - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - annual = pivot_annual(ts_hourly) - - ts_hourly = ts_hourly.astype(float) - for i in [1, 1416, 1417, 1418, 1439, 1440, 1441, 8784]: - subset = ts_hourly[hoy == i] - subset.index = [x.year for x in subset.index] - - result = annual[i].dropna() - tm.assert_series_equal(result, subset, check_names=False) - assert result.name == i - - leaps = ts_hourly[(ts_hourly.index.month == 2) & ( - ts_hourly.index.day == 29) & (ts_hourly.index.hour == 0)] - hour = leaps.index.dayofyear[0] * 24 - 23 - leaps.index = leaps.index.year - leaps.name = 1417 - tm.assert_series_equal(annual[hour].dropna(), leaps) - - def test_weekly(self): - pass - - def test_monthly(self): - rng = date_range('1/1/2000', '12/31/2004', freq='M') - ts = Series(np.random.randn(len(rng)), index=rng) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - annual = pivot_annual(ts, 'M') - - month = ts.index.month - for i in range(1, 13): - subset = ts[month == i] - subset.index = [x.year for x in subset.index] - result = annual[i].dropna() - tm.assert_series_equal(result, subset, check_names=False) - assert result.name == i - - def test_period_monthly(self): - pass - - def test_period_daily(self): - pass - - def test_period_weekly(self): - pass - - def test_isleapyear_deprecate(self): - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert isleapyear(2000) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert not isleapyear(2001) - - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert isleapyear(2004) - - def test_pivot_margins_name_unicode(self): - # issue #13292 - greek = u'\u0394\u03bf\u03ba\u03b9\u03bc\u03ae' - frame = pd.DataFrame({'foo': [1, 2, 3]}) - table = pd.pivot_table(frame, index=['foo'], aggfunc=len, margins=True, - margins_name=greek) - index = pd.Index([1, 2, 3, greek], dtype='object', name='foo') - expected = pd.DataFrame(index=index) - tm.assert_frame_equal(table, expected) diff --git a/pandas/tseries/util.py b/pandas/tseries/util.py deleted file mode 100644 index dc8a41215139d..0000000000000 --- a/pandas/tseries/util.py +++ /dev/null @@ -1,104 +0,0 @@ -import warnings - -from pandas.compat import lrange -import numpy as np -from pandas.core.dtypes.common import _ensure_platform_int -from pandas.core.frame import DataFrame -import pandas.core.algorithms as algorithms - - -def pivot_annual(series, freq=None): - """ - Deprecated. Use ``pivot_table`` instead. - - Group a series by years, taking leap years into account. - - The output has as many rows as distinct years in the original series, - and as many columns as the length of a leap year in the units corresponding - to the original frequency (366 for daily frequency, 366*24 for hourly...). - The first column of the output corresponds to Jan. 1st, 00:00:00, - while the last column corresponds to Dec, 31st, 23:59:59. - Entries corresponding to Feb. 29th are masked for non-leap years. - - For example, if the initial series has a daily frequency, the 59th column - of the output always corresponds to Feb. 28th, the 61st column to Mar. 1st, - and the 60th column is masked for non-leap years. - With a hourly initial frequency, the (59*24)th column of the output always - correspond to Feb. 28th 23:00, the (61*24)th column to Mar. 1st, 00:00, and - the 24 columns between (59*24) and (61*24) are masked. - - If the original frequency is less than daily, the output is equivalent to - ``series.convert('A', func=None)``. - - Parameters - ---------- - series : Series - freq : string or None, default None - - Returns - ------- - annual : DataFrame - """ - - msg = "pivot_annual is deprecated. Use pivot_table instead" - warnings.warn(msg, FutureWarning) - - index = series.index - year = index.year - years = algorithms.unique1d(year) - - if freq is not None: - freq = freq.upper() - else: - freq = series.index.freq - - if freq == 'D': - width = 366 - offset = np.asarray(index.dayofyear) - 1 - - # adjust for leap year - offset[(~isleapyear(year)) & (offset >= 59)] += 1 - - columns = lrange(1, 367) - # todo: strings like 1/1, 1/25, etc.? - elif freq in ('M', 'BM'): - width = 12 - offset = np.asarray(index.month) - 1 - columns = lrange(1, 13) - elif freq == 'H': - width = 8784 - grouped = series.groupby(series.index.year) - defaulted = grouped.apply(lambda x: x.reset_index(drop=True)) - defaulted.index = defaulted.index.droplevel(0) - offset = np.asarray(defaulted.index) - offset[~isleapyear(year) & (offset >= 1416)] += 24 - columns = lrange(1, 8785) - else: - raise NotImplementedError(freq) - - flat_index = (year - years.min()) * width + offset - flat_index = _ensure_platform_int(flat_index) - - values = np.empty((len(years), width)) - values.fill(np.nan) - values.put(flat_index, series.values) - - return DataFrame(values, index=years, columns=columns) - - -def isleapyear(year): - """ - Returns true if year is a leap year. - - Parameters - ---------- - year : integer / sequence - A given (list of) year(s). - """ - - msg = "isleapyear is deprecated. Use .is_leap_year property instead" - warnings.warn(msg, FutureWarning) - - year = np.asarray(year) - return np.logical_or(year % 400 == 0, - np.logical_and(year % 4 == 0, year % 100 > 0))
``pivot_annual`` and ``isleapyear`` in ``tseries.util`` were deprecated in v0.19. This PR removes them from the code base.
https://api.github.com/repos/pandas-dev/pandas/pulls/18370
2017-11-19T18:13:49Z
2017-11-22T00:07:06Z
2017-11-22T00:07:05Z
2017-11-27T23:59:13Z
cut/paste _Timestamp+Timestamp to tslibs.timestamps
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 705336dfadf90..5e3eb1f00b18c 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -5,32 +5,23 @@ # distutils: define_macros=CYTHON_TRACE_NOGIL=0 cimport numpy as np -from numpy cimport (int32_t, int64_t, import_array, ndarray, - float64_t) +from numpy cimport int64_t, import_array, ndarray, float64_t import numpy as np -import sys -cdef bint PY3 = (sys.version_info[0] >= 3) from cpython cimport ( PyTypeObject, PyFloat_Check, - PyComplex_Check, - PyObject_RichCompareBool, - PyObject_RichCompare, - Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE, - PyUnicode_Check) + PyComplex_Check) cdef extern from "Python.h": cdef PyTypeObject *Py_TYPE(object) from util cimport (is_integer_object, is_float_object, is_string_object, - is_datetime64_object, is_timedelta64_object, - INT64_MAX) + is_datetime64_object, is_timedelta64_object) cimport util -from cpython.datetime cimport (PyDelta_Check, PyTZInfo_Check, - PyDateTime_Check, PyDate_Check, +from cpython.datetime cimport (PyDateTime_Check, PyDate_Check, PyDateTime_IMPORT, timedelta, datetime) # import datetime C API @@ -38,13 +29,8 @@ PyDateTime_IMPORT # this is our datetime.pxd from datetime cimport _string_to_dts -# stdlib datetime imports -from datetime import time as datetime_time - from tslibs.np_datetime cimport (check_dts_bounds, - reverse_ops, - cmp_scalar, pandas_datetimestruct, dt64_to_dtstruct, dtstruct_to_dt64, pydatetime_to_dt64, pydate_to_dt64, @@ -67,38 +53,24 @@ UTC = pytz.utc import_array() -from tslibs.timedeltas cimport cast_from_unit, delta_to_nanoseconds +from tslibs.timedeltas cimport cast_from_unit from tslibs.timedeltas import Timedelta from tslibs.timezones cimport ( is_utc, is_tzlocal, is_fixed_offset, treat_tz_as_pytz, - get_timezone, maybe_get_tz, + get_timezone, get_dst_info) -from tslibs.fields import get_start_end_field, get_date_field from tslibs.conversion cimport (tz_convert_single, _TSObject, - convert_to_tsobject, convert_datetime_to_tsobject, get_datetime64_nanos) -from tslibs.conversion import (tz_localize_to_utc, - tz_convert_single, date_normalize) +from tslibs.conversion import tz_convert_single from tslibs.nattype import NaT, nat_strings, iNaT from tslibs.nattype cimport _checknull_with_nat, NPY_NAT - -cdef inline object create_timestamp_from_ts( - int64_t value, pandas_datetimestruct dts, - object tz, object freq): - """ convenience routine to construct a Timestamp from its parts """ - cdef _Timestamp ts_base - ts_base = _Timestamp.__new__(Timestamp, dts.year, dts.month, - dts.day, dts.hour, dts.min, - dts.sec, dts.us, tz) - ts_base.value = value - ts_base.freq = freq - ts_base.nanosecond = dts.ps / 1000 - - return ts_base +from tslibs.timestamps cimport (create_timestamp_from_ts, + _NS_UPPER_BOUND, _NS_LOWER_BOUND) +from tslibs.timestamps import Timestamp cdef inline object create_datetime_from_ts( @@ -210,625 +182,6 @@ def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): return result -_zero_time = datetime_time(0, 0) -_no_input = object() - -# Python front end to C extension type _Timestamp -# This serves as the box for datetime64 - - -class Timestamp(_Timestamp): - """Pandas replacement for datetime.datetime - - TimeStamp is the pandas equivalent of python's Datetime - and is interchangable with it in most cases. It's the type used - for the entries that make up a DatetimeIndex, and other timeseries - oriented data structures in pandas. - - Parameters - ---------- - ts_input : datetime-like, str, int, float - Value to be converted to Timestamp - freq : str, DateOffset - Offset which Timestamp will have - tz : string, pytz.timezone, dateutil.tz.tzfile or None - Time zone for time which Timestamp will have. - unit : string - numpy unit used for conversion, if ts_input is int or float - offset : str, DateOffset - Deprecated, use freq - - year, month, day : int - .. versionadded:: 0.19.0 - hour, minute, second, microsecond : int, optional, default 0 - .. versionadded:: 0.19.0 - tzinfo : datetime.tzinfo, optional, default None - .. versionadded:: 0.19.0 - - Notes - ----- - There are essentially three calling conventions for the constructor. The - primary form accepts four parameters. They can be passed by position or - keyword. - - The other two forms mimic the parameters from ``datetime.datetime``. They - can be passed by either position or keyword, but not both mixed together. - - Examples - -------- - >>> pd.Timestamp('2017-01-01T12') - Timestamp('2017-01-01 12:00:00') - - >>> pd.Timestamp(2017, 1, 1, 12) - Timestamp('2017-01-01 12:00:00') - - >>> pd.Timestamp(year=2017, month=1, day=1, hour=12) - Timestamp('2017-01-01 12:00:00') - """ - - @classmethod - def fromordinal(cls, ordinal, freq=None, tz=None, offset=None): - """ - Timestamp.fromordinal(ordinal, freq=None, tz=None, offset=None) - - passed an ordinal, translate and convert to a ts - note: by definition there cannot be any tz info on the ordinal itself - - Parameters - ---------- - ordinal : int - date corresponding to a proleptic Gregorian ordinal - freq : str, DateOffset - Offset which Timestamp will have - tz : string, pytz.timezone, dateutil.tz.tzfile or None - Time zone for time which Timestamp will have. - offset : str, DateOffset - Deprecated, use freq - """ - return cls(datetime.fromordinal(ordinal), - freq=freq, tz=tz, offset=offset) - - @classmethod - def now(cls, tz=None): - """ - Timestamp.now(tz=None) - - Returns new Timestamp object representing current time local to - tz. - - Parameters - ---------- - tz : string / timezone object, default None - Timezone to localize to - """ - if is_string_object(tz): - tz = maybe_get_tz(tz) - return cls(datetime.now(tz)) - - @classmethod - def today(cls, tz=None): - """ - Timestamp.today(cls, tz=None) - - Return the current time in the local timezone. This differs - from datetime.today() in that it can be localized to a - passed timezone. - - Parameters - ---------- - tz : string / timezone object, default None - Timezone to localize to - """ - return cls.now(tz) - - @classmethod - def utcnow(cls): - """ - Timestamp.utcnow() - - Return a new Timestamp representing UTC day and time. - """ - return cls.now('UTC') - - @classmethod - def utcfromtimestamp(cls, ts): - """ - Timestamp.utcfromtimestamp(ts) - - Construct a naive UTC datetime from a POSIX timestamp. - """ - return cls(datetime.utcfromtimestamp(ts)) - - @classmethod - def fromtimestamp(cls, ts): - """ - Timestamp.fromtimestamp(ts) - - timestamp[, tz] -> tz's local time from POSIX timestamp. - """ - return cls(datetime.fromtimestamp(ts)) - - @classmethod - def combine(cls, date, time): - """ - Timsetamp.combine(date, time) - - date, time -> datetime with same date and time fields - """ - return cls(datetime.combine(date, time)) - - def __new__(cls, object ts_input=_no_input, - object freq=None, tz=None, unit=None, - year=None, month=None, day=None, - hour=None, minute=None, second=None, microsecond=None, - tzinfo=None, - object offset=None): - # The parameter list folds together legacy parameter names (the first - # four) and positional and keyword parameter names from pydatetime. - # - # There are three calling forms: - # - # - In the legacy form, the first parameter, ts_input, is required - # and may be datetime-like, str, int, or float. The second - # parameter, offset, is optional and may be str or DateOffset. - # - # - ints in the first, second, and third arguments indicate - # pydatetime positional arguments. Only the first 8 arguments - # (standing in for year, month, day, hour, minute, second, - # microsecond, tzinfo) may be non-None. As a shortcut, we just - # check that the second argument is an int. - # - # - Nones for the first four (legacy) arguments indicate pydatetime - # keyword arguments. year, month, and day are required. As a - # shortcut, we just check that the first argument was not passed. - # - # Mixing pydatetime positional and keyword arguments is forbidden! - - cdef _TSObject ts - - if offset is not None: - # deprecate offset kwd in 0.19.0, GH13593 - if freq is not None: - msg = "Can only specify freq or offset, not both" - raise TypeError(msg) - warnings.warn("offset is deprecated. Use freq instead", - FutureWarning) - freq = offset - - if tzinfo is not None: - if not PyTZInfo_Check(tzinfo): - # tzinfo must be a datetime.tzinfo object, GH#17690 - raise TypeError('tzinfo must be a datetime.tzinfo object, ' - 'not %s' % type(tzinfo)) - elif tz is not None: - raise ValueError('Can provide at most one of tz, tzinfo') - - if ts_input is _no_input: - # User passed keyword arguments. - if tz is None: - # Handle the case where the user passes `tz` and not `tzinfo` - tz = tzinfo - return Timestamp(datetime(year, month, day, hour or 0, - minute or 0, second or 0, - microsecond or 0, tzinfo), - tz=tz) - elif is_integer_object(freq): - # User passed positional arguments: - # Timestamp(year, month, day[, hour[, minute[, second[, - # microsecond[, tzinfo]]]]]) - return Timestamp(datetime(ts_input, freq, tz, unit or 0, - year or 0, month or 0, day or 0, - hour), tz=hour) - - if tzinfo is not None: - # User passed tzinfo instead of tz; avoid silently ignoring - tz, tzinfo = tzinfo, None - - ts = convert_to_tsobject(ts_input, tz, unit, 0, 0) - - if ts.value == NPY_NAT: - 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) - - def _round(self, freq, rounder): - - cdef: - int64_t unit, r, value, buff = 1000000 - object result - - from pandas.tseries.frequencies import to_offset - unit = to_offset(freq).nanos - if self.tz is not None: - value = self.tz_localize(None).value - else: - value = self.value - if unit < 1000 and unit % 1000 != 0: - # for nano rounding, work with the last 6 digits separately - # due to float precision - r = (buff * (value // buff) + unit * - (rounder((value % buff) / float(unit))).astype('i8')) - elif unit >= 1000 and unit % 1000 != 0: - msg = 'Precision will be lost using frequency: {}' - warnings.warn(msg.format(freq)) - r = (unit * rounder(value / float(unit)).astype('i8')) - else: - r = (unit * rounder(value / float(unit)).astype('i8')) - result = Timestamp(r, unit='ns') - if self.tz is not None: - result = result.tz_localize(self.tz) - return result - - def round(self, freq): - """ - Round the Timestamp to the specified resolution - - Returns - ------- - a new Timestamp rounded to the given resolution of `freq` - - Parameters - ---------- - freq : a freq string indicating the rounding resolution - - Raises - ------ - ValueError if the freq cannot be converted - """ - return self._round(freq, np.round) - - def floor(self, freq): - """ - return a new Timestamp floored to this resolution - - Parameters - ---------- - freq : a freq string indicating the flooring resolution - """ - return self._round(freq, np.floor) - - def ceil(self, freq): - """ - return a new Timestamp ceiled to this resolution - - Parameters - ---------- - freq : a freq string indicating the ceiling resolution - """ - return self._round(freq, np.ceil) - - @property - def tz(self): - """ - Alias for tzinfo - """ - return self.tzinfo - - @property - def offset(self): - warnings.warn(".offset is deprecated. Use .freq instead", - FutureWarning) - return self.freq - - def __setstate__(self, state): - self.value = state[0] - self.freq = state[1] - self.tzinfo = state[2] - - def __reduce__(self): - object_state = self.value, self.freq, self.tzinfo - return (Timestamp, object_state) - - def to_period(self, freq=None): - """ - Return an period of which this timestamp is an observation. - """ - from pandas import Period - - if freq is None: - freq = self.freq - - return Period(self, freq=freq) - - @property - def dayofweek(self): - return self.weekday() - - @property - def weekday_name(self): - cdef dict wdays = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', - 3: 'Thursday', 4: 'Friday', 5: 'Saturday', - 6: 'Sunday'} - return wdays[self.weekday()] - - @property - def dayofyear(self): - return self._get_field('doy') - - @property - def week(self): - return self._get_field('woy') - - weekofyear = week - - @property - def quarter(self): - return self._get_field('q') - - @property - def days_in_month(self): - return self._get_field('dim') - - daysinmonth = days_in_month - - @property - def freqstr(self): - return getattr(self.freq, 'freqstr', self.freq) - - @property - def is_month_start(self): - return self._get_start_end_field('is_month_start') - - @property - def is_month_end(self): - return self._get_start_end_field('is_month_end') - - @property - def is_quarter_start(self): - return self._get_start_end_field('is_quarter_start') - - @property - def is_quarter_end(self): - return self._get_start_end_field('is_quarter_end') - - @property - def is_year_start(self): - return self._get_start_end_field('is_year_start') - - @property - def is_year_end(self): - return self._get_start_end_field('is_year_end') - - @property - def is_leap_year(self): - return bool(is_leapyear(self.year)) - - def tz_localize(self, tz, ambiguous='raise', errors='raise'): - """ - Convert naive Timestamp to local time zone, or remove - timezone from tz-aware Timestamp. - - Parameters - ---------- - tz : string, pytz.timezone, dateutil.tz.tzfile or None - Time zone for time which Timestamp will be converted to. - None will remove timezone holding local time. - - ambiguous : bool, 'NaT', default 'raise' - - bool contains flags to determine if time is dst or not (note - that this flag is only applicable for ambiguous fall dst dates) - - 'NaT' will return NaT for an ambiguous time - - 'raise' will raise an AmbiguousTimeError for an ambiguous time - - errors : 'raise', 'coerce', default 'raise' - - 'raise' will raise a NonExistentTimeError if a timestamp is not - valid in the specified timezone (e.g. due to a transition from - or to DST time) - - 'coerce' will return NaT if the timestamp can not be converted - into the specified timezone - - .. versionadded:: 0.19.0 - - Returns - ------- - localized : Timestamp - - Raises - ------ - TypeError - If the Timestamp is tz-aware and tz is not None. - """ - if ambiguous == 'infer': - raise ValueError('Cannot infer offset with only one time.') - - if self.tzinfo is None: - # tz naive, localize - tz = maybe_get_tz(tz) - if not is_string_object(ambiguous): - ambiguous = [ambiguous] - value = tz_localize_to_utc(np.array([self.value], dtype='i8'), tz, - ambiguous=ambiguous, errors=errors)[0] - return Timestamp(value, tz=tz) - else: - if tz is None: - # reset tz - value = tz_convert_single(self.value, 'UTC', self.tz) - return Timestamp(value, tz=None) - else: - raise TypeError('Cannot localize tz-aware Timestamp, use ' - 'tz_convert for conversions') - - def tz_convert(self, tz): - """ - Convert tz-aware Timestamp to another time zone. - - Parameters - ---------- - tz : string, pytz.timezone, dateutil.tz.tzfile or None - Time zone for time which Timestamp will be converted to. - None will remove timezone holding UTC time. - - Returns - ------- - converted : Timestamp - - Raises - ------ - TypeError - If Timestamp is tz-naive. - """ - if self.tzinfo is None: - # tz naive, use tz_localize - raise TypeError('Cannot convert tz-naive Timestamp, use ' - 'tz_localize to localize') - else: - # Same UTC timestamp, different time zone - return Timestamp(self.value, tz=tz) - - astimezone = tz_convert - - def replace(self, year=None, month=None, day=None, - hour=None, minute=None, second=None, microsecond=None, - nanosecond=None, tzinfo=object, fold=0): - """ - implements datetime.replace, handles nanoseconds - - Parameters - ---------- - year : int, optional - month : int, optional - day : int, optional - hour : int, optional - minute : int, optional - second : int, optional - microsecond : int, optional - nanosecond: int, optional - tzinfo : tz-convertible, optional - fold : int, optional, default is 0 - added in 3.6, NotImplemented - - Returns - ------- - Timestamp with fields replaced - """ - - cdef: - pandas_datetimestruct dts - int64_t value, value_tz, offset - object _tzinfo, result, k, v - datetime ts_input - - # set to naive if needed - _tzinfo = self.tzinfo - value = self.value - if _tzinfo is not None: - value_tz = tz_convert_single(value, _tzinfo, 'UTC') - value += value - value_tz - - # setup components - dt64_to_dtstruct(value, &dts) - dts.ps = self.nanosecond * 1000 - - # replace - def validate(k, v): - """ validate integers """ - if not is_integer_object(v): - raise ValueError("value must be an integer, received " - "{v} for {k}".format(v=type(v), k=k)) - return v - - if year is not None: - dts.year = validate('year', year) - if month is not None: - dts.month = validate('month', month) - if day is not None: - dts.day = validate('day', day) - if hour is not None: - dts.hour = validate('hour', hour) - if minute is not None: - dts.min = validate('minute', minute) - if second is not None: - dts.sec = validate('second', second) - if microsecond is not None: - dts.us = validate('microsecond', microsecond) - if nanosecond is not None: - dts.ps = validate('nanosecond', nanosecond) * 1000 - if tzinfo is not object: - _tzinfo = tzinfo - - # reconstruct & check bounds - ts_input = datetime(dts.year, dts.month, dts.day, dts.hour, dts.min, - dts.sec, dts.us, tzinfo=_tzinfo) - ts = convert_datetime_to_tsobject(ts_input, _tzinfo) - value = ts.value + (dts.ps // 1000) - if value != NPY_NAT: - check_dts_bounds(&dts) - - return create_timestamp_from_ts(value, dts, _tzinfo, self.freq) - - def isoformat(self, sep='T'): - base = super(_Timestamp, self).isoformat(sep=sep) - if self.nanosecond == 0: - return base - - if self.tzinfo is not None: - base1, base2 = base[:-6], base[-6:] - else: - base1, base2 = base, "" - - if self.microsecond != 0: - base1 += "%.3d" % self.nanosecond - else: - base1 += ".%.9d" % self.nanosecond - - return base1 + base2 - - def _has_time_component(self): - """ - Returns if the Timestamp has a time component - in addition to the date part - """ - return (self.time() != _zero_time - or self.tzinfo is not None - or self.nanosecond != 0) - - def to_julian_date(self): - """ - Convert TimeStamp to a Julian Date. - 0 Julian date is noon January 1, 4713 BC. - """ - year = self.year - month = self.month - day = self.day - if month <= 2: - year -= 1 - month += 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) - - def normalize(self): - """ - Normalize Timestamp to midnight, preserving - tz information. - """ - normalized_value = date_normalize( - np.array([self.value], dtype='i8'), tz=self.tz)[0] - return Timestamp(normalized_value).tz_localize(self.tz) - - def __radd__(self, other): - # __radd__ on cython extension types like _Timestamp is not used, so - # define it here instead - return self + other - - -# ---------------------------------------------------------------------- - - cdef inline bint _check_all_nulls(object val): """ utility to check if a value is any type of null """ cdef bint res @@ -847,331 +200,6 @@ cdef inline bint _check_all_nulls(object val): return res -# Add the min and max fields at the class level -cdef int64_t _NS_UPPER_BOUND = INT64_MAX -# the smallest value we could actually represent is -# INT64_MIN + 1 == -9223372036854775807 -# but to allow overflow free conversion with a microsecond resolution -# use the smallest value with a 0 nanosecond unit (0s in last 3 digits) -cdef int64_t _NS_LOWER_BOUND = -9223372036854775000 - -# Resolution is in nanoseconds -Timestamp.min = Timestamp(_NS_LOWER_BOUND) -Timestamp.max = Timestamp(_NS_UPPER_BOUND) - - -cdef str _NDIM_STRING = "ndim" - -# This is PITA. Because we inherit from datetime, which has very specific -# construction requirements, we need to do object instantiation in python -# (see Timestamp class above). This will serve as a C extension type that -# shadows the python class, where we do any heavy lifting. -cdef class _Timestamp(datetime): - - cdef readonly: - int64_t value, nanosecond - object freq # frequency reference - - def __hash__(_Timestamp self): - if self.nanosecond: - return hash(self.value) - return datetime.__hash__(self) - - def __richcmp__(_Timestamp self, object other, int op): - cdef: - _Timestamp ots - int ndim - - if isinstance(other, _Timestamp): - ots = other - elif other is NaT: - return op == Py_NE - elif PyDateTime_Check(other): - if self.nanosecond == 0: - val = self.to_pydatetime() - return PyObject_RichCompareBool(val, other, op) - - try: - ots = Timestamp(other) - except ValueError: - return self._compare_outside_nanorange(other, op) - else: - ndim = getattr(other, _NDIM_STRING, -1) - - if ndim != -1: - if ndim == 0: - if is_datetime64_object(other): - other = Timestamp(other) - else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - - # only allow ==, != ops - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, - type(other).__name__)) - return PyObject_RichCompare(other, self, reverse_ops[op]) - else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - raise TypeError('Cannot compare type %r with type %r' % - (type(self).__name__, type(other).__name__)) - - self._assert_tzawareness_compat(other) - return cmp_scalar(self.value, ots.value, op) - - def __reduce_ex__(self, protocol): - # python 3.6 compat - # http://bugs.python.org/issue28730 - # now __reduce_ex__ is defined and higher priority than __reduce__ - return self.__reduce__() - - def __repr__(self): - stamp = self._repr_base - zone = None - - try: - stamp += self.strftime('%z') - if self.tzinfo: - zone = get_timezone(self.tzinfo) - except ValueError: - year2000 = self.replace(year=2000) - stamp += year2000.strftime('%z') - if self.tzinfo: - zone = get_timezone(self.tzinfo) - - try: - stamp += zone.strftime(' %%Z') - except: - pass - - tz = ", tz='{0}'".format(zone) if zone is not None else "" - freq = "" if self.freq is None else ", freq='{0}'".format(self.freqstr) - - return "Timestamp('{stamp}'{tz}{freq})".format(stamp=stamp, - tz=tz, freq=freq) - - cdef bint _compare_outside_nanorange(_Timestamp self, datetime other, - int op) except -1: - cdef datetime dtval = self.to_pydatetime() - - self._assert_tzawareness_compat(other) - - if self.nanosecond == 0: - return PyObject_RichCompareBool(dtval, other, op) - else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - elif op == Py_LT: - return dtval < other - elif op == Py_LE: - return dtval < other - elif op == Py_GT: - return dtval >= other - elif op == Py_GE: - return dtval >= other - - cdef int _assert_tzawareness_compat(_Timestamp self, - object other) except -1: - if self.tzinfo is None: - if other.tzinfo is not None: - raise TypeError('Cannot compare tz-naive and tz-aware ' - 'timestamps') - elif other.tzinfo is None: - raise TypeError('Cannot compare tz-naive and tz-aware timestamps') - - cpdef datetime to_datetime(_Timestamp self): - """ - DEPRECATED: use :meth:`to_pydatetime` instead. - - Convert a Timestamp object to a native Python datetime object. - """ - warnings.warn("to_datetime is deprecated. Use self.to_pydatetime()", - FutureWarning, stacklevel=2) - return self.to_pydatetime(warn=False) - - cpdef datetime to_pydatetime(_Timestamp self, warn=True): - """ - Convert a Timestamp object to a native Python datetime object. - - If warn=True, issue a warning if nanoseconds is nonzero. - """ - if self.nanosecond != 0 and warn: - warnings.warn("Discarding nonzero nanoseconds in conversion", - UserWarning, stacklevel=2) - - return datetime(self.year, self.month, self.day, - self.hour, self.minute, self.second, - self.microsecond, self.tzinfo) - - cpdef to_datetime64(self): - """ Returns a numpy.datetime64 object with 'ns' precision """ - return np.datetime64(self.value, 'ns') - - def __add__(self, other): - cdef int64_t other_int, nanos - - if is_timedelta64_object(other): - other_int = other.astype('timedelta64[ns]').view('i8') - return Timestamp(self.value + other_int, - tz=self.tzinfo, freq=self.freq) - - elif is_integer_object(other): - if self is NaT: - # to be compat with Period - return NaT - elif self.freq is None: - raise ValueError("Cannot add integral value to Timestamp " - "without freq.") - return Timestamp((self.freq * other).apply(self), freq=self.freq) - - elif PyDelta_Check(other) or hasattr(other, 'delta'): - # delta --> offsets.Tick - nanos = delta_to_nanoseconds(other) - result = Timestamp(self.value + nanos, - tz=self.tzinfo, freq=self.freq) - if getattr(other, 'normalize', False): - # DateOffset - result = result.normalize() - return result - - # index/series like - elif hasattr(other, '_typ'): - return NotImplemented - - result = datetime.__add__(self, other) - if PyDateTime_Check(result): - result = Timestamp(result) - result.nanosecond = self.nanosecond - return result - - def __sub__(self, other): - if (is_timedelta64_object(other) or is_integer_object(other) or - PyDelta_Check(other) or hasattr(other, 'delta')): - # `delta` attribute is for offsets.Tick or offsets.Week obj - neg_other = -other - return self + neg_other - - # a Timestamp-DatetimeIndex -> yields a negative TimedeltaIndex - elif getattr(other, '_typ', None) == 'datetimeindex': - # timezone comparison is performed in DatetimeIndex._sub_datelike - return -other.__sub__(self) - - # a Timestamp-TimedeltaIndex -> yields a negative TimedeltaIndex - elif getattr(other, '_typ', None) == 'timedeltaindex': - return (-other).__add__(self) - - elif other is NaT: - return NaT - - # coerce if necessary if we are a Timestamp-like - if (PyDateTime_Check(self) - and (PyDateTime_Check(other) or is_datetime64_object(other))): - self = Timestamp(self) - other = Timestamp(other) - - # validate tz's - if get_timezone(self.tzinfo) != get_timezone(other.tzinfo): - raise TypeError("Timestamp subtraction must have the " - "same timezones or no timezones") - - # scalar Timestamp/datetime - Timestamp/datetime -> yields a - # Timedelta - try: - return Timedelta(self.value - other.value) - except (OverflowError, OutOfBoundsDatetime): - pass - - # scalar Timestamp/datetime - Timedelta -> yields a Timestamp (with - # same timezone if specified) - return datetime.__sub__(self, other) - - cdef int64_t _maybe_convert_value_to_local(self): - """Convert UTC i8 value to local i8 value if tz exists""" - cdef: - int64_t val - val = self.value - if self.tz is not None and not is_utc(self.tz): - val = tz_convert_single(self.value, 'UTC', self.tz) - return val - - cpdef int _get_field(self, field): - cdef: - int64_t val - ndarray[int32_t] out - val = self._maybe_convert_value_to_local() - out = get_date_field(np.array([val], dtype=np.int64), field) - return int(out[0]) - - cpdef _get_start_end_field(self, field): - cdef: - int64_t val - dict kwds - - freq = self.freq - if freq: - kwds = freq.kwds - month_kw = kwds.get('startingMonth', kwds.get('month', 12)) - freqstr = self.freqstr - else: - month_kw = 12 - freqstr = None - - val = self._maybe_convert_value_to_local() - out = get_start_end_field(np.array([val], dtype=np.int64), - field, freqstr, month_kw) - return out[0] - - @property - def _repr_base(self): - return '{date} {time}'.format(date=self._date_repr, - time=self._time_repr) - - @property - def _date_repr(self): - # Ideal here would be self.strftime("%Y-%m-%d"), but - # the datetime strftime() methods require year >= 1900 - return '%d-%.2d-%.2d' % (self.year, self.month, self.day) - - @property - def _time_repr(self): - result = '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) - - if self.nanosecond != 0: - result += '.%.9d' % (self.nanosecond + 1000 * self.microsecond) - elif self.microsecond != 0: - result += '.%.6d' % self.microsecond - - return result - - @property - def _short_repr(self): - # format a Timestamp with only _date_repr if possible - # otherwise _repr_base - if (self.hour == 0 and - self.minute == 0 and - self.second == 0 and - self.microsecond == 0 and - self.nanosecond == 0): - return self._date_repr - return self._repr_base - - @property - def asm8(self): - return np.datetime64(self.value, 'ns') - - def timestamp(self): - """Return POSIX timestamp as float.""" - # py27 compat, see GH#17329 - return round(self.value / 1e9, 6) - - cdef PyTypeObject* ts_type = <PyTypeObject*> Timestamp diff --git a/pandas/_libs/tslibs/timestamps.pxd b/pandas/_libs/tslibs/timestamps.pxd new file mode 100644 index 0000000000000..8e7380b37209e --- /dev/null +++ b/pandas/_libs/tslibs/timestamps.pxd @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# cython: profile=False + +from numpy cimport int64_t +from np_datetime cimport pandas_datetimestruct + +cdef object create_timestamp_from_ts(int64_t value, + pandas_datetimestruct dts, + object tz, object freq) + +cdef int64_t _NS_UPPER_BOUND, _NS_LOWER_BOUND diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx new file mode 100644 index 0000000000000..8fdded0bcb07a --- /dev/null +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -0,0 +1,995 @@ +# -*- coding: utf-8 -*- +# cython: profile=False +import warnings + +from cpython cimport (PyObject_RichCompareBool, PyObject_RichCompare, + Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE) + +import numpy as np +cimport numpy as np +from numpy cimport int64_t, int32_t, ndarray +np.import_array() + +from datetime import time as datetime_time +from cpython.datetime cimport (datetime, + PyDateTime_Check, PyDelta_Check, PyTZInfo_Check, + PyDateTime_IMPORT) +PyDateTime_IMPORT + +from util cimport (is_datetime64_object, is_timedelta64_object, + is_integer_object, is_string_object, + INT64_MAX) + +from conversion import tz_localize_to_utc, date_normalize +from conversion cimport (tz_convert_single, _TSObject, + convert_to_tsobject, convert_datetime_to_tsobject) +from fields import get_date_field, get_start_end_field +from nattype import NaT +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, + is_leapyear) +from timedeltas import Timedelta +from timedeltas cimport delta_to_nanoseconds +from timezones cimport get_timezone, is_utc, maybe_get_tz + +# ---------------------------------------------------------------------- +# Constants +_zero_time = datetime_time(0, 0) +_no_input = object() + +# ---------------------------------------------------------------------- + + +cdef inline object create_timestamp_from_ts(int64_t value, + pandas_datetimestruct dts, + object tz, object freq): + """ convenience routine to construct a Timestamp from its parts """ + cdef _Timestamp ts_base + ts_base = _Timestamp.__new__(Timestamp, dts.year, dts.month, + dts.day, dts.hour, dts.min, + dts.sec, dts.us, tz) + ts_base.value = value + ts_base.freq = freq + ts_base.nanosecond = dts.ps / 1000 + + return ts_base + + +# This is PITA. Because we inherit from datetime, which has very specific +# construction requirements, we need to do object instantiation in python +# (see Timestamp class above). This will serve as a C extension type that +# shadows the python class, where we do any heavy lifting. +cdef class _Timestamp(datetime): + + cdef readonly: + int64_t value, nanosecond + object freq # frequency reference + + def __hash__(_Timestamp self): + if self.nanosecond: + return hash(self.value) + return datetime.__hash__(self) + + def __richcmp__(_Timestamp self, object other, int op): + cdef: + _Timestamp ots + int ndim + + if isinstance(other, _Timestamp): + ots = other + elif other is NaT: + return op == Py_NE + elif PyDateTime_Check(other): + if self.nanosecond == 0: + val = self.to_pydatetime() + return PyObject_RichCompareBool(val, other, op) + + try: + ots = Timestamp(other) + except ValueError: + return self._compare_outside_nanorange(other, op) + else: + ndim = getattr(other, "ndim", -1) + + if ndim != -1: + if ndim == 0: + if is_datetime64_object(other): + other = Timestamp(other) + else: + if op == Py_EQ: + return False + elif op == Py_NE: + return True + + # only allow ==, != ops + raise TypeError('Cannot compare type %r with type %r' % + (type(self).__name__, + type(other).__name__)) + return PyObject_RichCompare(other, self, reverse_ops[op]) + else: + if op == Py_EQ: + return False + elif op == Py_NE: + return True + raise TypeError('Cannot compare type %r with type %r' % + (type(self).__name__, type(other).__name__)) + + self._assert_tzawareness_compat(other) + return cmp_scalar(self.value, ots.value, op) + + def __reduce_ex__(self, protocol): + # python 3.6 compat + # http://bugs.python.org/issue28730 + # now __reduce_ex__ is defined and higher priority than __reduce__ + return self.__reduce__() + + def __repr__(self): + stamp = self._repr_base + zone = None + + try: + stamp += self.strftime('%z') + if self.tzinfo: + zone = get_timezone(self.tzinfo) + except ValueError: + year2000 = self.replace(year=2000) + stamp += year2000.strftime('%z') + if self.tzinfo: + zone = get_timezone(self.tzinfo) + + try: + stamp += zone.strftime(' %%Z') + except: + pass + + tz = ", tz='{0}'".format(zone) if zone is not None else "" + freq = "" if self.freq is None else ", freq='{0}'".format(self.freqstr) + + return "Timestamp('{stamp}'{tz}{freq})".format(stamp=stamp, + tz=tz, freq=freq) + + cdef bint _compare_outside_nanorange(_Timestamp self, datetime other, + int op) except -1: + cdef datetime dtval = self.to_pydatetime() + + self._assert_tzawareness_compat(other) + + if self.nanosecond == 0: + return PyObject_RichCompareBool(dtval, other, op) + else: + if op == Py_EQ: + return False + elif op == Py_NE: + return True + elif op == Py_LT: + return dtval < other + elif op == Py_LE: + return dtval < other + elif op == Py_GT: + return dtval >= other + elif op == Py_GE: + return dtval >= other + + cdef int _assert_tzawareness_compat(_Timestamp self, + object other) except -1: + if self.tzinfo is None: + if other.tzinfo is not None: + raise TypeError('Cannot compare tz-naive and tz-aware ' + 'timestamps') + elif other.tzinfo is None: + raise TypeError('Cannot compare tz-naive and tz-aware timestamps') + + cpdef datetime to_datetime(_Timestamp self): + """ + DEPRECATED: use :meth:`to_pydatetime` instead. + + Convert a Timestamp object to a native Python datetime object. + """ + warnings.warn("to_datetime is deprecated. Use self.to_pydatetime()", + FutureWarning, stacklevel=2) + return self.to_pydatetime(warn=False) + + cpdef datetime to_pydatetime(_Timestamp self, warn=True): + """ + Convert a Timestamp object to a native Python datetime object. + + If warn=True, issue a warning if nanoseconds is nonzero. + """ + if self.nanosecond != 0 and warn: + warnings.warn("Discarding nonzero nanoseconds in conversion", + UserWarning, stacklevel=2) + + return datetime(self.year, self.month, self.day, + self.hour, self.minute, self.second, + self.microsecond, self.tzinfo) + + cpdef to_datetime64(self): + """ Returns a numpy.datetime64 object with 'ns' precision """ + return np.datetime64(self.value, 'ns') + + def __add__(self, other): + cdef int64_t other_int, nanos + + if is_timedelta64_object(other): + other_int = other.astype('timedelta64[ns]').view('i8') + return Timestamp(self.value + other_int, + tz=self.tzinfo, freq=self.freq) + + elif is_integer_object(other): + if self is NaT: + # to be compat with Period + return NaT + elif self.freq is None: + raise ValueError("Cannot add integral value to Timestamp " + "without freq.") + return Timestamp((self.freq * other).apply(self), freq=self.freq) + + elif PyDelta_Check(other) or hasattr(other, 'delta'): + # delta --> offsets.Tick + nanos = delta_to_nanoseconds(other) + result = Timestamp(self.value + nanos, + tz=self.tzinfo, freq=self.freq) + if getattr(other, 'normalize', False): + # DateOffset + result = result.normalize() + return result + + # index/series like + elif hasattr(other, '_typ'): + return NotImplemented + + result = datetime.__add__(self, other) + if PyDateTime_Check(result): + result = Timestamp(result) + result.nanosecond = self.nanosecond + return result + + def __sub__(self, other): + if (is_timedelta64_object(other) or is_integer_object(other) or + PyDelta_Check(other) or hasattr(other, 'delta')): + # `delta` attribute is for offsets.Tick or offsets.Week obj + neg_other = -other + return self + neg_other + + # a Timestamp-DatetimeIndex -> yields a negative TimedeltaIndex + elif getattr(other, '_typ', None) == 'datetimeindex': + # timezone comparison is performed in DatetimeIndex._sub_datelike + return -other.__sub__(self) + + # a Timestamp-TimedeltaIndex -> yields a negative TimedeltaIndex + elif getattr(other, '_typ', None) == 'timedeltaindex': + return (-other).__add__(self) + + elif other is NaT: + return NaT + + # coerce if necessary if we are a Timestamp-like + if (PyDateTime_Check(self) + and (PyDateTime_Check(other) or is_datetime64_object(other))): + self = Timestamp(self) + other = Timestamp(other) + + # validate tz's + if get_timezone(self.tzinfo) != get_timezone(other.tzinfo): + raise TypeError("Timestamp subtraction must have the " + "same timezones or no timezones") + + # scalar Timestamp/datetime - Timestamp/datetime -> yields a + # Timedelta + try: + return Timedelta(self.value - other.value) + except (OverflowError, OutOfBoundsDatetime): + pass + + # scalar Timestamp/datetime - Timedelta -> yields a Timestamp (with + # same timezone if specified) + return datetime.__sub__(self, other) + + cdef int64_t _maybe_convert_value_to_local(self): + """Convert UTC i8 value to local i8 value if tz exists""" + cdef: + int64_t val + val = self.value + if self.tz is not None and not is_utc(self.tz): + val = tz_convert_single(self.value, 'UTC', self.tz) + return val + + cpdef int _get_field(self, field): + cdef: + int64_t val + ndarray[int32_t] out + val = self._maybe_convert_value_to_local() + out = get_date_field(np.array([val], dtype=np.int64), field) + return int(out[0]) + + cpdef _get_start_end_field(self, field): + cdef: + int64_t val + dict kwds + + freq = self.freq + if freq: + kwds = freq.kwds + month_kw = kwds.get('startingMonth', kwds.get('month', 12)) + freqstr = self.freqstr + else: + month_kw = 12 + freqstr = None + + val = self._maybe_convert_value_to_local() + out = get_start_end_field(np.array([val], dtype=np.int64), + field, freqstr, month_kw) + return out[0] + + @property + def _repr_base(self): + return '{date} {time}'.format(date=self._date_repr, + time=self._time_repr) + + @property + def _date_repr(self): + # Ideal here would be self.strftime("%Y-%m-%d"), but + # the datetime strftime() methods require year >= 1900 + return '%d-%.2d-%.2d' % (self.year, self.month, self.day) + + @property + def _time_repr(self): + result = '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) + + if self.nanosecond != 0: + result += '.%.9d' % (self.nanosecond + 1000 * self.microsecond) + elif self.microsecond != 0: + result += '.%.6d' % self.microsecond + + return result + + @property + def _short_repr(self): + # format a Timestamp with only _date_repr if possible + # otherwise _repr_base + if (self.hour == 0 and + self.minute == 0 and + self.second == 0 and + self.microsecond == 0 and + self.nanosecond == 0): + return self._date_repr + return self._repr_base + + @property + def asm8(self): + return np.datetime64(self.value, 'ns') + + def timestamp(self): + """Return POSIX timestamp as float.""" + # py27 compat, see GH#17329 + return round(self.value / 1e9, 6) + + +# ---------------------------------------------------------------------- + +# Python front end to C extension type _Timestamp +# This serves as the box for datetime64 + + +class Timestamp(_Timestamp): + """Pandas replacement for datetime.datetime + + TimeStamp is the pandas equivalent of python's Datetime + and is interchangable with it in most cases. It's the type used + for the entries that make up a DatetimeIndex, and other timeseries + oriented data structures in pandas. + + Parameters + ---------- + ts_input : datetime-like, str, int, float + Value to be converted to Timestamp + freq : str, DateOffset + Offset which Timestamp will have + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time which Timestamp will have. + unit : string + numpy unit used for conversion, if ts_input is int or float + offset : str, DateOffset + Deprecated, use freq + + year, month, day : int + .. versionadded:: 0.19.0 + hour, minute, second, microsecond : int, optional, default 0 + .. versionadded:: 0.19.0 + tzinfo : datetime.tzinfo, optional, default None + .. versionadded:: 0.19.0 + + Notes + ----- + There are essentially three calling conventions for the constructor. The + primary form accepts four parameters. They can be passed by position or + keyword. + + The other two forms mimic the parameters from ``datetime.datetime``. They + can be passed by either position or keyword, but not both mixed together. + + Examples + -------- + >>> pd.Timestamp('2017-01-01T12') + Timestamp('2017-01-01 12:00:00') + + >>> pd.Timestamp(2017, 1, 1, 12) + Timestamp('2017-01-01 12:00:00') + + >>> pd.Timestamp(year=2017, month=1, day=1, hour=12) + Timestamp('2017-01-01 12:00:00') + """ + + @classmethod + def fromordinal(cls, ordinal, freq=None, tz=None, offset=None): + """ + Timestamp.fromordinal(ordinal, freq=None, tz=None, offset=None) + + passed an ordinal, translate and convert to a ts + note: by definition there cannot be any tz info on the ordinal itself + + Parameters + ---------- + ordinal : int + date corresponding to a proleptic Gregorian ordinal + freq : str, DateOffset + Offset which Timestamp will have + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time which Timestamp will have. + offset : str, DateOffset + Deprecated, use freq + """ + return cls(datetime.fromordinal(ordinal), + freq=freq, tz=tz, offset=offset) + + @classmethod + def now(cls, tz=None): + """ + Timestamp.now(tz=None) + + Returns new Timestamp object representing current time local to + tz. + + Parameters + ---------- + tz : string / timezone object, default None + Timezone to localize to + """ + if is_string_object(tz): + tz = maybe_get_tz(tz) + return cls(datetime.now(tz)) + + @classmethod + def today(cls, tz=None): + """ + Timestamp.today(cls, tz=None) + + Return the current time in the local timezone. This differs + from datetime.today() in that it can be localized to a + passed timezone. + + Parameters + ---------- + tz : string / timezone object, default None + Timezone to localize to + """ + return cls.now(tz) + + @classmethod + def utcnow(cls): + """ + Timestamp.utcnow() + + Return a new Timestamp representing UTC day and time. + """ + return cls.now('UTC') + + @classmethod + def utcfromtimestamp(cls, ts): + """ + Timestamp.utcfromtimestamp(ts) + + Construct a naive UTC datetime from a POSIX timestamp. + """ + return cls(datetime.utcfromtimestamp(ts)) + + @classmethod + def fromtimestamp(cls, ts): + """ + Timestamp.fromtimestamp(ts) + + timestamp[, tz] -> tz's local time from POSIX timestamp. + """ + return cls(datetime.fromtimestamp(ts)) + + @classmethod + def combine(cls, date, time): + """ + Timsetamp.combine(date, time) + + date, time -> datetime with same date and time fields + """ + return cls(datetime.combine(date, time)) + + def __new__(cls, object ts_input=_no_input, + object freq=None, tz=None, unit=None, + year=None, month=None, day=None, + hour=None, minute=None, second=None, microsecond=None, + tzinfo=None, + object offset=None): + # The parameter list folds together legacy parameter names (the first + # four) and positional and keyword parameter names from pydatetime. + # + # There are three calling forms: + # + # - In the legacy form, the first parameter, ts_input, is required + # and may be datetime-like, str, int, or float. The second + # parameter, offset, is optional and may be str or DateOffset. + # + # - ints in the first, second, and third arguments indicate + # pydatetime positional arguments. Only the first 8 arguments + # (standing in for year, month, day, hour, minute, second, + # microsecond, tzinfo) may be non-None. As a shortcut, we just + # check that the second argument is an int. + # + # - Nones for the first four (legacy) arguments indicate pydatetime + # keyword arguments. year, month, and day are required. As a + # shortcut, we just check that the first argument was not passed. + # + # Mixing pydatetime positional and keyword arguments is forbidden! + + cdef _TSObject ts + + if offset is not None: + # deprecate offset kwd in 0.19.0, GH13593 + if freq is not None: + msg = "Can only specify freq or offset, not both" + raise TypeError(msg) + warnings.warn("offset is deprecated. Use freq instead", + FutureWarning) + freq = offset + + if tzinfo is not None: + if not PyTZInfo_Check(tzinfo): + # tzinfo must be a datetime.tzinfo object, GH#17690 + raise TypeError('tzinfo must be a datetime.tzinfo object, ' + 'not %s' % type(tzinfo)) + elif tz is not None: + raise ValueError('Can provide at most one of tz, tzinfo') + + if ts_input is _no_input: + # User passed keyword arguments. + if tz is None: + # Handle the case where the user passes `tz` and not `tzinfo` + tz = tzinfo + return Timestamp(datetime(year, month, day, hour or 0, + minute or 0, second or 0, + microsecond or 0, tzinfo), + tz=tz) + elif is_integer_object(freq): + # User passed positional arguments: + # Timestamp(year, month, day[, hour[, minute[, second[, + # microsecond[, tzinfo]]]]]) + return Timestamp(datetime(ts_input, freq, tz, unit or 0, + year or 0, month or 0, day or 0, + hour), tz=hour) + + if tzinfo is not None: + # User passed tzinfo instead of tz; avoid silently ignoring + tz, tzinfo = tzinfo, None + + ts = convert_to_tsobject(ts_input, tz, unit, 0, 0) + + if ts.value == NPY_NAT: + 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) + + def _round(self, freq, rounder): + + cdef: + int64_t unit, r, value, buff = 1000000 + object result + + from pandas.tseries.frequencies import to_offset + unit = to_offset(freq).nanos + if self.tz is not None: + value = self.tz_localize(None).value + else: + value = self.value + if unit < 1000 and unit % 1000 != 0: + # for nano rounding, work with the last 6 digits separately + # due to float precision + r = (buff * (value // buff) + unit * + (rounder((value % buff) / float(unit))).astype('i8')) + elif unit >= 1000 and unit % 1000 != 0: + msg = 'Precision will be lost using frequency: {}' + warnings.warn(msg.format(freq)) + r = (unit * rounder(value / float(unit)).astype('i8')) + else: + r = (unit * rounder(value / float(unit)).astype('i8')) + result = Timestamp(r, unit='ns') + if self.tz is not None: + result = result.tz_localize(self.tz) + return result + + def round(self, freq): + """ + Round the Timestamp to the specified resolution + + Returns + ------- + a new Timestamp rounded to the given resolution of `freq` + + Parameters + ---------- + freq : a freq string indicating the rounding resolution + + Raises + ------ + ValueError if the freq cannot be converted + """ + return self._round(freq, np.round) + + def floor(self, freq): + """ + return a new Timestamp floored to this resolution + + Parameters + ---------- + freq : a freq string indicating the flooring resolution + """ + return self._round(freq, np.floor) + + def ceil(self, freq): + """ + return a new Timestamp ceiled to this resolution + + Parameters + ---------- + freq : a freq string indicating the ceiling resolution + """ + return self._round(freq, np.ceil) + + @property + def tz(self): + """ + Alias for tzinfo + """ + return self.tzinfo + + @property + def offset(self): + warnings.warn(".offset is deprecated. Use .freq instead", + FutureWarning) + return self.freq + + def __setstate__(self, state): + self.value = state[0] + self.freq = state[1] + self.tzinfo = state[2] + + def __reduce__(self): + object_state = self.value, self.freq, self.tzinfo + return (Timestamp, object_state) + + def to_period(self, freq=None): + """ + Return an period of which this timestamp is an observation. + """ + from pandas import Period + + if freq is None: + freq = self.freq + + return Period(self, freq=freq) + + @property + def dayofweek(self): + return self.weekday() + + @property + def weekday_name(self): + cdef dict wdays = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', + 3: 'Thursday', 4: 'Friday', 5: 'Saturday', + 6: 'Sunday'} + return wdays[self.weekday()] + + @property + def dayofyear(self): + return self._get_field('doy') + + @property + def week(self): + return self._get_field('woy') + + weekofyear = week + + @property + def quarter(self): + return self._get_field('q') + + @property + def days_in_month(self): + return self._get_field('dim') + + daysinmonth = days_in_month + + @property + def freqstr(self): + return getattr(self.freq, 'freqstr', self.freq) + + @property + def is_month_start(self): + return self._get_start_end_field('is_month_start') + + @property + def is_month_end(self): + return self._get_start_end_field('is_month_end') + + @property + def is_quarter_start(self): + return self._get_start_end_field('is_quarter_start') + + @property + def is_quarter_end(self): + return self._get_start_end_field('is_quarter_end') + + @property + def is_year_start(self): + return self._get_start_end_field('is_year_start') + + @property + def is_year_end(self): + return self._get_start_end_field('is_year_end') + + @property + def is_leap_year(self): + return bool(is_leapyear(self.year)) + + def tz_localize(self, tz, ambiguous='raise', errors='raise'): + """ + Convert naive Timestamp to local time zone, or remove + timezone from tz-aware Timestamp. + + Parameters + ---------- + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time which Timestamp will be converted to. + None will remove timezone holding local time. + + ambiguous : bool, 'NaT', default 'raise' + - bool contains flags to determine if time is dst or not (note + that this flag is only applicable for ambiguous fall dst dates) + - 'NaT' will return NaT for an ambiguous time + - 'raise' will raise an AmbiguousTimeError for an ambiguous time + + errors : 'raise', 'coerce', default 'raise' + - 'raise' will raise a NonExistentTimeError if a timestamp is not + valid in the specified timezone (e.g. due to a transition from + or to DST time) + - 'coerce' will return NaT if the timestamp can not be converted + into the specified timezone + + .. versionadded:: 0.19.0 + + Returns + ------- + localized : Timestamp + + Raises + ------ + TypeError + If the Timestamp is tz-aware and tz is not None. + """ + if ambiguous == 'infer': + raise ValueError('Cannot infer offset with only one time.') + + if self.tzinfo is None: + # tz naive, localize + tz = maybe_get_tz(tz) + if not is_string_object(ambiguous): + ambiguous = [ambiguous] + value = tz_localize_to_utc(np.array([self.value], dtype='i8'), tz, + ambiguous=ambiguous, errors=errors)[0] + return Timestamp(value, tz=tz) + else: + if tz is None: + # reset tz + value = tz_convert_single(self.value, 'UTC', self.tz) + return Timestamp(value, tz=None) + else: + raise TypeError('Cannot localize tz-aware Timestamp, use ' + 'tz_convert for conversions') + + def tz_convert(self, tz): + """ + Convert tz-aware Timestamp to another time zone. + + Parameters + ---------- + tz : string, pytz.timezone, dateutil.tz.tzfile or None + Time zone for time which Timestamp will be converted to. + None will remove timezone holding UTC time. + + Returns + ------- + converted : Timestamp + + Raises + ------ + TypeError + If Timestamp is tz-naive. + """ + if self.tzinfo is None: + # tz naive, use tz_localize + raise TypeError('Cannot convert tz-naive Timestamp, use ' + 'tz_localize to localize') + else: + # Same UTC timestamp, different time zone + return Timestamp(self.value, tz=tz) + + astimezone = tz_convert + + def replace(self, year=None, month=None, day=None, + hour=None, minute=None, second=None, microsecond=None, + nanosecond=None, tzinfo=object, fold=0): + """ + implements datetime.replace, handles nanoseconds + + Parameters + ---------- + year : int, optional + month : int, optional + day : int, optional + hour : int, optional + minute : int, optional + second : int, optional + microsecond : int, optional + nanosecond: int, optional + tzinfo : tz-convertible, optional + fold : int, optional, default is 0 + added in 3.6, NotImplemented + + Returns + ------- + Timestamp with fields replaced + """ + + cdef: + pandas_datetimestruct dts + int64_t value, value_tz, offset + object _tzinfo, result, k, v + datetime ts_input + + # set to naive if needed + _tzinfo = self.tzinfo + value = self.value + if _tzinfo is not None: + value_tz = tz_convert_single(value, _tzinfo, 'UTC') + value += value - value_tz + + # setup components + dt64_to_dtstruct(value, &dts) + dts.ps = self.nanosecond * 1000 + + # replace + def validate(k, v): + """ validate integers """ + if not is_integer_object(v): + raise ValueError("value must be an integer, received " + "{v} for {k}".format(v=type(v), k=k)) + return v + + if year is not None: + dts.year = validate('year', year) + if month is not None: + dts.month = validate('month', month) + if day is not None: + dts.day = validate('day', day) + if hour is not None: + dts.hour = validate('hour', hour) + if minute is not None: + dts.min = validate('minute', minute) + if second is not None: + dts.sec = validate('second', second) + if microsecond is not None: + dts.us = validate('microsecond', microsecond) + if nanosecond is not None: + dts.ps = validate('nanosecond', nanosecond) * 1000 + if tzinfo is not object: + _tzinfo = tzinfo + + # reconstruct & check bounds + ts_input = datetime(dts.year, dts.month, dts.day, dts.hour, dts.min, + dts.sec, dts.us, tzinfo=_tzinfo) + ts = convert_datetime_to_tsobject(ts_input, _tzinfo) + value = ts.value + (dts.ps // 1000) + if value != NPY_NAT: + check_dts_bounds(&dts) + + return create_timestamp_from_ts(value, dts, _tzinfo, self.freq) + + def isoformat(self, sep='T'): + base = super(_Timestamp, self).isoformat(sep=sep) + if self.nanosecond == 0: + return base + + if self.tzinfo is not None: + base1, base2 = base[:-6], base[-6:] + else: + base1, base2 = base, "" + + if self.microsecond != 0: + base1 += "%.3d" % self.nanosecond + else: + base1 += ".%.9d" % self.nanosecond + + return base1 + base2 + + def _has_time_component(self): + """ + Returns if the Timestamp has a time component + in addition to the date part + """ + return (self.time() != _zero_time + or self.tzinfo is not None + or self.nanosecond != 0) + + def to_julian_date(self): + """ + Convert TimeStamp to a Julian Date. + 0 Julian date is noon January 1, 4713 BC. + """ + year = self.year + month = self.month + day = self.day + if month <= 2: + year -= 1 + month += 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) + + def normalize(self): + """ + Normalize Timestamp to midnight, preserving + tz information. + """ + normalized_value = date_normalize( + np.array([self.value], dtype='i8'), tz=self.tz)[0] + return Timestamp(normalized_value).tz_localize(self.tz) + + def __radd__(self, other): + # __radd__ on cython extension types like _Timestamp is not used, so + # define it here instead + return self + other + + +# Add the min and max fields at the class level +cdef int64_t _NS_UPPER_BOUND = INT64_MAX +# the smallest value we could actually represent is +# INT64_MIN + 1 == -9223372036854775807 +# but to allow overflow free conversion with a microsecond resolution +# use the smallest value with a 0 nanosecond unit (0s in last 3 digits) +cdef int64_t _NS_LOWER_BOUND = -9223372036854775000 + +# Resolution is in nanoseconds +Timestamp.min = Timestamp(_NS_LOWER_BOUND) +Timestamp.max = Timestamp(_NS_UPPER_BOUND) diff --git a/setup.py b/setup.py index 44e7de1665bf0..c5ec33b8d5064 100755 --- a/setup.py +++ b/setup.py @@ -345,6 +345,7 @@ class CheckSDist(sdist_class): 'pandas/_libs/tslibs/strptime.pyx', 'pandas/_libs/tslibs/np_datetime.pyx', 'pandas/_libs/tslibs/timedeltas.pyx', + 'pandas/_libs/tslibs/timestamps.pyx', 'pandas/_libs/tslibs/timezones.pyx', 'pandas/_libs/tslibs/conversion.pyx', 'pandas/_libs/tslibs/fields.pyx', @@ -546,6 +547,7 @@ def pxd(name): '_libs/src/khash', '_libs/tslibs/conversion', '_libs/tslibs/timedeltas', + '_libs/tslibs/timestamps', '_libs/tslibs/timezones', '_libs/tslibs/nattype'], 'depends': tseries_depends, @@ -591,7 +593,8 @@ def pxd(name): '_libs/src/khash', '_libs/tslibs/frequencies', '_libs/tslibs/timezones'], - 'depends': tseries_depends}, + 'depends': tseries_depends, + 'sources': np_datetime_sources}, '_libs.tslibs.strptime': { 'pyxfile': '_libs/tslibs/strptime', 'pxdfiles': ['_libs/src/util', @@ -604,6 +607,15 @@ def pxd(name): '_libs/tslibs/nattype'], 'depends': np_datetime_headers, 'sources': np_datetime_sources}, + '_libs.tslibs.timestamps': { + 'pyxfile': '_libs/tslibs/timestamps', + 'pxdfiles': ['_libs/src/util', + '_libs/tslibs/conversion', + '_libs/tslibs/nattype', + '_libs/tslibs/timedeltas', + '_libs/tslibs/timezones'], + 'depends': tseries_depends, + 'sources': np_datetime_sources}, '_libs.tslibs.timezones': { 'pyxfile': '_libs/tslibs/timezones', 'pxdfiles': ['_libs/src/util']},
Then remove unused imports in tslibs. If/when this is merged, it'll be official: we've taken tslib from a 5500 line beast down to ~1k.
https://api.github.com/repos/pandas-dev/pandas/pulls/18369
2017-11-19T17:16:35Z
2017-11-22T01:56:18Z
2017-11-22T01:56:18Z
2017-12-08T19:40:11Z
Revert "explicitly set 'include' to numpy_incls (#18112)"
diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx index c4104b66e009f..db2e8b43d1ead 100644 --- a/pandas/_libs/reshape.pyx +++ b/pandas/_libs/reshape.pyx @@ -10,7 +10,7 @@ np.import_array() from numpy cimport (ndarray, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, - uint32_t, uint64_t, float32_t, float64_t) + uint32_t, uint64_t, float16_t, float32_t, float64_t) cdef double NaN = <double> np.NaN cdef double nan = NaN diff --git a/pandas/_libs/sparse.pyx b/pandas/_libs/sparse.pyx index bbdd5f0d8334c..5484cbda5bdf9 100644 --- a/pandas/_libs/sparse.pyx +++ b/pandas/_libs/sparse.pyx @@ -1,5 +1,5 @@ from numpy cimport (ndarray, uint8_t, int64_t, int32_t, int16_t, int8_t, - float64_t, float32_t) + float64_t, float32_t, float16_t) cimport numpy as np cimport cython diff --git a/setup.py b/setup.py index 33251d9aabedc..76847e66b8bd5 100755 --- a/setup.py +++ b/setup.py @@ -461,13 +461,6 @@ def pxd(name): return os.path.abspath(pjoin('pandas', name + '.pxd')) -if _have_setuptools: - # Note: this is a list, whereas `numpy_incl` in build_ext.build_extensions - # is a string - numpy_incls = [pkg_resources.resource_filename('numpy', 'core/include')] -else: - numpy_incls = [] - # args to ignore warnings if is_platform_windows(): extra_compile_args = [] @@ -510,8 +503,7 @@ def pxd(name): 'depends': _pxi_dep['index'], 'sources': np_datetime_sources}, '_libs.indexing': { - 'pyxfile': '_libs/indexing', - 'include': []}, + 'pyxfile': '_libs/indexing'}, '_libs.interval': { 'pyxfile': '_libs/interval', 'pxdfiles': ['_libs/hashtable'], @@ -544,12 +536,10 @@ def pxd(name): 'include': []}, '_libs.reshape': { 'pyxfile': '_libs/reshape', - 'depends': _pxi_dep['reshape'], - 'include': numpy_incls}, + 'depends': _pxi_dep['reshape']}, '_libs.sparse': { 'pyxfile': '_libs/sparse', - 'depends': _pxi_dep['sparse'], - 'include': numpy_incls}, + 'depends': _pxi_dep['sparse']}, '_libs.tslib': { 'pyxfile': '_libs/tslib', 'pxdfiles': ['_libs/src/util', @@ -590,7 +580,8 @@ def pxd(name): '_libs/tslibs/frequencies']}, '_libs.tslibs.parsing': { 'pyxfile': '_libs/tslibs/parsing', - 'include': numpy_incls}, + 'pxdfiles': ['_libs/src/util', + '_libs/src/khash']}, '_libs.tslibs.resolution': { 'pyxfile': '_libs/tslibs/resolution', 'pxdfiles': ['_libs/src/util', @@ -614,16 +605,14 @@ def pxd(name): 'pyxfile': '_libs/tslibs/timezones', 'pxdfiles': ['_libs/src/util']}, '_libs.testing': { - 'pyxfile': '_libs/testing', - 'include': []}, + 'pyxfile': '_libs/testing'}, '_libs.window': { 'pyxfile': '_libs/window', 'pxdfiles': ['_libs/src/skiplist', '_libs/src/util'], 'depends': ['pandas/_libs/src/skiplist.pyx', 'pandas/_libs/src/skiplist.h']}, 'io.sas._sas': { - 'pyxfile': 'io/sas/sas', - 'include': numpy_incls}} + 'pyxfile': 'io/sas/sas'}} extensions = []
This reverts commit 54f2a5e91e90e35f7cbd15214297169831d6a6a6. xref #18112 our 2.7 wheels started breaking with this: https://travis-ci.org/MacPython/pandas-wheels/builds/302788535
https://api.github.com/repos/pandas-dev/pandas/pulls/18365
2017-11-19T01:55:41Z
2017-11-19T14:57:20Z
2017-11-19T14:57:20Z
2017-11-19T14:58:18Z
BUG: do not fail when stack()ing unsortable level
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 2c0ccd377492a..d641050adfda4 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -142,7 +142,8 @@ Sparse Reshaping ^^^^^^^^^ -- +- Bug in :func:`DataFrame.stack` which fails trying to sort mixed type levels under Python 3 (:issue:`18310`) + - - diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 50e1a9d2fc68b..b1e24bb48fc85 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1292,19 +1292,19 @@ def _sort_levels_monotonic(self): for lev, lab in zip(self.levels, self.labels): - if lev.is_monotonic: - new_levels.append(lev) - new_labels.append(lab) - continue - - # indexer to reorder the levels - indexer = lev.argsort() - lev = lev.take(indexer) + if not lev.is_monotonic: + try: + # indexer to reorder the levels + indexer = lev.argsort() + except TypeError: + pass + else: + lev = lev.take(indexer) - # indexer to reorder the labels - indexer = _ensure_int64(indexer) - ri = lib.get_reverse_indexer(indexer, len(indexer)) - lab = algos.take_1d(ri, lab) + # indexer to reorder the labels + indexer = _ensure_int64(indexer) + ri = lib.get_reverse_indexer(indexer, len(indexer)) + lab = algos.take_1d(ri, lab) new_levels.append(lev) new_labels.append(lab) diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index d795aa835b00a..500b04df865bd 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -133,6 +133,30 @@ def test_stack_unstack(self): assert_frame_equal(unstacked_cols.T, df) assert_frame_equal(unstacked_cols_df['bar'].T, df) + def test_stack_mixed_level(self): + # GH 18310 + levels = [range(3), [3, 'a', 'b'], [1, 2]] + + # flat columns: + df = DataFrame(1, index=levels[0], columns=levels[1]) + result = df.stack() + expected = Series(1, index=MultiIndex.from_product(levels[:2])) + assert_series_equal(result, expected) + + # MultiIndex columns: + df = DataFrame(1, index=levels[0], + columns=MultiIndex.from_product(levels[1:])) + result = df.stack(1) + expected = DataFrame(1, index=MultiIndex.from_product([levels[0], + levels[2]]), + columns=levels[1]) + assert_frame_equal(result, expected) + + # as above, but used labels in level are actually of homogeneous type + result = df[['a', 'b']].stack(1) + expected = expected[['a', 'b']] + assert_frame_equal(result, expected) + def test_unstack_fill(self): # GH #9746: fill_value keyword argument for Series
- [x] closes #18310 - [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/18363
2017-11-19T00:51:46Z
2017-12-01T18:59:02Z
2017-12-01T18:59:02Z
2017-12-01T19:10:26Z
TST: don't skip statsmodels tests on network builds
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index 56bc29a7bca1e..0f0abd8cd3400 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -53,7 +53,6 @@ def test_xarray(df): assert df.to_xarray() is not None -@tm.network def test_statsmodels(): statsmodels = import_module('statsmodels') # noqa
https://api.github.com/repos/pandas-dev/pandas/pulls/18362
2017-11-19T00:43:29Z
2017-11-19T01:26:30Z
2017-11-19T01:26:30Z
2017-11-19T01:26:30Z
BUG: prevent coercion to datetime64[ns] when a Series is initialized with both tz-naive and tz-aware
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 4a4d60b4dfbb2..245798d63386f 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -195,5 +195,5 @@ Other ^^^^^ - Improved error message when attempting to use a Python keyword as an identifier in a numexpr query (:issue:`18221`) -- +- Fixed a bug where creating a Series from an array that contains both tz-naive and tz-aware values will result in a Series whose dtype is tz-aware instead of object (:issue:`16406`) - diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index 066beb29c24ce..6e964077dd56e 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -464,7 +464,8 @@ cpdef object infer_datetimelike_array(object arr): - timedelta: we have *only* timedeltas and maybe strings, nulls - nat: we do not have *any* date, datetimes or timedeltas, but do have at least a NaT - - mixed: other objects (strings or actual objects) + - mixed: other objects (strings, a mix of tz-aware and tz-naive, or + actual objects) Parameters ---------- @@ -479,6 +480,7 @@ cpdef object infer_datetimelike_array(object arr): cdef: Py_ssize_t i, n = len(arr) bint seen_timedelta = 0, seen_date = 0, seen_datetime = 0 + bint seen_tz_aware = 0, seen_tz_naive = 0 bint seen_nat = 0 list objs = [] object v @@ -496,8 +498,20 @@ cpdef object infer_datetimelike_array(object arr): pass elif v is NaT: seen_nat = 1 - elif is_datetime(v) or util.is_datetime64_object(v): - # datetime, or np.datetime64 + elif is_datetime(v): + # datetime + seen_datetime = 1 + + # disambiguate between tz-naive and tz-aware + if v.tzinfo is None: + seen_tz_naive = 1 + else: + seen_tz_aware = 1 + + if seen_tz_naive and seen_tz_aware: + return 'mixed' + elif util.is_datetime64_object(v): + # np.datetime64 seen_datetime = 1 elif is_date(v): seen_date = 1 diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index a96dd3c232636..ef12416ef4e1c 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -419,6 +419,10 @@ def test_mixed_dtypes_remain_object_array(self): class TestTypeInference(object): + # Dummy class used for testing with Python objects + class Dummy(): + pass + def test_length_zero(self): result = lib.infer_dtype(np.array([], dtype='i4')) assert result == 'integer' @@ -655,6 +659,72 @@ def test_infer_dtype_period(self): dtype=object) assert lib.infer_dtype(arr) == 'mixed' + @pytest.mark.parametrize( + "data", + [ + [datetime(2017, 6, 12, 19, 30), datetime(2017, 3, 11, 1, 15)], + [Timestamp("20170612"), Timestamp("20170311")], + [Timestamp("20170612", tz='US/Eastern'), + Timestamp("20170311", tz='US/Eastern')], + [date(2017, 6, 12), + Timestamp("20170311", tz='US/Eastern')], + [np.datetime64("2017-06-12"), np.datetime64("2017-03-11")], + [np.datetime64("2017-06-12"), datetime(2017, 3, 11, 1, 15)] + ] + ) + def test_infer_datetimelike_array_datetime(self, data): + assert lib.infer_datetimelike_array(data) == "datetime" + + @pytest.mark.parametrize( + "data", + [ + [timedelta(2017, 6, 12), timedelta(2017, 3, 11)], + [timedelta(2017, 6, 12), date(2017, 3, 11)], + [np.timedelta64(2017, "D"), np.timedelta64(6, "s")], + [np.timedelta64(2017, "D"), timedelta(2017, 3, 11)] + ] + ) + def test_infer_datetimelike_array_timedelta(self, data): + assert lib.infer_datetimelike_array(data) == "timedelta" + + def test_infer_datetimelike_array_date(self): + arr = [date(2017, 6, 12), date(2017, 3, 11)] + assert lib.infer_datetimelike_array(arr) == "date" + + @pytest.mark.parametrize( + "data", + [ + ["2017-06-12", "2017-03-11"], + [20170612, 20170311], + [20170612.5, 20170311.8], + [Dummy(), Dummy()], + [Timestamp("20170612"), Timestamp("20170311", tz='US/Eastern')], + [Timestamp("20170612"), 20170311], + [timedelta(2017, 6, 12), Timestamp("20170311", tz='US/Eastern')] + ] + ) + def test_infer_datetimelike_array_mixed(self, data): + assert lib.infer_datetimelike_array(data) == "mixed" + + @pytest.mark.parametrize( + "first, expected", + [ + [[None], "mixed"], + [[np.nan], "mixed"], + [[pd.NaT], "nat"], + [[datetime(2017, 6, 12, 19, 30), pd.NaT], "datetime"], + [[np.datetime64("2017-06-12"), pd.NaT], "datetime"], + [[date(2017, 6, 12), pd.NaT], "date"], + [[timedelta(2017, 6, 12), pd.NaT], "timedelta"], + [[np.timedelta64(2017, "D"), pd.NaT], "timedelta"] + ] + ) + @pytest.mark.parametrize("second", [None, np.nan]) + def test_infer_datetimelike_array_nan_nat_like(self, first, second, + expected): + first.append(second) + assert lib.infer_datetimelike_array(first) == expected + def test_infer_dtype_all_nan_nat_like(self): arr = np.array([np.nan, np.nan]) assert lib.infer_dtype(arr) == 'floating' diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index e62b19294a07b..86e5cc54bd490 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -777,6 +777,15 @@ def f(): s = Series([pd.NaT, np.nan, '1 Day']) assert s.dtype == 'timedelta64[ns]' + # GH 16406 + def test_constructor_mixed_tz(self): + s = Series([Timestamp('20130101'), + Timestamp('20130101', tz='US/Eastern')]) + expected = Series([Timestamp('20130101'), + Timestamp('20130101', tz='US/Eastern')], + dtype='object') + assert_series_equal(s, expected) + def test_NaT_scalar(self): series = Series([0, 1000, 2000, iNaT], dtype='M8[ns]')
- [x] closes #16406 - [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/18361
2017-11-18T23:06:07Z
2017-11-23T16:05:16Z
2017-11-23T16:05:16Z
2017-11-24T00:46:48Z
Move remaining conversion functions to tslibs.conversion
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index d74673b17c8d9..e4c188b28bb6e 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -13,7 +13,7 @@ cimport util import numpy as np -from tslib cimport _to_i8 +from tslibs.conversion cimport maybe_datetimelike_to_i8 from hashtable cimport HashTable @@ -405,12 +405,12 @@ cdef class DatetimeEngine(Int64Engine): if not self.is_unique: return self._get_loc_duplicates(val) values = self._get_index_values() - conv = _to_i8(val) + conv = maybe_datetimelike_to_i8(val) loc = values.searchsorted(conv, side='left') return util.get_value_at(values, loc) == conv self._ensure_mapping_populated() - return _to_i8(val) in self.mapping + return maybe_datetimelike_to_i8(val) in self.mapping cdef _get_index_values(self): return self.vgetter().view('i8') @@ -425,12 +425,12 @@ cdef class DatetimeEngine(Int64Engine): # Welcome to the spaghetti factory if self.over_size_threshold and self.is_monotonic_increasing: if not self.is_unique: - val = _to_i8(val) + val = maybe_datetimelike_to_i8(val) return self._get_loc_duplicates(val) values = self._get_index_values() try: - conv = _to_i8(val) + conv = maybe_datetimelike_to_i8(val) loc = values.searchsorted(conv, side='left') except TypeError: self._date_check_type(val) @@ -442,7 +442,7 @@ cdef class DatetimeEngine(Int64Engine): self._ensure_mapping_populated() if not self.unique: - val = _to_i8(val) + val = maybe_datetimelike_to_i8(val) return self._get_loc_duplicates(val) try: @@ -453,7 +453,7 @@ cdef class DatetimeEngine(Int64Engine): pass try: - val = _to_i8(val) + val = maybe_datetimelike_to_i8(val) return self.mapping.get_item(val) except (TypeError, ValueError): self._date_check_type(val) diff --git a/pandas/_libs/tslib.pxd b/pandas/_libs/tslib.pxd index 1c2c679904868..c764f486c0b12 100644 --- a/pandas/_libs/tslib.pxd +++ b/pandas/_libs/tslib.pxd @@ -3,5 +3,3 @@ from numpy cimport ndarray, int64_t from tslibs.conversion cimport convert_to_tsobject cdef bint _check_all_nulls(obj) - -cdef _to_i8(object val) diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 0777b83de4645..bd2bc98deda4f 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -36,7 +36,7 @@ from cpython.datetime cimport (PyDelta_Check, PyTZInfo_Check, # import datetime C API PyDateTime_IMPORT # this is our datetime.pxd -from datetime cimport pandas_datetime_to_datetimestruct, _string_to_dts +from datetime cimport _string_to_dts # stdlib datetime imports from datetime import time as datetime_time @@ -46,10 +46,9 @@ from tslibs.np_datetime cimport (check_dts_bounds, reverse_ops, cmp_scalar, pandas_datetimestruct, - PANDAS_DATETIMEUNIT, PANDAS_FR_ns, dt64_to_dtstruct, dtstruct_to_dt64, pydatetime_to_dt64, pydate_to_dt64, - get_datetime64_unit, get_datetime64_value, + get_datetime64_value, get_timedelta64_value, days_per_month_table, dayofweek, is_leapyear) @@ -1242,43 +1241,6 @@ cpdef inline object _localize_pydatetime(object dt, object tz): return dt.replace(tzinfo=tz) -def datetime_to_datetime64(ndarray[object] values): - cdef: - Py_ssize_t i, n = len(values) - object val, inferred_tz = None - ndarray[int64_t] iresult - pandas_datetimestruct dts - _TSObject _ts - - 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): - if val.tzinfo is not None: - if inferred_tz is not None: - if get_timezone(val.tzinfo) != inferred_tz: - raise ValueError('Array must be all same time zone') - else: - inferred_tz = get_timezone(val.tzinfo) - - _ts = convert_datetime_to_tsobject(val, None) - iresult[i] = _ts.value - check_dts_bounds(&_ts.dts) - else: - if inferred_tz is not None: - raise ValueError('Cannot mix tz-aware with ' - 'tz-naive values') - iresult[i] = pydatetime_to_dt64(val, &dts) - check_dts_bounds(&dts) - else: - raise TypeError('Unrecognized value type: %s' % type(val)) - - return result, inferred_tz - - def format_array_from_datetime(ndarray[int64_t] values, object tz=None, object format=None, object na_rep=None): """ @@ -1758,50 +1720,6 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', return oresult -# ---------------------------------------------------------------------- -# Conversion routines - -def cast_to_nanoseconds(ndarray arr): - cdef: - Py_ssize_t i, n = arr.size - ndarray[int64_t] ivalues, iresult - PANDAS_DATETIMEUNIT unit - pandas_datetimestruct dts - - shape = (<object> arr).shape - - ivalues = arr.view(np.int64).ravel() - - result = np.empty(shape, dtype='M8[ns]') - iresult = result.ravel().view(np.int64) - - if len(iresult) == 0: - return result - - unit = get_datetime64_unit(arr.flat[0]) - for i in range(n): - if ivalues[i] != NPY_NAT: - pandas_datetime_to_datetimestruct(ivalues[i], unit, &dts) - iresult[i] = dtstruct_to_dt64(&dts) - check_dts_bounds(&dts) - else: - iresult[i] = NPY_NAT - - return result - - -cdef inline _to_i8(object val): - cdef pandas_datetimestruct dts - try: - return val.value - except AttributeError: - if is_datetime64_object(val): - return get_datetime64_value(val) - elif PyDateTime_Check(val): - return Timestamp(val).value - return val - - # ---------------------------------------------------------------------- # Accessors diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index ad817ce8852f2..6e7df10e7c424 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -28,3 +28,5 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2) cdef int64_t get_datetime64_nanos(object val) except? -1 cpdef int64_t pydt_to_i8(object pydt) except? -1 + +cdef maybe_datetimelike_to_i8(object val) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 2a55180b53498..16e88bcaeea3e 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -40,7 +40,7 @@ from timezones cimport ( from parsing import parse_datetime_string from nattype import nat_strings, NaT -from nattype cimport NPY_NAT +from nattype cimport NPY_NAT, _checknull_with_nat # ---------------------------------------------------------------------- # Constants @@ -73,6 +73,123 @@ cdef inline int64_t get_datetime64_nanos(object val) except? -1: return ival + +def ensure_datetime64ns(ndarray arr): + """ + Ensure a np.datetime64 array has dtype specifically 'datetime64[ns]' + + Parameters + ---------- + arr : ndarray + + Returns + ------- + result : ndarray with dtype datetime64[ns] + + """ + cdef: + Py_ssize_t i, n = arr.size + ndarray[int64_t] ivalues, iresult + PANDAS_DATETIMEUNIT unit + pandas_datetimestruct dts + + shape = (<object> arr).shape + + ivalues = arr.view(np.int64).ravel() + + result = np.empty(shape, dtype='M8[ns]') + iresult = result.ravel().view(np.int64) + + if len(iresult) == 0: + return result + + unit = get_datetime64_unit(arr.flat[0]) + for i in range(n): + if ivalues[i] != NPY_NAT: + pandas_datetime_to_datetimestruct(ivalues[i], unit, &dts) + iresult[i] = dtstruct_to_dt64(&dts) + check_dts_bounds(&dts) + else: + iresult[i] = NPY_NAT + + return result + + +def datetime_to_datetime64(ndarray[object] values): + """ + Convert ndarray of datetime-like objects to int64 array representing + nanosecond timestamps. + + Parameters + ---------- + values : ndarray + + Returns + ------- + result : ndarray with dtype int64 + inferred_tz : tzinfo or None + """ + cdef: + Py_ssize_t i, n = len(values) + object val, inferred_tz = None + ndarray[int64_t] iresult + pandas_datetimestruct dts + _TSObject _ts + + 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): + if val.tzinfo is not None: + if inferred_tz is not None: + if get_timezone(val.tzinfo) != inferred_tz: + raise ValueError('Array must be all same time zone') + else: + inferred_tz = get_timezone(val.tzinfo) + + _ts = convert_datetime_to_tsobject(val, None) + iresult[i] = _ts.value + check_dts_bounds(&_ts.dts) + else: + if inferred_tz is not None: + raise ValueError('Cannot mix tz-aware with ' + 'tz-naive values') + iresult[i] = pydatetime_to_dt64(val, &dts) + check_dts_bounds(&dts) + else: + raise TypeError('Unrecognized value type: %s' % type(val)) + + return result, inferred_tz + + +cdef inline maybe_datetimelike_to_i8(object val): + """ + Try to convert to a nanosecond timestamp. Fall back to returning the + input value. + + Parameters + ---------- + val : object + + Returns + ------- + val : int64 timestamp or original input + """ + cdef: + pandas_datetimestruct dts + try: + return val.value + except AttributeError: + if is_datetime64_object(val): + return get_datetime64_value(val) + elif PyDateTime_Check(val): + return convert_datetime_to_tsobject(val, None).value + return val + + # ---------------------------------------------------------------------- # _TSObject Conversion diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index ba96979435f81..64b5b9f958880 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -409,7 +409,7 @@ def __new__(cls, data=None, verify_integrity = False else: if data.dtype != _NS_DTYPE: - subarr = libts.cast_to_nanoseconds(data) + subarr = conversion.ensure_datetime64ns(data) else: subarr = data else: diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 665f9ff8eb7a0..c5b38851f51fd 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -68,6 +68,7 @@ from pandas._libs import lib, tslib from pandas._libs.tslib import Timedelta from pandas._libs.lib import BlockPlacement +from pandas._libs.tslibs import conversion from pandas.util._decorators import cache_readonly from pandas.util._validators import validate_bool_kwarg @@ -2462,7 +2463,7 @@ class DatetimeBlock(DatetimeLikeBlockMixin, Block): def __init__(self, values, placement, fastpath=False, **kwargs): if values.dtype != _NS_DTYPE: - values = tslib.cast_to_nanoseconds(values) + values = conversion.ensure_datetime64ns(values) super(DatetimeBlock, self).__init__(values, fastpath=True, placement=placement, **kwargs) @@ -2584,7 +2585,7 @@ def set(self, locs, values, check=False): """ if values.dtype != _NS_DTYPE: # Workaround for numpy 1.6 bug - values = tslib.cast_to_nanoseconds(values) + values = conversion.ensure_datetime64ns(values) self.values[locs] = values @@ -4674,7 +4675,7 @@ def form_blocks(arrays, names, axes): complex_items.append((i, k, v)) elif issubclass(v.dtype.type, np.datetime64): if v.dtype != _NS_DTYPE: - v = tslib.cast_to_nanoseconds(v) + v = conversion.ensure_datetime64ns(v) if is_datetimetz(v): datetime_tz_items.append((i, k, v)) diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index cbf393046907f..65f4704da3800 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -4,7 +4,7 @@ from pandas._libs import tslib from pandas._libs.tslibs.strptime import array_strptime -from pandas._libs.tslibs import parsing +from pandas._libs.tslibs import parsing, conversion from pandas._libs.tslibs.parsing import ( # noqa parse_time_string, DateParseError, @@ -373,7 +373,7 @@ def _convert_listlike(arg, box, format, name=None, tz=tz): except ValueError as e: try: - values, tz = tslib.datetime_to_datetime64(arg) + values, tz = conversion.datetime_to_datetime64(arg) return DatetimeIndex._simple_new(values, name=name, tz=tz) except (ValueError, TypeError): raise e diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index a4706dd8a3767..b59dd25ead57f 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -7,8 +7,9 @@ import pandas as pd from pandas import offsets import pandas.util.testing as tm -from pandas._libs import tslib, lib +from pandas._libs import lib from pandas._libs.tslib import OutOfBoundsDatetime +from pandas._libs.tslibs import conversion from pandas import (DatetimeIndex, Index, Timestamp, datetime, date_range, to_datetime) @@ -496,7 +497,7 @@ def test_index_cast_datetime64_other_units(self): arr = np.arange(0, 100, 10, dtype=np.int64).view('M8[D]') idx = Index(arr) - assert (idx.values == tslib.cast_to_nanoseconds(arr)).all() + assert (idx.values == conversion.ensure_datetime64ns(arr)).all() def test_constructor_int64_nocopy(self): # #1624
Slightly more efficient implementation of `_to_i8`. Importantly (or at least satisfyingly) gets `pandas_datetime_to_datetimestruct` usage centralized in conversion.
https://api.github.com/repos/pandas-dev/pandas/pulls/18358
2017-11-18T16:46:15Z
2017-11-19T20:20:51Z
2017-11-19T20:20:51Z
2017-12-08T19:40:16Z
implement libmissing; untangles _libs dependencies
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index bb7f69f04b32d..a5aae6d6af656 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -32,8 +32,7 @@ from libc.math cimport sqrt, fabs # this is our util.pxd from util cimport numeric, get_nat -cimport lib -from pandas._libs import lib +import missing cdef int64_t iNaT = get_nat() diff --git a/pandas/_libs/algos_rank_helper.pxi.in b/pandas/_libs/algos_rank_helper.pxi.in index 0945aec638b1d..78a67d2e40be2 100644 --- a/pandas/_libs/algos_rank_helper.pxi.in +++ b/pandas/_libs/algos_rank_helper.pxi.in @@ -83,7 +83,7 @@ def rank_1d_{{dtype}}(object in_arr, ties_method='average', ascending=True, nan_value = {{neg_nan_value}} {{if dtype == 'object'}} - mask = lib.isnaobj(values) + mask = missing.isnaobj(values) {{elif dtype == 'float64'}} mask = np.isnan(values) {{elif dtype == 'int64'}} @@ -259,7 +259,7 @@ def rank_2d_{{dtype}}(object in_arr, axis=0, ties_method='average', nan_value = {{neg_nan_value}} {{if dtype == 'object'}} - mask = lib.isnaobj2d(values) + mask = missing.isnaobj2d(values) {{elif dtype == 'float64'}} mask = np.isnan(values) {{elif dtype == 'int64'}} diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx index b6b81055f89b2..4bbe8c654ea0e 100644 --- a/pandas/_libs/hashtable.pyx +++ b/pandas/_libs/hashtable.pyx @@ -42,7 +42,7 @@ cdef extern from "numpy/npy_math.h": cimport cython cimport numpy as cnp -from pandas._libs.lib import checknull +from missing cimport checknull cnp.import_array() cnp.import_ufunc() diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in index 3ef52c5c59c9d..6e1c4397810b7 100644 --- a/pandas/_libs/hashtable_class_helper.pxi.in +++ b/pandas/_libs/hashtable_class_helper.pxi.in @@ -4,7 +4,7 @@ Template for each `dtype` helper function for hashtable WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in """ -from lib cimport is_null_datetimelike +from missing cimport is_null_datetimelike #---------------------------------------------------------------------- diff --git a/pandas/_libs/lib.pxd b/pandas/_libs/lib.pxd index 554b0248e97ea..b06c071c358c1 100644 --- a/pandas/_libs/lib.pxd +++ b/pandas/_libs/lib.pxd @@ -1,4 +1,3 @@ # prototypes for sharing -cdef bint is_null_datetimelike(v) cpdef bint is_period(val) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 6a92815ef84de..956aeaf39b021 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -53,14 +53,14 @@ PyDateTime_IMPORT from tslibs.np_datetime cimport get_timedelta64_value, get_datetime64_value -from tslib cimport _check_all_nulls from tslib import NaT, Timestamp, Timedelta, array_to_datetime from interval import Interval +from missing cimport checknull cdef int64_t NPY_NAT = util.get_nat() cimport util -from util cimport is_array, _checknull, _checknan +from util cimport is_array, _checknull from libc.math cimport sqrt, fabs @@ -112,54 +112,6 @@ def memory_usage_of_objects(ndarray[object, ndim=1] arr): # ---------------------------------------------------------------------- -# isnull / notnull related - -cdef double INF = <double> np.inf -cdef double NEGINF = -INF - - -cpdef bint checknull(object val): - if util.is_float_object(val) or util.is_complex_object(val): - return val != val # and val != INF and val != NEGINF - elif util.is_datetime64_object(val): - return get_datetime64_value(val) == NPY_NAT - elif val is NaT: - return True - elif util.is_timedelta64_object(val): - return get_timedelta64_value(val) == NPY_NAT - elif is_array(val): - return False - else: - return _checknull(val) - - -cpdef bint checknull_old(object val): - if util.is_float_object(val) or util.is_complex_object(val): - return val != val or val == INF or val == NEGINF - elif util.is_datetime64_object(val): - return get_datetime64_value(val) == NPY_NAT - elif val is NaT: - return True - elif util.is_timedelta64_object(val): - return get_timedelta64_value(val) == NPY_NAT - elif is_array(val): - return False - else: - return _checknull(val) - - -cpdef bint isposinf_scalar(object val): - if util.is_float_object(val) and val == INF: - return True - else: - return False - - -cpdef bint isneginf_scalar(object val): - if util.is_float_object(val) and val == NEGINF: - return True - else: - return False cpdef bint isscalar(object val): @@ -212,78 +164,6 @@ def item_from_zerodim(object val): return util.unbox_if_zerodim(val) -@cython.wraparound(False) -@cython.boundscheck(False) -def isnaobj(ndarray arr): - cdef Py_ssize_t i, n - cdef object val - cdef ndarray[uint8_t] result - - assert arr.ndim == 1, "'arr' must be 1-D." - - n = len(arr) - result = np.empty(n, dtype=np.uint8) - for i from 0 <= i < n: - val = arr[i] - result[i] = _check_all_nulls(val) - return result.view(np.bool_) - - -@cython.wraparound(False) -@cython.boundscheck(False) -def isnaobj_old(ndarray arr): - cdef Py_ssize_t i, n - cdef object val - cdef ndarray[uint8_t] result - - assert arr.ndim == 1, "'arr' must be 1-D." - - n = len(arr) - result = np.zeros(n, dtype=np.uint8) - for i from 0 <= i < n: - val = arr[i] - result[i] = val is NaT or util._checknull_old(val) - return result.view(np.bool_) - - -@cython.wraparound(False) -@cython.boundscheck(False) -def isnaobj2d(ndarray arr): - cdef Py_ssize_t i, j, n, m - cdef object val - cdef ndarray[uint8_t, ndim=2] result - - assert arr.ndim == 2, "'arr' must be 2-D." - - n, m = (<object> arr).shape - result = np.zeros((n, m), dtype=np.uint8) - for i from 0 <= i < n: - for j from 0 <= j < m: - val = arr[i, j] - if checknull(val): - result[i, j] = 1 - return result.view(np.bool_) - - -@cython.wraparound(False) -@cython.boundscheck(False) -def isnaobj2d_old(ndarray arr): - cdef Py_ssize_t i, j, n, m - cdef object val - cdef ndarray[uint8_t, ndim=2] result - - assert arr.ndim == 2, "'arr' must be 2-D." - - n, m = (<object> arr).shape - result = np.zeros((n, m), dtype=np.uint8) - for i from 0 <= i < n: - for j from 0 <= j < m: - val = arr[i, j] - if checknull_old(val): - result[i, j] = 1 - return result.view(np.bool_) - - @cython.wraparound(False) @cython.boundscheck(False) cpdef ndarray[object] list_to_object_array(list obj): diff --git a/pandas/_libs/missing.pxd b/pandas/_libs/missing.pxd new file mode 100644 index 0000000000000..f3d990db1c3fd --- /dev/null +++ b/pandas/_libs/missing.pxd @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# cython: profile=False + +cdef bint is_null_datetimelike(object val) +cpdef bint checknull(object val) +cpdef bint checknull_old(object val) diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx new file mode 100644 index 0000000000000..0b60fc2c5b4d1 --- /dev/null +++ b/pandas/_libs/missing.pyx @@ -0,0 +1,310 @@ +# -*- coding: utf-8 -*- +# cython: profile=False + +from cpython cimport PyFloat_Check, PyComplex_Check + +cimport cython +from cython cimport Py_ssize_t + +import numpy as np +cimport numpy as np +from numpy cimport ndarray, int64_t, uint8_t +np.import_array() + +cimport util + +from tslibs.np_datetime cimport get_timedelta64_value, get_datetime64_value +from tslibs.nattype import NaT + +cdef double INF = <double> np.inf +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 + if PyFloat_Check(val) or PyComplex_Check(val): + res = val != val + elif val is NaT: + res = 1 + elif val is None: + res = 1 + elif util.is_datetime64_object(val): + res = get_datetime64_value(val) == NPY_NAT + elif util.is_timedelta64_object(val): + res = get_timedelta64_value(val) == NPY_NAT + else: + res = 0 + return res + + +cpdef bint checknull(object val): + """ + Return boolean describing of the input is NA-like, defined here as any + of: + - None + - nan + - NaT + - np.datetime64 representation of NaT + - np.timedelta64 representation of NaT + + Parameters + ---------- + val : object + + Returns + ------- + result : bool + + Notes + ----- + The difference between `checknull` and `checknull_old` is that `checknull` + does *not* consider INF or NEGINF to be NA. + """ + if util.is_float_object(val) or util.is_complex_object(val): + return val != val # and val != INF and val != NEGINF + elif util.is_datetime64_object(val): + return get_datetime64_value(val) == NPY_NAT + elif val is NaT: + return True + elif util.is_timedelta64_object(val): + return get_timedelta64_value(val) == NPY_NAT + elif util.is_array(val): + return False + else: + return util._checknull(val) + + +cpdef bint checknull_old(object val): + """ + Return boolean describing of the input is NA-like, defined here as any + of: + - None + - nan + - INF + - NEGINF + - NaT + - np.datetime64 representation of NaT + - np.timedelta64 representation of NaT + + Parameters + ---------- + val : object + + Returns + ------- + result : bool + + Notes + ----- + The difference between `checknull` and `checknull_old` is that `checknull` + does *not* consider INF or NEGINF to be NA. + """ + if util.is_float_object(val) or util.is_complex_object(val): + return val != val or val == INF or val == NEGINF + elif util.is_datetime64_object(val): + return get_datetime64_value(val) == NPY_NAT + elif val is NaT: + return True + elif util.is_timedelta64_object(val): + return get_timedelta64_value(val) == NPY_NAT + elif util.is_array(val): + return False + else: + return util._checknull(val) + + +cdef inline bint _check_none_nan_inf_neginf(object val): + try: + return val is None or (PyFloat_Check(val) and + (val != val or val == INF or val == NEGINF)) + except ValueError: + return False + + +@cython.wraparound(False) +@cython.boundscheck(False) +def isnaobj(ndarray arr): + """ + Return boolean mask denoting which elements of a 1-D array are na-like, + according to the criteria defined in `_check_all_nulls`: + - None + - nan + - NaT + - np.datetime64 representation of NaT + - np.timedelta64 representation of NaT + + Parameters + ---------- + arr : ndarray + + Returns + ------- + result : ndarray (dtype=np.bool_) + """ + cdef: + Py_ssize_t i, n + object val + ndarray[uint8_t] result + + assert arr.ndim == 1, "'arr' must be 1-D." + + n = len(arr) + result = np.empty(n, dtype=np.uint8) + for i in range(n): + val = arr[i] + result[i] = _check_all_nulls(val) + return result.view(np.bool_) + + +@cython.wraparound(False) +@cython.boundscheck(False) +def isnaobj_old(ndarray arr): + """ + Return boolean mask denoting which elements of a 1-D array are na-like, + defined as being any of: + - None + - nan + - INF + - NEGINF + - NaT + + Parameters + ---------- + arr : ndarray + + Returns + ------- + result : ndarray (dtype=np.bool_) + """ + cdef: + Py_ssize_t i, n + object val + ndarray[uint8_t] result + + assert arr.ndim == 1, "'arr' must be 1-D." + + n = len(arr) + result = np.zeros(n, dtype=np.uint8) + for i in range(n): + val = arr[i] + result[i] = val is NaT or _check_none_nan_inf_neginf(val) + return result.view(np.bool_) + + +@cython.wraparound(False) +@cython.boundscheck(False) +def isnaobj2d(ndarray arr): + """ + Return boolean mask denoting which elements of a 2-D array are na-like, + according to the criteria defined in `checknull`: + - None + - nan + - NaT + - np.datetime64 representation of NaT + - np.timedelta64 representation of NaT + + Parameters + ---------- + arr : ndarray + + Returns + ------- + result : ndarray (dtype=np.bool_) + + Notes + ----- + The difference between `isnaobj2d` and `isnaobj2d_old` is that `isnaobj2d` + does *not* consider INF or NEGINF to be NA. + """ + cdef: + Py_ssize_t i, j, n, m + object val + ndarray[uint8_t, ndim=2] result + + assert arr.ndim == 2, "'arr' must be 2-D." + + n, m = (<object> arr).shape + result = np.zeros((n, m), dtype=np.uint8) + for i in range(n): + for j in range(m): + val = arr[i, j] + if checknull(val): + result[i, j] = 1 + return result.view(np.bool_) + + +@cython.wraparound(False) +@cython.boundscheck(False) +def isnaobj2d_old(ndarray arr): + """ + Return boolean mask denoting which elements of a 2-D array are na-like, + according to the criteria defined in `checknull_old`: + - None + - nan + - INF + - NEGINF + - NaT + - np.datetime64 representation of NaT + - np.timedelta64 representation of NaT + + Parameters + ---------- + arr : ndarray + + Returns + ------- + result : ndarray (dtype=np.bool_) + + Notes + ----- + The difference between `isnaobj2d` and `isnaobj2d_old` is that `isnaobj2d` + does *not* consider INF or NEGINF to be NA. + """ + cdef: + Py_ssize_t i, j, n, m + object val + ndarray[uint8_t, ndim=2] result + + assert arr.ndim == 2, "'arr' must be 2-D." + + n, m = (<object> arr).shape + result = np.zeros((n, m), dtype=np.uint8) + for i in range(n): + for j in range(m): + val = arr[i, j] + if checknull_old(val): + result[i, j] = 1 + return result.view(np.bool_) + + +cpdef bint isposinf_scalar(object val): + if util.is_float_object(val) and val == INF: + return True + else: + return False + + +cpdef bint isneginf_scalar(object val): + if util.is_float_object(val) and val == NEGINF: + return True + else: + return False diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx index 0a1d4a241b795..d09459898321e 100644 --- a/pandas/_libs/period.pyx +++ b/pandas/_libs/period.pyx @@ -25,7 +25,7 @@ from tslibs.np_datetime cimport (pandas_datetimestruct, cimport util from util cimport is_period_object, is_string_object, INT32_MIN -from lib cimport is_null_datetimelike +from missing cimport is_null_datetimelike from pandas._libs.tslib import Timestamp from tslibs.timezones cimport ( is_utc, is_tzlocal, get_utcoffset, get_dst_info) diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index ad2defc7b362f..066beb29c24ce 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -533,22 +533,6 @@ cpdef object infer_datetimelike_array(object arr): return 'mixed' -cdef inline bint is_null_datetimelike(v): - # determine if we have a null for a timedelta/datetime (or integer - # versions) - if util._checknull(v): - return True - elif v is NaT: - return True - elif util.is_timedelta64_object(v): - return v.view('int64') == iNaT - elif util.is_datetime64_object(v): - return v.view('int64') == iNaT - elif util.is_integer_object(v): - return v == iNaT - 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') diff --git a/pandas/_libs/src/util.pxd b/pandas/_libs/src/util.pxd index 7361aa36144c5..61783ab47cb86 100644 --- a/pandas/_libs/src/util.pxd +++ b/pandas/_libs/src/util.pxd @@ -111,16 +111,6 @@ cdef inline bint _checknull(object val): except ValueError: return False -cdef inline bint _checknull_old(object val): - import numpy as np - cdef double INF = <double> np.inf - cdef double NEGINF = -INF - try: - return val is None or (cpython.PyFloat_Check(val) and - (val != val or val == INF or val == NEGINF)) - except ValueError: - return False - cdef inline bint _checknan(object val): return not cnp.PyArray_Check(val) and val != val diff --git a/pandas/_libs/tslib.pxd b/pandas/_libs/tslib.pxd index c764f486c0b12..b74cf5b79c4cb 100644 --- a/pandas/_libs/tslib.pxd +++ b/pandas/_libs/tslib.pxd @@ -1,5 +1,3 @@ from numpy cimport ndarray, int64_t from tslibs.conversion cimport convert_to_tsobject - -cdef bint _check_all_nulls(obj) diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index a119e22b8e3ee..ea4f4728a0741 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -9,17 +9,13 @@ from numpy cimport int64_t, import_array, ndarray, float64_t import numpy as np -from cpython cimport ( - PyTypeObject, - PyFloat_Check, - PyComplex_Check) +from cpython cimport PyTypeObject, PyFloat_Check cdef extern from "Python.h": cdef PyTypeObject *Py_TYPE(object) from util cimport (is_integer_object, is_float_object, is_string_object, - is_datetime64_object, is_timedelta64_object) -cimport util + is_datetime64_object) from cpython.datetime cimport (PyDateTime_Check, PyDate_Check, PyDateTime_IMPORT, @@ -35,7 +31,6 @@ from tslibs.np_datetime cimport (check_dts_bounds, dt64_to_dtstruct, dtstruct_to_dt64, pydatetime_to_dt64, pydate_to_dt64, get_datetime64_value, - get_timedelta64_value, days_per_month_table, dayofweek, is_leapyear) from tslibs.np_datetime import OutOfBoundsDatetime @@ -58,7 +53,6 @@ from tslibs.timedeltas import Timedelta from tslibs.timezones cimport ( is_utc, is_tzlocal, is_fixed_offset, treat_tz_as_pytz, - get_timezone, get_dst_info) from tslibs.conversion cimport (tz_convert_single, _TSObject, convert_datetime_to_tsobject, @@ -213,24 +207,6 @@ def ints_to_pytimedelta(ndarray[int64_t] arr, box=False): return result -cdef inline bint _check_all_nulls(object val): - """ utility to check if a value is any type of null """ - cdef bint res - if PyFloat_Check(val) or PyComplex_Check(val): - res = val != val - elif val is NaT: - res = 1 - elif val is None: - res = 1 - elif is_datetime64_object(val): - res = get_datetime64_value(val) == NPY_NAT - elif is_timedelta64_object(val): - res = get_timedelta64_value(val) == NPY_NAT - else: - res = 0 - return res - - cdef PyTypeObject* ts_type = <PyTypeObject*> Timestamp diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index d8973dd2eb27a..7cae536c5edd9 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -2,7 +2,7 @@ missing types & inference """ import numpy as np -from pandas._libs import lib +from pandas._libs import lib, missing as libmissing from pandas._libs.tslib import NaT, iNaT from .generic import (ABCMultiIndex, ABCSeries, ABCIndexClass, ABCGeneric) @@ -22,6 +22,9 @@ _NS_DTYPE) from .inference import is_list_like +isposinf_scalar = libmissing.isposinf_scalar +isneginf_scalar = libmissing.isneginf_scalar + def isna(obj): """Detect missing values (NaN in numeric arrays, None/NaN in object arrays) @@ -50,7 +53,7 @@ def isna(obj): def _isna_new(obj): if is_scalar(obj): - return lib.checknull(obj) + return libmissing.checknull(obj) # hack (for now) because MI registers as ndarray elif isinstance(obj, ABCMultiIndex): raise NotImplementedError("isna is not defined for MultiIndex") @@ -76,7 +79,7 @@ def _isna_old(obj): boolean ndarray or boolean """ if is_scalar(obj): - return lib.checknull_old(obj) + return libmissing.checknull_old(obj) # hack (for now) because MI registers as ndarray elif isinstance(obj, ABCMultiIndex): raise NotImplementedError("isna is not defined for MultiIndex") @@ -143,7 +146,7 @@ def _isna_ndarraylike(obj): result = np.zeros(values.shape, dtype=bool) else: result = np.empty(shape, dtype=bool) - vec = lib.isnaobj(values.ravel()) + vec = libmissing.isnaobj(values.ravel()) result[...] = vec.reshape(shape) elif needs_i8_conversion(obj): @@ -172,7 +175,7 @@ def _isna_ndarraylike_old(obj): result = np.zeros(values.shape, dtype=bool) else: result = np.empty(shape, dtype=bool) - vec = lib.isnaobj_old(values.ravel()) + vec = libmissing.isnaobj_old(values.ravel()) result[:] = vec.reshape(shape) elif is_datetime64_dtype(dtype): diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index af24537cabf90..a36e82edf6e57 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -11,8 +11,8 @@ from pandas.io.formats.css import CSSResolver, CSSWarning from pandas.io.formats.printing import pprint_thing from pandas.core.common import _any_not_none -from pandas.core.dtypes.common import is_float -import pandas._libs.lib as lib +from pandas.core.dtypes.common import is_float, is_scalar +from pandas.core.dtypes import missing from pandas import Index, MultiIndex, PeriodIndex from pandas.io.formats.common import get_level_lengths @@ -381,12 +381,12 @@ def __init__(self, df, na_rep='', float_format=None, cols=None, self.inf_rep = inf_rep def _format_value(self, val): - if lib.checknull(val): + if is_scalar(val) and missing.isna(val): val = self.na_rep elif is_float(val): - if lib.isposinf_scalar(val): + if missing.isposinf_scalar(val): val = self.inf_rep - elif lib.isneginf_scalar(val): + elif missing.isneginf_scalar(val): val = '-{inf}'.format(inf=self.inf_rep) elif self.float_format is not None: val = float(self.float_format % val) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index ca3b1cfb18b18..e116635c99264 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -20,6 +20,7 @@ is_datetimetz, is_integer, is_float, + is_scalar, is_numeric_dtype, is_datetime64_dtype, is_timedelta64_dtype, @@ -37,7 +38,7 @@ _stringify_path) from pandas.io.formats.printing import adjoin, justify, pprint_thing from pandas.io.formats.common import get_level_lengths -import pandas._libs.lib as lib +from pandas._libs import lib from pandas._libs.tslib import (iNaT, Timestamp, Timedelta, format_array_from_datetime) from pandas.core.indexes.datetimes import DatetimeIndex @@ -1860,7 +1861,7 @@ def _format_strings(self): (lambda x: pprint_thing(x, escape_chars=('\t', '\r', '\n')))) def _format(x): - if self.na_rep is not None and lib.checknull(x): + if self.na_rep is not None and is_scalar(x) and isna(x): if x is None: return 'None' elif x is pd.NaT: @@ -2186,7 +2187,7 @@ def _is_dates_only(values): def _format_datetime64(x, tz=None, nat_rep='NaT'): - if x is None or lib.checknull(x): + if x is None or (is_scalar(x) and isna(x)): return nat_rep if tz is not None or not isinstance(x, Timestamp): @@ -2196,7 +2197,7 @@ def _format_datetime64(x, tz=None, nat_rep='NaT'): def _format_datetime64_dateonly(x, nat_rep='NaT', date_format=None): - if x is None or lib.checknull(x): + if x is None or (is_scalar(x) and isna(x)): return nat_rep if not isinstance(x, Timestamp): @@ -2281,7 +2282,7 @@ def _get_format_timedelta64(values, nat_rep='NaT', box=False): format = 'long' def _formatter(x): - if x is None or lib.checknull(x): + if x is None or (is_scalar(x) and isna(x)): return nat_rep if not isinstance(x, Timedelta): diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 34ed9d3142923..a96dd3c232636 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -15,7 +15,7 @@ import pytest import pandas as pd -from pandas._libs import tslib, lib +from pandas._libs import tslib, lib, missing as libmissing from pandas import (Series, Index, DataFrame, Timedelta, DatetimeIndex, TimedeltaIndex, Timestamp, Panel, Period, Categorical, isna) @@ -260,17 +260,17 @@ def test_infer_dtype_bytes(self): def test_isinf_scalar(self): # GH 11352 - assert lib.isposinf_scalar(float('inf')) - assert lib.isposinf_scalar(np.inf) - assert not lib.isposinf_scalar(-np.inf) - assert not lib.isposinf_scalar(1) - assert not lib.isposinf_scalar('a') - - assert lib.isneginf_scalar(float('-inf')) - assert lib.isneginf_scalar(-np.inf) - assert not lib.isneginf_scalar(np.inf) - assert not lib.isneginf_scalar(1) - assert not lib.isneginf_scalar('a') + assert libmissing.isposinf_scalar(float('inf')) + assert libmissing.isposinf_scalar(np.inf) + assert not libmissing.isposinf_scalar(-np.inf) + assert not libmissing.isposinf_scalar(1) + assert not libmissing.isposinf_scalar('a') + + assert libmissing.isneginf_scalar(float('-inf')) + assert libmissing.isneginf_scalar(-np.inf) + assert not libmissing.isneginf_scalar(np.inf) + assert not libmissing.isneginf_scalar(1) + assert not libmissing.isneginf_scalar('a') def test_maybe_convert_numeric_infinities(self): # see gh-13274 diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index d3c9ca51af18f..fd2c63ef5b37e 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -9,6 +9,8 @@ import pandas as pd from pandas.core import config as cf from pandas.compat import u + +from pandas._libs import missing as libmissing from pandas._libs.tslib import iNaT from pandas import (NaT, Float64Index, Series, DatetimeIndex, TimedeltaIndex, date_range) @@ -333,3 +335,52 @@ def test_na_value_for_dtype(): for dtype in ['O']: assert np.isnan(na_value_for_dtype(np.dtype(dtype))) + + +class TestNAObj(object): + + _1d_methods = ['isnaobj', 'isnaobj_old'] + _2d_methods = ['isnaobj2d', 'isnaobj2d_old'] + + def _check_behavior(self, arr, expected): + for method in TestNAObj._1d_methods: + result = getattr(libmissing, method)(arr) + tm.assert_numpy_array_equal(result, expected) + + arr = np.atleast_2d(arr) + expected = np.atleast_2d(expected) + + for method in TestNAObj._2d_methods: + result = getattr(libmissing, method)(arr) + tm.assert_numpy_array_equal(result, expected) + + def test_basic(self): + arr = np.array([1, None, 'foo', -5.1, pd.NaT, np.nan]) + expected = np.array([False, True, False, False, True, True]) + + self._check_behavior(arr, expected) + + def test_non_obj_dtype(self): + arr = np.array([1, 3, np.nan, 5], dtype=float) + expected = np.array([False, False, True, False]) + + self._check_behavior(arr, expected) + + def test_empty_arr(self): + arr = np.array([]) + expected = np.array([], dtype=bool) + + self._check_behavior(arr, expected) + + def test_empty_str_inp(self): + arr = np.array([""]) # empty but not na + expected = np.array([False]) + + self._check_behavior(arr, expected) + + def test_empty_like(self): + # see gh-13717: no segfaults! + arr = np.empty_like([None]) + expected = np.array([True]) + + self._check_behavior(arr, expected) diff --git a/pandas/tests/test_lib.py b/pandas/tests/test_lib.py index 75aa9aa4e8198..10061204df42a 100644 --- a/pandas/tests/test_lib.py +++ b/pandas/tests/test_lib.py @@ -3,8 +3,7 @@ import pytest import numpy as np -import pandas as pd -import pandas._libs.lib as lib +from pandas._libs import lib import pandas.util.testing as tm @@ -199,52 +198,3 @@ def test_get_reverse_indexer(self): result = lib.get_reverse_indexer(indexer, 5) expected = np.array([4, 2, 3, 6, 7], dtype=np.int64) tm.assert_numpy_array_equal(result, expected) - - -class TestNAObj(object): - - _1d_methods = ['isnaobj', 'isnaobj_old'] - _2d_methods = ['isnaobj2d', 'isnaobj2d_old'] - - def _check_behavior(self, arr, expected): - for method in TestNAObj._1d_methods: - result = getattr(lib, method)(arr) - tm.assert_numpy_array_equal(result, expected) - - arr = np.atleast_2d(arr) - expected = np.atleast_2d(expected) - - for method in TestNAObj._2d_methods: - result = getattr(lib, method)(arr) - tm.assert_numpy_array_equal(result, expected) - - def test_basic(self): - arr = np.array([1, None, 'foo', -5.1, pd.NaT, np.nan]) - expected = np.array([False, True, False, False, True, True]) - - self._check_behavior(arr, expected) - - def test_non_obj_dtype(self): - arr = np.array([1, 3, np.nan, 5], dtype=float) - expected = np.array([False, False, True, False]) - - self._check_behavior(arr, expected) - - def test_empty_arr(self): - arr = np.array([]) - expected = np.array([], dtype=bool) - - self._check_behavior(arr, expected) - - def test_empty_str_inp(self): - arr = np.array([""]) # empty but not na - expected = np.array([False]) - - self._check_behavior(arr, expected) - - def test_empty_like(self): - # see gh-13717: no segfaults! - arr = np.empty_like([None]) - expected = np.array([True]) - - self._check_behavior(arr, expected) diff --git a/setup.py b/setup.py index c5ec33b8d5064..7e56298d1b20b 100755 --- a/setup.py +++ b/setup.py @@ -338,6 +338,7 @@ class CheckSDist(sdist_class): 'pandas/_libs/indexing.pyx', 'pandas/_libs/interval.pyx', 'pandas/_libs/hashing.pyx', + 'pandas/_libs/missing.pyx', 'pandas/_libs/testing.pyx', 'pandas/_libs/window.pyx', 'pandas/_libs/sparse.pyx', @@ -495,7 +496,7 @@ def pxd(name): 'pyxfile': '_libs/hashing'}, '_libs.hashtable': { 'pyxfile': '_libs/hashtable', - 'pxdfiles': ['_libs/hashtable'], + 'pxdfiles': ['_libs/hashtable', '_libs/missing'], 'depends': (['pandas/_libs/src/klib/khash_python.h'] + _pxi_dep['hashtable'])}, '_libs.index': { @@ -515,7 +516,12 @@ def pxd(name): 'depends': _pxi_dep['join']}, '_libs.lib': { 'pyxfile': '_libs/lib', + 'pxdfiles': ['_libs/src/util', '_libs/missing'], 'depends': lib_depends + tseries_depends}, + '_libs.missing': { + 'pyxfile': '_libs/missing', + 'pxdfiles': ['_libs/src/util'], + 'depends': tseries_depends}, '_libs.parsers': { 'pyxfile': '_libs/parsers', 'depends': ['pandas/_libs/src/parser/tokenizer.h',
In the status quo, `algos`, `hashtable`, `parsers`, and `period` depend on `lib`. On top of that `groupby`, `join`, and `index` depend on `algos` and `intervaltree` depends on `hashtable`. (In fairness, some of these dependency relationships are python imports, not cimports.) `lib` depends on `tslib` which depends on essentially all of `tslibs`. So we've got a whole bunch of dependencies (many of which aren't declared in setup.py). But the `lib` functions needed by `algos`, `hashtable`, and `period` are basically all a small handful of null-checking `checnull`, `isnaobj`, `isnaobj2d` which depend only on `util` and `NaT`. So this PR takes those functions and puts them into `_libs.missing`, then updates the relevant imports.
https://api.github.com/repos/pandas-dev/pandas/pulls/18357
2017-11-18T16:36:34Z
2017-11-22T22:52:29Z
2017-11-22T22:52:29Z
2017-11-23T01:15:12Z
BUG fixes tuple agg issue 18079
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 78b8ca8d5a480..bd3fe7750a0a1 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -169,7 +169,7 @@ Plotting Groupby/Resample/Rolling ^^^^^^^^^^^^^^^^^^^^^^^^ -- +- Bug when grouping by a single column and aggregating with a class like ``list`` or ``tuple`` (:issue:`18079`) - - diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index ba180cc98cb08..69de7630ede2c 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -2299,8 +2299,7 @@ def _aggregate_series_pure_python(self, obj, func): for label, group in splitter: res = func(group) if result is None: - if (isinstance(res, (Series, Index, np.ndarray)) or - isinstance(res, list)): + if (isinstance(res, (Series, Index, np.ndarray))): raise ValueError('Function does not reduce') result = np.empty(ngroups, dtype='O') @@ -3022,7 +3021,9 @@ def aggregate(self, func_or_funcs, *args, **kwargs): if isinstance(func_or_funcs, compat.string_types): return getattr(self, func_or_funcs)(*args, **kwargs) - if hasattr(func_or_funcs, '__iter__'): + 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: diff --git a/pandas/tests/groupby/test_aggregate.py b/pandas/tests/groupby/test_aggregate.py index 913d3bcc09869..3d27df31cee6e 100644 --- a/pandas/tests/groupby/test_aggregate.py +++ b/pandas/tests/groupby/test_aggregate.py @@ -637,7 +637,7 @@ def test_agg_consistency(self): def P1(a): try: return np.percentile(a.dropna(), q=1) - except: + except Exception: return np.nan import datetime as dt @@ -892,3 +892,36 @@ def test_sum_uint64_overflow(self): expected.index.name = 0 result = df.groupby(0).sum() tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("structure, expected", [ + (tuple, pd.DataFrame({'C': {(1, 1): (1, 1, 1), (3, 4): (3, 4, 4)}})), + (list, pd.DataFrame({'C': {(1, 1): [1, 1, 1], (3, 4): [3, 4, 4]}})), + (lambda x: tuple(x), pd.DataFrame({'C': {(1, 1): (1, 1, 1), + (3, 4): (3, 4, 4)}})), + (lambda x: list(x), pd.DataFrame({'C': {(1, 1): [1, 1, 1], + (3, 4): [3, 4, 4]}})) + ]) + def test_agg_structs_dataframe(self, structure, expected): + df = pd.DataFrame({'A': [1, 1, 1, 3, 3, 3], + 'B': [1, 1, 1, 4, 4, 4], 'C': [1, 1, 1, 3, 4, 4]}) + + result = df.groupby(['A', 'B']).aggregate(structure) + expected.index.names = ['A', 'B'] + assert_frame_equal(result, expected) + + @pytest.mark.parametrize("structure, expected", [ + (tuple, pd.Series([(1, 1, 1), (3, 4, 4)], index=[1, 3], name='C')), + (list, pd.Series([[1, 1, 1], [3, 4, 4]], index=[1, 3], name='C')), + (lambda x: tuple(x), pd.Series([(1, 1, 1), (3, 4, 4)], + index=[1, 3], name='C')), + (lambda x: list(x), pd.Series([[1, 1, 1], [3, 4, 4]], + index=[1, 3], name='C')) + ]) + def test_agg_structs_series(self, structure, expected): + # Issue #18079 + df = pd.DataFrame({'A': [1, 1, 1, 3, 3, 3], + 'B': [1, 1, 1, 4, 4, 4], 'C': [1, 1, 1, 3, 4, 4]}) + + result = df.groupby('A')['C'].aggregate(structure) + expected.index.name = 'A' + assert_series_equal(result, expected)
- [x] closes #18079 - [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/18354
2017-11-18T04:21:32Z
2017-11-26T23:42:49Z
2017-11-26T23:42:49Z
2017-11-27T00:16:06Z
BUG: Keep float dtype in merge on int and float column
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 4a4d60b4dfbb2..1a6327554f61a 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -51,7 +51,7 @@ Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :func:`Series.fillna` now raises a ``TypeError`` instead of a ``ValueError`` when passed a list, tuple or DataFrame as a ``value`` (:issue:`18293`) -- +- :func:`pandas.DataFrame.merge` no longer casts a ``float`` column to ``object`` when merging on ``int`` and ``float`` columns (:issue:`16572`) - diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 412c00dc95ec0..d00aa1003988a 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -906,16 +906,31 @@ def _maybe_coerce_merge_keys(self): continue # if we are numeric, then allow differing - # kinds to proceed, eg. int64 and int8 + # kinds to proceed, eg. int64 and int8, int and float # further if we are object, but we infer to # the same, then proceed if is_numeric_dtype(lk) and is_numeric_dtype(rk): if lk.dtype.kind == rk.dtype.kind: - continue + pass + + # check whether ints and floats + elif is_integer_dtype(rk) and is_float_dtype(lk): + if not (lk == lk.astype(rk.dtype)).all(): + warnings.warn('You are merging on int and float ' + 'columns where the float values ' + 'are not equal to their int ' + 'representation', UserWarning) + + elif is_float_dtype(rk) and is_integer_dtype(lk): + if not (rk == rk.astype(lk.dtype)).all(): + warnings.warn('You are merging on int and float ' + 'columns where the float values ' + 'are not equal to their int ' + 'representation', UserWarning) # let's infer and see if we are ok - if lib.infer_dtype(lk) == lib.infer_dtype(rk): - continue + elif lib.infer_dtype(lk) == lib.infer_dtype(rk): + pass # Houston, we have a problem! # let's coerce to object if the dtypes aren't @@ -924,14 +939,15 @@ 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. - 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)}) + 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)}) def _validate_specification(self): # Hm, any way to make this logic less complicated?? diff --git a/pandas/tests/reshape/test_merge.py b/pandas/tests/reshape/test_merge.py index 172667c9a0fb8..ee7c4e5c90bb8 100644 --- a/pandas/tests/reshape/test_merge.py +++ b/pandas/tests/reshape/test_merge.py @@ -13,7 +13,10 @@ from pandas.core.reshape.merge import merge, MergeError from pandas.util.testing import assert_frame_equal, assert_series_equal from pandas.core.dtypes.dtypes import CategoricalDtype -from pandas.core.dtypes.common import is_categorical_dtype, is_object_dtype +from pandas.core.dtypes.common import ( + is_categorical_dtype, + is_object_dtype, +) from pandas import DataFrame, Index, MultiIndex, Series, Categorical import pandas.util.testing as tm from pandas.api.types import CategoricalDtype as CDT @@ -1408,6 +1411,42 @@ def test_join_multi_dtypes(self, d1, d2): expected.sort_values(['k1', 'k2'], kind='mergesort', inplace=True) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize('int_vals, float_vals, exp_vals', [ + ([1, 2, 3], [1.0, 2.0, 3.0], {'X': [1, 2, 3], 'Y': [1.0, 2.0, 3.0]}), + ([1, 2, 3], [1.0, 3.0], {'X': [1, 3], 'Y': [1.0, 3.0]}), + ([1, 2], [1.0, 2.0, 3.0], {'X': [1, 2], 'Y': [1.0, 2.0]}), + ]) + def test_merge_on_ints_floats(self, int_vals, float_vals, exp_vals): + # GH 16572 + # Check that float column is not cast to object if + # merging on float and int columns + A = DataFrame({'X': int_vals}) + B = DataFrame({'Y': float_vals}) + expected = DataFrame(exp_vals) + + result = A.merge(B, left_on='X', right_on='Y') + assert_frame_equal(result, expected) + + result = B.merge(A, left_on='Y', right_on='X') + assert_frame_equal(result, expected[['Y', 'X']]) + + def test_merge_on_ints_floats_warning(self): + # GH 16572 + # merge will produce a warning when merging on int and + # float columns where the float values are not exactly + # equal to their int representation + A = DataFrame({'X': [1, 2, 3]}) + B = DataFrame({'Y': [1.1, 2.5, 3.0]}) + expected = DataFrame({'X': [3], 'Y': [3.0]}) + + with tm.assert_produces_warning(UserWarning): + result = A.merge(B, left_on='X', right_on='Y') + assert_frame_equal(result, expected) + + with tm.assert_produces_warning(UserWarning): + result = B.merge(A, left_on='Y', right_on='X') + assert_frame_equal(result, expected[['Y', 'X']]) + @pytest.fixture def left():
- [ ] closes #16572 - [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/18352
2017-11-18T00:47:22Z
2017-11-23T15:56:05Z
2017-11-23T15:56:05Z
2017-11-27T14:50:50Z
CLN: replace %s syntax with .format in tests.io.formats/json/sas
diff --git a/pandas/tests/io/formats/test_css.py b/pandas/tests/io/formats/test_css.py index c07856dc63602..e7adfe4883d98 100644 --- a/pandas/tests/io/formats/test_css.py +++ b/pandas/tests/io/formats/test_css.py @@ -69,25 +69,25 @@ def test_css_parse_invalid(invalid_css, remainder): def test_css_side_shorthands(shorthand, expansions): top, right, bottom, left = expansions - assert_resolves('%s: 1pt' % shorthand, + assert_resolves('{shorthand}: 1pt'.format(shorthand=shorthand), {top: '1pt', right: '1pt', bottom: '1pt', left: '1pt'}) - assert_resolves('%s: 1pt 4pt' % shorthand, + assert_resolves('{shorthand}: 1pt 4pt'.format(shorthand=shorthand), {top: '1pt', right: '4pt', bottom: '1pt', left: '4pt'}) - assert_resolves('%s: 1pt 4pt 2pt' % shorthand, + assert_resolves('{shorthand}: 1pt 4pt 2pt'.format(shorthand=shorthand), {top: '1pt', right: '4pt', bottom: '2pt', left: '4pt'}) - assert_resolves('%s: 1pt 4pt 2pt 0pt' % shorthand, + assert_resolves('{shorthand}: 1pt 4pt 2pt 0pt'.format(shorthand=shorthand), {top: '1pt', right: '4pt', bottom: '2pt', left: '0pt'}) with tm.assert_produces_warning(CSSWarning): - assert_resolves('%s: 1pt 1pt 1pt 1pt 1pt' % shorthand, - {}) + assert_resolves( + '{shorthand}: 1pt 1pt 1pt 1pt 1pt'.format(shorthand=shorthand), {}) @pytest.mark.parametrize('style,inherited,equiv', [ @@ -127,10 +127,10 @@ def test_css_none_absent(style, equiv): @pytest.mark.parametrize('size,resolved', [ ('xx-small', '6pt'), - ('x-small', '%fpt' % 7.5), - ('small', '%fpt' % 9.6), + ('x-small', '{pt:f}pt'.format(pt=7.5)), + ('small', '{pt:f}pt'.format(pt=9.6)), ('medium', '12pt'), - ('large', '%fpt' % 13.5), + ('large', '{pt:f}pt'.format(pt=13.5)), ('x-large', '18pt'), ('xx-large', '24pt'), @@ -149,8 +149,8 @@ def test_css_absolute_font_size(size, relative_to, resolved): inherited = None else: inherited = {'font-size': relative_to} - assert_resolves('font-size: %s' % size, {'font-size': resolved}, - inherited=inherited) + assert_resolves('font-size: {size}'.format(size=size), + {'font-size': resolved}, inherited=inherited) @pytest.mark.parametrize('size,relative_to,resolved', [ @@ -174,7 +174,7 @@ def test_css_absolute_font_size(size, relative_to, resolved): ('smaller', None, '10pt'), ('smaller', '18pt', '15pt'), - ('larger', None, '%fpt' % 14.4), + ('larger', None, '{pt:f}pt'.format(pt=14.4)), ('larger', '15pt', '18pt'), ]) def test_css_relative_font_size(size, relative_to, resolved): @@ -182,5 +182,5 @@ def test_css_relative_font_size(size, relative_to, resolved): inherited = None else: inherited = {'font-size': relative_to} - assert_resolves('font-size: %s' % size, {'font-size': resolved}, - inherited=inherited) + assert_resolves('font-size: {size}'.format(size=size), + {'font-size': resolved}, inherited=inherited) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index e1499565ce4a6..8d2745689cad1 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -313,7 +313,7 @@ def test_repr_max_columns_max_rows(self): "{0} x {1}".format(term_width, term_height)) def mkframe(n): - index = ['%05d' % i for i in range(n)] + index = ['{i:05d}'.format(i=i) for i in range(n)] return DataFrame(0, index, index) df6 = mkframe(6) @@ -465,9 +465,9 @@ def test_to_string_with_formatters(self): 'object': [(1, 2), True, False]}, columns=['int', 'float', 'object']) - formatters = [('int', lambda x: '0x%x' % x), - ('float', lambda x: '[% 4.1f]' % x), - ('object', lambda x: '-%s-' % str(x))] + formatters = [('int', lambda x: '0x{x:x}'.format(x=x)), + ('float', lambda x: '[{x: 4.1f}]'.format(x=x)), + ('object', lambda x: '-{x!s}-'.format(x=x))] result = df.to_string(formatters=dict(formatters)) result2 = df.to_string(formatters=lzip(*formatters)[1]) assert result == (' int float object\n' @@ -500,7 +500,8 @@ def format_func(x): def test_to_string_with_formatters_unicode(self): df = DataFrame({u('c/\u03c3'): [1, 2, 3]}) - result = df.to_string(formatters={u('c/\u03c3'): lambda x: '%s' % x}) + result = df.to_string( + formatters={u('c/\u03c3'): lambda x: '{x}'.format(x=x)}) assert result == u(' c/\u03c3\n') + '0 1\n1 2\n2 3' def test_east_asian_unicode_frame(self): @@ -944,7 +945,7 @@ def test_wide_repr(self): set_option('display.expand_frame_repr', False) rep_str = repr(df) - assert "10 rows x %d columns" % (max_cols - 1) in rep_str + assert "10 rows x {c} columns".format(c=max_cols - 1) in rep_str set_option('display.expand_frame_repr', True) wide_repr = repr(df) assert rep_str != wide_repr @@ -1056,7 +1057,7 @@ def test_long_series(self): n = 1000 s = Series( np.random.randint(-50, 50, n), - index=['s%04d' % x for x in range(n)], dtype='int64') + index=['s{x:04d}'.format(x=x) for x in range(n)], dtype='int64') import re str_rep = str(s) @@ -1174,7 +1175,7 @@ def test_to_string(self): assert header == expected biggie.to_string(columns=['B', 'A'], - formatters={'A': lambda x: '%.1f' % x}) + formatters={'A': lambda x: '{x:.1f}'.format(x=x)}) biggie.to_string(columns=['B', 'A'], float_format=str) biggie.to_string(columns=['B', 'A'], col_space=12, float_format=str) @@ -1269,7 +1270,7 @@ def test_to_string_small_float_values(self): result = df.to_string() # sadness per above - if '%.4g' % 1.7e8 == '1.7e+008': + if '{x:.4g}'.format(x=1.7e8) == '1.7e+008': expected = (' a\n' '0 1.500000e+000\n' '1 1.000000e-017\n' @@ -1456,7 +1457,7 @@ def test_repr_html_long(self): long_repr = df._repr_html_() assert '..' in long_repr assert str(41 + max_rows // 2) not in long_repr - assert u('%d rows ') % h in long_repr + assert u('{h} rows ').format(h=h) in long_repr assert u('2 columns') in long_repr def test_repr_html_float(self): @@ -1478,7 +1479,7 @@ def test_repr_html_float(self): long_repr = df._repr_html_() assert '..' in long_repr assert '31' not in long_repr - assert u('%d rows ') % h in long_repr + assert u('{h} rows ').format(h=h) in long_repr assert u('2 columns') in long_repr def test_repr_html_long_multiindex(self): @@ -1673,7 +1674,7 @@ def test_to_string(self): result = cp.to_string(length=True, name=True, dtype=True) last_line = result.split('\n')[-1].strip() assert last_line == ("Freq: B, Name: foo, " - "Length: %d, dtype: float64" % len(cp)) + "Length: {cp}, dtype: float64".format(cp=len(cp))) def test_freq_name_separation(self): s = Series(np.random.randn(10), @@ -2176,7 +2177,7 @@ def test_to_string_header(self): def _three_digit_exp(): - return '%.4g' % 1.7e8 == '1.7e+008' + return '{x:.4g}'.format(x=1.7e8) == '1.7e+008' class TestFloatArrayFormatter(object): diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 811381e4cbd2a..7335e1ce0f06f 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -22,7 +22,8 @@ def setup_method(self, method): self.g = lambda x: x def h(x, foo='bar'): - return pd.Series(['color: %s' % foo], index=x.index, name=x.name) + return pd.Series( + ['color: {foo}'.format(foo=foo)], index=x.index, name=x.name) self.h = h self.styler = Styler(self.df) @@ -214,7 +215,7 @@ def test_numeric_columns(self): def test_apply_axis(self): df = pd.DataFrame({'A': [0, 0], 'B': [1, 1]}) - f = lambda x: ['val: %s' % x.max() for v in x] + f = lambda x: ['val: {max}'.format(max=x.max()) for v in x] result = df.style.apply(f, axis=1) assert len(result._todo) == 1 assert len(result.ctx) == 0 @@ -658,7 +659,8 @@ def test_highlight_max(self): def test_export(self): f = lambda x: 'color: red' if x > 0 else 'color: blue' - g = lambda x, y, z: 'color: %s' if x > 0 else 'color: %s' % z + g = lambda x, y, z: 'color: {z}'.format(z=z) \ + if x > 0 else 'color: {z}'.format(z=z) style1 = self.styler style1.applymap(f)\ .applymap(g, y='a', z='b')\ diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index 0c8ea98a44d50..082a37a94f75b 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -1435,7 +1435,7 @@ def test_to_html(self): biggie.to_html(columns=['B', 'A'], col_space=17) biggie.to_html(columns=['B', 'A'], - formatters={'A': lambda x: '%.1f' % x}) + formatters={'A': lambda x: '{x:.1f}'.format(x=x)}) biggie.to_html(columns=['B', 'A'], float_format=str) biggie.to_html(columns=['B', 'A'], col_space=12, float_format=str) diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index aa86d1d9231fb..639c11a3d3fbb 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -99,11 +99,11 @@ def test_to_latex_with_formatters(self): datetime(2016, 2, 5), datetime(2016, 3, 3)]}) - formatters = {'int': lambda x: '0x%x' % x, - 'float': lambda x: '[% 4.1f]' % x, - 'object': lambda x: '-%s-' % str(x), + formatters = {'int': lambda x: '0x{x:x}'.format(x=x), + 'float': lambda x: '[{x: 4.1f}]'.format(x=x), + 'object': lambda x: '-{x!s}-'.format(x=x), 'datetime64': lambda x: x.strftime('%Y-%m'), - '__index__': lambda x: 'index: %s' % x} + '__index__': lambda x: 'index: {x}'.format(x=x)} result = df.to_latex(formatters=dict(formatters)) expected = r"""\begin{tabular}{llrrl} diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 6625446bea469..1c895f7e9e89a 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -531,7 +531,8 @@ def __str__(self): # verify the proper conversion of printable content df_printable = DataFrame({'A': [binthing.hexed]}) - assert df_printable.to_json() == '{"A":{"0":"%s"}}' % hexed + assert df_printable.to_json() == \ + '{{"A":{{"0":"{hex}"}}}}'.format(hex=hexed) # check if non-printable content throws appropriate Exception df_nonprintable = DataFrame({'A': [binthing]}) @@ -546,15 +547,16 @@ def __str__(self): # default_handler should resolve exceptions for non-string types assert df_nonprintable.to_json(default_handler=str) == \ - '{"A":{"0":"%s"}}' % hexed + '{{"A":{{"0":"{hex}"}}}}'.format(hex=hexed) assert df_mixed.to_json(default_handler=str) == \ - '{"A":{"0":"%s"},"B":{"0":1}}' % hexed + '{{"A":{{"0":"{hex}"}},"B":{{"0":1}}}}'.format(hex=hexed) def test_label_overflow(self): # GH14256: buffer length not checked when writing label df = pd.DataFrame({'foo': [1337], 'bar' * 100000: [1]}) assert df.to_json() == \ - '{"%s":{"0":1},"foo":{"0":1337}}' % ('bar' * 100000) + '{{"{bar}":{{"0":1}},"foo":{{"0":1337}}}}'.format( + bar=('bar' * 100000)) def test_series_non_unique_index(self): s = Series(['a', 'b'], index=[1, 1]) diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py index 95f23e82fced0..3f61f702b7c9c 100644 --- a/pandas/tests/io/json/test_readlines.py +++ b/pandas/tests/io/json/test_readlines.py @@ -131,7 +131,7 @@ def test_readjson_chunks_closes(chunksize): lines=True, chunksize=chunksize, compression=None) reader.read() assert reader.open_stream.closed, "didn't close stream with \ - chunksize = %s" % chunksize + chunksize = {chunksize}".format(chunksize=chunksize) @pytest.mark.parametrize("chunksize", [0, -1, 2.2, "foo"]) @@ -165,4 +165,5 @@ def test_readjson_chunks_multiple_empty_lines(chunksize): test = pd.read_json(j, lines=True, chunksize=chunksize) if chunksize is not None: test = pd.concat(test) - tm.assert_frame_equal(orig, test, obj="chunksize: %s" % chunksize) + tm.assert_frame_equal( + orig, test, obj="chunksize: {chunksize}".format(chunksize=chunksize)) diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 76fb6d442a25a..18b91bb3d9324 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -394,21 +394,21 @@ def test_encodeTimeConversion(self): ] for test in tests: output = ujson.encode(test) - expected = '"%s"' % test.isoformat() + expected = '"{iso}"'.format(iso=test.isoformat()) assert expected == output def test_encodeTimeConversion_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 = '"%s"' % test.isoformat() + expected = '"{iso}"'.format(iso=test.isoformat()) assert expected == output def test_encodeTimeConversion_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 = '"%s"' % test.isoformat() + expected = '"{iso}"'.format(iso=test.isoformat()) assert expected == output def test_nat(self): @@ -856,9 +856,9 @@ def test_decodeNumberWith32bitSignBit(self): boundary2 = 2**32 # noqa docs = ( '{"id": 3590016419}', - '{"id": %s}' % 2**31, - '{"id": %s}' % 2**32, - '{"id": %s}' % ((2**32) - 1), + '{{"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): diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py index a5546b1198fc6..c059f01ecf3f4 100644 --- a/pandas/tests/io/sas/test_sas7bdat.py +++ b/pandas/tests/io/sas/test_sas7bdat.py @@ -15,7 +15,8 @@ def setup_method(self, method): self.data = [] self.test_ix = [list(range(1, 16)), [16]] for j in 1, 2: - fname = os.path.join(self.dirpath, "test_sas7bdat_%d.csv" % j) + fname = os.path.join( + self.dirpath, "test_sas7bdat_{j}.csv".format(j=j)) df = pd.read_csv(fname) epoch = pd.datetime(1960, 1, 1) t1 = pd.to_timedelta(df["Column4"], unit='d') @@ -37,7 +38,8 @@ def test_from_file(self): for j in 0, 1: df0 = self.data[j] for k in self.test_ix[j]: - fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k) + fname = os.path.join( + self.dirpath, "test{k}.sas7bdat".format(k=k)) df = pd.read_sas(fname, encoding='utf-8') tm.assert_frame_equal(df, df0) @@ -45,7 +47,8 @@ def test_from_buffer(self): for j in 0, 1: df0 = self.data[j] for k in self.test_ix[j]: - fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k) + fname = os.path.join( + self.dirpath, "test{k}.sas7bdat".format(k=k)) with open(fname, 'rb') as f: byts = f.read() buf = io.BytesIO(byts) @@ -59,7 +62,8 @@ def test_from_iterator(self): for j in 0, 1: df0 = self.data[j] for k in self.test_ix[j]: - fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k) + fname = os.path.join( + self.dirpath, "test{k}.sas7bdat".format(k=k)) rdr = pd.read_sas(fname, iterator=True, encoding='utf-8') df = rdr.read(2) tm.assert_frame_equal(df, df0.iloc[0:2, :]) @@ -73,7 +77,8 @@ def test_path_pathlib(self): for j in 0, 1: df0 = self.data[j] for k in self.test_ix[j]: - fname = Path(os.path.join(self.dirpath, "test%d.sas7bdat" % k)) + fname = Path(os.path.join( + self.dirpath, "test{k}.sas7bdat".format(k=k))) df = pd.read_sas(fname, encoding='utf-8') tm.assert_frame_equal(df, df0) @@ -83,8 +88,8 @@ def test_path_localpath(self): for j in 0, 1: df0 = self.data[j] for k in self.test_ix[j]: - fname = LocalPath(os.path.join(self.dirpath, - "test%d.sas7bdat" % k)) + fname = LocalPath(os.path.join( + self.dirpath, "test{k}.sas7bdat".format(k=k))) df = pd.read_sas(fname, encoding='utf-8') tm.assert_frame_equal(df, df0) @@ -93,7 +98,8 @@ def test_iterator_loop(self): for j in 0, 1: for k in self.test_ix[j]: for chunksize in 3, 5, 10, 11: - fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k) + fname = os.path.join( + self.dirpath, "test{k}.sas7bdat".format(k=k)) rdr = pd.read_sas(fname, chunksize=10, encoding='utf-8') y = 0 for x in rdr: @@ -104,7 +110,7 @@ def test_iterator_loop(self): def test_iterator_read_too_much(self): # github #14734 k = self.test_ix[0][0] - fname = os.path.join(self.dirpath, "test%d.sas7bdat" % k) + fname = os.path.join(self.dirpath, "test{k}.sas7bdat".format(k=k)) rdr = pd.read_sas(fname, format="sas7bdat", iterator=True, encoding='utf-8') d1 = rdr.read(rdr.row_count + 20)
- [x] Progress towards #16130 - [x] tests passed - [x] passes git diff upstream/master -u -- "*.py" | flake8 --diff
https://api.github.com/repos/pandas-dev/pandas/pulls/18351
2017-11-18T00:46:52Z
2017-11-19T00:30:46Z
2017-11-19T00:30:46Z
2017-11-19T22:28:52Z
algebra cleanup in FY5253 and Easter offsets
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 615d703f66932..9c8727327d185 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -9,7 +9,6 @@ from pandas.core.common import AbstractMethodError # import after tools, dateutil check -from dateutil.relativedelta import relativedelta, weekday from dateutil.easter import easter from pandas._libs import tslib, Timestamp, OutOfBoundsDatetime, Timedelta from pandas.util._decorators import cache_readonly @@ -1938,10 +1937,7 @@ class FY5253(DateOffset): variation : str {"nearest", "last"} for "LastOfMonth" or "NearestEndMonth" """ - _prefix = 'RE' - _suffix_prefix_last = 'L' - _suffix_prefix_nearest = 'N' _adjust_dst = True def __init__(self, n=1, normalize=False, weekday=0, startingMonth=1, @@ -1963,22 +1959,6 @@ def __init__(self, n=1, normalize=False, weekday=0, startingMonth=1, raise ValueError('{variation} is not a valid variation' .format(variation=self.variation)) - @cache_readonly - def _relativedelta_forward(self): - if self.variation == "nearest": - weekday_offset = weekday(self.weekday) - return relativedelta(weekday=weekday_offset) - else: - return None - - @cache_readonly - def _relativedelta_backward(self): - if self.variation == "nearest": - weekday_offset = weekday(self.weekday) - return relativedelta(weekday=weekday_offset(-1)) - else: - return None - @cache_readonly def _offset_lwom(self): if self.variation == "nearest": @@ -1987,9 +1967,9 @@ def _offset_lwom(self): return LastWeekOfMonth(n=1, weekday=self.weekday) def isAnchored(self): - return self.n == 1 \ - and self.startingMonth is not None \ - and self.weekday is not None + return (self.n == 1 and + self.startingMonth is not None and + self.weekday is not None) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): @@ -2013,63 +1993,45 @@ def apply(self, other): datetime(other.year, self.startingMonth, 1)) 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) - if n > 0: - if other == prev_year: - year = other.year - 1 - elif other == cur_year: - year = other.year - elif other == next_year: - year = other.year + 1 - elif other < prev_year: - year = other.year - 1 - n -= 1 + if other == prev_year: + n -= 1 + elif other == cur_year: + pass + elif other == next_year: + n += 1 + # TODO: Not hit in tests + elif n > 0: + if other < prev_year: + n -= 2 + # TODO: Not hit in tests elif other < cur_year: - year = other.year n -= 1 elif other < next_year: - year = other.year + 1 - n -= 1 + pass else: assert False - - result = self.get_year_end( - datetime(year + n, self.startingMonth, 1)) - - result = datetime(result.year, result.month, result.day, - other.hour, other.minute, other.second, - other.microsecond) - return result else: - n = -n - if other == prev_year: - year = other.year - 1 - elif other == cur_year: - year = other.year - elif other == next_year: - year = other.year + 1 - elif other > next_year: - year = other.year + 1 - n -= 1 + if other > next_year: + n += 2 + # TODO: Not hit in tests elif other > cur_year: - year = other.year - n -= 1 + n += 1 elif other > prev_year: - year = other.year - 1 - n -= 1 + pass else: assert False - result = self.get_year_end( - datetime(year - n, self.startingMonth, 1)) - - result = datetime(result.year, result.month, result.day, - other.hour, other.minute, other.second, - other.microsecond) - return result + shifted = datetime(other.year + n, self.startingMonth, 1) + result = self.get_year_end(shifted) + result = datetime(result.year, result.month, result.day, + other.hour, other.minute, other.second, + other.microsecond) + return result def get_year_end(self, dt): if self.variation == "nearest": @@ -2078,43 +2040,41 @@ def get_year_end(self, dt): return self._get_year_end_last(dt) def get_target_month_end(self, dt): - target_month = datetime( - dt.year, self.startingMonth, 1, tzinfo=dt.tzinfo) - next_month_first_of = shift_month(target_month, 1, None) - return next_month_first_of + timedelta(days=-1) + target_month = datetime(dt.year, self.startingMonth, 1, + tzinfo=dt.tzinfo) + return shift_month(target_month, 0, 'end') + # TODO: is this DST-safe? def _get_year_end_nearest(self, dt): target_date = self.get_target_month_end(dt) - if target_date.weekday() == self.weekday: + wkday_diff = self.weekday - target_date.weekday() + if wkday_diff == 0: return target_date - else: - forward = target_date + self._relativedelta_forward - backward = target_date + self._relativedelta_backward - if forward - target_date < target_date - backward: - return forward - else: - return backward + days_forward = wkday_diff % 7 + if days_forward <= 3: + # The upcoming self.weekday is closer than the previous one + return target_date + timedelta(days_forward) + else: + # The previous self.weekday is closer than the upcoming one + return target_date + timedelta(days_forward - 7) def _get_year_end_last(self, dt): - current_year = datetime( - dt.year, self.startingMonth, 1, tzinfo=dt.tzinfo) + current_year = datetime(dt.year, self.startingMonth, 1, + tzinfo=dt.tzinfo) return current_year + self._offset_lwom @property def rule_code(self): - prefix = self._get_prefix() + prefix = self._prefix suffix = self.get_rule_code_suffix() return "{prefix}-{suffix}".format(prefix=prefix, suffix=suffix) - def _get_prefix(self): - return self._prefix - def _get_suffix_prefix(self): if self.variation == "nearest": - return self._suffix_prefix_nearest + return 'N' else: - return self._suffix_prefix_last + return 'L' def get_rule_code_suffix(self): prefix = self._get_suffix_prefix() @@ -2130,17 +2090,15 @@ def _parse_suffix(cls, varion_code, startingMonth_code, weekday_code): elif varion_code == "L": variation = "last" else: - raise ValueError( - "Unable to parse varion_code: {code}".format(code=varion_code)) + raise ValueError("Unable to parse varion_code: " + "{code}".format(code=varion_code)) startingMonth = _month_to_int[startingMonth_code] weekday = _weekday_to_int[weekday_code] - return { - "weekday": weekday, - "startingMonth": startingMonth, - "variation": variation, - } + return {"weekday": weekday, + "startingMonth": startingMonth, + "variation": variation} @classmethod def _from_name(cls, *args): @@ -2213,10 +2171,9 @@ def __init__(self, n=1, normalize=False, weekday=0, startingMonth=1, @cache_readonly def _offset(self): - return FY5253( - startingMonth=self.startingMonth, - weekday=self.weekday, - variation=self.variation) + return FY5253(startingMonth=self.startingMonth, + weekday=self.weekday, + variation=self.variation) def isAnchored(self): return self.n == 1 and self._offset.isAnchored() @@ -2325,24 +2282,21 @@ class Easter(DateOffset): @apply_wraps def apply(self, other): - currentEaster = easter(other.year) - currentEaster = datetime( - currentEaster.year, currentEaster.month, currentEaster.day) - currentEaster = tslib._localize_pydatetime(currentEaster, other.tzinfo) + 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) + + n = self.n + if n >= 0 and other < current_easter: + n -= 1 + elif n < 0 and other > current_easter: + n += 1 # NOTE: easter returns a datetime.date so we have to convert to type of # other - if self.n >= 0: - if other >= currentEaster: - new = easter(other.year + self.n) - else: - new = easter(other.year + self.n - 1) - else: - if other > currentEaster: - new = easter(other.year + self.n + 1) - else: - new = easter(other.year + self.n) - + new = easter(other.year + n) new = datetime(new.year, new.month, new.day, other.hour, other.minute, other.second, other.microsecond) return new
Same types of cleanups you've gotten used to seeing elsewhere, now applied to FY5253 and Easter. This should be orthogonal to others.
https://api.github.com/repos/pandas-dev/pandas/pulls/18350
2017-11-17T21:18:22Z
2017-11-22T21:01:42Z
2017-11-22T21:01:42Z
2017-12-08T19:38:33Z
parametrize more tests, move to test_liboffstes
diff --git a/pandas/tests/tseries/offsets/test_liboffsets.py b/pandas/tests/tseries/offsets/test_liboffsets.py index e3ec6fdf2fbcc..321104222936b 100644 --- a/pandas/tests/tseries/offsets/test_liboffsets.py +++ b/pandas/tests/tseries/offsets/test_liboffsets.py @@ -6,12 +6,51 @@ import pytest -import pandas as pd +from pandas._libs import tslib +from pandas import Timestamp import pandas._libs.tslibs.offsets as liboffsets +def test_get_lastbday(): + dt = datetime(2017, 11, 30) + assert dt.weekday() == 3 # i.e. this is a business day + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_lastbday(wkday, days_in_month) == 30 + + dt = datetime(1993, 10, 31) + assert dt.weekday() == 6 # i.e. this is not a business day + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_lastbday(wkday, days_in_month) == 29 + + +def test_get_firstbday(): + dt = datetime(2017, 4, 1) + assert dt.weekday() == 5 # i.e. not a weekday + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_firstbday(wkday, days_in_month) == 3 + + dt = datetime(1993, 10, 1) + assert dt.weekday() == 4 # i.e. a business day + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_firstbday(wkday, days_in_month) == 1 + + def test_shift_month(): + dt = datetime(2017, 11, 30) + assert liboffsets.shift_month(dt, 0, 'business_end') == dt + assert liboffsets.shift_month(dt, 0, + 'business_start') == datetime(2017, 11, 1) + + ts = Timestamp('1929-05-05') + assert liboffsets.shift_month(ts, 1, 'start') == Timestamp('1929-06-01') + assert liboffsets.shift_month(ts, -3, 'end') == Timestamp('1929-02-28') + + assert liboffsets.shift_month(ts, 25, None) == Timestamp('1931-06-5') + + # Try to shift to April 31, then shift back to Apr 30 to get a real date + assert liboffsets.shift_month(ts, -1, 31) == Timestamp('1929-04-30') + dt = datetime(2017, 11, 15) assert liboffsets.shift_month(dt, 0, day_opt=None) == dt @@ -45,7 +84,7 @@ def test_roll_yearday(): assert liboffsets.roll_yearday(other, -7, month, day_opt) == -7 assert liboffsets.roll_yearday(other, 0, month, day_opt) == 0 - other = pd.Timestamp('2014-03-15', tz='US/Eastern') # after March 1 + other = Timestamp('2014-03-15', tz='US/Eastern') # after March 1 assert liboffsets.roll_yearday(other, 2, month, day_opt) == 2 assert liboffsets.roll_yearday(other, -7, month, day_opt) == -6 assert liboffsets.roll_yearday(other, 0, month, day_opt) == 1 @@ -57,7 +96,7 @@ def test_roll_yearday(): assert liboffsets.roll_yearday(other, -7, month, day_opt) == -7 assert liboffsets.roll_yearday(other, 0, month, day_opt) == 0 - other = pd.Timestamp(2072, 8, 24, 6, 17, 18) # after June 30 + other = Timestamp(2072, 8, 24, 6, 17, 18) # after June 30 assert liboffsets.roll_yearday(other, 5, month, day_opt) == 5 assert liboffsets.roll_yearday(other, -7, month, day_opt) == -6 assert liboffsets.roll_yearday(other, 0, month, day_opt) == 1 diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 250e57c273603..e0a19b4025555 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -34,7 +34,7 @@ to_datetime, DateParseError) import pandas.tseries.offsets as offsets from pandas.io.pickle import read_pickle -from pandas._libs.tslibs import timezones, offsets as liboffsets +from pandas._libs.tslibs import timezones from pandas._libs.tslib import normalize_date, NaT, Timestamp import pandas._libs.tslib as tslib import pandas.util.testing as tm @@ -2997,79 +2997,80 @@ def test_isAnchored(self): assert BQuarterBegin().isAnchored() assert not BQuarterBegin(2, startingMonth=1).isAnchored() - def test_offset(self): - tests = [] - - tests.append((BQuarterBegin(startingMonth=1), - {datetime(2008, 1, 1): datetime(2008, 4, 1), - datetime(2008, 1, 31): datetime(2008, 4, 1), - datetime(2008, 2, 15): datetime(2008, 4, 1), - datetime(2008, 2, 29): datetime(2008, 4, 1), - datetime(2008, 3, 15): datetime(2008, 4, 1), - datetime(2008, 3, 31): datetime(2008, 4, 1), - datetime(2008, 4, 15): datetime(2008, 7, 1), - datetime(2007, 3, 15): datetime(2007, 4, 2), - datetime(2007, 2, 28): datetime(2007, 4, 2), - datetime(2007, 1, 1): datetime(2007, 4, 2), - datetime(2007, 4, 15): datetime(2007, 7, 2), - datetime(2007, 7, 1): datetime(2007, 7, 2), - datetime(2007, 4, 1): datetime(2007, 4, 2), - datetime(2007, 4, 2): datetime(2007, 7, 2), - datetime(2008, 4, 30): datetime(2008, 7, 1), })) - - tests.append((BQuarterBegin(startingMonth=2), - {datetime(2008, 1, 1): datetime(2008, 2, 1), - datetime(2008, 1, 31): datetime(2008, 2, 1), - datetime(2008, 1, 15): datetime(2008, 2, 1), - datetime(2008, 2, 29): datetime(2008, 5, 1), - datetime(2008, 3, 15): datetime(2008, 5, 1), - datetime(2008, 3, 31): datetime(2008, 5, 1), - datetime(2008, 4, 15): datetime(2008, 5, 1), - datetime(2008, 8, 15): datetime(2008, 11, 3), - datetime(2008, 9, 15): datetime(2008, 11, 3), - datetime(2008, 11, 1): datetime(2008, 11, 3), - datetime(2008, 4, 30): datetime(2008, 5, 1), })) - - tests.append((BQuarterBegin(startingMonth=1, n=0), - {datetime(2008, 1, 1): datetime(2008, 1, 1), - datetime(2007, 12, 31): datetime(2008, 1, 1), - datetime(2008, 2, 15): datetime(2008, 4, 1), - datetime(2008, 2, 29): datetime(2008, 4, 1), - datetime(2008, 1, 15): datetime(2008, 4, 1), - datetime(2008, 2, 27): datetime(2008, 4, 1), - datetime(2008, 3, 15): datetime(2008, 4, 1), - datetime(2007, 4, 1): datetime(2007, 4, 2), - datetime(2007, 4, 2): datetime(2007, 4, 2), - datetime(2007, 7, 1): datetime(2007, 7, 2), - datetime(2007, 4, 15): datetime(2007, 7, 2), - datetime(2007, 7, 2): datetime(2007, 7, 2), })) - - tests.append((BQuarterBegin(startingMonth=1, n=-1), - {datetime(2008, 1, 1): datetime(2007, 10, 1), - datetime(2008, 1, 31): datetime(2008, 1, 1), - datetime(2008, 2, 15): datetime(2008, 1, 1), - datetime(2008, 2, 29): datetime(2008, 1, 1), - datetime(2008, 3, 15): datetime(2008, 1, 1), - datetime(2008, 3, 31): datetime(2008, 1, 1), - datetime(2008, 4, 15): datetime(2008, 4, 1), - datetime(2007, 7, 3): datetime(2007, 7, 2), - datetime(2007, 4, 3): datetime(2007, 4, 2), - datetime(2007, 7, 2): datetime(2007, 4, 2), - datetime(2008, 4, 1): datetime(2008, 1, 1), })) - - tests.append((BQuarterBegin(startingMonth=1, n=2), - {datetime(2008, 1, 1): datetime(2008, 7, 1), - datetime(2008, 1, 15): datetime(2008, 7, 1), - datetime(2008, 2, 29): datetime(2008, 7, 1), - datetime(2008, 3, 15): datetime(2008, 7, 1), - datetime(2007, 3, 31): datetime(2007, 7, 2), - datetime(2007, 4, 15): datetime(2007, 10, 1), - datetime(2008, 4, 30): datetime(2008, 10, 1), })) + offset_cases = [] + offset_cases.append((BQuarterBegin(startingMonth=1), { + datetime(2008, 1, 1): datetime(2008, 4, 1), + datetime(2008, 1, 31): datetime(2008, 4, 1), + datetime(2008, 2, 15): datetime(2008, 4, 1), + datetime(2008, 2, 29): datetime(2008, 4, 1), + datetime(2008, 3, 15): datetime(2008, 4, 1), + datetime(2008, 3, 31): datetime(2008, 4, 1), + datetime(2008, 4, 15): datetime(2008, 7, 1), + datetime(2007, 3, 15): datetime(2007, 4, 2), + datetime(2007, 2, 28): datetime(2007, 4, 2), + datetime(2007, 1, 1): datetime(2007, 4, 2), + datetime(2007, 4, 15): datetime(2007, 7, 2), + datetime(2007, 7, 1): datetime(2007, 7, 2), + datetime(2007, 4, 1): datetime(2007, 4, 2), + datetime(2007, 4, 2): datetime(2007, 7, 2), + datetime(2008, 4, 30): datetime(2008, 7, 1)})) + + offset_cases.append((BQuarterBegin(startingMonth=2), { + datetime(2008, 1, 1): datetime(2008, 2, 1), + datetime(2008, 1, 31): datetime(2008, 2, 1), + datetime(2008, 1, 15): datetime(2008, 2, 1), + datetime(2008, 2, 29): datetime(2008, 5, 1), + datetime(2008, 3, 15): datetime(2008, 5, 1), + datetime(2008, 3, 31): datetime(2008, 5, 1), + datetime(2008, 4, 15): datetime(2008, 5, 1), + datetime(2008, 8, 15): datetime(2008, 11, 3), + datetime(2008, 9, 15): datetime(2008, 11, 3), + datetime(2008, 11, 1): datetime(2008, 11, 3), + datetime(2008, 4, 30): datetime(2008, 5, 1)})) + + offset_cases.append((BQuarterBegin(startingMonth=1, n=0), { + datetime(2008, 1, 1): datetime(2008, 1, 1), + datetime(2007, 12, 31): datetime(2008, 1, 1), + datetime(2008, 2, 15): datetime(2008, 4, 1), + datetime(2008, 2, 29): datetime(2008, 4, 1), + datetime(2008, 1, 15): datetime(2008, 4, 1), + datetime(2008, 2, 27): datetime(2008, 4, 1), + datetime(2008, 3, 15): datetime(2008, 4, 1), + datetime(2007, 4, 1): datetime(2007, 4, 2), + datetime(2007, 4, 2): datetime(2007, 4, 2), + datetime(2007, 7, 1): datetime(2007, 7, 2), + datetime(2007, 4, 15): datetime(2007, 7, 2), + datetime(2007, 7, 2): datetime(2007, 7, 2)})) + + offset_cases.append((BQuarterBegin(startingMonth=1, n=-1), { + datetime(2008, 1, 1): datetime(2007, 10, 1), + datetime(2008, 1, 31): datetime(2008, 1, 1), + datetime(2008, 2, 15): datetime(2008, 1, 1), + datetime(2008, 2, 29): datetime(2008, 1, 1), + datetime(2008, 3, 15): datetime(2008, 1, 1), + datetime(2008, 3, 31): datetime(2008, 1, 1), + datetime(2008, 4, 15): datetime(2008, 4, 1), + datetime(2007, 7, 3): datetime(2007, 7, 2), + datetime(2007, 4, 3): datetime(2007, 4, 2), + datetime(2007, 7, 2): datetime(2007, 4, 2), + datetime(2008, 4, 1): datetime(2008, 1, 1)})) + + offset_cases.append((BQuarterBegin(startingMonth=1, n=2), { + datetime(2008, 1, 1): datetime(2008, 7, 1), + datetime(2008, 1, 15): datetime(2008, 7, 1), + datetime(2008, 2, 29): datetime(2008, 7, 1), + datetime(2008, 3, 15): datetime(2008, 7, 1), + datetime(2007, 3, 31): datetime(2007, 7, 2), + datetime(2007, 4, 15): datetime(2007, 10, 1), + datetime(2008, 4, 30): datetime(2008, 10, 1)})) - for offset, cases in tests: - for base, expected in compat.iteritems(cases): - assert_offset_equal(offset, base, expected) + @pytest.mark.parametrize('case', offset_cases) + def test_offset(self, case): + offset, cases = case + for base, expected in compat.iteritems(cases): + assert_offset_equal(offset, base, expected) + def test_offset_corner_case(self): # corner offset = BQuarterBegin(n=-1, startingMonth=1) assert datetime(2007, 4, 3) + offset == datetime(2007, 4, 2) @@ -3204,58 +3205,55 @@ def makeFY5253LastOfMonth(*args, **kwds): class TestFY5253LastOfMonth(Base): + offset_lom_sat_aug = makeFY5253LastOfMonth(1, startingMonth=8, + weekday=WeekDay.SAT) + offset_lom_sat_sep = makeFY5253LastOfMonth(1, startingMonth=9, + weekday=WeekDay.SAT) - def test_onOffset(self): - - offset_lom_sat_aug = makeFY5253LastOfMonth(1, startingMonth=8, - weekday=WeekDay.SAT) - offset_lom_sat_sep = makeFY5253LastOfMonth(1, startingMonth=9, - weekday=WeekDay.SAT) - - tests = [ - # From Wikipedia (see: - # http://en.wikipedia.org/wiki/4%E2%80%934%E2%80%935_calendar#Last_Saturday_of_the_month_at_fiscal_year_end) - (offset_lom_sat_aug, datetime(2006, 8, 26), True), - (offset_lom_sat_aug, datetime(2007, 8, 25), True), - (offset_lom_sat_aug, datetime(2008, 8, 30), True), - (offset_lom_sat_aug, datetime(2009, 8, 29), True), - (offset_lom_sat_aug, datetime(2010, 8, 28), True), - (offset_lom_sat_aug, datetime(2011, 8, 27), True), - (offset_lom_sat_aug, datetime(2012, 8, 25), True), - (offset_lom_sat_aug, datetime(2013, 8, 31), True), - (offset_lom_sat_aug, datetime(2014, 8, 30), True), - (offset_lom_sat_aug, datetime(2015, 8, 29), True), - (offset_lom_sat_aug, datetime(2016, 8, 27), True), - (offset_lom_sat_aug, datetime(2017, 8, 26), True), - (offset_lom_sat_aug, datetime(2018, 8, 25), True), - (offset_lom_sat_aug, datetime(2019, 8, 31), True), - - (offset_lom_sat_aug, datetime(2006, 8, 27), False), - (offset_lom_sat_aug, datetime(2007, 8, 28), False), - (offset_lom_sat_aug, datetime(2008, 8, 31), False), - (offset_lom_sat_aug, datetime(2009, 8, 30), False), - (offset_lom_sat_aug, datetime(2010, 8, 29), False), - (offset_lom_sat_aug, datetime(2011, 8, 28), False), - - (offset_lom_sat_aug, datetime(2006, 8, 25), False), - (offset_lom_sat_aug, datetime(2007, 8, 24), False), - (offset_lom_sat_aug, datetime(2008, 8, 29), False), - (offset_lom_sat_aug, datetime(2009, 8, 28), False), - (offset_lom_sat_aug, datetime(2010, 8, 27), False), - (offset_lom_sat_aug, datetime(2011, 8, 26), False), - (offset_lom_sat_aug, datetime(2019, 8, 30), False), - - # From GMCR (see for example: - # http://yahoo.brand.edgar-online.com/Default.aspx? - # companyid=3184&formtypeID=7) - (offset_lom_sat_sep, datetime(2010, 9, 25), True), - (offset_lom_sat_sep, datetime(2011, 9, 24), True), - (offset_lom_sat_sep, datetime(2012, 9, 29), True), - - ] + on_offset_cases = [ + # From Wikipedia (see: + # http://en.wikipedia.org/wiki/4%E2%80%934%E2%80%935_calendar#Last_Saturday_of_the_month_at_fiscal_year_end) + (offset_lom_sat_aug, datetime(2006, 8, 26), True), + (offset_lom_sat_aug, datetime(2007, 8, 25), True), + (offset_lom_sat_aug, datetime(2008, 8, 30), True), + (offset_lom_sat_aug, datetime(2009, 8, 29), True), + (offset_lom_sat_aug, datetime(2010, 8, 28), True), + (offset_lom_sat_aug, datetime(2011, 8, 27), True), + (offset_lom_sat_aug, datetime(2012, 8, 25), True), + (offset_lom_sat_aug, datetime(2013, 8, 31), True), + (offset_lom_sat_aug, datetime(2014, 8, 30), True), + (offset_lom_sat_aug, datetime(2015, 8, 29), True), + (offset_lom_sat_aug, datetime(2016, 8, 27), True), + (offset_lom_sat_aug, datetime(2017, 8, 26), True), + (offset_lom_sat_aug, datetime(2018, 8, 25), True), + (offset_lom_sat_aug, datetime(2019, 8, 31), True), + + (offset_lom_sat_aug, datetime(2006, 8, 27), False), + (offset_lom_sat_aug, datetime(2007, 8, 28), False), + (offset_lom_sat_aug, datetime(2008, 8, 31), False), + (offset_lom_sat_aug, datetime(2009, 8, 30), False), + (offset_lom_sat_aug, datetime(2010, 8, 29), False), + (offset_lom_sat_aug, datetime(2011, 8, 28), False), + + (offset_lom_sat_aug, datetime(2006, 8, 25), False), + (offset_lom_sat_aug, datetime(2007, 8, 24), False), + (offset_lom_sat_aug, datetime(2008, 8, 29), False), + (offset_lom_sat_aug, datetime(2009, 8, 28), False), + (offset_lom_sat_aug, datetime(2010, 8, 27), False), + (offset_lom_sat_aug, datetime(2011, 8, 26), False), + (offset_lom_sat_aug, datetime(2019, 8, 30), False), + + # From GMCR (see for example: + # http://yahoo.brand.edgar-online.com/Default.aspx? + # companyid=3184&formtypeID=7) + (offset_lom_sat_sep, datetime(2010, 9, 25), True), + (offset_lom_sat_sep, datetime(2011, 9, 24), True), + (offset_lom_sat_sep, datetime(2012, 9, 29), True)] - for offset, dt, expected in tests: - assert_onOffset(offset, dt, expected) + @pytest.mark.parametrize('case', on_offset_cases) + def test_onOffset(self, case): + offset, dt, expected = case + assert_onOffset(offset, dt, expected) def test_apply(self): offset_lom_aug_sat = makeFY5253LastOfMonth(startingMonth=8, @@ -3333,71 +3331,71 @@ def test_get_year_end(self): assert (JNJ.get_year_end(datetime(2006, 1, 1)) == datetime(2006, 12, 31)) - def test_onOffset(self): - offset_lom_aug_sat = makeFY5253NearestEndMonth(1, startingMonth=8, - weekday=WeekDay.SAT) - offset_lom_aug_thu = makeFY5253NearestEndMonth(1, startingMonth=8, - weekday=WeekDay.THU) - offset_n = FY5253(weekday=WeekDay.TUE, startingMonth=12, - variation="nearest") + offset_lom_aug_sat = makeFY5253NearestEndMonth(1, startingMonth=8, + weekday=WeekDay.SAT) + offset_lom_aug_thu = makeFY5253NearestEndMonth(1, startingMonth=8, + weekday=WeekDay.THU) + offset_n = FY5253(weekday=WeekDay.TUE, startingMonth=12, + variation="nearest") - tests = [ - # From Wikipedia (see: - # http://en.wikipedia.org/wiki/4%E2%80%934%E2%80%935_calendar - # #Saturday_nearest_the_end_of_month) - # 2006-09-02 2006 September 2 - # 2007-09-01 2007 September 1 - # 2008-08-30 2008 August 30 (leap year) - # 2009-08-29 2009 August 29 - # 2010-08-28 2010 August 28 - # 2011-09-03 2011 September 3 - # 2012-09-01 2012 September 1 (leap year) - # 2013-08-31 2013 August 31 - # 2014-08-30 2014 August 30 - # 2015-08-29 2015 August 29 - # 2016-09-03 2016 September 3 (leap year) - # 2017-09-02 2017 September 2 - # 2018-09-01 2018 September 1 - # 2019-08-31 2019 August 31 - (offset_lom_aug_sat, datetime(2006, 9, 2), True), - (offset_lom_aug_sat, datetime(2007, 9, 1), True), - (offset_lom_aug_sat, datetime(2008, 8, 30), True), - (offset_lom_aug_sat, datetime(2009, 8, 29), True), - (offset_lom_aug_sat, datetime(2010, 8, 28), True), - (offset_lom_aug_sat, datetime(2011, 9, 3), True), - - (offset_lom_aug_sat, datetime(2016, 9, 3), True), - (offset_lom_aug_sat, datetime(2017, 9, 2), True), - (offset_lom_aug_sat, datetime(2018, 9, 1), True), - (offset_lom_aug_sat, datetime(2019, 8, 31), True), - - (offset_lom_aug_sat, datetime(2006, 8, 27), False), - (offset_lom_aug_sat, datetime(2007, 8, 28), False), - (offset_lom_aug_sat, datetime(2008, 8, 31), False), - (offset_lom_aug_sat, datetime(2009, 8, 30), False), - (offset_lom_aug_sat, datetime(2010, 8, 29), False), - (offset_lom_aug_sat, datetime(2011, 8, 28), False), - - (offset_lom_aug_sat, datetime(2006, 8, 25), False), - (offset_lom_aug_sat, datetime(2007, 8, 24), False), - (offset_lom_aug_sat, datetime(2008, 8, 29), False), - (offset_lom_aug_sat, datetime(2009, 8, 28), False), - (offset_lom_aug_sat, datetime(2010, 8, 27), False), - (offset_lom_aug_sat, datetime(2011, 8, 26), False), - (offset_lom_aug_sat, datetime(2019, 8, 30), False), - - # From Micron, see: - # http://google.brand.edgar-online.com/?sym=MU&formtypeID=7 - (offset_lom_aug_thu, datetime(2012, 8, 30), True), - (offset_lom_aug_thu, datetime(2011, 9, 1), True), - - (offset_n, datetime(2012, 12, 31), False), - (offset_n, datetime(2013, 1, 1), True), - (offset_n, datetime(2013, 1, 2), False), - ] + on_offset_cases = [ + # From Wikipedia (see: + # http://en.wikipedia.org/wiki/4%E2%80%934%E2%80%935_calendar + # #Saturday_nearest_the_end_of_month) + # 2006-09-02 2006 September 2 + # 2007-09-01 2007 September 1 + # 2008-08-30 2008 August 30 (leap year) + # 2009-08-29 2009 August 29 + # 2010-08-28 2010 August 28 + # 2011-09-03 2011 September 3 + # 2012-09-01 2012 September 1 (leap year) + # 2013-08-31 2013 August 31 + # 2014-08-30 2014 August 30 + # 2015-08-29 2015 August 29 + # 2016-09-03 2016 September 3 (leap year) + # 2017-09-02 2017 September 2 + # 2018-09-01 2018 September 1 + # 2019-08-31 2019 August 31 + (offset_lom_aug_sat, datetime(2006, 9, 2), True), + (offset_lom_aug_sat, datetime(2007, 9, 1), True), + (offset_lom_aug_sat, datetime(2008, 8, 30), True), + (offset_lom_aug_sat, datetime(2009, 8, 29), True), + (offset_lom_aug_sat, datetime(2010, 8, 28), True), + (offset_lom_aug_sat, datetime(2011, 9, 3), True), + + (offset_lom_aug_sat, datetime(2016, 9, 3), True), + (offset_lom_aug_sat, datetime(2017, 9, 2), True), + (offset_lom_aug_sat, datetime(2018, 9, 1), True), + (offset_lom_aug_sat, datetime(2019, 8, 31), True), + + (offset_lom_aug_sat, datetime(2006, 8, 27), False), + (offset_lom_aug_sat, datetime(2007, 8, 28), False), + (offset_lom_aug_sat, datetime(2008, 8, 31), False), + (offset_lom_aug_sat, datetime(2009, 8, 30), False), + (offset_lom_aug_sat, datetime(2010, 8, 29), False), + (offset_lom_aug_sat, datetime(2011, 8, 28), False), + + (offset_lom_aug_sat, datetime(2006, 8, 25), False), + (offset_lom_aug_sat, datetime(2007, 8, 24), False), + (offset_lom_aug_sat, datetime(2008, 8, 29), False), + (offset_lom_aug_sat, datetime(2009, 8, 28), False), + (offset_lom_aug_sat, datetime(2010, 8, 27), False), + (offset_lom_aug_sat, datetime(2011, 8, 26), False), + (offset_lom_aug_sat, datetime(2019, 8, 30), False), + + # From Micron, see: + # http://google.brand.edgar-online.com/?sym=MU&formtypeID=7 + (offset_lom_aug_thu, datetime(2012, 8, 30), True), + (offset_lom_aug_thu, datetime(2011, 9, 1), True), + + (offset_n, datetime(2012, 12, 31), False), + (offset_n, datetime(2013, 1, 1), True), + (offset_n, datetime(2013, 1, 2), False)] - for offset, dt, expected in tests: - assert_onOffset(offset, dt, expected) + @pytest.mark.parametrize('case', on_offset_cases) + def test_onOffset(self, case): + offset, dt, expected = case + assert_onOffset(offset, dt, expected) def test_apply(self): date_seq_nem_8_sat = [datetime(2006, 9, 2), datetime(2007, 9, 1), @@ -3526,78 +3524,78 @@ def test_offset(self): assert_offset_equal(offset_neg1, date, expected) date = date + offset_neg1 - def test_onOffset(self): - lomq_aug_sat_4 = makeFY5253LastOfMonthQuarter(1, startingMonth=8, - weekday=WeekDay.SAT, - qtr_with_extra_week=4) - lomq_sep_sat_4 = makeFY5253LastOfMonthQuarter(1, startingMonth=9, - weekday=WeekDay.SAT, - qtr_with_extra_week=4) + lomq_aug_sat_4 = makeFY5253LastOfMonthQuarter(1, startingMonth=8, + weekday=WeekDay.SAT, + qtr_with_extra_week=4) + lomq_sep_sat_4 = makeFY5253LastOfMonthQuarter(1, startingMonth=9, + weekday=WeekDay.SAT, + qtr_with_extra_week=4) - tests = [ - # From Wikipedia - (lomq_aug_sat_4, datetime(2006, 8, 26), True), - (lomq_aug_sat_4, datetime(2007, 8, 25), True), - (lomq_aug_sat_4, datetime(2008, 8, 30), True), - (lomq_aug_sat_4, datetime(2009, 8, 29), True), - (lomq_aug_sat_4, datetime(2010, 8, 28), True), - (lomq_aug_sat_4, datetime(2011, 8, 27), True), - (lomq_aug_sat_4, datetime(2019, 8, 31), True), - - (lomq_aug_sat_4, datetime(2006, 8, 27), False), - (lomq_aug_sat_4, datetime(2007, 8, 28), False), - (lomq_aug_sat_4, datetime(2008, 8, 31), False), - (lomq_aug_sat_4, datetime(2009, 8, 30), False), - (lomq_aug_sat_4, datetime(2010, 8, 29), False), - (lomq_aug_sat_4, datetime(2011, 8, 28), False), - - (lomq_aug_sat_4, datetime(2006, 8, 25), False), - (lomq_aug_sat_4, datetime(2007, 8, 24), False), - (lomq_aug_sat_4, datetime(2008, 8, 29), False), - (lomq_aug_sat_4, datetime(2009, 8, 28), False), - (lomq_aug_sat_4, datetime(2010, 8, 27), False), - (lomq_aug_sat_4, datetime(2011, 8, 26), False), - (lomq_aug_sat_4, datetime(2019, 8, 30), False), - - # From GMCR - (lomq_sep_sat_4, datetime(2010, 9, 25), True), - (lomq_sep_sat_4, datetime(2011, 9, 24), True), - (lomq_sep_sat_4, datetime(2012, 9, 29), True), - - (lomq_sep_sat_4, datetime(2013, 6, 29), True), - (lomq_sep_sat_4, datetime(2012, 6, 23), True), - (lomq_sep_sat_4, datetime(2012, 6, 30), False), - - (lomq_sep_sat_4, datetime(2013, 3, 30), True), - (lomq_sep_sat_4, datetime(2012, 3, 24), True), - - (lomq_sep_sat_4, datetime(2012, 12, 29), True), - (lomq_sep_sat_4, datetime(2011, 12, 24), True), - - # INTC (extra week in Q1) - # See: http://www.intc.com/releasedetail.cfm?ReleaseID=542844 - (makeFY5253LastOfMonthQuarter(1, startingMonth=12, - weekday=WeekDay.SAT, - qtr_with_extra_week=1), - datetime(2011, 4, 2), True), - - # see: http://google.brand.edgar-online.com/?sym=INTC&formtypeID=7 - (makeFY5253LastOfMonthQuarter(1, startingMonth=12, - weekday=WeekDay.SAT, - qtr_with_extra_week=1), - datetime(2012, 12, 29), True), - (makeFY5253LastOfMonthQuarter(1, startingMonth=12, - weekday=WeekDay.SAT, - qtr_with_extra_week=1), - datetime(2011, 12, 31), True), - (makeFY5253LastOfMonthQuarter(1, startingMonth=12, - weekday=WeekDay.SAT, - qtr_with_extra_week=1), - datetime(2010, 12, 25), True), - ] + on_offset_cases = [ + # From Wikipedia + (lomq_aug_sat_4, datetime(2006, 8, 26), True), + (lomq_aug_sat_4, datetime(2007, 8, 25), True), + (lomq_aug_sat_4, datetime(2008, 8, 30), True), + (lomq_aug_sat_4, datetime(2009, 8, 29), True), + (lomq_aug_sat_4, datetime(2010, 8, 28), True), + (lomq_aug_sat_4, datetime(2011, 8, 27), True), + (lomq_aug_sat_4, datetime(2019, 8, 31), True), + + (lomq_aug_sat_4, datetime(2006, 8, 27), False), + (lomq_aug_sat_4, datetime(2007, 8, 28), False), + (lomq_aug_sat_4, datetime(2008, 8, 31), False), + (lomq_aug_sat_4, datetime(2009, 8, 30), False), + (lomq_aug_sat_4, datetime(2010, 8, 29), False), + (lomq_aug_sat_4, datetime(2011, 8, 28), False), + + (lomq_aug_sat_4, datetime(2006, 8, 25), False), + (lomq_aug_sat_4, datetime(2007, 8, 24), False), + (lomq_aug_sat_4, datetime(2008, 8, 29), False), + (lomq_aug_sat_4, datetime(2009, 8, 28), False), + (lomq_aug_sat_4, datetime(2010, 8, 27), False), + (lomq_aug_sat_4, datetime(2011, 8, 26), False), + (lomq_aug_sat_4, datetime(2019, 8, 30), False), + + # From GMCR + (lomq_sep_sat_4, datetime(2010, 9, 25), True), + (lomq_sep_sat_4, datetime(2011, 9, 24), True), + (lomq_sep_sat_4, datetime(2012, 9, 29), True), + + (lomq_sep_sat_4, datetime(2013, 6, 29), True), + (lomq_sep_sat_4, datetime(2012, 6, 23), True), + (lomq_sep_sat_4, datetime(2012, 6, 30), False), + + (lomq_sep_sat_4, datetime(2013, 3, 30), True), + (lomq_sep_sat_4, datetime(2012, 3, 24), True), + + (lomq_sep_sat_4, datetime(2012, 12, 29), True), + (lomq_sep_sat_4, datetime(2011, 12, 24), True), + + # INTC (extra week in Q1) + # See: http://www.intc.com/releasedetail.cfm?ReleaseID=542844 + (makeFY5253LastOfMonthQuarter(1, startingMonth=12, + weekday=WeekDay.SAT, + qtr_with_extra_week=1), + datetime(2011, 4, 2), True), + + # see: http://google.brand.edgar-online.com/?sym=INTC&formtypeID=7 + (makeFY5253LastOfMonthQuarter(1, startingMonth=12, + weekday=WeekDay.SAT, + qtr_with_extra_week=1), + datetime(2012, 12, 29), True), + (makeFY5253LastOfMonthQuarter(1, startingMonth=12, + weekday=WeekDay.SAT, + qtr_with_extra_week=1), + datetime(2011, 12, 31), True), + (makeFY5253LastOfMonthQuarter(1, startingMonth=12, + weekday=WeekDay.SAT, + qtr_with_extra_week=1), + datetime(2010, 12, 25), True)] - for offset, dt, expected in tests: - assert_onOffset(offset, dt, expected) + @pytest.mark.parametrize('case', on_offset_cases) + def test_onOffset(self, case): + offset, dt, expected = case + assert_onOffset(offset, dt, expected) def test_year_has_extra_week(self): # End of long Q1 @@ -3651,66 +3649,65 @@ def test_get_weeks(self): class TestFY5253NearestEndMonthQuarter(Base): - def test_onOffset(self): - - offset_nem_sat_aug_4 = makeFY5253NearestEndMonthQuarter( - 1, startingMonth=8, weekday=WeekDay.SAT, - qtr_with_extra_week=4) - offset_nem_thu_aug_4 = makeFY5253NearestEndMonthQuarter( - 1, startingMonth=8, weekday=WeekDay.THU, - qtr_with_extra_week=4) - offset_n = FY5253(weekday=WeekDay.TUE, startingMonth=12, - variation="nearest") + offset_nem_sat_aug_4 = makeFY5253NearestEndMonthQuarter( + 1, startingMonth=8, weekday=WeekDay.SAT, + qtr_with_extra_week=4) + offset_nem_thu_aug_4 = makeFY5253NearestEndMonthQuarter( + 1, startingMonth=8, weekday=WeekDay.THU, + qtr_with_extra_week=4) + offset_n = FY5253(weekday=WeekDay.TUE, startingMonth=12, + variation="nearest") - tests = [ - # From Wikipedia - (offset_nem_sat_aug_4, datetime(2006, 9, 2), True), - (offset_nem_sat_aug_4, datetime(2007, 9, 1), True), - (offset_nem_sat_aug_4, datetime(2008, 8, 30), True), - (offset_nem_sat_aug_4, datetime(2009, 8, 29), True), - (offset_nem_sat_aug_4, datetime(2010, 8, 28), True), - (offset_nem_sat_aug_4, datetime(2011, 9, 3), True), - - (offset_nem_sat_aug_4, datetime(2016, 9, 3), True), - (offset_nem_sat_aug_4, datetime(2017, 9, 2), True), - (offset_nem_sat_aug_4, datetime(2018, 9, 1), True), - (offset_nem_sat_aug_4, datetime(2019, 8, 31), True), - - (offset_nem_sat_aug_4, datetime(2006, 8, 27), False), - (offset_nem_sat_aug_4, datetime(2007, 8, 28), False), - (offset_nem_sat_aug_4, datetime(2008, 8, 31), False), - (offset_nem_sat_aug_4, datetime(2009, 8, 30), False), - (offset_nem_sat_aug_4, datetime(2010, 8, 29), False), - (offset_nem_sat_aug_4, datetime(2011, 8, 28), False), - - (offset_nem_sat_aug_4, datetime(2006, 8, 25), False), - (offset_nem_sat_aug_4, datetime(2007, 8, 24), False), - (offset_nem_sat_aug_4, datetime(2008, 8, 29), False), - (offset_nem_sat_aug_4, datetime(2009, 8, 28), False), - (offset_nem_sat_aug_4, datetime(2010, 8, 27), False), - (offset_nem_sat_aug_4, datetime(2011, 8, 26), False), - (offset_nem_sat_aug_4, datetime(2019, 8, 30), False), - - # From Micron, see: - # http://google.brand.edgar-online.com/?sym=MU&formtypeID=7 - (offset_nem_thu_aug_4, datetime(2012, 8, 30), True), - (offset_nem_thu_aug_4, datetime(2011, 9, 1), True), - - # See: http://google.brand.edgar-online.com/?sym=MU&formtypeID=13 - (offset_nem_thu_aug_4, datetime(2013, 5, 30), True), - (offset_nem_thu_aug_4, datetime(2013, 2, 28), True), - (offset_nem_thu_aug_4, datetime(2012, 11, 29), True), - (offset_nem_thu_aug_4, datetime(2012, 5, 31), True), - (offset_nem_thu_aug_4, datetime(2007, 3, 1), True), - (offset_nem_thu_aug_4, datetime(1994, 3, 3), True), - - (offset_n, datetime(2012, 12, 31), False), - (offset_n, datetime(2013, 1, 1), True), - (offset_n, datetime(2013, 1, 2), False) - ] + on_offset_cases = [ + # From Wikipedia + (offset_nem_sat_aug_4, datetime(2006, 9, 2), True), + (offset_nem_sat_aug_4, datetime(2007, 9, 1), True), + (offset_nem_sat_aug_4, datetime(2008, 8, 30), True), + (offset_nem_sat_aug_4, datetime(2009, 8, 29), True), + (offset_nem_sat_aug_4, datetime(2010, 8, 28), True), + (offset_nem_sat_aug_4, datetime(2011, 9, 3), True), + + (offset_nem_sat_aug_4, datetime(2016, 9, 3), True), + (offset_nem_sat_aug_4, datetime(2017, 9, 2), True), + (offset_nem_sat_aug_4, datetime(2018, 9, 1), True), + (offset_nem_sat_aug_4, datetime(2019, 8, 31), True), + + (offset_nem_sat_aug_4, datetime(2006, 8, 27), False), + (offset_nem_sat_aug_4, datetime(2007, 8, 28), False), + (offset_nem_sat_aug_4, datetime(2008, 8, 31), False), + (offset_nem_sat_aug_4, datetime(2009, 8, 30), False), + (offset_nem_sat_aug_4, datetime(2010, 8, 29), False), + (offset_nem_sat_aug_4, datetime(2011, 8, 28), False), + + (offset_nem_sat_aug_4, datetime(2006, 8, 25), False), + (offset_nem_sat_aug_4, datetime(2007, 8, 24), False), + (offset_nem_sat_aug_4, datetime(2008, 8, 29), False), + (offset_nem_sat_aug_4, datetime(2009, 8, 28), False), + (offset_nem_sat_aug_4, datetime(2010, 8, 27), False), + (offset_nem_sat_aug_4, datetime(2011, 8, 26), False), + (offset_nem_sat_aug_4, datetime(2019, 8, 30), False), + + # From Micron, see: + # http://google.brand.edgar-online.com/?sym=MU&formtypeID=7 + (offset_nem_thu_aug_4, datetime(2012, 8, 30), True), + (offset_nem_thu_aug_4, datetime(2011, 9, 1), True), + + # See: http://google.brand.edgar-online.com/?sym=MU&formtypeID=13 + (offset_nem_thu_aug_4, datetime(2013, 5, 30), True), + (offset_nem_thu_aug_4, datetime(2013, 2, 28), True), + (offset_nem_thu_aug_4, datetime(2012, 11, 29), True), + (offset_nem_thu_aug_4, datetime(2012, 5, 31), True), + (offset_nem_thu_aug_4, datetime(2007, 3, 1), True), + (offset_nem_thu_aug_4, datetime(1994, 3, 3), True), + + (offset_n, datetime(2012, 12, 31), False), + (offset_n, datetime(2013, 1, 1), True), + (offset_n, datetime(2013, 1, 2), False)] - for offset, dt, expected in tests: - assert_onOffset(offset, dt, expected) + @pytest.mark.parametrize('case', on_offset_cases) + def test_onOffset(self, case): + offset, dt, expected = case + assert_onOffset(offset, dt, expected) def test_offset(self): offset = makeFY5253NearestEndMonthQuarter(1, startingMonth=8, @@ -4683,43 +4680,3 @@ def test_all_offset_classes(self, tup): first = Timestamp(test_values[0], tz='US/Eastern') + offset() second = Timestamp(test_values[1], tz='US/Eastern') assert first == second - - -def test_get_lastbday(): - dt = datetime(2017, 11, 30) - assert dt.weekday() == 3 # i.e. this is a business day - wkday, days_in_month = tslib.monthrange(dt.year, dt.month) - assert liboffsets.get_lastbday(wkday, days_in_month) == 30 - - dt = datetime(1993, 10, 31) - assert dt.weekday() == 6 # i.e. this is not a business day - wkday, days_in_month = tslib.monthrange(dt.year, dt.month) - assert liboffsets.get_lastbday(wkday, days_in_month) == 29 - - -def test_get_firstbday(): - dt = datetime(2017, 4, 1) - assert dt.weekday() == 5 # i.e. not a weekday - wkday, days_in_month = tslib.monthrange(dt.year, dt.month) - assert liboffsets.get_firstbday(wkday, days_in_month) == 3 - - dt = datetime(1993, 10, 1) - assert dt.weekday() == 4 # i.e. a business day - wkday, days_in_month = tslib.monthrange(dt.year, dt.month) - assert liboffsets.get_firstbday(wkday, days_in_month) == 1 - - -def test_shift_month(): - dt = datetime(2017, 11, 30) - assert liboffsets.shift_month(dt, 0, 'business_end') == dt - assert liboffsets.shift_month(dt, 0, - 'business_start') == datetime(2017, 11, 1) - - ts = Timestamp('1929-05-05') - assert liboffsets.shift_month(ts, 1, 'start') == Timestamp('1929-06-01') - assert liboffsets.shift_month(ts, -3, 'end') == Timestamp('1929-02-28') - - assert liboffsets.shift_month(ts, 25, None) == Timestamp('1931-06-5') - - # Try to shift to April 31, then shift back to Apr 30 to get a real date - assert liboffsets.shift_month(ts, -1, 31) == Timestamp('1929-04-30')
Some tests currently in test_offsets belong in test_liboffsets, this moves them. There is a test_shift_month in test_offsets and another in test_liboffsets. This combines them. Continuing the process of making the big lists of tests in test_offsets use pytest.mark.parametrize. Is there any downside to doing this? e.g. when it collects the tests, will it hold them all in memory (instead of as a generator)? - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/18346
2017-11-17T15:23:15Z
2017-11-19T00:48:51Z
2017-11-19T00:48:51Z
2017-12-08T19:38:36Z
CI: remove pandas-gbq
diff --git a/ci/requirements-3.6.sh b/ci/requirements-3.6.sh index dfc123c88f24b..f5c3dbf59a29d 100644 --- a/ci/requirements-3.6.sh +++ b/ci/requirements-3.6.sh @@ -4,4 +4,4 @@ source activate pandas echo "[install 3.6 downstream deps]" -conda install -n pandas -c conda-forge pandas-gbq pandas-datareader xarray geopandas seaborn statsmodels scikit-learn dask +conda install -n pandas -c conda-forge pandas-datareader xarray geopandas seaborn statsmodels scikit-learn dask
https://api.github.com/repos/pandas-dev/pandas/pulls/18343
2017-11-17T12:10:54Z
2017-11-17T12:33:55Z
2017-11-17T12:33:55Z
2017-12-08T18:51:39Z
Revert "Revert "MAINT: Remove Long and WidePanel (#15748)" (#15802)"
diff --git a/asv_bench/benchmarks/pandas_vb_common.py b/asv_bench/benchmarks/pandas_vb_common.py index c0d24afae4219..e255cd94f265b 100644 --- a/asv_bench/benchmarks/pandas_vb_common.py +++ b/asv_bench/benchmarks/pandas_vb_common.py @@ -2,10 +2,7 @@ from importlib import import_module import numpy as np -try: - from pandas import Panel -except ImportError: - from pandas import WidePanel as Panel # noqa +from pandas import Panel # Compatibility import for lib for imp in ['pandas._libs.lib', 'pandas.lib']: diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3886b6c142305..b94377af770f4 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -45,6 +45,7 @@ Deprecations Removal of prior version deprecations/changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +- The ``LongPanel`` and ``WidePanel`` classes have been removed (:issue:`10892`) - - - diff --git a/pandas/core/api.py b/pandas/core/api.py index 640baf31268a7..fa58e932ead13 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -21,7 +21,7 @@ from pandas.core.series import Series from pandas.core.frame import DataFrame -from pandas.core.panel import Panel, WidePanel +from pandas.core.panel import Panel # TODO: Remove import when statsmodels updates #18264 from pandas.core.reshape.reshape import get_dummies diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 16e64192fdb20..fe46b8a66e5ef 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -1533,24 +1533,3 @@ def _extract_axis(self, data, axis=0, intersect=False): ops.add_special_arithmetic_methods(Panel) ops.add_flex_arithmetic_methods(Panel) Panel._add_numeric_operations() - - -# legacy -class WidePanel(Panel): - - def __init__(self, *args, **kwargs): - # deprecation, #10892 - warnings.warn("WidePanel is deprecated. Please use Panel", - FutureWarning, stacklevel=2) - - super(WidePanel, self).__init__(*args, **kwargs) - - -class LongPanel(DataFrame): - - def __init__(self, *args, **kwargs): - # deprecation, #10892 - warnings.warn("LongPanel is deprecated. Please use DataFrame", - FutureWarning, stacklevel=2) - - super(LongPanel, self).__init__(*args, **kwargs) diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index ea6c250420b13..ddee4894456ea 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -50,7 +50,7 @@ class TestPDApi(Base): 'TimedeltaIndex', 'Timestamp', 'Interval', 'IntervalIndex'] # these are already deprecated; awaiting removal - deprecated_classes = ['WidePanel', 'TimeGrouper', 'Expr', 'Term'] + deprecated_classes = ['TimeGrouper', 'Expr', 'Term'] # these should be deprecated in the future deprecated_classes_in_future = ['Panel'] diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 5ac91c15047ff..381a059244858 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -3006,9 +3006,6 @@ def _check(left, right): wp = tm.makePanel() self._check_roundtrip(wp.to_frame(), _check) - def test_longpanel(self): - pass - def test_overwrite_node(self): with ensure_clean_store(self.path) as store: diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 7973b27601237..12d803a76e7f3 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -183,10 +183,6 @@ def wrapper(x): class SafeForSparse(object): - @classmethod - def assert_panel_equal(cls, x, y): - assert_panel_equal(x, y) - def test_get_axis(self): assert (self.panel._get_axis(0) is self.panel.items) assert (self.panel._get_axis(1) is self.panel.major_axis) @@ -477,8 +473,6 @@ def test_delitem_and_pop(self): def test_setitem(self): with catch_warnings(record=True): - - # LongPanel with one item lp = self.panel.filter(['ItemA', 'ItemB']).to_frame() with pytest.raises(ValueError): self.panel['ItemE'] = lp @@ -905,10 +899,6 @@ def test_set_value(self): class TestPanel(PanelTests, CheckIndexing, SafeForLongAndSparse, SafeForSparse): - @classmethod - def assert_panel_equal(cls, x, y): - assert_panel_equal(x, y) - def setup_method(self, method): self.panel = make_test_panel() self.panel.major_axis.name = None @@ -2154,8 +2144,8 @@ def test_multiindex_get(self): assert (f1.items == [1, 2]).all() assert (f2.items == [1, 2]).all() - ind = MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1)], - names=['first', 'second']) + MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1)], + names=['first', 'second']) def test_multiindex_blocks(self): with catch_warnings(record=True): @@ -2462,9 +2452,9 @@ def test_sort_values(self): pytest.raises(NotImplementedError, self.panel.sort_values, 'ItemA') -class TestLongPanel(object): +class TestPanelFrame(object): """ - LongPanel no longer exists, but... + Check that conversions to and from Panel to DataFrame work. """ def setup_method(self, method):
With https://github.com/statsmodels/statsmodels/issues/3580 now resolved, we can safely revert #15802
https://api.github.com/repos/pandas-dev/pandas/pulls/18341
2017-11-17T09:12:22Z
2018-05-16T13:32:20Z
2018-05-16T13:32:20Z
2018-05-19T23:25:15Z
BUG: Fix IntervalIndex constructor and copy with non-default closed
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 0ab536f2898c7..83aa2d96f565c 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -62,6 +62,8 @@ Bug Fixes - Bug in ``pd.Series.rolling.skew()`` and ``rolling.kurt()`` with all equal values has floating issue (:issue:`18044`) - Bug in ``pd.DataFrameGroupBy.count()`` when counting over a datetimelike column (:issue:`13393`) - Bug in ``pd.concat`` when empty and non-empty DataFrames or Series are concatenated (:issue:`18178` :issue:`18187`) +- Bug in :class:`IntervalIndex` constructor when a list of intervals is passed with non-default ``closed`` (:issue:`18334`) +- Bug in :meth:`IntervalIndex.copy` when copying and ``IntervalIndex`` with non-default ``closed`` (:issue:`18339`) Conversion ^^^^^^^^^^ diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 6ae55b063b676..ca9deaa722d9d 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -190,7 +190,7 @@ def __new__(cls, data, closed='right', if isinstance(data, IntervalIndex): left = data.left right = data.right - + closed = data.closed else: # don't allow scalars @@ -198,7 +198,7 @@ def __new__(cls, data, closed='right', cls._scalar_data_error(data) data = IntervalIndex.from_intervals(data, name=name) - left, right = data.left, data.right + left, right, closed = data.left, data.right, data.closed return cls._simple_new(left, right, closed, name, copy=copy, verify_integrity=verify_integrity) @@ -580,7 +580,8 @@ def copy(self, deep=False, name=None): left = self.left.copy(deep=True) if deep else self.left right = self.right.copy(deep=True) if deep else self.right name = name if name is not None else self.name - return type(self).from_arrays(left, right, name=name) + closed = self.closed + return type(self).from_arrays(left, right, closed=closed, name=name) @Appender(_index_shared_docs['astype']) def astype(self, dtype, copy=True): diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index b55bab3a210cc..399d88309072e 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -6,6 +6,7 @@ from pandas import (Interval, IntervalIndex, Index, isna, interval_range, Timestamp, Timedelta, compat, date_range, timedelta_range, DateOffset) +from pandas.compat import zip from pandas.tseries.offsets import Day from pandas._libs.interval import IntervalTree from pandas.tests.indexes.common import Base @@ -13,6 +14,11 @@ import pandas as pd +@pytest.fixture(scope='class', params=['left', 'right', 'both', 'neither']) +def closed(request): + return request.param + + class TestIntervalIndex(Base): _holder = IntervalIndex @@ -22,34 +28,63 @@ def setup_method(self, method): [(0, 1), np.nan, (1, 2)]) self.indices = dict(intervalIndex=tm.makeIntervalIndex(10)) - def create_index(self): - return IntervalIndex.from_breaks(np.arange(10)) + def create_index(self, closed='right'): + return IntervalIndex.from_breaks(np.arange(3), closed=closed) - def test_constructors(self): - expected = self.index - actual = IntervalIndex.from_breaks(np.arange(3), closed='right') - assert expected.equals(actual) + def create_index_with_nan(self, closed='right'): + return IntervalIndex.from_tuples( + [(0, 1), np.nan, (1, 2)], closed=closed) - alternate = IntervalIndex.from_breaks(np.arange(3), closed='left') - assert not expected.equals(alternate) + @pytest.mark.parametrize('name', [None, 'foo']) + def test_constructors(self, closed, name): + left, right = Index([0, 1, 2, 3]), Index([1, 2, 3, 4]) + ivs = [Interval(l, r, closed=closed) for l, r in zip(left, right)] + expected = IntervalIndex._simple_new( + left=left, right=right, closed=closed, name=name) - actual = IntervalIndex.from_intervals([Interval(0, 1), Interval(1, 2)]) - assert expected.equals(actual) + result = IntervalIndex(ivs, name=name) + tm.assert_index_equal(result, expected) - actual = IntervalIndex([Interval(0, 1), Interval(1, 2)]) - assert expected.equals(actual) + result = IntervalIndex.from_intervals(ivs, name=name) + tm.assert_index_equal(result, expected) - actual = IntervalIndex.from_arrays(np.arange(2), np.arange(2) + 1, - closed='right') - assert expected.equals(actual) + result = IntervalIndex.from_breaks( + np.arange(5), closed=closed, name=name) + tm.assert_index_equal(result, expected) - actual = Index([Interval(0, 1), Interval(1, 2)]) - assert isinstance(actual, IntervalIndex) - assert expected.equals(actual) + result = IntervalIndex.from_arrays( + left.values, right.values, closed=closed, name=name) + tm.assert_index_equal(result, expected) - actual = Index(expected) - assert isinstance(actual, IntervalIndex) - assert expected.equals(actual) + result = IntervalIndex.from_tuples( + zip(left, right), closed=closed, name=name) + tm.assert_index_equal(result, expected) + + result = Index(ivs, name=name) + assert isinstance(result, IntervalIndex) + tm.assert_index_equal(result, expected) + + # idempotent + tm.assert_index_equal(Index(expected), expected) + tm.assert_index_equal(IntervalIndex(expected), expected) + + result = IntervalIndex.from_intervals( + expected.values, name=expected.name) + tm.assert_index_equal(result, expected) + + left, right = expected.left, expected.right + result = IntervalIndex.from_arrays( + left, right, closed=expected.closed, name=expected.name) + tm.assert_index_equal(result, expected) + + result = IntervalIndex.from_tuples( + expected.to_tuples(), closed=expected.closed, name=expected.name) + tm.assert_index_equal(result, expected) + + breaks = expected.left.tolist() + [expected.right[-1]] + result = IntervalIndex.from_breaks( + breaks, closed=expected.closed, name=expected.name) + tm.assert_index_equal(result, expected) def test_constructors_other(self): @@ -66,43 +101,57 @@ def test_constructors_other(self): def test_constructors_errors(self): # scalar - with pytest.raises(TypeError): + msg = ('IntervalIndex(...) must be called with a collection of ' + 'some kind, 5 was passed') + with pytest.raises(TypeError, message=msg): IntervalIndex(5) # not an interval - with pytest.raises(TypeError): + msg = "type <class 'numpy.int32'> with value 0 is not an interval" + with pytest.raises(TypeError, message=msg): IntervalIndex([0, 1]) - with pytest.raises(TypeError): + with pytest.raises(TypeError, message=msg): IntervalIndex.from_intervals([0, 1]) # invalid closed - with pytest.raises(ValueError): + msg = "invalid options for 'closed': invalid" + with pytest.raises(ValueError, message=msg): IntervalIndex.from_arrays([0, 1], [1, 2], closed='invalid') # mismatched closed - with pytest.raises(ValueError): + msg = 'intervals must all be closed on the same side' + with pytest.raises(ValueError, message=msg): IntervalIndex.from_intervals([Interval(0, 1), Interval(1, 2, closed='left')]) - with pytest.raises(ValueError): + with pytest.raises(ValueError, message=msg): IntervalIndex.from_arrays([0, 10], [3, 5]) - with pytest.raises(ValueError): + with pytest.raises(ValueError, message=msg): Index([Interval(0, 1), Interval(2, 3, closed='left')]) # no point in nesting periods in an IntervalIndex - with pytest.raises(ValueError): + msg = 'Period dtypes are not supported, use a PeriodIndex instead' + with pytest.raises(ValueError, message=msg): IntervalIndex.from_breaks( pd.period_range('2000-01-01', periods=3)) - def test_constructors_datetimelike(self): + # decreasing breaks/arrays + msg = 'left side of interval must be <= right side' + with pytest.raises(ValueError, message=msg): + IntervalIndex.from_breaks(range(10, -1, -1)) + + with pytest.raises(ValueError, message=msg): + IntervalIndex.from_arrays(range(10, -1, -1), range(9, -2, -1)) + + def test_constructors_datetimelike(self, closed): # DTI / TDI for idx in [pd.date_range('20130101', periods=5), pd.timedelta_range('1 day', periods=5)]: - result = IntervalIndex.from_breaks(idx) - expected = IntervalIndex.from_breaks(idx.values) + result = IntervalIndex.from_breaks(idx, closed=closed) + expected = IntervalIndex.from_breaks(idx.values, closed=closed) tm.assert_index_equal(result, expected) expected_scalar_type = type(idx[0]) @@ -117,8 +166,8 @@ def f(): IntervalIndex.from_intervals([0.997, 4.0]) pytest.raises(TypeError, f) - def test_properties(self): - index = self.index + def test_properties(self, closed): + index = self.create_index(closed=closed) assert len(index) == 2 assert index.size == 2 assert index.shape == (2, ) @@ -127,14 +176,15 @@ def test_properties(self): tm.assert_index_equal(index.right, Index([1, 2])) tm.assert_index_equal(index.mid, Index([0.5, 1.5])) - assert index.closed == 'right' + assert index.closed == closed - expected = np.array([Interval(0, 1), Interval(1, 2)], dtype=object) + expected = np.array([Interval(0, 1, closed=closed), + Interval(1, 2, closed=closed)], dtype=object) tm.assert_numpy_array_equal(np.asarray(index), expected) tm.assert_numpy_array_equal(index.values, expected) # with nans - index = self.index_with_nan + index = self.create_index_with_nan(closed=closed) assert len(index) == 3 assert index.size == 3 assert index.shape == (3, ) @@ -143,41 +193,43 @@ def test_properties(self): tm.assert_index_equal(index.right, Index([1, np.nan, 2])) tm.assert_index_equal(index.mid, Index([0.5, np.nan, 1.5])) - assert index.closed == 'right' + assert index.closed == closed - expected = np.array([Interval(0, 1), np.nan, - Interval(1, 2)], dtype=object) + expected = np.array([Interval(0, 1, closed=closed), np.nan, + Interval(1, 2, closed=closed)], dtype=object) tm.assert_numpy_array_equal(np.asarray(index), expected) tm.assert_numpy_array_equal(index.values, expected) - def test_with_nans(self): - index = self.index + def test_with_nans(self, closed): + index = self.create_index(closed=closed) assert not index.hasnans tm.assert_numpy_array_equal(index.isna(), np.array([False, False])) tm.assert_numpy_array_equal(index.notna(), np.array([True, True])) - index = self.index_with_nan + index = self.create_index_with_nan(closed=closed) assert index.hasnans tm.assert_numpy_array_equal(index.notna(), np.array([True, False, True])) tm.assert_numpy_array_equal(index.isna(), np.array([False, True, False])) - def test_copy(self): - actual = self.index.copy() - assert actual.equals(self.index) + def test_copy(self, closed): + expected = IntervalIndex.from_breaks(np.arange(5), closed=closed) + + result = expected.copy() + assert result.equals(expected) - actual = self.index.copy(deep=True) - assert actual.equals(self.index) - assert actual.left is not self.index.left + result = expected.copy(deep=True) + assert result.equals(expected) + assert result.left is not expected.left - def test_ensure_copied_data(self): + def test_ensure_copied_data(self, closed): # exercise the copy flag in the constructor # not copying - index = self.index + index = self.create_index(closed=closed) result = IntervalIndex(index, copy=False) tm.assert_numpy_array_equal(index.left.values, result.left.values, check_same='same') @@ -191,23 +243,34 @@ def test_ensure_copied_data(self): tm.assert_numpy_array_equal(index.right.values, result.right.values, check_same='copy') - def test_equals(self): + def test_equals(self, closed): + expected = IntervalIndex.from_breaks(np.arange(5), closed=closed) + assert expected.equals(expected) + assert expected.equals(expected.copy()) - idx = self.index - assert idx.equals(idx) - assert idx.equals(idx.copy()) + assert not expected.equals(expected.astype(object)) + assert not expected.equals(np.array(expected)) + assert not expected.equals(list(expected)) - assert not idx.equals(idx.astype(object)) - assert not idx.equals(np.array(idx)) - assert not idx.equals(list(idx)) + assert not expected.equals([1, 2]) + assert not expected.equals(np.array([1, 2])) + assert not expected.equals(pd.date_range('20130101', periods=2)) - assert not idx.equals([1, 2]) - assert not idx.equals(np.array([1, 2])) - assert not idx.equals(pd.date_range('20130101', periods=2)) + expected_name1 = IntervalIndex.from_breaks( + np.arange(5), closed=closed, name='foo') + expected_name2 = IntervalIndex.from_breaks( + np.arange(5), closed=closed, name='bar') + assert expected.equals(expected_name1) + assert expected_name1.equals(expected_name2) - def test_astype(self): + for other_closed in {'left', 'right', 'both', 'neither'} - {closed}: + expected_other_closed = IntervalIndex.from_breaks( + np.arange(5), closed=other_closed) + assert not expected.equals(expected_other_closed) - idx = self.index + def test_astype(self, closed): + + idx = self.create_index(closed=closed) for dtype in [np.int64, np.float64, 'datetime64[ns]', 'datetime64[ns, US/Eastern]', 'timedelta64', @@ -227,24 +290,24 @@ def test_astype(self): expected = pd.Categorical(idx, ordered=True) tm.assert_categorical_equal(result, expected) - def test_where(self): - expected = self.index - result = self.index.where(self.index.notna()) + def test_where(self, closed): + expected = self.create_index(closed=closed) + result = expected.where(expected.notna()) tm.assert_index_equal(result, expected) - idx = IntervalIndex.from_breaks([1, 2]) + idx = IntervalIndex.from_breaks([1, 2], closed=closed) result = idx.where([True, False]) expected = IntervalIndex.from_intervals( - [Interval(1.0, 2.0, closed='right'), np.nan]) + [Interval(1.0, 2.0, closed=closed), np.nan]) tm.assert_index_equal(result, expected) def test_where_array_like(self): pass - def test_delete(self): - expected = IntervalIndex.from_breaks([1, 2]) - actual = self.index.delete(0) - assert expected.equals(actual) + def test_delete(self, closed): + expected = IntervalIndex.from_breaks([1, 2], closed=closed) + result = self.create_index(closed=closed).delete(0) + tm.assert_index_equal(result, expected) def test_insert(self): expected = IntervalIndex.from_breaks(range(4)) @@ -255,113 +318,128 @@ def test_insert(self): pytest.raises(ValueError, self.index.insert, 0, Interval(2, 3, closed='left')) - def test_take(self): - actual = self.index.take([0, 1]) - assert self.index.equals(actual) + def test_take(self, closed): + index = self.create_index(closed=closed) - expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2]) - actual = self.index.take([0, 0, 1]) - assert expected.equals(actual) + actual = index.take([0, 1]) + tm.assert_index_equal(actual, index) + + expected = IntervalIndex.from_arrays( + [0, 0, 1], [1, 1, 2], closed=closed) + actual = index.take([0, 0, 1]) + tm.assert_index_equal(actual, expected) - def test_unique(self): + def test_unique(self, closed): # unique non-overlapping - idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)]) + idx = IntervalIndex.from_tuples( + [(0, 1), (2, 3), (4, 5)], closed=closed) assert idx.is_unique # unique overlapping - distinct endpoints - idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)]) + idx = IntervalIndex.from_tuples([(0, 1), (0.5, 1.5)], closed=closed) assert idx.is_unique # unique overlapping - shared endpoints - idx = pd.IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)]) + idx = pd.IntervalIndex.from_tuples( + [(1, 2), (1, 3), (2, 3)], closed=closed) assert idx.is_unique # unique nested - idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)]) + idx = IntervalIndex.from_tuples([(-1, 1), (-2, 2)], closed=closed) assert idx.is_unique # duplicate - idx = IntervalIndex.from_tuples([(0, 1), (0, 1), (2, 3)]) + idx = IntervalIndex.from_tuples( + [(0, 1), (0, 1), (2, 3)], closed=closed) assert not idx.is_unique # unique mixed - idx = IntervalIndex.from_tuples([(0, 1), ('a', 'b')]) + idx = IntervalIndex.from_tuples([(0, 1), ('a', 'b')], closed=closed) assert idx.is_unique # duplicate mixed - idx = IntervalIndex.from_tuples([(0, 1), ('a', 'b'), (0, 1)]) + idx = IntervalIndex.from_tuples( + [(0, 1), ('a', 'b'), (0, 1)], closed=closed) assert not idx.is_unique # empty - idx = IntervalIndex([]) + idx = IntervalIndex([], closed=closed) assert idx.is_unique - def test_monotonic(self): + def test_monotonic(self, closed): # increasing non-overlapping - idx = IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)]) + idx = IntervalIndex.from_tuples( + [(0, 1), (2, 3), (4, 5)], closed=closed) assert idx.is_monotonic assert idx._is_strictly_monotonic_increasing assert not idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing # decreasing non-overlapping - idx = IntervalIndex.from_tuples([(4, 5), (2, 3), (1, 2)]) + idx = IntervalIndex.from_tuples( + [(4, 5), (2, 3), (1, 2)], closed=closed) assert not idx.is_monotonic assert not idx._is_strictly_monotonic_increasing assert idx.is_monotonic_decreasing assert idx._is_strictly_monotonic_decreasing # unordered non-overlapping - idx = IntervalIndex.from_tuples([(0, 1), (4, 5), (2, 3)]) + idx = IntervalIndex.from_tuples( + [(0, 1), (4, 5), (2, 3)], closed=closed) assert not idx.is_monotonic assert not idx._is_strictly_monotonic_increasing assert not idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing # increasing overlapping - idx = IntervalIndex.from_tuples([(0, 2), (0.5, 2.5), (1, 3)]) + idx = IntervalIndex.from_tuples( + [(0, 2), (0.5, 2.5), (1, 3)], closed=closed) assert idx.is_monotonic assert idx._is_strictly_monotonic_increasing assert not idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing # decreasing overlapping - idx = IntervalIndex.from_tuples([(1, 3), (0.5, 2.5), (0, 2)]) + idx = IntervalIndex.from_tuples( + [(1, 3), (0.5, 2.5), (0, 2)], closed=closed) assert not idx.is_monotonic assert not idx._is_strictly_monotonic_increasing assert idx.is_monotonic_decreasing assert idx._is_strictly_monotonic_decreasing # unordered overlapping - idx = IntervalIndex.from_tuples([(0.5, 2.5), (0, 2), (1, 3)]) + idx = IntervalIndex.from_tuples( + [(0.5, 2.5), (0, 2), (1, 3)], closed=closed) assert not idx.is_monotonic assert not idx._is_strictly_monotonic_increasing assert not idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing # increasing overlapping shared endpoints - idx = pd.IntervalIndex.from_tuples([(1, 2), (1, 3), (2, 3)]) + idx = pd.IntervalIndex.from_tuples( + [(1, 2), (1, 3), (2, 3)], closed=closed) assert idx.is_monotonic assert idx._is_strictly_monotonic_increasing assert not idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing # decreasing overlapping shared endpoints - idx = pd.IntervalIndex.from_tuples([(2, 3), (1, 3), (1, 2)]) + idx = pd.IntervalIndex.from_tuples( + [(2, 3), (1, 3), (1, 2)], closed=closed) assert not idx.is_monotonic assert not idx._is_strictly_monotonic_increasing assert idx.is_monotonic_decreasing assert idx._is_strictly_monotonic_decreasing # stationary - idx = IntervalIndex.from_tuples([(0, 1), (0, 1)]) + idx = IntervalIndex.from_tuples([(0, 1), (0, 1)], closed=closed) assert idx.is_monotonic assert not idx._is_strictly_monotonic_increasing assert idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing # empty - idx = IntervalIndex([]) + idx = IntervalIndex([], closed=closed) assert idx.is_monotonic assert idx._is_strictly_monotonic_increasing assert idx.is_monotonic_decreasing @@ -395,24 +473,24 @@ def test_repr_max_seq_item_setting(self): def test_repr_roundtrip(self): super(TestIntervalIndex, self).test_repr_roundtrip() - def test_get_item(self): + def test_get_item(self, closed): i = IntervalIndex.from_arrays((0, 1, np.nan), (1, 2, np.nan), - closed='right') - assert i[0] == Interval(0.0, 1.0) - assert i[1] == Interval(1.0, 2.0) + closed=closed) + assert i[0] == Interval(0.0, 1.0, closed=closed) + assert i[1] == Interval(1.0, 2.0, closed=closed) assert isna(i[2]) result = i[0:1] - expected = IntervalIndex.from_arrays((0.,), (1.,), closed='right') + expected = IntervalIndex.from_arrays((0.,), (1.,), closed=closed) tm.assert_index_equal(result, expected) result = i[0:2] - expected = IntervalIndex.from_arrays((0., 1), (1., 2.), closed='right') + expected = IntervalIndex.from_arrays((0., 1), (1., 2.), closed=closed) tm.assert_index_equal(result, expected) result = i[1:3] expected = IntervalIndex.from_arrays((1., np.nan), (2., np.nan), - closed='right') + closed=closed) tm.assert_index_equal(result, expected) def test_get_loc_value(self): @@ -581,20 +659,22 @@ def testcontains(self): assert not i.contains(20) assert not i.contains(-20) - def test_dropna(self): + def test_dropna(self, closed): - expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)]) + expected = IntervalIndex.from_tuples( + [(0.0, 1.0), (1.0, 2.0)], closed=closed) - ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan]) + ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed) result = ii.dropna() tm.assert_index_equal(result, expected) - ii = IntervalIndex.from_arrays([0, 1, np.nan], [1, 2, np.nan]) + ii = IntervalIndex.from_arrays( + [0, 1, np.nan], [1, 2, np.nan], closed=closed) result = ii.dropna() tm.assert_index_equal(result, expected) - def test_non_contiguous(self): - index = IntervalIndex.from_tuples([(0, 1), (2, 3)]) + def test_non_contiguous(self, closed): + index = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) target = [0.5, 1.5, 2.5] actual = index.get_indexer(target) expected = np.array([0, -1, 1], dtype='intp') @@ -602,31 +682,32 @@ def test_non_contiguous(self): assert 1.5 not in index - def test_union(self): - other = IntervalIndex.from_arrays([2], [3]) - expected = IntervalIndex.from_arrays(range(3), range(1, 4)) - actual = self.index.union(other) + def test_union(self, closed): + idx = self.create_index(closed=closed) + other = IntervalIndex.from_arrays([2], [3], closed=closed) + expected = IntervalIndex.from_arrays( + range(3), range(1, 4), closed=closed) + actual = idx.union(other) assert expected.equals(actual) - actual = other.union(self.index) + actual = other.union(idx) assert expected.equals(actual) - tm.assert_index_equal(self.index.union(self.index), self.index) - tm.assert_index_equal(self.index.union(self.index[:1]), - self.index) + tm.assert_index_equal(idx.union(idx), idx) + tm.assert_index_equal(idx.union(idx[:1]), idx) - def test_intersection(self): - other = IntervalIndex.from_breaks([1, 2, 3]) - expected = IntervalIndex.from_breaks([1, 2]) - actual = self.index.intersection(other) + def test_intersection(self, closed): + idx = self.create_index(closed=closed) + other = IntervalIndex.from_breaks([1, 2, 3], closed=closed) + expected = IntervalIndex.from_breaks([1, 2], closed=closed) + actual = idx.intersection(other) assert expected.equals(actual) - tm.assert_index_equal(self.index.intersection(self.index), - self.index) + tm.assert_index_equal(idx.intersection(idx), idx) - def test_difference(self): - tm.assert_index_equal(self.index.difference(self.index[:1]), - self.index[1:]) + def test_difference(self, closed): + idx = self.create_index(closed=closed) + tm.assert_index_equal(idx.difference(idx[:1]), idx[1:]) def test_symmetric_difference(self): result = self.index[:1].symmetric_difference(self.index[1:]) @@ -639,11 +720,12 @@ def test_set_operation_errors(self): other = IntervalIndex.from_breaks([0, 1, 2], closed='neither') pytest.raises(ValueError, self.index.union, other) - def test_isin(self): - actual = self.index.isin(self.index) + def test_isin(self, closed): + idx = self.create_index(closed=closed) + actual = idx.isin(idx) tm.assert_numpy_array_equal(np.array([True, True]), actual) - actual = self.index.isin(self.index[:1]) + actual = idx.isin(idx[:1]) tm.assert_numpy_array_equal(np.array([True, False]), actual) def test_comparison(self): @@ -702,25 +784,28 @@ def test_comparison(self): with pytest.raises(ValueError): self.index > np.arange(3) - def test_missing_values(self): - idx = pd.Index([np.nan, pd.Interval(0, 1), pd.Interval(1, 2)]) - idx2 = pd.IntervalIndex.from_arrays([np.nan, 0, 1], [np.nan, 1, 2]) + def test_missing_values(self, closed): + idx = Index([np.nan, Interval(0, 1, closed=closed), + Interval(1, 2, closed=closed)]) + idx2 = IntervalIndex.from_arrays( + [np.nan, 0, 1], [np.nan, 1, 2], closed=closed) assert idx.equals(idx2) with pytest.raises(ValueError): - IntervalIndex.from_arrays([np.nan, 0, 1], np.array([0, 1, 2])) + IntervalIndex.from_arrays( + [np.nan, 0, 1], np.array([0, 1, 2]), closed=closed) tm.assert_numpy_array_equal(isna(idx), np.array([True, False, False])) - def test_sort_values(self): - expected = IntervalIndex.from_breaks([1, 2, 3, 4]) - actual = IntervalIndex.from_tuples([(3, 4), (1, 2), - (2, 3)]).sort_values() + def test_sort_values(self, closed): + expected = IntervalIndex.from_breaks([1, 2, 3, 4], closed=closed) + actual = IntervalIndex.from_tuples( + [(3, 4), (1, 2), (2, 3)], closed=closed).sort_values() tm.assert_index_equal(expected, actual) # nan - idx = self.index_with_nan + idx = self.create_index_with_nan(closed=closed) mask = idx.isna() tm.assert_numpy_array_equal(mask, np.array([False, True, False])) @@ -733,84 +818,83 @@ def test_sort_values(self): tm.assert_numpy_array_equal(mask, np.array([True, False, False])) def test_datetime(self): - dates = pd.date_range('2000', periods=3) + dates = date_range('2000', periods=3) idx = IntervalIndex.from_breaks(dates) tm.assert_index_equal(idx.left, dates[:2]) tm.assert_index_equal(idx.right, dates[-2:]) - expected = pd.date_range('2000-01-01T12:00', periods=2) + expected = date_range('2000-01-01T12:00', periods=2) tm.assert_index_equal(idx.mid, expected) - assert pd.Timestamp('2000-01-01T12') not in idx - assert pd.Timestamp('2000-01-01T12') not in idx + assert Timestamp('2000-01-01T12') not in idx + assert Timestamp('2000-01-01T12') not in idx - target = pd.date_range('1999-12-31T12:00', periods=7, freq='12H') + target = date_range('1999-12-31T12:00', periods=7, freq='12H') actual = idx.get_indexer(target) expected = np.array([-1, -1, 0, 0, 1, 1, -1], dtype='intp') tm.assert_numpy_array_equal(actual, expected) - def test_append(self): + def test_append(self, closed): - index1 = IntervalIndex.from_arrays([0, 1], [1, 2]) - index2 = IntervalIndex.from_arrays([1, 2], [2, 3]) + index1 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed) + index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed) result = index1.append(index2) - expected = IntervalIndex.from_arrays([0, 1, 1, 2], [1, 2, 2, 3]) + expected = IntervalIndex.from_arrays( + [0, 1, 1, 2], [1, 2, 2, 3], closed=closed) tm.assert_index_equal(result, expected) result = index1.append([index1, index2]) - expected = IntervalIndex.from_arrays([0, 1, 0, 1, 1, 2], - [1, 2, 1, 2, 2, 3]) + expected = IntervalIndex.from_arrays( + [0, 1, 0, 1, 1, 2], [1, 2, 1, 2, 2, 3], closed=closed) tm.assert_index_equal(result, expected) - def f(): - index1.append(IntervalIndex.from_arrays([0, 1], [1, 2], - closed='both')) - - pytest.raises(ValueError, f) + msg = ('can only append two IntervalIndex objects that are closed ' + 'on the same side') + for other_closed in {'left', 'right', 'both', 'neither'} - {closed}: + index_other_closed = IntervalIndex.from_arrays( + [0, 1], [1, 2], closed=other_closed) + with tm.assert_raises_regex(ValueError, msg): + index1.append(index_other_closed) - def test_is_non_overlapping_monotonic(self): + def test_is_non_overlapping_monotonic(self, closed): # Should be True in all cases tpls = [(0, 1), (2, 3), (4, 5), (6, 7)] - for closed in ('left', 'right', 'neither', 'both'): - idx = IntervalIndex.from_tuples(tpls, closed=closed) - assert idx.is_non_overlapping_monotonic is True + idx = IntervalIndex.from_tuples(tpls, closed=closed) + assert idx.is_non_overlapping_monotonic is True - idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) - assert idx.is_non_overlapping_monotonic is True + idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) + assert idx.is_non_overlapping_monotonic is True # Should be False in all cases (overlapping) tpls = [(0, 2), (1, 3), (4, 5), (6, 7)] - for closed in ('left', 'right', 'neither', 'both'): - idx = IntervalIndex.from_tuples(tpls, closed=closed) - assert idx.is_non_overlapping_monotonic is False + idx = IntervalIndex.from_tuples(tpls, closed=closed) + assert idx.is_non_overlapping_monotonic is False - idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) - assert idx.is_non_overlapping_monotonic is False + idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) + assert idx.is_non_overlapping_monotonic is False # Should be False in all cases (non-monotonic) tpls = [(0, 1), (2, 3), (6, 7), (4, 5)] - for closed in ('left', 'right', 'neither', 'both'): - idx = IntervalIndex.from_tuples(tpls, closed=closed) - assert idx.is_non_overlapping_monotonic is False - - idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) - assert idx.is_non_overlapping_monotonic is False + idx = IntervalIndex.from_tuples(tpls, closed=closed) + assert idx.is_non_overlapping_monotonic is False - # Should be False for closed='both', overwise True (GH16560) - idx = IntervalIndex.from_breaks(range(4), closed='both') + idx = IntervalIndex.from_tuples(reversed(tpls), closed=closed) assert idx.is_non_overlapping_monotonic is False - for closed in ('left', 'right', 'neither'): + # Should be False for closed='both', overwise True (GH16560) + if closed == 'both': + idx = IntervalIndex.from_breaks(range(4), closed=closed) + assert idx.is_non_overlapping_monotonic is False + else: idx = IntervalIndex.from_breaks(range(4), closed=closed) assert idx.is_non_overlapping_monotonic is True class TestIntervalRange(object): - @pytest.mark.parametrize('closed', ['left', 'right', 'neither', 'both']) def test_construction_from_numeric(self, closed): # combinations of start/end/periods without freq expected = IntervalIndex.from_breaks( @@ -848,7 +932,6 @@ def test_construction_from_numeric(self, closed): closed=closed) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize('closed', ['left', 'right', 'neither', 'both']) def test_construction_from_timestamp(self, closed): # combinations of start/end/periods without freq start, end = Timestamp('2017-01-01'), Timestamp('2017-01-06') @@ -915,7 +998,6 @@ def test_construction_from_timestamp(self, closed): closed=closed) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize('closed', ['left', 'right', 'neither', 'both']) def test_construction_from_timedelta(self, closed): # combinations of start/end/periods without freq start, end = Timedelta('1 day'), Timedelta('6 days')
- [X] closes #18334 - [X] closes #18339 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry Lumped the two issues together since they're dealing with the same thing, and the fixes are identical/small. Rewrote relevant tests to be parametrized over ``closed``. I also went through unrelated `IntervalIndex` tests and where it was straighforward parametrized over ``closed``. Didn't include those in the initial commit though. Not sure if it was best to include them here, or do them separately.
https://api.github.com/repos/pandas-dev/pandas/pulls/18340
2017-11-17T07:50:41Z
2017-11-20T00:25:29Z
2017-11-20T00:25:29Z
2017-12-04T20:43:26Z
!I fix for BUG: resample with tz-aware: Values falls after last bin #15549
diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 83aa2d96f565c..f7b54d10508f9 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -62,6 +62,7 @@ Bug Fixes - Bug in ``pd.Series.rolling.skew()`` and ``rolling.kurt()`` with all equal values has floating issue (:issue:`18044`) - Bug in ``pd.DataFrameGroupBy.count()`` when counting over a datetimelike column (:issue:`13393`) - Bug in ``pd.concat`` when empty and non-empty DataFrames or Series are concatenated (:issue:`18178` :issue:`18187`) +- Bug in ``DataFrame.resample(...)`` when there is a time change (DST) and resampling frequecy is 12h or higher (:issue:`15549`) - Bug in :class:`IntervalIndex` constructor when a list of intervals is passed with non-default ``closed`` (:issue:`18334`) - Bug in :meth:`IntervalIndex.copy` when copying and ``IntervalIndex`` with non-default ``closed`` (:issue:`18339`) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index eeb6faf20ffce..6988528af415f 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1141,6 +1141,16 @@ def _get_time_bins(self, ax): tz=tz, name=ax.name) + # GH 15549 + # In edge case of tz-aware resapmling binner last index can be + # less than the last variable in data object, this happens because of + # DST time change + if len(binner) > 1 and binner[-1] < last: + extra_date_range = pd.date_range(binner[-1], last + self.freq, + freq=self.freq, tz=tz, + name=ax.name) + binner = labels = binner.append(extra_date_range[1:]) + # a little hack trimmed = False if (len(binner) > 2 and binner[-2] == last and diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 5f8c69a8152ac..c9e40074c06ad 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -2719,6 +2719,34 @@ def test_resample_weekly_bug_1726(self): # it works! df.resample('W-MON', closed='left', label='left').first() + def test_resample_with_dst_time_change(self): + # GH 15549 + index = pd.DatetimeIndex([1457537600000000000, 1458059600000000000], + tz='UTC').tz_convert('America/Chicago') + df = pd.DataFrame([1, 2], index=index) + result = df.resample('12h', closed='right', + label='right').last().ffill() + + expected_index_values = ['2016-03-09 12:00:00-06:00', + '2016-03-10 00:00:00-06:00', + '2016-03-10 12:00:00-06:00', + '2016-03-11 00:00:00-06:00', + '2016-03-11 12:00:00-06:00', + '2016-03-12 00:00:00-06:00', + '2016-03-12 12:00:00-06:00', + '2016-03-13 00:00:00-06:00', + '2016-03-13 13:00:00-05:00', + '2016-03-14 01:00:00-05:00', + '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') + 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) + assert_frame_equal(result, expected) + def test_resample_bms_2752(self): # GH2753 foo = Series(index=pd.bdate_range('20000101', '20000201'))
- [ ] closes #15549 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/18337
2017-11-17T03:21:38Z
2017-11-21T13:14:14Z
2017-11-21T13:14:14Z
2017-11-21T13:14:17Z
CLN: Lint for lists instead of generators in built-in Python functions
diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index dec4fcba0eb5e..7f95e8d06eb72 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -132,7 +132,7 @@ def setup(self, offset, n_steps): offset = getattr(offsets, offset) self.idx = get_index_for_offset(offset(n_steps, **kwargs)) self.df = DataFrame(np.random.randn(len(self.idx), 10), index=self.idx) - self.d = dict([(col, self.df[col]) for col in self.df.columns]) + self.d = dict(self.df.items()) def time_frame_ctor(self, offset, n_steps): DataFrame(self.d) diff --git a/asv_bench/benchmarks/io_bench.py b/asv_bench/benchmarks/io_bench.py index 93273955a29b9..d5eedf63dfe8a 100644 --- a/asv_bench/benchmarks/io_bench.py +++ b/asv_bench/benchmarks/io_bench.py @@ -202,7 +202,7 @@ class read_json_lines(object): def setup(self): self.N = 100000 self.C = 5 - self.df = DataFrame(dict([('float{0}'.format(i), randn(self.N)) for i in range(self.C)])) + self.df = DataFrame({('float{0}'.format(i), randn(self.N)) for i in range(self.C)}) self.df.to_json(self.fname,orient="records",lines=True) def teardown(self): diff --git a/asv_bench/benchmarks/packers.py b/asv_bench/benchmarks/packers.py index 24f80cc836dd4..e3d95aa3586c5 100644 --- a/asv_bench/benchmarks/packers.py +++ b/asv_bench/benchmarks/packers.py @@ -17,7 +17,7 @@ def _setup(self): self.N = 100000 self.C = 5 self.index = date_range('20000101', periods=self.N, freq='H') - self.df = DataFrame(dict([('float{0}'.format(i), randn(self.N)) for i in range(self.C)]), index=self.index) + self.df = DataFrame(dict(('float{0}'.format(i), randn(self.N)) for i in range(self.C)), index=self.index) self.df2 = self.df.copy() self.df2['object'] = [('%08x' % randrange((16 ** 8))) for _ in range(self.N)] self.remove(self.f) diff --git a/asv_bench/vbench_to_asv.py b/asv_bench/vbench_to_asv.py index 2a4ce5d183ea2..b1179387e65d5 100644 --- a/asv_bench/vbench_to_asv.py +++ b/asv_bench/vbench_to_asv.py @@ -69,7 +69,7 @@ def visit_ClassDef(self, node): return node def visit_TryExcept(self, node): - if any([isinstance(x, (ast.Import, ast.ImportFrom)) for x in node.body]): + if any(isinstance(x, (ast.Import, ast.ImportFrom)) for x in node.body): self.imports.append(node) else: self.generic_visit(node) diff --git a/ci/lint.sh b/ci/lint.sh index 71d8c5c7e1621..4027737900bf9 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -84,6 +84,19 @@ if [ "$LINT" ]; then fi echo "Check for invalid testing DONE" + echo "Check for use of lists instead of generators in built-in Python functions" + + # Example: Avoid `any([i for i in some_iterator])` in favor of `any(i for i in some_iterator)` + # + # Check the following functions: + # any(), all(), sum(), max(), min(), list(), dict(), set(), frozenset(), tuple(), str.join() + grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" + + if [ $? = "0" ]; then + RET=1 + fi + echo "Check for use of lists instead of generators in built-in Python functions DONE" + else echo "NOT Linting" fi diff --git a/doc/source/conf.py b/doc/source/conf.py index c8189b86b095c..bcb83d5699d7e 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -78,7 +78,7 @@ # JP: added from sphinxdocs autosummary_generate = False -if any([re.match("\s*api\s*", l) for l in index_rst_lines]): +if any(re.match("\s*api\s*", l) for l in index_rst_lines): autosummary_generate = True files_to_delete = [] @@ -89,7 +89,7 @@ _file_basename = os.path.splitext(f)[0] _regex_to_match = "\s*{}\s*$".format(_file_basename) - if not any([re.match(_regex_to_match, line) for line in index_rst_lines]): + if not any(re.match(_regex_to_match, line) for line in index_rst_lines): files_to_delete.append(f) if files_to_delete: diff --git a/doc/sphinxext/ipython_sphinxext/ipython_directive.py b/doc/sphinxext/ipython_sphinxext/ipython_directive.py index 922767a8e2d46..4f7b32840680d 100644 --- a/doc/sphinxext/ipython_sphinxext/ipython_directive.py +++ b/doc/sphinxext/ipython_sphinxext/ipython_directive.py @@ -522,7 +522,7 @@ def process_output(self, data, output_prompt, source = self.directive.state.document.current_source content = self.directive.content # Add tabs and join into a single string. - content = '\n'.join([TAB + line for line in content]) + content = '\n'.join(TAB + line for line in content) # Make sure the output contains the output prompt. ind = found.find(output_prompt) diff --git a/doc/sphinxext/numpydoc/compiler_unparse.py b/doc/sphinxext/numpydoc/compiler_unparse.py index 8933a83db3f23..eabb5934c9cc8 100755 --- a/doc/sphinxext/numpydoc/compiler_unparse.py +++ b/doc/sphinxext/numpydoc/compiler_unparse.py @@ -399,7 +399,7 @@ def _Return(self, t): self._fill("return ") if t.value: if isinstance(t.value, Tuple): - text = ', '.join([ name.name for name in t.value.asList() ]) + text = ', '.join(name.name for name in t.value.asList()) self._write(text) else: self._dispatch(t.value) diff --git a/doc/sphinxext/numpydoc/docscrape.py b/doc/sphinxext/numpydoc/docscrape.py index 2c49ed84ad224..38cb62581ae76 100755 --- a/doc/sphinxext/numpydoc/docscrape.py +++ b/doc/sphinxext/numpydoc/docscrape.py @@ -270,7 +270,7 @@ def _parse_summary(self): # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() - summary_str = " ".join([s.strip() for s in summary]).strip() + summary_str = " ".join(s.strip() for s in summary).strip() if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): @@ -289,7 +289,7 @@ def _parse(self): for (section,content) in self._read_sections(): if not section.startswith('..'): - section = ' '.join([s.capitalize() for s in section.split(' ')]) + section = ' '.join(s.capitalize() for s in section.split(' ')) if section in ('Parameters', 'Returns', 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) diff --git a/doc/sphinxext/numpydoc/docscrape_sphinx.py b/doc/sphinxext/numpydoc/docscrape_sphinx.py index 5a582b4d03282..9017480c9ab76 100755 --- a/doc/sphinxext/numpydoc/docscrape_sphinx.py +++ b/doc/sphinxext/numpydoc/docscrape_sphinx.py @@ -130,7 +130,7 @@ def _str_member_list(self, name): out += [''] + autosum if others: - maxlen_0 = max(3, max([len(x[0]) for x in others])) + maxlen_0 = max(3, max(len(x[0]) for x in others)) hdr = sixu("=")*maxlen_0 + sixu(" ") + sixu("=")*10 fmt = sixu('%%%ds %%s ') % (maxlen_0,) out += ['', hdr] @@ -203,7 +203,7 @@ def _str_references(self): m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) - out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] + out += [' ' + ", ".join("[%s]_" % item for item in items), ''] return out def _str_examples(self): diff --git a/doc/sphinxext/numpydoc/phantom_import.py b/doc/sphinxext/numpydoc/phantom_import.py index 4b4fec863a0e3..e0bd645f5db76 100755 --- a/doc/sphinxext/numpydoc/phantom_import.py +++ b/doc/sphinxext/numpydoc/phantom_import.py @@ -60,7 +60,7 @@ def import_phantom_module(xml_file): # Sort items so that # - Base classes come before classes inherited from them # - Modules come before their contents - all_nodes = dict([(n.attrib['id'], n) for n in root]) + all_nodes = dict((n.attrib['id'], n) for n in root) def _get_bases(node, recurse=False): bases = [x.attrib['ref'] for x in node.findall('base')] diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 85857c158f96e..546f08d651eea 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -770,7 +770,7 @@ cdef class TextReader: msg = self.orig_header if isinstance(msg, list): msg = "[%s], len of %d," % ( - ','.join([ str(m) for m in msg ]), len(msg)) + ','.join(str(m) for m in msg), len(msg)) raise ParserError( 'Passed header=%s but only %d lines in file' % (msg, self.parser.lines)) @@ -2227,7 +2227,7 @@ def _concatenate_chunks(list chunks): for name in names: arrs = [chunk.pop(name) for chunk in chunks] # Check each arr for consistent types. - dtypes = set([a.dtype for a in arrs]) + dtypes = set(a.dtype for a in arrs) if len(dtypes) > 1: common_type = np.find_common_type(dtypes, []) if common_type == np.object: diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index c432c40c8f6b3..ad2defc7b362f 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -1309,7 +1309,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0, # we try to coerce datetime w/tz but must all have the same tz if seen.datetimetz_: - if len(set([getattr(val, 'tzinfo', None) for val in objects])) == 1: + if len({getattr(val, 'tzinfo', None) for val in objects}) == 1: from pandas import DatetimeIndex return DatetimeIndex(objects) seen.object_ = 1 diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index b590121b9021a..388075903a8ba 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -218,7 +218,7 @@ class Resolution(object): 'U': 'N', 'N': None} - _str_reso_map = dict([(v, k) for k, v in _reso_str_map.items()]) + _str_reso_map = {v: k for k, v in _reso_str_map.items()} _reso_freq_map = { 'year': 'A', @@ -232,8 +232,7 @@ class Resolution(object): 'microsecond': 'U', 'nanosecond': 'N'} - _freq_reso_map = dict([(v, k) - for k, v in _reso_freq_map.items()]) + _freq_reso_map = {v: k for k, v in _reso_freq_map.items()} @classmethod def get_str(cls, reso): diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 64a972dacbaf0..439cc21a360c7 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -568,7 +568,7 @@ class TimeRE(dict): break else: return '' - regex = '|'.join([re.escape(stuff) for stuff in to_convert]) + regex = '|'.join(re.escape(stuff) for stuff in to_convert) regex = '(?P<%s>%s' % (directive, regex) return '%s)' % regex diff --git a/pandas/_version.py b/pandas/_version.py index 0fdb0efde1f05..4a469ebb8630e 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -141,11 +141,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -154,7 +154,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set(r for r in refs if re.search(r'\d', r)) if verbose: print("discarding '{}', no digits".format(",".join(refs - tags))) if verbose: diff --git a/pandas/core/common.py b/pandas/core/common.py index 29d278b6efcb0..8e12ce3647340 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -347,7 +347,7 @@ def map_indices_py(arr): Returns a dictionary with (element, index) pairs for each element in the given array/list """ - return dict([(x, i) for i, x in enumerate(arr)]) + return dict((x, i) for i, x in enumerate(arr)) def union(*seqs): diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 23884869a4d9f..fe306b51de8d0 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -459,7 +459,7 @@ def _concat_datetimetz(to_concat, name=None): it is used in DatetimeIndex.append also """ # do not pass tz to set because tzlocal cannot be hashed - if len(set([str(x.dtype) for x in to_concat])) != 1: + if len(set(str(x.dtype) for x in to_concat)) != 1: raise ValueError('to_concat must have the same tz') tz = to_concat[0].tz # no need to localize because internal repr will not be changed diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4d8fb9d03db0c..7145fa709c345 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3895,7 +3895,7 @@ def f(col): return self._constructor_sliced(r, index=new_index, dtype=r.dtype) - result = dict([(col, f(col)) for col in this]) + result = dict((col, f(col)) for col in this) # non-unique else: @@ -3906,9 +3906,7 @@ def f(i): return self._constructor_sliced(r, index=new_index, dtype=r.dtype) - result = dict([ - (i, f(i)) for i, col in enumerate(this.columns) - ]) + result = dict((i, f(i)) for i, col in enumerate(this.columns)) result = self._constructor(result, index=new_index, copy=False) result.columns = new_columns return result @@ -3986,7 +3984,7 @@ def _compare_frame_evaluate(self, other, func, str_rep, try_cast=True): if self.columns.is_unique: def _compare(a, b): - return dict([(col, func(a[col], b[col])) for col in a.columns]) + return dict((col, func(a[col], b[col])) for col in a.columns) new_data = expressions.evaluate(_compare, str_rep, self, other) return self._constructor(data=new_data, index=self.index, @@ -3995,8 +3993,8 @@ def _compare(a, b): else: def _compare(a, b): - return dict([(i, func(a.iloc[:, i], b.iloc[:, i])) - for i, col in enumerate(a.columns)]) + return dict((i, func(a.iloc[:, i], b.iloc[:, i])) + for i, col in enumerate(a.columns)) new_data = expressions.evaluate(_compare, str_rep, self, other) result = self._constructor(data=new_data, index=self.index, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5f0630feba653..d93fe52d5ca9c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -279,21 +279,21 @@ def set_axis(a, i): def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" - d = dict([(a, self._get_axis(a)) for a in (axes or self._AXIS_ORDERS)]) + d = dict((a, self._get_axis(a)) for a in (axes or self._AXIS_ORDERS)) d.update(kwargs) return d @staticmethod def _construct_axes_dict_from(self, axes, **kwargs): """Return an axes dictionary for the passed axes.""" - d = dict([(a, ax) for a, ax in zip(self._AXIS_ORDERS, axes)]) + d = dict((a, ax) for a, ax in zip(self._AXIS_ORDERS, axes)) d.update(kwargs) return d def _construct_axes_dict_for_slice(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" - d = dict([(self._AXIS_SLICEMAP[a], self._get_axis(a)) - for a in (axes or self._AXIS_ORDERS)]) + d = dict((self._AXIS_SLICEMAP[a], self._get_axis(a)) + for a in (axes or self._AXIS_ORDERS)) d.update(kwargs) return d @@ -329,7 +329,7 @@ def _construct_axes_from_arguments(self, args, kwargs, require_all=False): raise TypeError("not enough/duplicate arguments " "specified!") - axes = dict([(a, kwargs.pop(a, None)) for a in self._AXIS_ORDERS]) + axes = dict((a, kwargs.pop(a, None)) for a in self._AXIS_ORDERS) return axes, kwargs @classmethod @@ -586,10 +586,10 @@ def transpose(self, *args, **kwargs): # construct the args axes, kwargs = self._construct_axes_from_arguments(args, kwargs, require_all=True) - axes_names = tuple([self._get_axis_name(axes[a]) - for a in self._AXIS_ORDERS]) - axes_numbers = tuple([self._get_axis_number(axes[a]) - for a in self._AXIS_ORDERS]) + axes_names = tuple(self._get_axis_name(axes[a]) + for a in self._AXIS_ORDERS) + axes_numbers = tuple(self._get_axis_number(axes[a]) + for a in self._AXIS_ORDERS) # we must have unique axes if len(axes) != len(set(axes)): @@ -699,8 +699,8 @@ def squeeze(self, axis=None): (self._get_axis_number(axis),)) try: return self.iloc[ - tuple([0 if i in axis and len(a) == 1 else slice(None) - for i, a in enumerate(self.axes)])] + tuple(0 if i in axis and len(a) == 1 else slice(None) + for i, a in enumerate(self.axes))] except Exception: return self @@ -4277,8 +4277,8 @@ def fillna(self, value=None, method=None, axis=None, inplace=False, elif self.ndim == 3: # fill in 2d chunks - result = dict([(col, s.fillna(method=method, value=value)) - for col, s in self.iteritems()]) + result = dict((col, s.fillna(method=method, value=value)) + for col, s in self.iteritems()) new_obj = self._constructor.\ from_dict(result).__finalize__(self) new_data = new_obj._data diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 8bd9b822ee62e..8338df33f5cde 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -471,7 +471,7 @@ def get_converter(s): raise ValueError(msg) converters = [get_converter(s) for s in index_sample] - names = [tuple([f(n) for f, n in zip(converters, name)]) + names = [tuple(f(n) for f, n in zip(converters, name)) for name in names] else: diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 08cda8a06ba64..b7af533f96ddc 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -101,7 +101,7 @@ def conv(i): def _sanitize_and_check(indexes): - kinds = list(set([type(index) for index in indexes])) + kinds = list({type(index) for index in indexes}) if list in kinds: if len(kinds) > 1: @@ -122,8 +122,8 @@ def _get_consensus_names(indexes): # find the non-none names, need to tupleify to make # the set hashable, then reverse on return - consensus_names = set([tuple(i.names) for i in indexes - if com._any_not_none(*i.names)]) + consensus_names = set(tuple(i.names) for i in indexes + if com._any_not_none(*i.names)) if len(consensus_names) == 1: return list(list(consensus_names)[0]) return [None] * indexes[0].nlevels diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 57454e6fce118..121bf6a66dee5 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -732,7 +732,7 @@ def _coerce_to_ndarray(cls, data): def _get_attributes_dict(self): """ return an attributes dict for my class """ - return dict([(k, getattr(self, k, None)) for k in self._attributes]) + return dict((k, getattr(self, k, None)) for k in self._attributes) def view(self, cls=None): @@ -838,7 +838,7 @@ def __unicode__(self): space = self._format_space() prepr = (u(",%s") % - space).join([u("%s=%s") % (k, v) for k, v in attrs]) + space).join(u("%s=%s") % (k, v) for k, v in attrs) # no data provided, just attributes if data is None: @@ -1781,7 +1781,7 @@ def append(self, other): if not isinstance(obj, Index): raise TypeError('all inputs must be Index') - names = set([obj.name for obj in to_concat]) + names = set(obj.name for obj in to_concat) name = None if len(names) > 1 else self.name return self._concat(to_concat, name) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 6ae55b063b676..2461355df5461 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1002,7 +1002,7 @@ def _concat_same_dtype(self, to_concat, name): assert that we all have the same .closed we allow a 0-len index here as well """ - if not len(set([i.closed for i in to_concat if len(i)])) == 1: + if not len(set(i.closed for i in to_concat if len(i))) == 1: msg = ('can only append two IntervalIndex objects ' 'that are closed on the same side') raise ValueError(msg) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index ae799afdb4135..90733fa6d68d1 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2055,7 +2055,7 @@ def get_indexer(_i, _idx): return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else _idx) - return tuple([get_indexer(_i, _idx) for _i, _idx in enumerate(indexer)]) + return tuple(get_indexer(_i, _idx) for _i, _idx in enumerate(indexer)) def maybe_convert_indices(indices, n): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 07d0f0ffe54ba..5a19e4c38c3e1 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -241,7 +241,7 @@ def __unicode__(self): else: - shape = ' x '.join([pprint_thing(s) for s in self.shape]) + shape = ' x '.join(pprint_thing(s) for s in self.shape) result = '{name}: {index}, {shape}, dtype: {dtype}'.format( name=name, index=pprint_thing(self.mgr_locs.indexer), shape=shape, dtype=self.dtype) @@ -3376,7 +3376,7 @@ def reduction(self, f, axis=0, consolidate=True, transposed=False, blocks.append(block) # note that some DatetimeTZ, Categorical are always ndim==1 - ndim = set([b.ndim for b in blocks]) + ndim = set(b.ndim for b in blocks) if 2 in ndim: @@ -4870,7 +4870,7 @@ def _merge_blocks(blocks, dtype=None, _can_consolidate=True): if _can_consolidate: if dtype is None: - if len(set([b.dtype for b in blocks])) != 1: + if len(set(b.dtype for b in blocks)) != 1: raise AssertionError("_merge_blocks are invalid!") dtype = blocks[0].dtype diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 327180b6a6e84..0a5e705071b5e 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -1080,7 +1080,7 @@ def _apply_1d(self, func, axis): for i in range(np.prod(shape)): # construct the object - pts = tuple([p[i] for p in points]) + pts = tuple(p[i] for p in points) indexer.put(indlist, slice_indexer) obj = Series(values[tuple(indexer)], index=slice_axis, name=pts) @@ -1417,10 +1417,10 @@ def _extract_axes(self, data, axes, **kwargs): @staticmethod def _extract_axes_for_slice(self, axes): """ return the slice dictionary for these axes """ - return dict([(self._AXIS_SLICEMAP[i], a) - for i, a in zip( - self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], - axes)]) + return dict((self._AXIS_SLICEMAP[i], a) + for i, a in zip( + self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], + axes)) @staticmethod def _prep_ndarray(self, values, copy=True): @@ -1468,8 +1468,8 @@ def _homogenize_dict(self, frames, intersect=True, dtype=None): adj_frames[k] = v axes = self._AXIS_ORDERS[1:] - axes_dict = dict([(a, ax) for a, ax in zip(axes, self._extract_axes( - self, adj_frames, axes, intersect=intersect))]) + axes_dict = dict((a, ax) for a, ax in zip(axes, self._extract_axes( + self, adj_frames, axes, intersect=intersect))) reindex_dict = dict( [(self._AXIS_SLICEMAP[a], axes_dict[a]) for a in axes]) diff --git a/pandas/core/panelnd.py b/pandas/core/panelnd.py index 7a5cb63cd4f07..691787125043d 100644 --- a/pandas/core/panelnd.py +++ b/pandas/core/panelnd.py @@ -105,7 +105,7 @@ def _combine_with_constructor(self, other, func): new_axes.append(getattr(self, a).union(getattr(other, a))) # reindex: could check that everything's the same size, but forget it - d = dict([(a, ax) for a, ax in zip(self._AXIS_ORDERS, new_axes)]) + d = dict((a, ax) for a, ax in zip(self._AXIS_ORDERS, new_axes)) d['copy'] = False this = self.reindex(**d) other = other.reindex(**d) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 6b07054edb775..6139f093202fe 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -568,7 +568,7 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None): names = list(names) else: # make sure that all of the passed indices have the same nlevels - if not len(set([idx.nlevels for idx in indexes])) == 1: + if not len(set(idx.nlevels for idx in indexes)) == 1: raise AssertionError("Cannot concat indices that do" " not have the same number of levels") diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index 22a88264cad3e..0c9a55e0c9acd 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -173,7 +173,7 @@ def _init_matrix(self, data, index, columns, dtype=None): """ Init self from ndarray or list of lists """ data = _prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) - data = dict([(idx, data[:, i]) for i, idx in enumerate(columns)]) + data = dict((idx, data[:, i]) for i, idx in enumerate(columns)) return self._init_dict(data, index, columns, dtype) def _init_spmatrix(self, data, index, columns, dtype=None, diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py index 6252a02b0d63d..117c96d00171c 100644 --- a/pandas/io/clipboards.py +++ b/pandas/io/clipboards.py @@ -53,7 +53,7 @@ def read_clipboard(sep='\s+', **kwargs): # pragma: no cover # 0 1 2 # 1 3 4 - counts = set([x.lstrip().count('\t') for x in lines]) + counts = set(x.lstrip().count('\t') for x in lines) if len(lines) > 1 and len(counts) == 1 and counts.pop() != 0: sep = '\t' diff --git a/pandas/io/html.py b/pandas/io/html.py index f29062968bff1..d0861f1aa4ec6 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -699,7 +699,7 @@ def _parser_dispatch(flavor): def _print_as_set(s): - return '{{arg}}'.format(arg=', '.join([pprint_thing(el) for el in s])) + return '{{arg}}'.format(arg=', '.join(pprint_thing(el) for el in s)) def _validate_flavor(flavor): diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index ee336dff000b2..38d9baee834b3 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1133,8 +1133,8 @@ def _evaluate_usecols(usecols, names): If not a callable, returns 'usecols'. """ if callable(usecols): - return set([i for i, name in enumerate(names) - if usecols(name)]) + return set(i for i, name in enumerate(names) + if usecols(name)) return usecols @@ -1356,7 +1356,7 @@ def _extract_multi_indexer_columns(self, header, index_names, col_names, field_count = len(header[0]) def extract(r): - return tuple([r[i] for i in range(field_count) if i not in sic]) + return tuple(r[i] for i in range(field_count) if i not in sic) columns = lzip(*[extract(r) for r in header]) names = ic + columns @@ -1371,7 +1371,7 @@ def tostr(x): raise ParserError( "Passed header=[%s] are too many rows for this " "multi_index of columns" - % ','.join([str(x) for x in self.header]) + % ','.join(str(x) for x in self.header) ) # clean the column names (if we have an index_col) @@ -3133,7 +3133,7 @@ def _try_convert_dates(parser, colspec, data_dict, columns): else: colnames.append(c) - new_name = '_'.join([str(x) for x in colnames]) + new_name = '_'.join(str(x) for x in colnames) to_parse = [data_dict[c] for c in colnames if c in data_dict] new_col = parser(*to_parse) @@ -3156,9 +3156,9 @@ def _clean_na_values(na_values, keep_default_na=True): v = [v] v = set(v) | _NA_VALUES na_values[k] = v - na_fvalues = dict([ + na_fvalues = dict( (k, _floatify_na_values(v)) for k, v in na_values.items() # noqa - ]) + ) else: if not is_list_like(na_values): na_values = [na_values] @@ -3310,7 +3310,7 @@ def _concat_date_cols(date_cols): for x in date_cols[0] ], dtype=object) - rs = np.array([' '.join([compat.text_type(y) for y in x]) + rs = np.array([' '.join(compat.text_type(y) for y in x) for x in zip(*date_cols)], dtype=object) return rs @@ -3381,7 +3381,7 @@ def get_rows(self, n, skiprows=None): def detect_colspecs(self, n=100, skiprows=None): # Regex escape the delimiters - delimiters = ''.join([r'\%s' % x for x in self.delimiter]) + delimiters = ''.join(r'\%s' % x for x in self.delimiter) pattern = re.compile('([^%s]+)' % delimiters) rows = self.get_rows(n, skiprows) if not rows: diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 5d8299ff1a2be..b9cddce55c096 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -815,7 +815,7 @@ def select_as_multiple(self, keys, where=None, selector=None, columns=None, "all tables must have exactly the same nrows!") # axis is the concentation axes - axis = list(set([t.non_index_axes[0][0] for t in tbls]))[0] + axis = list(set(t.non_index_axes[0][0] for t in tbls))[0] def func(_start, _stop, _where): @@ -2238,7 +2238,7 @@ def set_version(self): version = _ensure_decoded( getattr(self.group._v_attrs, 'pandas_version', None)) try: - self.version = tuple([int(x) for x in version.split('.')]) + self.version = tuple(int(x) for x in version.split('.')) if len(self.version) == 2: self.version = self.version + (0,) except: @@ -2259,7 +2259,7 @@ def __unicode__(self): s = self.shape if s is not None: if isinstance(s, (list, tuple)): - s = "[%s]" % ','.join([pprint_thing(x) for x in s]) + s = "[%s]" % ','.join(pprint_thing(x) for x in s) return "%-12.12s (shape->%s)" % (self.pandas_type, s) return self.pandas_type @@ -2374,8 +2374,8 @@ class GenericFixed(Fixed): """ a generified fixed version """ _index_type_map = {DatetimeIndex: 'datetime', PeriodIndex: 'period'} - _reverse_index_map = dict([(v, k) - for k, v in compat.iteritems(_index_type_map)]) + _reverse_index_map = dict((v, k) + for k, v in compat.iteritems(_index_type_map)) attributes = [] # indexer helpders @@ -2997,11 +2997,11 @@ def __unicode__(self): ver = '' if self.is_old_version: - ver = "[%s]" % '.'.join([str(x) for x in self.version]) + ver = "[%s]" % '.'.join(str(x) for x in self.version) return "%-12.12s%s (typ->%s,nrows->%s,ncols->%s,indexers->[%s]%s)" % ( self.pandas_type, ver, self.table_type_short, self.nrows, - self.ncols, ','.join([a.name for a in self.index_axes]), dc + self.ncols, ','.join(a.name for a in self.index_axes), dc ) def __getitem__(self, c): @@ -3510,8 +3510,8 @@ def get_blk_items(mgr, blocks): # reorder the blocks in the same order as the existing_table if we can if existing_table is not None: - by_items = dict([(tuple(b_items.tolist()), (b, b_items)) - for b, b_items in zip(blocks, blk_items)]) + by_items = dict((tuple(b_items.tolist()), (b, b_items)) + for b, b_items in zip(blocks, blk_items)) new_blocks = [] new_blk_items = [] for ea in existing_table.values_axes: @@ -3659,7 +3659,7 @@ def create_description(self, complib=None, complevel=None, d = dict(name='table', expectedrows=expectedrows) # description from the axes & values - d['description'] = dict([(a.cname, a.typ) for a in self.axes]) + d['description'] = dict((a.cname, a.typ) for a in self.axes) if complib: if complevel is None: diff --git a/pandas/io/sql.py b/pandas/io/sql.py index c42c19e1357bc..82b1bff75b114 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1322,7 +1322,7 @@ def _create_table_setup(self): keys = [self.keys] else: keys = self.keys - cnames_br = ", ".join([escape(c) for c in keys]) + cnames_br = ", ".join(escape(c) for c in keys) create_tbl_stmts.append( "CONSTRAINT {tbl}_pk PRIMARY KEY ({cnames_br})".format( tbl=self.name, cnames_br=cnames_br)) @@ -1334,7 +1334,7 @@ def _create_table_setup(self): if is_index] if len(ix_cols): cnames = "_".join(ix_cols) - cnames_br = ",".join([escape(c) for c in ix_cols]) + cnames_br = ",".join(escape(c) for c in ix_cols) create_stmts.append( "CREATE INDEX " + escape("ix_" + self.name + "_" + cnames) + "ON " + escape(self.name) + " (" + cnames_br + ")") diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index aadd5a1beb28b..0f06d87726905 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -994,7 +994,7 @@ def _set_default_format(self, vmin, vmax): info) else: format = np.compress(info['maj'], info) - self.formatdict = dict([(x, f) for (x, _, _, f) in format]) + self.formatdict = dict((x, f) for (x, _, _, f) in format) return self.formatdict def set_locs(self, locs): diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index c934648a1d111..c18e17c69e753 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -608,7 +608,7 @@ def _get_index_name(self): if isinstance(self.data.index, MultiIndex): name = self.data.index.names if _any_not_none(*name): - name = ','.join([pprint_thing(x) for x in name]) + name = ','.join(pprint_thing(x) for x in name) else: name = None else: diff --git a/pandas/stats/moments.py b/pandas/stats/moments.py index 4e9e1b51e6fda..a0e94aa0c8581 100644 --- a/pandas/stats/moments.py +++ b/pandas/stats/moments.py @@ -219,8 +219,8 @@ def ensure_compat(dispatch, name, arg, func_kw=None, *args, **kwargs): # give a helpful deprecation message # with copy-pastable arguments - pargs = ','.join(["{a}={b}".format(a=a, b=b) - for a, b in kwargs.items() if b is not None]) + pargs = ','.join("{a}={b}".format(a=a, b=b) + for a, b in kwargs.items() if b is not None) aargs = ','.join(args) if len(aargs): aargs += ',' @@ -229,7 +229,7 @@ def f(a, b): if is_scalar(b): return "{a}={b}".format(a=a, b=b) return "{a}=<{b}>".format(a=a, b=type(b).__name__) - aargs = ','.join([f(a, b) for a, b in kwds.items() if b is not None]) + aargs = ','.join(f(a, b) for a, b in kwds.items() if b is not None) warnings.warn("pd.{dispatch}_{name} is deprecated for {klass} " "and will be removed in a future version, replace with " "\n\t{klass}.{dispatch}({pargs}).{name}({aargs})" diff --git a/pandas/tests/frame/common.py b/pandas/tests/frame/common.py index b475d25eb5dac..3786facdd4ebd 100644 --- a/pandas/tests/frame/common.py +++ b/pandas/tests/frame/common.py @@ -32,8 +32,8 @@ def frame2(self): @cache_readonly def intframe(self): # force these all to int64 to avoid platform testing issues - return pd.DataFrame(dict([(c, s) for c, s in - compat.iteritems(_intframe)]), + return pd.DataFrame(dict((c, s) for c, s in + compat.iteritems(_intframe)), dtype=np.int64) @cache_readonly @@ -112,7 +112,7 @@ def _check_mixed_float(df, dtype=None): # float16 are most likely to be upcasted to float32 dtypes = dict(A='float32', B='float32', C='float16', D='float64') if isinstance(dtype, compat.string_types): - dtypes = dict([(k, dtype) for k, v in dtypes.items()]) + dtypes = dict((k, dtype) for k, v in dtypes.items()) elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): @@ -128,7 +128,7 @@ def _check_mixed_float(df, dtype=None): def _check_mixed_int(df, dtype=None): dtypes = dict(A='int32', B='uint64', C='uint8', D='int64') if isinstance(dtype, compat.string_types): - dtypes = dict([(k, dtype) for k, v in dtypes.items()]) + dtypes = dict((k, dtype) for k, v in dtypes.items()) elif isinstance(dtype, dict): dtypes.update(dtype) if dtypes.get('A'): diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 8291e9d452348..6ca90d715cb0b 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -120,7 +120,7 @@ def _make_mixed_dtypes_df(typ, ad=None): assert(a.dtype == d) if ad is None: ad = dict() - ad.update(dict([(d, a) for d, a in zipper])) + ad.update(dict((d, a) for d, a in zipper)) return DataFrame(ad) def _check_mixed_dtypes(df, dtypes=None): @@ -696,8 +696,8 @@ def test_constructor_mrecarray(self): mrecs = mrecords.fromarrays(data, names=names) # fill the comb - comb = dict([(k, v.filled()) if hasattr( - v, 'filled') else (k, v) for k, v in comb]) + comb = dict((k, v.filled()) if hasattr( + v, 'filled') else (k, v) for k, v in comb) expected = DataFrame(comb, columns=names) result = DataFrame(mrecs) diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 5adcd3b6855ce..7591f1f1459be 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -420,8 +420,8 @@ def test_astype(self): # mixed casting def _check_cast(df, v): - assert (list(set([s.dtype.name for - _, s in compat.iteritems(df)]))[0] == v) + assert (list(set(s.dtype.name for + _, s in compat.iteritems(df)))[0] == v) mn = self.all_mixed._get_numeric_data().copy() mn['little_float'] = np.array(12345., dtype='float16') diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 78554d98ab5df..d35b67b52d16a 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -269,8 +269,8 @@ def test_getitem_boolean(self): data = df._get_numeric_data() bif = df[df > 0] - bifw = DataFrame(dict([(c, np.where(data[c] > 0, data[c], np.nan)) - for c in data.columns]), + bifw = DataFrame(dict((c, np.where(data[c] > 0, data[c], np.nan)) + for c in data.columns), index=data.index, columns=data.columns) # add back other columns to compare @@ -2375,8 +2375,8 @@ def is_ok(s): return (issubclass(s.dtype.type, (np.integer, np.floating)) and s.dtype != 'uint8') - return DataFrame(dict([(c, s + 1) if is_ok(s) else (c, s) - for c, s in compat.iteritems(df)])) + return DataFrame(dict((c, s + 1) if is_ok(s) else (c, s) + for c, s in compat.iteritems(df))) def _check_get(df, cond, check_dtypes=True): other1 = _safe_add(df) @@ -2399,9 +2399,9 @@ def _check_get(df, cond, check_dtypes=True): _check_get(df, cond) # upcasting case (GH # 2794) - df = DataFrame(dict([(c, Series([1] * 3, dtype=c)) - for c in ['int64', 'int32', - 'float32', 'float64']])) + df = DataFrame(dict((c, Series([1] * 3, dtype=c)) + for c in ['int64', 'int32', + 'float32', 'float64'])) df.iloc[1, :] = 0 result = df.where(df >= 0).get_dtype_counts() @@ -2453,8 +2453,8 @@ def _check_align(df, cond, other, check_dtypes=True): # integers are upcast, so don't check the dtypes cond = df > 0 - check_dtypes = all([not issubclass(s.type, np.integer) - for s in df.dtypes]) + check_dtypes = all(not issubclass(s.type, np.integer) + for s in df.dtypes) _check_align(df, cond, np.nan, check_dtypes=check_dtypes) # invalid conditions diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 03f780957b15e..91a5569b352e9 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -257,7 +257,7 @@ def test_len(self): assert len(grouped) == len(df) grouped = df.groupby([lambda x: x.year, lambda x: x.month]) - expected = len(set([(x.year, x.month) for x in df.index])) + expected = len(set((x.year, x.month) for x in df.index)) assert len(grouped) == expected # issue 11016 diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index e8e2150558edb..977c639d79711 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -238,7 +238,7 @@ def test_groupby_blacklist(df_letters): def test_tab_completion(mframe): grp = mframe.groupby(level='second') - results = set([v for v in dir(grp) if not v.startswith('_')]) + results = set(v for v in dir(grp) if not v.startswith('_')) expected = { 'A', 'B', 'C', 'agg', 'aggregate', 'apply', 'boxplot', 'filter', 'first', 'get_group', 'groups', 'hist', 'indices', 'last', 'max', diff --git a/pandas/tests/indexing/test_panel.py b/pandas/tests/indexing/test_panel.py index 2d4ffd6a4e783..4d7768c9e8083 100644 --- a/pandas/tests/indexing/test_panel.py +++ b/pandas/tests/indexing/test_panel.py @@ -119,7 +119,7 @@ def test_panel_getitem(self): df = DataFrame( np.random.randn( len(ind), 5), index=ind, columns=list('ABCDE')) - panel = Panel(dict([('frame_' + c, df) for c in list('ABC')])) + panel = Panel(dict(('frame_' + c, df) for c in list('ABC'))) test2 = panel.loc[:, "2002":"2002-12-31"] test1 = panel.loc[:, "2002"] diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 8d2745689cad1..bfaa47bf39f83 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1158,7 +1158,7 @@ def test_to_string(self): float_format='%.5f'.__mod__) lines = result.split('\n') header = lines[0].strip().split() - joined = '\n'.join([re.sub(r'\s+', ' ', x).strip() for x in lines[1:]]) + joined = '\n'.join(re.sub(r'\s+', ' ', x).strip() for x in lines[1:]) recons = read_table(StringIO(joined), names=header, header=None, sep=' ') tm.assert_series_equal(recons['B'], biggie['B']) diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 7335e1ce0f06f..eb3db24d36947 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -675,9 +675,10 @@ def test_display_format(self): df = pd.DataFrame(np.random.random(size=(2, 2))) ctx = df.style.format("{:0.1f}")._translate() - assert all(['display_value' in c for c in row] for row in ctx['body']) - assert (all([len(c['display_value']) <= 3 for c in row[1:]] - for row in ctx['body'])) + assert all(['display_value' in c for c in row] + for row in ctx['body']) + assert all([len(c['display_value']) <= 3 for c in row[1:]] + for row in ctx['body']) assert len(ctx['body'][0][1]['display_value'].lstrip('-')) <= 3 def test_display_format_raises(self): diff --git a/pandas/tests/io/msgpack/test_case.py b/pandas/tests/io/msgpack/test_case.py index 3927693a94dd8..9bb34a70e2593 100644 --- a/pandas/tests/io/msgpack/test_case.py +++ b/pandas/tests/io/msgpack/test_case.py @@ -98,10 +98,10 @@ def test_match(): (tuple(range(16)), (b"\xdc\x00\x10\x00\x01\x02\x03\x04\x05\x06\x07" b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")), ({}, b'\x80'), - (dict([(x, x) for x in range(15)]), + (dict((x, x) for x in range(15)), (b'\x8f\x00\x00\x01\x01\x02\x02\x03\x03\x04\x04\x05\x05\x06\x06\x07' b'\x07\x08\x08\t\t\n\n\x0b\x0b\x0c\x0c\r\r\x0e\x0e')), - (dict([(x, x) for x in range(16)]), + (dict((x, x) for x in range(16)), (b'\xde\x00\x10\x00\x00\x01\x01\x02\x02\x03\x03\x04\x04\x05\x05\x06' b'\x06\x07\x07\x08\x08\t\t\n\n\x0b\x0b\x0c\x0c\r\r\x0e\x0e' b'\x0f\x0f')), diff --git a/pandas/tests/io/parser/na_values.py b/pandas/tests/io/parser/na_values.py index 8dc599b42ddc7..f8906d5a1f7ba 100644 --- a/pandas/tests/io/parser/na_values.py +++ b/pandas/tests/io/parser/na_values.py @@ -88,7 +88,7 @@ def f(i, v): return buf - data = StringIO('\n'.join([f(i, v) for i, v in enumerate(_NA_VALUES)])) + data = StringIO('\n'.join(f(i, v) for i, v in enumerate(_NA_VALUES))) expected = DataFrame(np.nan, columns=range(nv), index=range(nv)) df = self.read_csv(data, header=None) tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 13bf81889af1a..ca20d089ee5f7 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -1391,7 +1391,7 @@ def test_append_with_strings(self): with catch_warnings(record=True): wp = tm.makePanel() wp2 = wp.rename_axis( - dict([(x, "%s_extra" % x) for x in wp.minor_axis]), axis=2) + dict((x, "%s_extra" % x) for x in wp.minor_axis), axis=2) def check_col(key, name, size): assert getattr(store.get_storer(key) @@ -2143,9 +2143,9 @@ def test_table_values_dtypes_roundtrip(self): assert df1.dtypes[0] == 'float32' # check with mixed dtypes - df1 = DataFrame(dict([(c, Series(np.random.randn(5), dtype=c)) - for c in ['float32', 'float64', 'int32', - 'int64', 'int16', 'int8']])) + df1 = DataFrame(dict((c, Series(np.random.randn(5), dtype=c)) + for c in ['float32', 'float64', 'int32', + 'int64', 'int16', 'int8'])) df1['string'] = 'foo' df1['float322'] = 1. df1['float322'] = df1['float322'].astype('float32') diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 2df43158b5370..00a30940ca352 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -2243,8 +2243,8 @@ def test_onecolumn_of_integer(self): sql.to_sql(mono_df, con=self.conn, name='mono_df', index=False) # computing the sum via sql con_x = self.conn - the_sum = sum([my_c0[0] - for my_c0 in con_x.execute("select * from mono_df")]) + the_sum = sum(my_c0[0] + for my_c0 in con_x.execute("select * from mono_df")) # it should not fail, and gives 3 ( Issue #3628 ) assert the_sum == 3 diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 11dca1abc5ec7..3887271edb2a3 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1162,14 +1162,13 @@ def _check_bar_alignment(self, df, kind='bar', stacked=False, if kind == 'bar': axis = ax.xaxis ax_min, ax_max = ax.get_xlim() - min_edge = min([p.get_x() for p in ax.patches]) - max_edge = max([p.get_x() + p.get_width() for p in ax.patches]) + min_edge = min(p.get_x() for p in ax.patches) + max_edge = max(p.get_x() + p.get_width() for p in ax.patches) elif kind == 'barh': axis = ax.yaxis ax_min, ax_max = ax.get_ylim() - min_edge = min([p.get_y() for p in ax.patches]) - max_edge = max([p.get_y() + p.get_height() for p in ax.patches - ]) + min_edge = min(p.get_y() for p in ax.patches) + max_edge = max(p.get_y() + p.get_height() for p in ax.patches) else: raise ValueError diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index fd5b4611e58d6..ae41502f237f1 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -1385,14 +1385,14 @@ def df(): return DataFrame(np.random.randn(index, cols), index=["I%s" % i for i in range(index)], columns=["C%s" % i for i in range(cols)]) - return Panel(dict([("Item%s" % x, df()) - for x in ['A', 'B', 'C']])) + return Panel(dict(("Item%s" % x, df()) + for x in ['A', 'B', 'C'])) panel1 = make_panel() panel2 = make_panel() - panel2 = panel2.rename_axis(dict([(x, "%s_1" % x) - for x in panel2.major_axis]), + panel2 = panel2.rename_axis(dict((x, "%s_1" % x) + for x in panel2.major_axis), axis=1) panel3 = panel2.rename_axis(lambda x: '%s_1' % x, axis=1) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 42df2e26b301f..0e783d67517ac 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1350,18 +1350,18 @@ def test_apply_slabs(self): # make sure that we don't trigger any warnings result = self.panel.apply(f, axis=['items', 'major_axis']) - expected = Panel(dict([(ax, f(self.panel.loc[:, :, ax])) - for ax in self.panel.minor_axis])) + expected = Panel(dict((ax, f(self.panel.loc[:, :, ax])) + for ax in self.panel.minor_axis)) assert_panel_equal(result, expected) result = self.panel.apply(f, axis=['major_axis', 'minor_axis']) - expected = Panel(dict([(ax, f(self.panel.loc[ax])) - for ax in self.panel.items])) + expected = Panel(dict((ax, f(self.panel.loc[ax])) + for ax in self.panel.items)) assert_panel_equal(result, expected) result = self.panel.apply(f, axis=['minor_axis', 'items']) - expected = Panel(dict([(ax, f(self.panel.loc[:, ax])) - for ax in self.panel.major_axis])) + expected = Panel(dict((ax, f(self.panel.loc[:, ax])) + for ax in self.panel.major_axis)) assert_panel_equal(result, expected) # with multi-indexes diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 742b8a5ac9a55..2427bcea4053d 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -2505,14 +2505,14 @@ def test_corr_sanity(self): [0.84780328, 0.33394331], [0.78369152, 0.63919667]])) res = df[0].rolling(5, center=True).corr(df[1]) - assert all([np.abs(np.nan_to_num(x)) <= 1 for x in res]) + assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res) # and some fuzzing for _ in range(10): df = DataFrame(np.random.rand(30, 2)) res = df[0].rolling(5, center=True).corr(df[1]) try: - assert all([np.abs(np.nan_to_num(x)) <= 1 for x in res]) + assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res) except AssertionError: print(res) diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index d8bfa3013f8f7..957352d9ff13f 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -439,7 +439,7 @@ def merge_class(base, other): if not isinstance(base, list): base = [base] - base_holidays = dict([(holiday.name, holiday) for holiday in base]) + base_holidays = dict((holiday.name, holiday) for holiday in base) other_holidays.update(base_holidays) return list(other_holidays.values()) diff --git a/scripts/api_rst_coverage.py b/scripts/api_rst_coverage.py index 6bb5383509be6..45340ba0923c4 100644 --- a/scripts/api_rst_coverage.py +++ b/scripts/api_rst_coverage.py @@ -22,7 +22,7 @@ def class_name_sort_key(x): api_rst_members = set() file_name = '../doc/source/api.rst' with open(file_name, 'r') as f: - pattern = re.compile('({})\.(\w+)'.format('|'.join([cls.__name__ for cls in classes]))) + pattern = re.compile('({})\.(\w+)'.format('|'.join(cls.__name__ for cls in classes))) for line in f: match = pattern.search(line) if match: diff --git a/scripts/find_commits_touching_func.py b/scripts/find_commits_touching_func.py index 74ea120bf0b64..f9440f6f8807a 100755 --- a/scripts/find_commits_touching_func.py +++ b/scripts/find_commits_touching_func.py @@ -88,7 +88,7 @@ def get_hits(defname,files=()): # remove comment lines lines = [x for x in lines if not re.search("^\w+\s*\(.+\)\s*#",x)] hits = set(map(lambda x: x.split(" ")[0],lines)) - cs.update(set([Hit(commit=c,path=f) for c in hits])) + cs.update(set(Hit(commit=c,path=f) for c in hits)) return cs @@ -101,12 +101,12 @@ def get_commit_vitals(c,hlen=HASH_LEN): return h[:hlen],s,parse_date(d) def file_filter(state,dirname,fnames): - if args.dir_masks and not any([re.search(x,dirname) for x in args.dir_masks]): + if args.dir_masks and not any(re.search(x,dirname) for x in args.dir_masks): return for f in fnames: p = os.path.abspath(os.path.join(os.path.realpath(dirname),f)) - if any([re.search(x,f) for x in args.file_masks])\ - or any([re.search(x,p) for x in args.path_masks]): + if any(re.search(x,f) for x in args.file_masks)\ + or any(re.search(x,p) for x in args.path_masks): if os.path.isfile(p): state['files'].append(p) diff --git a/scripts/merge-pr.py b/scripts/merge-pr.py index 1fc4eef3d0583..11cc96609be94 100755 --- a/scripts/merge-pr.py +++ b/scripts/merge-pr.py @@ -160,7 +160,7 @@ def merge_pr(pr_num, target_ref): if body is not None: merge_message_flags += ["-m", '\n'.join(textwrap.wrap(body))] - authors = "\n".join(["Author: %s" % a for a in distinct_authors]) + authors = "\n".join("Author: %s" % a for a in distinct_authorsS) merge_message_flags += ["-m", authors] diff --git a/versioneer.py b/versioneer.py index 104e8e97c6bd6..59228ec63c136 100644 --- a/versioneer.py +++ b/versioneer.py @@ -606,11 +606,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d @@ -619,7 +619,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set(r for r in refs if re.search(r'\d', r)) if verbose: print("discarding '%%s', no digits" %% ",".join(refs-tags)) if verbose: @@ -960,11 +960,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -973,7 +973,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set(r for r in refs if re.search(r'\d', r)) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose:
- [x] tests passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Continuation of #18276 plus a lint check for list comprehension in built-in Python functions. The grep will only catch list comprehensions on single lines though. I'm all ears for greps that can catch multi-line list comprehensions or a better grep in general.
https://api.github.com/repos/pandas-dev/pandas/pulls/18335
2017-11-17T02:20:45Z
2017-11-19T15:05:35Z
2017-11-19T15:05:35Z
2017-11-22T19:21:38Z
TST: add downstream deps in 3.6 build
diff --git a/ci/requirements-3.6.sh b/ci/requirements-3.6.sh new file mode 100644 index 0000000000000..dfc123c88f24b --- /dev/null +++ b/ci/requirements-3.6.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +source activate pandas + +echo "[install 3.6 downstream deps]" + +conda install -n pandas -c conda-forge pandas-gbq pandas-datareader xarray geopandas seaborn statsmodels scikit-learn dask diff --git a/ci/script_multi.sh b/ci/script_multi.sh index 863613e14af98..e03d60360c800 100755 --- a/ci/script_multi.sh +++ b/ci/script_multi.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/bin/bash -e echo "[script multi]"
https://api.github.com/repos/pandas-dev/pandas/pulls/18333
2017-11-17T00:52:21Z
2017-11-17T11:28:38Z
2017-11-17T11:28:38Z
2017-12-11T20:24:09Z
CLN: replace %s syntax with .format in core.indexing and core.internals
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index e242e928687ff..ae799afdb4135 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1842,8 +1842,8 @@ def _convert_to_indexer(self, obj, axis=None, is_setter=False): elif self._has_valid_type(obj, axis): return obj - raise ValueError("Can only index by location with a [%s]" % - self._valid_types) + raise ValueError("Can only index by location with " + "a [{types}]".format(types=self._valid_types)) class _ScalarAccessIndexer(_NDFrameIndexer): diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 665f9ff8eb7a0..07d0f0ffe54ba 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -115,9 +115,9 @@ def __init__(self, values, placement, ndim=None, fastpath=False): self.values = values if ndim and len(self.mgr_locs) != len(self.values): - raise ValueError('Wrong number of items passed %d, placement ' - 'implies %d' % (len(self.values), - len(self.mgr_locs))) + raise ValueError( + 'Wrong number of items passed {val}, placement implies ' + '{mgr}'.format(val=len(self.values), mgr=len(self.mgr_locs))) @property def _consolidate_key(self): @@ -236,13 +236,15 @@ def __unicode__(self): name = pprint_thing(self.__class__.__name__) if self._is_single_block: - result = '%s: %s dtype: %s' % (name, len(self), self.dtype) + result = '{name}: {len} dtype: {dtype}'.format( + name=name, len=len(self), dtype=self.dtype) else: shape = ' x '.join([pprint_thing(s) for s in self.shape]) - result = '%s: %s, %s, dtype: %s' % (name, pprint_thing( - self.mgr_locs.indexer), shape, self.dtype) + result = '{name}: {index}, {shape}, dtype: {dtype}'.format( + name=name, index=pprint_thing(self.mgr_locs.indexer), + shape=shape, dtype=self.dtype) return result @@ -310,7 +312,7 @@ def dtype(self): @property def ftype(self): - return "%s:%s" % (self.dtype, self._ftype) + return "{dtype}:{ftype}".format(dtype=self.dtype, ftype=self._ftype) def merge(self, other): return _merge_blocks([self, other]) @@ -330,7 +332,8 @@ def reindex_axis(self, indexer, method=None, axis=1, fill_value=None, Reindex using pre-computed indexer information """ if axis < 1: - raise AssertionError('axis must be at least 1, got %d' % axis) + raise AssertionError( + 'axis must be at least 1, got {axis}'.format(axis=axis)) if fill_value is None: fill_value = self.fill_value @@ -634,11 +637,13 @@ def _astype(self, dtype, copy=False, errors='raise', values=None, if newb.is_numeric and self.is_numeric: if newb.shape != self.shape: - raise TypeError("cannot set astype for copy = [%s] for dtype " - "(%s [%s]) with smaller itemsize that current " - "(%s [%s])" % (copy, self.dtype.name, - self.itemsize, newb.dtype.name, - newb.itemsize)) + raise TypeError( + "cannot set astype for copy = [{copy}] for dtype " + "({dtype} [{itemsize}]) with smaller itemsize than " + "current ({newb_dtype} [{newb_size}])".format( + copy=copy, dtype=self.dtype.name, + itemsize=self.itemsize, newb_dtype=newb.dtype.name, + newb_size=newb.itemsize)) return newb def convert(self, copy=True, **kwargs): @@ -1306,9 +1311,10 @@ def eval(self, func, other, errors='raise', try_cast=False, mgr=None): is_transposed = True else: # this is a broadcast error heree - raise ValueError("cannot broadcast shape [%s] with block " - "values [%s]" % (values.T.shape, - other.shape)) + raise ValueError( + "cannot broadcast shape [{t_shape}] with " + "block values [{oth_shape}]".format( + t_shape=values.T.shape, oth_shape=other.shape)) transf = (lambda x: x.T) if is_transposed else (lambda x: x) @@ -1363,8 +1369,9 @@ def handle_error(): if errors == 'raise': # The 'detail' variable is defined in outer scope. - raise TypeError('Could not operate %s with block values %s' % - (repr(other), str(detail))) # noqa + raise TypeError( + 'Could not operate {other!r} with block values ' + '{detail!s}'.format(other=other, detail=detail)) # noqa else: # return the values result = np.empty(values.shape, dtype='O') @@ -1391,11 +1398,12 @@ def handle_error(): # differentiate between an invalid ndarray-ndarray comparison # and an invalid type comparison if isinstance(values, np.ndarray) and is_list_like(other): - raise ValueError('Invalid broadcasting comparison [%s] ' - 'with block values' % repr(other)) + raise ValueError( + 'Invalid broadcasting comparison [{other!r}] with ' + 'block values'.format(other=other)) - raise TypeError('Could not compare [%s] with block values' % - repr(other)) + raise TypeError('Could not compare [{other!r}] ' + 'with block values'.format(other=other)) # transpose if needed result = transf(result) @@ -1466,8 +1474,9 @@ def func(cond, values, other): cond, values, other)) except Exception as detail: if errors == 'raise': - raise TypeError('Could not operate [%s] with block values ' - '[%s]' % (repr(other), str(detail))) + raise TypeError( + 'Could not operate [{other!r}] with block values ' + '[{detail!s}]'.format(other=other, detail=detail)) else: # return the values result = np.empty(values.shape, dtype='float64') @@ -2894,7 +2903,8 @@ def reindex_axis(self, indexer, method=None, axis=1, fill_value=None, Reindex using pre-computed indexer information """ if axis < 1: - raise AssertionError('axis must be at least 1, got %d' % axis) + raise AssertionError( + 'axis must be at least 1, got {axis}'.format(axis=axis)) # taking on the 0th axis always here if fill_value is None: @@ -3020,9 +3030,10 @@ def __init__(self, blocks, axes, do_integrity_check=True, fastpath=True): "items") else: if self.ndim != block.ndim: - raise AssertionError('Number of Block dimensions (%d) ' - 'must equal number of axes (%d)' % - (block.ndim, self.ndim)) + raise AssertionError( + 'Number of Block dimensions ({block}) must equal ' + 'number of axes ({self})'.format(block=block.ndim, + self=self.ndim)) if do_integrity_check: self._verify_integrity() @@ -3064,9 +3075,9 @@ def set_axis(self, axis, new_labels): new_len = len(new_labels) if new_len != old_len: - raise ValueError('Length mismatch: Expected axis has %d elements, ' - 'new values have %d elements' % - (old_len, new_len)) + raise ValueError( + 'Length mismatch: Expected axis has {old} elements, new ' + 'values have {new} elements'.format(old=old_len, new=new_len)) self.axes[axis] = new_labels @@ -3223,12 +3234,12 @@ def __unicode__(self): output = pprint_thing(self.__class__.__name__) for i, ax in enumerate(self.axes): if i == 0: - output += u('\nItems: %s') % ax + output += u('\nItems: {ax}'.format(ax=ax)) else: - output += u('\nAxis %d: %s') % (i, ax) + output += u('\nAxis {i}: {ax}'.format(i=i, ax=ax)) for block in self.blocks: - output += u('\n%s') % pprint_thing(block) + output += u('\n{block}'.format(block=pprint_thing(block))) return output def _verify_integrity(self): @@ -3732,8 +3743,8 @@ def to_dict(self, copy=True): def xs(self, key, axis=1, copy=True, takeable=False): if axis < 1: - raise AssertionError('Can only take xs across axis >= 1, got %d' % - axis) + raise AssertionError( + 'Can only take xs across axis >= 1, got {ax}'.format(ax=axis)) # take by position if takeable: @@ -4284,8 +4295,9 @@ def _is_indexed_like(self, other): Check all axes except items """ if self.ndim != other.ndim: - raise AssertionError('Number of dimensions must agree ' - 'got %d and %d' % (self.ndim, other.ndim)) + raise AssertionError( + 'Number of dimensions must agree got {ndim} and ' + '{oth_ndim}'.format(ndim=self.ndim, oth_ndim=other.ndim)) for ax, oax in zip(self.axes[1:], other.axes[1:]): if not ax.equals(oax): return False @@ -4934,12 +4946,14 @@ def _maybe_compare(a, b, op): type_names = [type(a).__name__, type(b).__name__] if is_a_array: - type_names[0] = 'ndarray(dtype=%s)' % a.dtype + type_names[0] = 'ndarray(dtype={dtype})'.format(dtype=a.dtype) if is_b_array: - type_names[1] = 'ndarray(dtype=%s)' % b.dtype + type_names[1] = 'ndarray(dtype={dtype})'.format(dtype=b.dtype) - raise TypeError("Cannot compare types %r and %r" % tuple(type_names)) + raise TypeError( + "Cannot compare types {a!r} and {b!r}".format(a=type_names[0], + b=type_names[1])) return result @@ -5017,17 +5031,17 @@ def items_overlap_with_suffix(left, lsuffix, right, rsuffix): return left, right else: if not lsuffix and not rsuffix: - raise ValueError('columns overlap but no suffix specified: %s' % - to_rename) + raise ValueError('columns overlap but no suffix specified: ' + '{rename}'.format(rename=to_rename)) def lrenamer(x): if x in to_rename: - return '%s%s' % (x, lsuffix) + return '{x}{lsuffix}'.format(x=x, lsuffix=lsuffix) return x def rrenamer(x): if x in to_rename: - return '%s%s' % (x, rsuffix) + return '{x}{rsuffix}'.format(x=x, rsuffix=rsuffix) return x return (_transform_index(left, lrenamer), @@ -5519,8 +5533,9 @@ def __init__(self, block, shape, indexers=None): self.shape = shape def __repr__(self): - return '%s(%r, %s)' % (self.__class__.__name__, self.block, - self.indexers) + return '{name}({block!r}, {indexers})'.format( + name=self.__class__.__name__, block=self.block, + indexers=self.indexers) @cache_readonly def needs_filling(self):
- [x] Progress towards #16130 - [x] tests added / passed - [x] passes git diff upstream/master -u -- "*.py" | flake8 --diff
https://api.github.com/repos/pandas-dev/pandas/pulls/18331
2017-11-16T23:53:41Z
2017-11-19T00:34:04Z
2017-11-19T00:34:04Z
2017-11-19T22:28:45Z
ENH: allow get_dummies to accept dtype argument
diff --git a/doc/source/reshaping.rst b/doc/source/reshaping.rst index 1209c4a8d6be8..1b81d83bb76c7 100644 --- a/doc/source/reshaping.rst +++ b/doc/source/reshaping.rst @@ -240,7 +240,7 @@ values will be set to ``NaN``. df3 df3.unstack() -.. versionadded: 0.18.0 +.. versionadded:: 0.18.0 Alternatively, unstack takes an optional ``fill_value`` argument, for specifying the value of missing data. @@ -634,6 +634,17 @@ When a column contains only one level, it will be omitted in the result. pd.get_dummies(df, drop_first=True) +By default new columns will have ``np.uint8`` dtype. To choose another dtype use ``dtype`` argument: + +.. ipython:: python + + df = pd.DataFrame({'A': list('abc'), 'B': [1.1, 2.2, 3.3]}) + + pd.get_dummies(df, dtype=bool).dtypes + +.. versionadded:: 0.22.0 + + .. _reshaping.factorize: Factorizing values diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 4f403ff8053a7..162a1ca2bfcb3 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -17,6 +17,21 @@ New features - - + +.. _whatsnew_0210.enhancements.get_dummies_dtype: + +``get_dummies`` now supports ``dtype`` argument +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The :func:`get_dummies` now accepts a ``dtype`` argument, which specifies a dtype for the new columns. The default remains uint8. (:issue:`18330`) + +.. ipython:: python + + df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}) + pd.get_dummies(df, columns=['c']).dtypes + pd.get_dummies(df, columns=['c'], dtype=bool).dtypes + + .. _whatsnew_0220.enhancements.other: Other Enhancements diff --git a/pandas/core/generic.py b/pandas/core/generic.py index cbc259ba7bceb..782971a742b54 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -965,7 +965,7 @@ def _set_axis_name(self, name, axis=0, inplace=False): inplace : bool whether to modify `self` directly or return a copy - .. versionadded: 0.21.0 + .. versionadded:: 0.21.0 Returns ------- diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 8b656d8ba25e9..5bb86885c0875 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -10,7 +10,7 @@ from pandas.core.dtypes.common import ( _ensure_platform_int, is_list_like, is_bool_dtype, - needs_i8_conversion, is_sparse) + needs_i8_conversion, is_sparse, is_object_dtype) from pandas.core.dtypes.cast import maybe_promote from pandas.core.dtypes.missing import notna @@ -697,7 +697,7 @@ def _convert_level_number(level_num, columns): def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, - columns=None, sparse=False, drop_first=False): + columns=None, sparse=False, drop_first=False, dtype=None): """ Convert categorical variable into dummy/indicator variables @@ -728,6 +728,11 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, .. versionadded:: 0.18.0 + dtype : dtype, default np.uint8 + Data type for new columns. Only a single dtype is allowed. + + .. versionadded:: 0.22.0 + Returns ------- dummies : DataFrame or SparseDataFrame @@ -783,6 +788,12 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, 3 0 0 4 0 0 + >>> pd.get_dummies(pd.Series(list('abc')), dtype=float) + a b c + 0 1.0 0.0 0.0 + 1 0.0 1.0 0.0 + 2 0.0 0.0 1.0 + See Also -------- Series.str.get_dummies @@ -835,20 +846,29 @@ def check_len(item, name): dummy = _get_dummies_1d(data[col], prefix=pre, prefix_sep=sep, dummy_na=dummy_na, sparse=sparse, - drop_first=drop_first) + drop_first=drop_first, dtype=dtype) with_dummies.append(dummy) result = concat(with_dummies, axis=1) else: result = _get_dummies_1d(data, prefix, prefix_sep, dummy_na, - sparse=sparse, drop_first=drop_first) + sparse=sparse, + drop_first=drop_first, + dtype=dtype) return result def _get_dummies_1d(data, prefix, prefix_sep='_', dummy_na=False, - sparse=False, drop_first=False): + sparse=False, drop_first=False, dtype=None): # Series avoids inconsistent NaN handling codes, levels = _factorize_from_iterable(Series(data)) + if dtype is None: + dtype = np.uint8 + dtype = np.dtype(dtype) + + if is_object_dtype(dtype): + raise ValueError("dtype=object is not a valid dtype for get_dummies") + def get_empty_Frame(data, sparse): if isinstance(data, Series): index = data.index @@ -903,18 +923,18 @@ def get_empty_Frame(data, sparse): sp_indices = sp_indices[1:] dummy_cols = dummy_cols[1:] for col, ixs in zip(dummy_cols, sp_indices): - sarr = SparseArray(np.ones(len(ixs), dtype=np.uint8), + sarr = SparseArray(np.ones(len(ixs), dtype=dtype), sparse_index=IntIndex(N, ixs), fill_value=0, - dtype=np.uint8) + dtype=dtype) sparse_series[col] = SparseSeries(data=sarr, index=index) out = SparseDataFrame(sparse_series, index=index, columns=dummy_cols, default_fill_value=0, - dtype=np.uint8) + dtype=dtype) return out else: - dummy_mat = np.eye(number_of_cols, dtype=np.uint8).take(codes, axis=0) + dummy_mat = np.eye(number_of_cols, dtype=dtype).take(codes, axis=0) if not dummy_na: # reset NaN GH4446 diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index 2722c3e92d85a..5d4aa048ae303 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -218,35 +218,51 @@ def test_multiindex(self): class TestGetDummies(object): - sparse = False - - def setup_method(self, method): - self.df = DataFrame({'A': ['a', 'b', 'a'], - 'B': ['b', 'b', 'c'], - 'C': [1, 2, 3]}) + @pytest.fixture + def df(self): + return DataFrame({'A': ['a', 'b', 'a'], + 'B': ['b', 'b', 'c'], + 'C': [1, 2, 3]}) + + @pytest.fixture(params=['uint8', 'i8', np.float64, bool, None]) + def dtype(self, request): + return np.dtype(request.param) + + @pytest.fixture(params=['dense', 'sparse']) + def sparse(self, request): + # params are strings to simplify reading test results, + # e.g. TestGetDummies::test_basic[uint8-sparse] instead of [uint8-True] + return request.param == 'sparse' + + def effective_dtype(self, dtype): + if dtype is None: + return np.uint8 + return dtype + + def test_raises_on_dtype_object(self, df): + with pytest.raises(ValueError): + get_dummies(df, dtype='object') - def test_basic(self): + def test_basic(self, sparse, dtype): s_list = list('abc') s_series = Series(s_list) s_series_index = Series(s_list, list('ABC')) - expected = DataFrame({'a': {0: 1, - 1: 0, - 2: 0}, - 'b': {0: 0, - 1: 1, - 2: 0}, - 'c': {0: 0, - 1: 0, - 2: 1}}, dtype=np.uint8) - assert_frame_equal(get_dummies(s_list, sparse=self.sparse), expected) - assert_frame_equal(get_dummies(s_series, sparse=self.sparse), expected) + expected = DataFrame({'a': [1, 0, 0], + 'b': [0, 1, 0], + 'c': [0, 0, 1]}, + dtype=self.effective_dtype(dtype)) + result = get_dummies(s_list, sparse=sparse, dtype=dtype) + assert_frame_equal(result, expected) + + result = get_dummies(s_series, sparse=sparse, dtype=dtype) + assert_frame_equal(result, expected) expected.index = list('ABC') - assert_frame_equal( - get_dummies(s_series_index, sparse=self.sparse), expected) + result = get_dummies(s_series_index, sparse=sparse, dtype=dtype) + assert_frame_equal(result, expected) - def test_basic_types(self): + def test_basic_types(self, sparse, dtype): # GH 10531 s_list = list('abc') s_series = Series(s_list) @@ -257,38 +273,43 @@ def test_basic_types(self): expected = DataFrame({'a': [1, 0, 0], 'b': [0, 1, 0], 'c': [0, 0, 1]}, - dtype='uint8', + dtype=self.effective_dtype(dtype), columns=list('abc')) - if not self.sparse: + if not sparse: compare = tm.assert_frame_equal else: expected = expected.to_sparse(fill_value=0, kind='integer') compare = tm.assert_sp_frame_equal - result = get_dummies(s_list, sparse=self.sparse) + result = get_dummies(s_list, sparse=sparse, dtype=dtype) compare(result, expected) - result = get_dummies(s_series, sparse=self.sparse) + result = get_dummies(s_series, sparse=sparse, dtype=dtype) compare(result, expected) - result = get_dummies(s_df, sparse=self.sparse, columns=s_df.columns) + result = get_dummies(s_df, columns=s_df.columns, + sparse=sparse, dtype=dtype) tm.assert_series_equal(result.get_dtype_counts(), - Series({'uint8': 8})) + Series({dtype.name: 8})) - result = get_dummies(s_df, sparse=self.sparse, columns=['a']) - expected = Series({'uint8': 3, 'int64': 1, 'object': 1}).sort_values() + result = get_dummies(s_df, columns=['a'], sparse=sparse, dtype=dtype) + dtype_name = self.effective_dtype(dtype).name + + expected_counts = {'int64': 1, 'object': 1} + expected_counts[dtype_name] = 3 + expected_counts.get(dtype_name, 0) + + expected = Series(expected_counts).sort_values() tm.assert_series_equal(result.get_dtype_counts().sort_values(), expected) - def test_just_na(self): + def test_just_na(self, sparse): just_na_list = [np.nan] just_na_series = Series(just_na_list) just_na_series_index = Series(just_na_list, index=['A']) - res_list = get_dummies(just_na_list, sparse=self.sparse) - res_series = get_dummies(just_na_series, sparse=self.sparse) - res_series_index = get_dummies(just_na_series_index, - sparse=self.sparse) + res_list = get_dummies(just_na_list, sparse=sparse) + res_series = get_dummies(just_na_series, sparse=sparse) + res_series_index = get_dummies(just_na_series_index, sparse=sparse) assert res_list.empty assert res_series.empty @@ -298,216 +319,209 @@ def test_just_na(self): assert res_series.index.tolist() == [0] assert res_series_index.index.tolist() == ['A'] - def test_include_na(self): + def test_include_na(self, sparse, dtype): + if sparse: + pytest.xfail(reason='nan in index is problematic (GH 16894)') + s = ['a', 'b', np.nan] - res = get_dummies(s, sparse=self.sparse) - exp = DataFrame({'a': {0: 1, 1: 0, 2: 0}, - 'b': {0: 0, 1: 1, 2: 0}}, dtype=np.uint8) + res = get_dummies(s, sparse=sparse, dtype=dtype) + exp = DataFrame({'a': [1, 0, 0], + 'b': [0, 1, 0]}, + dtype=self.effective_dtype(dtype)) assert_frame_equal(res, exp) # Sparse dataframes do not allow nan labelled columns, see #GH8822 - res_na = get_dummies(s, dummy_na=True, sparse=self.sparse) - exp_na = DataFrame({nan: {0: 0, 1: 0, 2: 1}, - 'a': {0: 1, 1: 0, 2: 0}, - 'b': {0: 0, 1: 1, 2: 0}}, - dtype=np.uint8) + res_na = get_dummies(s, dummy_na=True, sparse=sparse, dtype=dtype) + exp_na = DataFrame({nan: [0, 0, 1], + 'a': [1, 0, 0], + 'b': [0, 1, 0]}, + dtype=self.effective_dtype(dtype)) exp_na = exp_na.reindex(['a', 'b', nan], axis=1) # hack (NaN handling in assert_index_equal) exp_na.columns = res_na.columns assert_frame_equal(res_na, exp_na) - res_just_na = get_dummies([nan], dummy_na=True, sparse=self.sparse) + res_just_na = get_dummies([nan], dummy_na=True, + sparse=sparse, dtype=dtype) exp_just_na = DataFrame(Series(1, index=[0]), columns=[nan], - dtype=np.uint8) + dtype=self.effective_dtype(dtype)) tm.assert_numpy_array_equal(res_just_na.values, exp_just_na.values) - def test_unicode(self - ): # See GH 6885 - get_dummies chokes on unicode values + def test_unicode(self, sparse): + # See GH 6885 - get_dummies chokes on unicode values import unicodedata e = 'e' eacute = unicodedata.lookup('LATIN SMALL LETTER E WITH ACUTE') s = [e, eacute, eacute] - res = get_dummies(s, prefix='letter', sparse=self.sparse) - exp = DataFrame({'letter_e': {0: 1, - 1: 0, - 2: 0}, - u('letter_%s') % eacute: {0: 0, - 1: 1, - 2: 1}}, + res = get_dummies(s, prefix='letter', sparse=sparse) + exp = DataFrame({'letter_e': [1, 0, 0], + u('letter_%s') % eacute: [0, 1, 1]}, dtype=np.uint8) assert_frame_equal(res, exp) - def test_dataframe_dummies_all_obj(self): - df = self.df[['A', 'B']] - result = get_dummies(df, sparse=self.sparse) + def test_dataframe_dummies_all_obj(self, df, sparse): + df = df[['A', 'B']] + result = get_dummies(df, sparse=sparse) expected = DataFrame({'A_a': [1, 0, 1], 'A_b': [0, 1, 0], 'B_b': [1, 1, 0], - 'B_c': [0, 0, 1]}, dtype=np.uint8) + 'B_c': [0, 0, 1]}, + dtype=np.uint8) assert_frame_equal(result, expected) - def test_dataframe_dummies_mix_default(self): - df = self.df - result = get_dummies(df, sparse=self.sparse) + def test_dataframe_dummies_mix_default(self, df, sparse, dtype): + result = get_dummies(df, sparse=sparse, dtype=dtype) expected = DataFrame({'C': [1, 2, 3], 'A_a': [1, 0, 1], 'A_b': [0, 1, 0], 'B_b': [1, 1, 0], 'B_c': [0, 0, 1]}) cols = ['A_a', 'A_b', 'B_b', 'B_c'] - expected[cols] = expected[cols].astype(np.uint8) + expected[cols] = expected[cols].astype(dtype) expected = expected[['C', 'A_a', 'A_b', 'B_b', 'B_c']] assert_frame_equal(result, expected) - def test_dataframe_dummies_prefix_list(self): + def test_dataframe_dummies_prefix_list(self, df, sparse): prefixes = ['from_A', 'from_B'] - df = DataFrame({'A': ['a', 'b', 'a'], - 'B': ['b', 'b', 'c'], - 'C': [1, 2, 3]}) - result = get_dummies(df, prefix=prefixes, sparse=self.sparse) + result = get_dummies(df, prefix=prefixes, sparse=sparse) expected = DataFrame({'C': [1, 2, 3], 'from_A_a': [1, 0, 1], 'from_A_b': [0, 1, 0], 'from_B_b': [1, 1, 0], - 'from_B_c': [0, 0, 1]}) - cols = expected.columns[1:] - expected[cols] = expected[cols].astype(np.uint8) - expected = expected[['C', 'from_A_a', 'from_A_b', 'from_B_b', - 'from_B_c']] + 'from_B_c': [0, 0, 1]}, + dtype=np.uint8) + expected[['C']] = df[['C']] + expected = expected[['C', 'from_A_a', 'from_A_b', + 'from_B_b', 'from_B_c']] assert_frame_equal(result, expected) - def test_dataframe_dummies_prefix_str(self): + def test_dataframe_dummies_prefix_str(self, df, sparse): # not that you should do this... - df = self.df - result = get_dummies(df, prefix='bad', sparse=self.sparse) + result = get_dummies(df, prefix='bad', sparse=sparse) + bad_columns = ['bad_a', 'bad_b', 'bad_b', 'bad_c'] expected = DataFrame([[1, 1, 0, 1, 0], [2, 0, 1, 1, 0], [3, 1, 0, 0, 1]], - columns=['C', 'bad_a', 'bad_b', 'bad_b', 'bad_c'], + columns=['C'] + bad_columns, dtype=np.uint8) expected = expected.astype({"C": np.int64}) assert_frame_equal(result, expected) - def test_dataframe_dummies_subset(self): - df = self.df + def test_dataframe_dummies_subset(self, df, sparse): result = get_dummies(df, prefix=['from_A'], columns=['A'], - sparse=self.sparse) + sparse=sparse) expected = DataFrame({'from_A_a': [1, 0, 1], 'from_A_b': [0, 1, 0], 'B': ['b', 'b', 'c'], - 'C': [1, 2, 3]}) - cols = ['from_A_a', 'from_A_b'] - expected[cols] = expected[cols].astype(np.uint8) + 'C': [1, 2, 3]}, dtype=np.uint8) + expected[['C']] = df[['C']] assert_frame_equal(result, expected) - def test_dataframe_dummies_prefix_sep(self): - df = self.df - result = get_dummies(df, prefix_sep='..', sparse=self.sparse) + def test_dataframe_dummies_prefix_sep(self, df, sparse): + result = get_dummies(df, prefix_sep='..', sparse=sparse) expected = DataFrame({'C': [1, 2, 3], 'A..a': [1, 0, 1], 'A..b': [0, 1, 0], 'B..b': [1, 1, 0], - 'B..c': [0, 0, 1]}) + 'B..c': [0, 0, 1]}, + dtype=np.uint8) + expected[['C']] = df[['C']] expected = expected[['C', 'A..a', 'A..b', 'B..b', 'B..c']] - cols = expected.columns[1:] - expected[cols] = expected[cols].astype(np.uint8) assert_frame_equal(result, expected) - result = get_dummies(df, prefix_sep=['..', '__'], sparse=self.sparse) + result = get_dummies(df, prefix_sep=['..', '__'], sparse=sparse) expected = expected.rename(columns={'B..b': 'B__b', 'B..c': 'B__c'}) assert_frame_equal(result, expected) - result = get_dummies(df, prefix_sep={'A': '..', - 'B': '__'}, sparse=self.sparse) + result = get_dummies(df, prefix_sep={'A': '..', 'B': '__'}, + sparse=sparse) assert_frame_equal(result, expected) - def test_dataframe_dummies_prefix_bad_length(self): + def test_dataframe_dummies_prefix_bad_length(self, df, sparse): with pytest.raises(ValueError): - get_dummies(self.df, prefix=['too few'], sparse=self.sparse) + get_dummies(df, prefix=['too few'], sparse=sparse) - def test_dataframe_dummies_prefix_sep_bad_length(self): + def test_dataframe_dummies_prefix_sep_bad_length(self, df, sparse): with pytest.raises(ValueError): - get_dummies(self.df, prefix_sep=['bad'], sparse=self.sparse) + get_dummies(df, prefix_sep=['bad'], sparse=sparse) - def test_dataframe_dummies_prefix_dict(self): + def test_dataframe_dummies_prefix_dict(self, sparse): prefixes = {'A': 'from_A', 'B': 'from_B'} df = DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'b', 'c'], 'C': [1, 2, 3]}) - result = get_dummies(df, prefix=prefixes, sparse=self.sparse) + result = get_dummies(df, prefix=prefixes, sparse=sparse) + expected = DataFrame({'from_A_a': [1, 0, 1], 'from_A_b': [0, 1, 0], 'from_B_b': [1, 1, 0], 'from_B_c': [0, 0, 1], 'C': [1, 2, 3]}) - cols = ['from_A_a', 'from_A_b', 'from_B_b', 'from_B_c'] - expected[cols] = expected[cols].astype(np.uint8) + + columns = ['from_A_a', 'from_A_b', 'from_B_b', 'from_B_c'] + expected[columns] = expected[columns].astype(np.uint8) assert_frame_equal(result, expected) - def test_dataframe_dummies_with_na(self): - df = self.df + def test_dataframe_dummies_with_na(self, df, sparse, dtype): df.loc[3, :] = [np.nan, np.nan, np.nan] - result = get_dummies(df, dummy_na=True, sparse=self.sparse) + result = get_dummies(df, dummy_na=True, + sparse=sparse, dtype=dtype).sort_index(axis=1) expected = DataFrame({'C': [1, 2, 3, np.nan], 'A_a': [1, 0, 1, 0], 'A_b': [0, 1, 0, 0], 'A_nan': [0, 0, 0, 1], 'B_b': [1, 1, 0, 0], 'B_c': [0, 0, 1, 0], - 'B_nan': [0, 0, 0, 1]}) - cols = ['A_a', 'A_b', 'A_nan', 'B_b', 'B_c', 'B_nan'] - expected[cols] = expected[cols].astype(np.uint8) - expected = expected[['C', 'A_a', 'A_b', 'A_nan', - 'B_b', 'B_c', 'B_nan']] + 'B_nan': [0, 0, 0, 1]}).sort_index(axis=1) + + e_dtype = self.effective_dtype(dtype) + columns = ['A_a', 'A_b', 'A_nan', 'B_b', 'B_c', 'B_nan'] + expected[columns] = expected[columns].astype(e_dtype) assert_frame_equal(result, expected) - result = get_dummies(df, dummy_na=False, sparse=self.sparse) + result = get_dummies(df, dummy_na=False, sparse=sparse, dtype=dtype) expected = expected[['C', 'A_a', 'A_b', 'B_b', 'B_c']] assert_frame_equal(result, expected) - def test_dataframe_dummies_with_categorical(self): - df = self.df + def test_dataframe_dummies_with_categorical(self, df, sparse, dtype): df['cat'] = pd.Categorical(['x', 'y', 'y']) - result = get_dummies(df, sparse=self.sparse) + result = get_dummies(df, sparse=sparse, dtype=dtype).sort_index(axis=1) expected = DataFrame({'C': [1, 2, 3], 'A_a': [1, 0, 1], 'A_b': [0, 1, 0], 'B_b': [1, 1, 0], 'B_c': [0, 0, 1], 'cat_x': [1, 0, 0], - 'cat_y': [0, 1, 1]}) - cols = ['A_a', 'A_b', 'B_b', 'B_c', 'cat_x', 'cat_y'] - expected[cols] = expected[cols].astype(np.uint8) - expected = expected[['C', 'A_a', 'A_b', 'B_b', 'B_c', - 'cat_x', 'cat_y']] + 'cat_y': [0, 1, 1]}).sort_index(axis=1) + + columns = ['A_a', 'A_b', 'B_b', 'B_c', 'cat_x', 'cat_y'] + effective_dtype = self.effective_dtype(dtype) + expected[columns] = expected[columns].astype(effective_dtype) + expected.sort_index(axis=1) assert_frame_equal(result, expected) - def test_basic_drop_first(self): + def test_basic_drop_first(self, sparse): # GH12402 Add a new parameter `drop_first` to avoid collinearity # Basic case s_list = list('abc') s_series = Series(s_list) s_series_index = Series(s_list, list('ABC')) - expected = DataFrame({'b': {0: 0, - 1: 1, - 2: 0}, - 'c': {0: 0, - 1: 0, - 2: 1}}, dtype=np.uint8) + expected = DataFrame({'b': [0, 1, 0], + 'c': [0, 0, 1]}, + dtype=np.uint8) - result = get_dummies(s_list, sparse=self.sparse, drop_first=True) + result = get_dummies(s_list, drop_first=True, sparse=sparse) assert_frame_equal(result, expected) - result = get_dummies(s_series, sparse=self.sparse, drop_first=True) + result = get_dummies(s_series, drop_first=True, sparse=sparse) assert_frame_equal(result, expected) expected.index = list('ABC') - result = get_dummies(s_series_index, sparse=self.sparse, - drop_first=True) + result = get_dummies(s_series_index, drop_first=True, sparse=sparse) assert_frame_equal(result, expected) - def test_basic_drop_first_one_level(self): + def test_basic_drop_first_one_level(self, sparse): # Test the case that categorical variable only has one level. s_list = list('aaa') s_series = Series(s_list) @@ -515,53 +529,48 @@ def test_basic_drop_first_one_level(self): expected = DataFrame(index=np.arange(3)) - result = get_dummies(s_list, sparse=self.sparse, drop_first=True) + result = get_dummies(s_list, drop_first=True, sparse=sparse) assert_frame_equal(result, expected) - result = get_dummies(s_series, sparse=self.sparse, drop_first=True) + result = get_dummies(s_series, drop_first=True, sparse=sparse) assert_frame_equal(result, expected) expected = DataFrame(index=list('ABC')) - result = get_dummies(s_series_index, sparse=self.sparse, - drop_first=True) + result = get_dummies(s_series_index, drop_first=True, sparse=sparse) assert_frame_equal(result, expected) - def test_basic_drop_first_NA(self): + def test_basic_drop_first_NA(self, sparse): # Test NA hadling together with drop_first s_NA = ['a', 'b', np.nan] - res = get_dummies(s_NA, sparse=self.sparse, drop_first=True) - exp = DataFrame({'b': {0: 0, - 1: 1, - 2: 0}}, dtype=np.uint8) + res = get_dummies(s_NA, drop_first=True, sparse=sparse) + exp = DataFrame({'b': [0, 1, 0]}, dtype=np.uint8) assert_frame_equal(res, exp) - res_na = get_dummies(s_NA, dummy_na=True, sparse=self.sparse, - drop_first=True) - exp_na = DataFrame({'b': {0: 0, - 1: 1, - 2: 0}, - nan: {0: 0, - 1: 0, - 2: 1}}, dtype=np.uint8).reindex( - ['b', nan], axis=1) + res_na = get_dummies(s_NA, dummy_na=True, drop_first=True, + sparse=sparse) + exp_na = DataFrame( + {'b': [0, 1, 0], + nan: [0, 0, 1]}, + dtype=np.uint8).reindex(['b', nan], axis=1) assert_frame_equal(res_na, exp_na) - res_just_na = get_dummies([nan], dummy_na=True, sparse=self.sparse, - drop_first=True) + res_just_na = get_dummies([nan], dummy_na=True, drop_first=True, + sparse=sparse) exp_just_na = DataFrame(index=np.arange(1)) assert_frame_equal(res_just_na, exp_just_na) - def test_dataframe_dummies_drop_first(self): - df = self.df[['A', 'B']] - result = get_dummies(df, sparse=self.sparse, drop_first=True) + def test_dataframe_dummies_drop_first(self, df, sparse): + df = df[['A', 'B']] + result = get_dummies(df, drop_first=True, sparse=sparse) expected = DataFrame({'A_b': [0, 1, 0], - 'B_c': [0, 0, 1]}, dtype=np.uint8) + 'B_c': [0, 0, 1]}, + dtype=np.uint8) assert_frame_equal(result, expected) - def test_dataframe_dummies_drop_first_with_categorical(self): - df = self.df + def test_dataframe_dummies_drop_first_with_categorical( + self, df, sparse, dtype): df['cat'] = pd.Categorical(['x', 'y', 'y']) - result = get_dummies(df, sparse=self.sparse, drop_first=True) + result = get_dummies(df, drop_first=True, sparse=sparse) expected = DataFrame({'C': [1, 2, 3], 'A_b': [0, 1, 0], 'B_c': [0, 0, 1], @@ -571,11 +580,10 @@ def test_dataframe_dummies_drop_first_with_categorical(self): expected = expected[['C', 'A_b', 'B_c', 'cat_y']] assert_frame_equal(result, expected) - def test_dataframe_dummies_drop_first_with_na(self): - df = self.df + def test_dataframe_dummies_drop_first_with_na(self, df, sparse): df.loc[3, :] = [np.nan, np.nan, np.nan] - result = get_dummies(df, dummy_na=True, sparse=self.sparse, - drop_first=True) + result = get_dummies(df, dummy_na=True, drop_first=True, + sparse=sparse).sort_index(axis=1) expected = DataFrame({'C': [1, 2, 3, np.nan], 'A_b': [0, 1, 0, 0], 'A_nan': [0, 0, 0, 1], @@ -583,30 +591,34 @@ def test_dataframe_dummies_drop_first_with_na(self): 'B_nan': [0, 0, 0, 1]}) cols = ['A_b', 'A_nan', 'B_c', 'B_nan'] expected[cols] = expected[cols].astype(np.uint8) - - expected = expected[['C', 'A_b', 'A_nan', 'B_c', 'B_nan']] + expected = expected.sort_index(axis=1) assert_frame_equal(result, expected) - result = get_dummies(df, dummy_na=False, sparse=self.sparse, - drop_first=True) + result = get_dummies(df, dummy_na=False, drop_first=True, + sparse=sparse) expected = expected[['C', 'A_b', 'B_c']] assert_frame_equal(result, expected) def test_int_int(self): data = Series([1, 2, 1]) result = pd.get_dummies(data) - expected = DataFrame([[1, 0], [0, 1], [1, 0]], columns=[1, 2], + expected = DataFrame([[1, 0], + [0, 1], + [1, 0]], + columns=[1, 2], dtype=np.uint8) tm.assert_frame_equal(result, expected) data = Series(pd.Categorical(['a', 'b', 'a'])) result = pd.get_dummies(data) - expected = DataFrame([[1, 0], [0, 1], [1, 0]], + expected = DataFrame([[1, 0], + [0, 1], + [1, 0]], columns=pd.Categorical(['a', 'b']), dtype=np.uint8) tm.assert_frame_equal(result, expected) - def test_int_df(self): + def test_int_df(self, dtype): data = DataFrame( {'A': [1, 2, 1], 'B': pd.Categorical(['a', 'b', 'a']), @@ -620,34 +632,28 @@ def test_int_df(self): [2, 2., 0, 1, 0, 1], [1, 1., 1, 0, 1, 0] ], columns=columns) - expected[columns[2:]] = expected[columns[2:]].astype(np.uint8) - result = pd.get_dummies(data, columns=['A', 'B']) + expected[columns[2:]] = expected[columns[2:]].astype(dtype) + result = pd.get_dummies(data, columns=['A', 'B'], dtype=dtype) tm.assert_frame_equal(result, expected) - def test_dataframe_dummies_preserve_categorical_dtype(self): + def test_dataframe_dummies_preserve_categorical_dtype(self, dtype): # GH13854 for ordered in [False, True]: cat = pd.Categorical(list("xy"), categories=list("xyz"), ordered=ordered) - result = get_dummies(cat) + result = get_dummies(cat, dtype=dtype) - data = np.array([[1, 0, 0], [0, 1, 0]], dtype=np.uint8) + data = np.array([[1, 0, 0], [0, 1, 0]], + dtype=self.effective_dtype(dtype)) cols = pd.CategoricalIndex(cat.categories, categories=cat.categories, ordered=ordered) - expected = DataFrame(data, columns=cols) + expected = DataFrame(data, columns=cols, + dtype=self.effective_dtype(dtype)) tm.assert_frame_equal(result, expected) -class TestGetDummiesSparse(TestGetDummies): - sparse = True - - @pytest.mark.xfail(reason='nan in index is problematic (GH 16894)') - def test_include_na(self): - super(TestGetDummiesSparse, self).test_include_na() - - class TestMakeAxisDummies(object): def test_preserve_categorical_dtype(self):
- [x] closes #18330 (there's no issue for this one) - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Update in version 0.19.0 made `get_dummies` return uint8 values instead of floats (#8725). While I agree with the argument that `get_dummies` should output integers __by default__ (to save some memory), in many cases it would be beneficial for user to choose other dtype. In my case there was serious performance degradation between versions 0.18 and 0.19. After investigation, reason behind it turned out to be the change to `get_dummies` output type. DataFrame with dummy values was used as an argument to np.dot in an optimization function (second argument was matrix of floats). Since there were lots of iterations involved, and on each iteration np.dot was converting all uint8 values to float64, conversion overhead took unreasonably long time. It is possible to work around this issue by converting dummy columns "manually" afterwards, but it adds unnecessary complexity to the code and is clearly less convenient than calling `get_dummies` with `dtype=float`. Apart from performance considerations, I can imagine `dtype=bool` to be a common use case. `get_dummies(data, dtype=None)` is allowed and will return uint8 values to match the [DataFrame](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html) interface (where None allows inferring datatype, which is default behavior). I've extended the test suite to run all the `get_dummies` tests (except for those that don't deal with internal dtypes, like `test_just_na`) twice, once with `uint8` and once with `float64`.
https://api.github.com/repos/pandas-dev/pandas/pulls/18330
2017-11-16T21:29:01Z
2017-11-22T23:03:17Z
2017-11-22T23:03:16Z
2017-11-22T23:03:29Z
Follow-Up: Unify apply and onOffset implementations
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 2b896bcc930a7..f38aca21a0438 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -357,6 +357,7 @@ class _BaseOffset(object): _typ = "dateoffset" _normalize_cache = True _cacheable = False + _day_opt = None def __call__(self, other): return self.apply(other) @@ -394,6 +395,11 @@ class _BaseOffset(object): out = '<%s' % n_str + className + plural + self._repr_attrs() + '>' return out + def _get_offset_day(self, datetime other): + # subclass must implement `_day_opt`; calling from the base class + # will raise NotImplementedError. + return get_day_of_month(other, self._day_opt) + class BaseOffset(_BaseOffset): # Here we add __rfoo__ methods that don't play well with cdef classes @@ -468,7 +474,7 @@ cpdef datetime shift_month(datetime stamp, int months, object day_opt=None): return stamp.replace(year=year, month=month, day=day) -cdef int get_day_of_month(datetime other, day_opt) except? -1: +cpdef int get_day_of_month(datetime other, day_opt) except? -1: """ Find the day in `other`'s month that satisfies a DateOffset's onOffset policy, as described by the `day_opt` argument. @@ -493,10 +499,27 @@ cdef int get_day_of_month(datetime other, day_opt) except? -1: 30 """ + cdef: + int wkday, days_in_month + if day_opt == 'start': return 1 - elif day_opt == 'end': - return monthrange(other.year, other.month)[1] + + wkday, days_in_month = monthrange(other.year, other.month) + if day_opt == 'end': + return days_in_month + elif day_opt == 'business_start': + # first business day of month + return get_firstbday(wkday, days_in_month) + elif day_opt == 'business_end': + # last business day of month + return get_lastbday(wkday, days_in_month) + elif is_integer_object(day_opt): + day = min(day_opt, days_in_month) + elif day_opt is None: + # Note: unlike `shift_month`, get_day_of_month does not + # allow day_opt = None + raise NotImplementedError else: raise ValueError(day_opt) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index e0a19b4025555..6821017c89c3a 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -4680,3 +4680,11 @@ def test_all_offset_classes(self, tup): first = Timestamp(test_values[0], tz='US/Eastern') + offset() second = Timestamp(test_values[1], tz='US/Eastern') assert first == second + + +def test_get_offset_day_error(): + # subclass of _BaseOffset must override _day_opt attribute, or we should + # get a NotImplementedError + + with pytest.raises(NotImplementedError): + DateOffset()._get_offset_day(datetime.now()) diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 615d703f66932..c9c4d1b1e7119 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -1,4 +1,7 @@ # -*- coding: utf-8 -*- +import functools +import operator + from datetime import date, datetime, timedelta from pandas.compat import range from pandas import compat @@ -15,10 +18,10 @@ from pandas.util._decorators import cache_readonly from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds +import pandas._libs.tslibs.offsets as liboffsets from pandas._libs.tslibs.offsets import ( ApplyTypeError, as_datetime, _is_normalized, - get_firstbday, get_lastbday, _get_calendar, _to_dt64, _validate_business_time, _int_to_weekday, _weekday_to_int, _determine_offset, @@ -28,8 +31,6 @@ BeginMixin, EndMixin, BaseOffset) -import functools -import operator __all__ = ['Day', 'BusinessDay', 'BDay', 'CustomBusinessDay', 'CDay', 'CBMonthEnd', 'CBMonthBegin', @@ -912,6 +913,10 @@ def next_bday(self): calendar=self.calendar) +# --------------------------------------------------------------------- +# Month-Based Offset Classes + + class MonthOffset(SingleConstructorOffset): _adjust_dst = True @@ -927,52 +932,54 @@ def name(self): class MonthEnd(MonthOffset): """DateOffset of one month end""" _prefix = 'M' + _day_opt = 'end' @apply_wraps def apply(self, other): n = self.n - _, days_in_month = tslib.monthrange(other.year, other.month) - if other.day != days_in_month: - other = shift_month(other, -1, 'end') + compare_day = self._get_offset_day(other) + if other.day < compare_day: + other = shift_month(other, -1, self._day_opt) if n <= 0: n = n + 1 - other = shift_month(other, n, 'end') + other = shift_month(other, n, self._day_opt) return other @apply_index_wraps def apply_index(self, i): - shifted = tslib.shift_months(i.asi8, self.n, 'end') + shifted = tslib.shift_months(i.asi8, self.n, self._day_opt) return i._shallow_copy(shifted) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False - days_in_month = tslib.monthrange(dt.year, dt.month)[1] - return dt.day == days_in_month + return dt.day == self._get_offset_day(dt) class MonthBegin(MonthOffset): """DateOffset of one month at beginning""" _prefix = 'MS' + _day_opt = 'start' @apply_wraps def apply(self, other): n = self.n + compare_day = self._get_offset_day(other) - if other.day > 1 and n <= 0: # then roll forward if n<=0 + if other.day > compare_day and n <= 0: # then roll forward if n<=0 n += 1 - return shift_month(other, n, 'start') + return shift_month(other, n, self._day_opt) @apply_index_wraps def apply_index(self, i): - shifted = tslib.shift_months(i.asi8, self.n, 'start') + shifted = tslib.shift_months(i.asi8, self.n, self._day_opt) return i._shallow_copy(shifted) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False - return dt.day == 1 + return dt.day == self._get_offset_day(dt) class SemiMonthOffset(DateOffset): @@ -1177,45 +1184,43 @@ def _apply_index_days(self, i, roll): class BusinessMonthEnd(MonthOffset): """DateOffset increments between business EOM dates""" _prefix = 'BM' + _day_opt = 'business_end' @apply_wraps def apply(self, other): n = self.n - wkday, days_in_month = tslib.monthrange(other.year, other.month) - lastBDay = get_lastbday(wkday, days_in_month) + compare_day = self._get_offset_day(other) - if n > 0 and not other.day >= lastBDay: + if n > 0 and not other.day >= compare_day: n = n - 1 - elif n <= 0 and other.day > lastBDay: + elif n <= 0 and other.day > compare_day: n = n + 1 - return shift_month(other, n, 'business_end') + return shift_month(other, n, self._day_opt) class BusinessMonthBegin(MonthOffset): """DateOffset of one business month at beginning""" _prefix = 'BMS' + _day_opt = 'business_start' @apply_wraps def apply(self, other): n = self.n - wkday, _ = tslib.monthrange(other.year, other.month) - first = get_firstbday(wkday) + compare_day = self._get_offset_day(other) - if other.day > first and n <= 0: + if other.day > compare_day and n <= 0: # as if rolled forward already n += 1 - elif other.day < first and n > 0: - other = other + timedelta(days=first - other.day) + elif other.day < compare_day and n > 0: n -= 1 - return shift_month(other, n, 'business_start') + return shift_month(other, n, self._day_opt) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False - first_weekday, _ = tslib.monthrange(dt.year, dt.month) - return dt.day == get_firstbday(first_weekday) + return dt.day == self._get_offset_day(dt) class CustomBusinessMonthEnd(BusinessMixin, MonthOffset): @@ -1363,6 +1368,9 @@ def apply(self, other): return result +# --------------------------------------------------------------------- +# Week-Based Offset Classes + class Week(EndMixin, DateOffset): """ Weekly offset @@ -1594,6 +1602,9 @@ def _from_name(cls, suffix=None): weekday = _weekday_to_int[suffix] return cls(weekday=weekday) +# --------------------------------------------------------------------- +# Quarter-Based Offset Classes + class QuarterOffset(DateOffset): """Quarter representation - doesn't call super""" @@ -1641,24 +1652,23 @@ class BQuarterEnd(QuarterOffset): _default_startingMonth = 3 _from_name_startingMonth = 12 _prefix = 'BQ' + _day_opt = 'business_end' @apply_wraps def apply(self, other): n = self.n - - wkday, days_in_month = tslib.monthrange(other.year, other.month) - lastBDay = get_lastbday(wkday, days_in_month) + compare_day = self._get_offset_day(other) monthsToGo = 3 - ((other.month - self.startingMonth) % 3) if monthsToGo == 3: monthsToGo = 0 - if n > 0 and not (other.day >= lastBDay and monthsToGo == 0): + if n > 0 and not (other.day >= compare_day and monthsToGo == 0): n = n - 1 - elif n <= 0 and other.day > lastBDay and monthsToGo == 0: + elif n <= 0 and other.day > compare_day and monthsToGo == 0: n = n + 1 - return shift_month(other, monthsToGo + 3 * n, 'business_end') + return shift_month(other, monthsToGo + 3 * n, self._day_opt) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): @@ -1678,13 +1688,13 @@ class BQuarterBegin(QuarterOffset): _default_startingMonth = 3 _from_name_startingMonth = 1 _prefix = 'BQS' + _day_opt = 'business_start' @apply_wraps def apply(self, other): n = self.n - wkday, _ = tslib.monthrange(other.year, other.month) - first = get_firstbday(wkday) + compare_day = self._get_offset_day(other) monthsSince = (other.month - self.startingMonth) % 3 @@ -1692,13 +1702,13 @@ def apply(self, other): monthsSince = monthsSince - 3 # roll forward if on same month later than first bday - if n <= 0 and (monthsSince == 0 and other.day > first): + if n <= 0 and (monthsSince == 0 and other.day > compare_day): n = n + 1 # pretend to roll back if on same month but before firstbday - elif n > 0 and (monthsSince == 0 and other.day < first): + elif n > 0 and (monthsSince == 0 and other.day < compare_day): n = n - 1 - return shift_month(other, 3 * n - monthsSince, 'business_start') + return shift_month(other, 3 * n - monthsSince, self._day_opt) class QuarterEnd(EndMixin, QuarterOffset): @@ -1710,6 +1720,7 @@ class QuarterEnd(EndMixin, QuarterOffset): _outputName = 'QuarterEnd' _default_startingMonth = 3 _prefix = 'Q' + _day_opt = 'end' @apply_wraps def apply(self, other): @@ -1717,16 +1728,16 @@ def apply(self, other): other = datetime(other.year, other.month, other.day, other.hour, other.minute, other.second, other.microsecond) - wkday, days_in_month = tslib.monthrange(other.year, other.month) + compare_day = self._get_offset_day(other) monthsToGo = 3 - ((other.month - self.startingMonth) % 3) if monthsToGo == 3: monthsToGo = 0 - if n > 0 and not (other.day >= days_in_month and monthsToGo == 0): + if n > 0 and not (other.day >= compare_day and monthsToGo == 0): n = n - 1 - other = shift_month(other, monthsToGo + 3 * n, 'end') + other = shift_month(other, monthsToGo + 3 * n, self._day_opt) return other @apply_index_wraps @@ -1745,11 +1756,12 @@ class QuarterBegin(BeginMixin, QuarterOffset): _default_startingMonth = 3 _from_name_startingMonth = 1 _prefix = 'QS' + _day_opt = 'start' @apply_wraps def apply(self, other): n = self.n - wkday, days_in_month = tslib.monthrange(other.year, other.month) + compare_day = self._get_offset_day(other) monthsSince = (other.month - self.startingMonth) % 3 @@ -1757,11 +1769,11 @@ def apply(self, other): # make sure you roll forward, so negate monthsSince = monthsSince - 3 - if n <= 0 and (monthsSince == 0 and other.day > 1): + if n <= 0 and (monthsSince == 0 and other.day > compare_day): # after start, so come back an extra period as if rolled forward n = n + 1 - other = shift_month(other, 3 * n - monthsSince, 'start') + other = shift_month(other, 3 * n - monthsSince, self._day_opt) return other @apply_index_wraps @@ -1771,10 +1783,19 @@ def apply_index(self, i): return self._beg_apply_index(i, freqstr) +# --------------------------------------------------------------------- +# Year-Based Offset Classes + class YearOffset(DateOffset): """DateOffset that just needs a month""" _adjust_dst = True + def _get_offset_day(self, other): + # override BaseOffset method to use self.month instead of other.month + # TODO: there may be a more performant way to do this + return liboffsets.get_day_of_month(other.replace(month=self.month), + self._day_opt) + def __init__(self, n=1, normalize=False, month=None): month = month if month is not None else self._default_month self.month = month @@ -1802,25 +1823,25 @@ class BYearEnd(YearOffset): _outputName = 'BusinessYearEnd' _default_month = 12 _prefix = 'BA' + _day_opt = 'business_end' @apply_wraps def apply(self, other): n = self.n - wkday, days_in_month = tslib.monthrange(other.year, self.month) - lastBDay = get_lastbday(wkday, days_in_month) + compare_day = self._get_offset_day(other) years = n if n > 0: if (other.month < self.month or - (other.month == self.month and other.day < lastBDay)): + (other.month == self.month and other.day < compare_day)): years -= 1 elif n <= 0: if (other.month > self.month or - (other.month == self.month and other.day > lastBDay)): + (other.month == self.month and other.day > compare_day)): years += 1 months = years * 12 + (self.month - other.month) - return shift_month(other, months, 'business_end') + return shift_month(other, months, self._day_opt) class BYearBegin(YearOffset): @@ -1828,38 +1849,38 @@ class BYearBegin(YearOffset): _outputName = 'BusinessYearBegin' _default_month = 1 _prefix = 'BAS' + _day_opt = 'business_start' @apply_wraps def apply(self, other): n = self.n - wkday, days_in_month = tslib.monthrange(other.year, self.month) - - first = get_firstbday(wkday) + compare_day = self._get_offset_day(other) years = n if n > 0: # roll back first for positive n if (other.month < self.month or - (other.month == self.month and other.day < first)): + (other.month == self.month and other.day < compare_day)): years -= 1 elif n <= 0: # roll forward if (other.month > self.month or - (other.month == self.month and other.day > first)): + (other.month == self.month and other.day > compare_day)): years += 1 # set first bday for result months = years * 12 + (self.month - other.month) - return shift_month(other, months, 'business_start') + return shift_month(other, months, self._day_opt) class YearEnd(EndMixin, YearOffset): """DateOffset increments between calendar year ends""" _default_month = 12 _prefix = 'A' + _day_opt = 'end' @apply_wraps def apply(self, other): - n = roll_yearday(other, self.n, self.month, 'end') + n = roll_yearday(other, self.n, self.month, self._day_opt) year = other.year + n days_in_month = tslib.monthrange(year, self.month)[1] return datetime(year, self.month, days_in_month, @@ -1874,18 +1895,18 @@ def apply_index(self, i): def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False - wkday, days_in_month = tslib.monthrange(dt.year, self.month) - return self.month == dt.month and dt.day == days_in_month + return self.month == dt.month and dt.day == self._get_offset_day(dt) class YearBegin(BeginMixin, YearOffset): """DateOffset increments between calendar year begin dates""" _default_month = 1 _prefix = 'AS' + _day_opt = 'start' @apply_wraps def apply(self, other): - n = roll_yearday(other, self.n, self.month, 'start') + n = roll_yearday(other, self.n, self.month, self._day_opt) year = other.year + n return other.replace(year=year, month=self.month, day=1) @@ -1898,9 +1919,12 @@ def apply_index(self, i): def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False - return dt.month == self.month and dt.day == 1 + return dt.month == self.month and dt.day == self._get_offset_day(dt) +# --------------------------------------------------------------------- +# Special Offset Classes + class FY5253(DateOffset): """ Describes 52-53 week fiscal year. This is also known as a 4-4-5 calendar.
This follows up on #18280, #18278, and #18263. `get_day_of_month` is extended to handle `business_start` and `business_end` in addition to `start` and `end`. `_day_opt` attributes are added to YearFoo, QuarterFoo, and MonthFoo offsets. After some more algebraic simplification (done in a separate PR), their apply and onOffset methods will become identical and can be implemented in the base Year, Quarter, and Month classes. I expect a small performance penalty from calling `self._get_offset_day` in cases where could hard-code `1`, but the benefits of a unified+simplified implementation outweigh that.
https://api.github.com/repos/pandas-dev/pandas/pulls/18329
2017-11-16T18:47:45Z
2017-11-19T18:50:16Z
2017-11-19T18:50:16Z
2017-12-08T19:38:34Z
modernize syntax in Timestamp
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index a32f04fe7b156..5edfb0ea58e30 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -981,11 +981,10 @@ cdef class _Timestamp(datetime): pass tz = ", tz='{0}'".format(zone) if zone is not None else "" - freq = ", freq='{0}'".format( - self.freq.freqstr) if self.freq is not None else "" + freq = "" if self.freq is None else ", freq='{0}'".format(self.freqstr) - return "Timestamp('{stamp}'{tz}{freq})".format( - stamp=stamp, tz=tz, freq=freq) + return "Timestamp('{stamp}'{tz}{freq})".format(stamp=stamp, + tz=tz, freq=freq) cdef bint _compare_outside_nanorange(_Timestamp self, datetime other, int op) except -1: @@ -1064,11 +1063,13 @@ cdef class _Timestamp(datetime): return Timestamp((self.freq * other).apply(self), freq=self.freq) elif PyDelta_Check(other) or hasattr(other, 'delta'): + # delta --> offsets.Tick nanos = delta_to_nanoseconds(other) result = Timestamp(self.value + nanos, tz=self.tzinfo, freq=self.freq) if getattr(other, 'normalize', False): - result = Timestamp(normalize_date(result)) + # DateOffset + result = result.normalize() return result # index/series like @@ -1158,42 +1159,43 @@ cdef class _Timestamp(datetime): field, freqstr, month_kw) return out[0] - property _repr_base: - def __get__(self): - return '%s %s' % (self._date_repr, self._time_repr) + @property + def _repr_base(self): + return '{date} {time}'.format(date=self._date_repr, + time=self._time_repr) - property _date_repr: - def __get__(self): - # Ideal here would be self.strftime("%Y-%m-%d"), but - # the datetime strftime() methods require year >= 1900 - return '%d-%.2d-%.2d' % (self.year, self.month, self.day) + @property + def _date_repr(self): + # Ideal here would be self.strftime("%Y-%m-%d"), but + # the datetime strftime() methods require year >= 1900 + return '%d-%.2d-%.2d' % (self.year, self.month, self.day) - property _time_repr: - def __get__(self): - result = '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) + @property + def _time_repr(self): + result = '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second) - if self.nanosecond != 0: - result += '.%.9d' % (self.nanosecond + 1000 * self.microsecond) - elif self.microsecond != 0: - result += '.%.6d' % self.microsecond + if self.nanosecond != 0: + result += '.%.9d' % (self.nanosecond + 1000 * self.microsecond) + elif self.microsecond != 0: + result += '.%.6d' % self.microsecond - return result + return result - property _short_repr: - def __get__(self): - # format a Timestamp with only _date_repr if possible - # otherwise _repr_base - if (self.hour == 0 and - self.minute == 0 and - self.second == 0 and - self.microsecond == 0 and - self.nanosecond == 0): - return self._date_repr - return self._repr_base - - property asm8: - def __get__(self): - return np.datetime64(self.value, 'ns') + @property + def _short_repr(self): + # format a Timestamp with only _date_repr if possible + # otherwise _repr_base + if (self.hour == 0 and + self.minute == 0 and + self.second == 0 and + self.microsecond == 0 and + self.nanosecond == 0): + return self._date_repr + return self._repr_base + + @property + def asm8(self): + return np.datetime64(self.value, 'ns') def timestamp(self): """Return POSIX timestamp as float."""
Small cleanups to `Timestamp`+`_Timestamp`, use `@property` instead of older syntax. The only substantive change is in `__add__`, where `result = Timestamp(normalize_date(result))` is changed to `result = result.normalize()`. The latter has the benefits 1) is robust for tzaware timestamps, 2) does not require `normalize_date` in the namespace, so after this `Timestamp`+`_Timestamp` can be cut/paste into a new `tslibs.timestamps` and 3) is robust to subclassing of `Timestamp`.
https://api.github.com/repos/pandas-dev/pandas/pulls/18327
2017-11-16T17:48:23Z
2017-11-19T15:08:18Z
2017-11-19T15:08:18Z
2017-11-19T16:23:13Z
CI: revert back to dateutil released as many changes
diff --git a/ci/requirements-3.6_NUMPY_DEV.build.sh b/ci/requirements-3.6_NUMPY_DEV.build.sh index fd79142c5cebb..9145bf1d3481c 100644 --- a/ci/requirements-3.6_NUMPY_DEV.build.sh +++ b/ci/requirements-3.6_NUMPY_DEV.build.sh @@ -12,7 +12,8 @@ PRE_WHEELS="https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf pip install --pre --upgrade --timeout=60 -f $PRE_WHEELS numpy scipy # install dateutil from master -pip install -U git+git://github.com/dateutil/dateutil.git +# pip install -U git+git://github.com/dateutil/dateutil.git +pip install dateutil # cython via pip pip install cython
xref #18141
https://api.github.com/repos/pandas-dev/pandas/pulls/18325
2017-11-16T13:13:03Z
2017-11-16T17:28:06Z
2017-11-16T17:28:06Z
2017-11-16T17:29:24Z
Revert "DOC: Remove vendored IPython.sphinext (#18193)"
diff --git a/.gitignore b/.gitignore index 0c2058ffcdd71..ff0a6aef47163 100644 --- a/.gitignore +++ b/.gitignore @@ -106,4 +106,3 @@ doc/build/html/index.html doc/tmp.sv doc/source/styled.xlsx doc/source/templates/ -doc/source/savefig/ diff --git a/doc/source/conf.py b/doc/source/conf.py index 3ac41b0e7e0c9..c8189b86b095c 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -56,8 +56,9 @@ 'sphinx.ext.extlinks', 'sphinx.ext.todo', 'numpydoc', - 'IPython.sphinxext.ipython_directive', - 'IPython.sphinxext.ipython_console_highlighting', + 'ipython_sphinxext.ipython_directive', + 'ipython_sphinxext.ipython_console_highlighting', + 'IPython.sphinxext.ipython_console_highlighting', # lowercase didn't work 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', diff --git a/doc/source/whatsnew/v0.7.3.txt b/doc/source/whatsnew/v0.7.3.txt index 77cc72d8707cf..6b5199c55cbf5 100644 --- a/doc/source/whatsnew/v0.7.3.txt +++ b/doc/source/whatsnew/v0.7.3.txt @@ -22,7 +22,7 @@ New features from pandas.tools.plotting import scatter_matrix scatter_matrix(df, alpha=0.2) -.. image:: savefig/scatter_matrix_kde.png +.. image:: _static/scatter_matrix_kde.png :width: 5in - Add ``stacked`` argument to Series and DataFrame's ``plot`` method for @@ -32,14 +32,14 @@ New features df.plot(kind='bar', stacked=True) -.. image:: savefig/bar_plot_stacked_ex.png +.. image:: _static/bar_plot_stacked_ex.png :width: 4in .. code-block:: python df.plot(kind='barh', stacked=True) -.. image:: savefig/barh_plot_stacked_ex.png +.. image:: _static/barh_plot_stacked_ex.png :width: 4in - Add log x and y :ref:`scaling options <visualization.basic>` to diff --git a/doc/sphinxext/ipython_sphinxext/__init__.py b/doc/sphinxext/ipython_sphinxext/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/doc/sphinxext/ipython_sphinxext/ipython_console_highlighting.py b/doc/sphinxext/ipython_sphinxext/ipython_console_highlighting.py new file mode 100644 index 0000000000000..dfb489e49394d --- /dev/null +++ b/doc/sphinxext/ipython_sphinxext/ipython_console_highlighting.py @@ -0,0 +1,116 @@ +"""reST directive for syntax-highlighting ipython interactive sessions. + +XXX - See what improvements can be made based on the new (as of Sept 2009) +'pycon' lexer for the python console. At the very least it will give better +highlighted tracebacks. +""" + +#----------------------------------------------------------------------------- +# Needed modules + +# Standard library +import re + +# Third party +from pygments.lexer import Lexer, do_insertions +from pygments.lexers.agile import (PythonConsoleLexer, PythonLexer, + PythonTracebackLexer) +from pygments.token import Comment, Generic + +from sphinx import highlighting + +#----------------------------------------------------------------------------- +# Global constants +line_re = re.compile('.*?\n') + +#----------------------------------------------------------------------------- +# Code begins - classes and functions + + +class IPythonConsoleLexer(Lexer): + + """ + For IPython console output or doctests, such as: + + .. sourcecode:: ipython + + In [1]: a = 'foo' + + In [2]: a + Out[2]: 'foo' + + In [3]: print(a) + foo + + In [4]: 1 / 0 + + Notes: + + - Tracebacks are not currently supported. + + - It assumes the default IPython prompts, not customized ones. + """ + + name = 'IPython console session' + aliases = ['ipython'] + mimetypes = ['text/x-ipython-console'] + input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)") + output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)") + continue_prompt = re.compile(" \.\.\.+:") + tb_start = re.compile("\-+") + + def get_tokens_unprocessed(self, text): + pylexer = PythonLexer(**self.options) + tblexer = PythonTracebackLexer(**self.options) + + curcode = '' + insertions = [] + for match in line_re.finditer(text): + line = match.group() + input_prompt = self.input_prompt.match(line) + continue_prompt = self.continue_prompt.match(line.rstrip()) + output_prompt = self.output_prompt.match(line) + if line.startswith("#"): + insertions.append((len(curcode), + [(0, Comment, line)])) + elif input_prompt is not None: + insertions.append((len(curcode), + [(0, Generic.Prompt, input_prompt.group())])) + curcode += line[input_prompt.end():] + elif continue_prompt is not None: + insertions.append((len(curcode), + [(0, Generic.Prompt, continue_prompt.group())])) + curcode += line[continue_prompt.end():] + elif output_prompt is not None: + # Use the 'error' token for output. We should probably make + # our own token, but error is typicaly in a bright color like + # red, so it works fine for our output prompts. + insertions.append((len(curcode), + [(0, Generic.Error, output_prompt.group())])) + curcode += line[output_prompt.end():] + else: + if curcode: + for item in do_insertions(insertions, + pylexer.get_tokens_unprocessed(curcode)): + yield item + curcode = '' + insertions = [] + yield match.start(), Generic.Output, line + if curcode: + for item in do_insertions(insertions, + pylexer.get_tokens_unprocessed(curcode)): + yield item + + +def setup(app): + """Setup as a sphinx extension.""" + + # This is only a lexer, so adding it below to pygments appears sufficient. + # But if somebody knows that the right API usage should be to do that via + # sphinx, by all means fix it here. At least having this setup.py + # suppresses the sphinx warning we'd get without it. + pass + +#----------------------------------------------------------------------------- +# Register the extension as a valid pygments lexer +highlighting.lexers['ipython'] = IPythonConsoleLexer() diff --git a/doc/sphinxext/ipython_sphinxext/ipython_directive.py b/doc/sphinxext/ipython_sphinxext/ipython_directive.py new file mode 100644 index 0000000000000..922767a8e2d46 --- /dev/null +++ b/doc/sphinxext/ipython_sphinxext/ipython_directive.py @@ -0,0 +1,1091 @@ +# -*- coding: utf-8 -*- +""" +Sphinx directive to support embedded IPython code. + +This directive allows pasting of entire interactive IPython sessions, prompts +and all, and their code will actually get re-executed at doc build time, with +all prompts renumbered sequentially. It also allows you to input code as a pure +python input by giving the argument python to the directive. The output looks +like an interactive ipython section. + +To enable this directive, simply list it in your Sphinx ``conf.py`` file +(making sure the directory where you placed it is visible to sphinx, as is +needed for all Sphinx directives). For example, to enable syntax highlighting +and the IPython directive:: + + extensions = ['IPython.sphinxext.ipython_console_highlighting', + 'IPython.sphinxext.ipython_directive'] + +The IPython directive outputs code-blocks with the language 'ipython'. So +if you do not have the syntax highlighting extension enabled as well, then +all rendered code-blocks will be uncolored. By default this directive assumes +that your prompts are unchanged IPython ones, but this can be customized. +The configurable options that can be placed in conf.py are: + +ipython_savefig_dir: + The directory in which to save the figures. This is relative to the + Sphinx source directory. The default is `html_static_path`. +ipython_rgxin: + The compiled regular expression to denote the start of IPython input + lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You + shouldn't need to change this. +ipython_rgxout: + The compiled regular expression to denote the start of IPython output + lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You + shouldn't need to change this. +ipython_promptin: + The string to represent the IPython input prompt in the generated ReST. + The default is 'In [%d]:'. This expects that the line numbers are used + in the prompt. +ipython_promptout: + The string to represent the IPython prompt in the generated ReST. The + default is 'Out [%d]:'. This expects that the line numbers are used + in the prompt. +ipython_mplbackend: + The string which specifies if the embedded Sphinx shell should import + Matplotlib and set the backend. The value specifies a backend that is + passed to `matplotlib.use()` before any lines in `ipython_execlines` are + executed. If not specified in conf.py, then the default value of 'agg' is + used. To use the IPython directive without matplotlib as a dependency, set + the value to `None`. It may end up that matplotlib is still imported + if the user specifies so in `ipython_execlines` or makes use of the + @savefig pseudo decorator. +ipython_execlines: + A list of strings to be exec'd in the embedded Sphinx shell. Typical + usage is to make certain packages always available. Set this to an empty + list if you wish to have no imports always available. If specified in + conf.py as `None`, then it has the effect of making no imports available. + If omitted from conf.py altogether, then the default value of + ['import numpy as np', 'import matplotlib.pyplot as plt'] is used. +ipython_holdcount + When the @suppress pseudo-decorator is used, the execution count can be + incremented or not. The default behavior is to hold the execution count, + corresponding to a value of `True`. Set this to `False` to increment + the execution count after each suppressed command. + +As an example, to use the IPython directive when `matplotlib` is not available, +one sets the backend to `None`:: + + ipython_mplbackend = None + +An example usage of the directive is: + +.. code-block:: rst + + .. ipython:: + + In [1]: x = 1 + + In [2]: y = x**2 + + In [3]: print(y) + +See http://matplotlib.org/sampledoc/ipython_directive.html for additional +documentation. + +ToDo +---- + +- Turn the ad-hoc test() function into a real test suite. +- Break up ipython-specific functionality from matplotlib stuff into better + separated code. + +Authors +------- + +- John D Hunter: orignal author. +- Fernando Perez: refactoring, documentation, cleanups, port to 0.11. +- VáclavŠmilauer <eudoxos-AT-arcig.cz>: Prompt generalizations. +- Skipper Seabold, refactoring, cleanups, pure python addition +""" +from __future__ import print_function +from __future__ import unicode_literals + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Stdlib +import os +import re +import sys +import tempfile +import ast +from pandas.compat import zip, range, map, lmap, u, text_type, cStringIO as StringIO +import warnings + +# To keep compatibility with various python versions +try: + from hashlib import md5 +except ImportError: + from md5 import md5 + +# Third-party +import sphinx +from docutils.parsers.rst import directives +from docutils import nodes +from sphinx.util.compat import Directive + +# Our own +try: + from traitlets.config import Config +except ImportError: + from IPython import Config +from IPython import InteractiveShell +from IPython.core.profiledir import ProfileDir +from IPython.utils import io +from IPython.utils.py3compat import PY3 + +if PY3: + from io import StringIO +else: + from StringIO import StringIO + +#----------------------------------------------------------------------------- +# Globals +#----------------------------------------------------------------------------- +# for tokenizing blocks +COMMENT, INPUT, OUTPUT = range(3) + +#----------------------------------------------------------------------------- +# Functions and class declarations +#----------------------------------------------------------------------------- + +def block_parser(part, rgxin, rgxout, fmtin, fmtout): + """ + part is a string of ipython text, comprised of at most one + input, one ouput, comments, and blank lines. The block parser + parses the text into a list of:: + + blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] + + where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and + data is, depending on the type of token:: + + COMMENT : the comment string + + INPUT: the (DECORATOR, INPUT_LINE, REST) where + DECORATOR: the input decorator (or None) + INPUT_LINE: the input as string (possibly multi-line) + REST : any stdout generated by the input line (not OUTPUT) + + OUTPUT: the output string, possibly multi-line + + """ + block = [] + lines = part.split('\n') + N = len(lines) + i = 0 + decorator = None + while 1: + + if i==N: + # nothing left to parse -- the last line + break + + line = lines[i] + i += 1 + line_stripped = line.strip() + if line_stripped.startswith('#'): + block.append((COMMENT, line)) + continue + + if line_stripped.startswith('@'): + # we're assuming at most one decorator -- may need to + # rethink + decorator = line_stripped + continue + + # does this look like an input line? + matchin = rgxin.match(line) + if matchin: + lineno, inputline = int(matchin.group(1)), matchin.group(2) + + # the ....: continuation string + continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) + Nc = len(continuation) + # input lines can continue on for more than one line, if + # we have a '\' line continuation char or a function call + # echo line 'print'. The input line can only be + # terminated by the end of the block or an output line, so + # we parse out the rest of the input line if it is + # multiline as well as any echo text + + rest = [] + while i<N: + + # look ahead; if the next line is blank, or a comment, or + # an output line, we're done + + nextline = lines[i] + matchout = rgxout.match(nextline) + #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation)) + if matchout or nextline.startswith('#'): + break + elif nextline.startswith(continuation): + nextline = nextline[Nc:] + if nextline and nextline[0] == ' ': + nextline = nextline[1:] + + inputline += '\n' + nextline + + else: + rest.append(nextline) + i+= 1 + + block.append((INPUT, (decorator, inputline, '\n'.join(rest)))) + continue + + # if it looks like an output line grab all the text to the end + # of the block + matchout = rgxout.match(line) + if matchout: + lineno, output = int(matchout.group(1)), matchout.group(2) + if i<N-1: + output = '\n'.join([output] + lines[i:]) + + block.append((OUTPUT, output)) + break + + return block + + +class DecodingStringIO(StringIO, object): + def __init__(self,buf='',encodings=('utf8',), *args, **kwds): + super(DecodingStringIO, self).__init__(buf, *args, **kwds) + self.set_encodings(encodings) + + def set_encodings(self, encodings): + self.encodings = encodings + + def write(self,data): + if isinstance(data, text_type): + return super(DecodingStringIO, self).write(data) + else: + for enc in self.encodings: + try: + data = data.decode(enc) + return super(DecodingStringIO, self).write(data) + except : + pass + # default to brute utf8 if no encoding succeded + return super(DecodingStringIO, self).write(data.decode('utf8', 'replace')) + + +class EmbeddedSphinxShell(object): + """An embedded IPython instance to run inside Sphinx""" + + def __init__(self, exec_lines=None,state=None): + + self.cout = DecodingStringIO(u'') + + if exec_lines is None: + exec_lines = [] + + self.state = state + + # Create config object for IPython + config = Config() + config.InteractiveShell.autocall = False + config.InteractiveShell.autoindent = False + config.InteractiveShell.colors = 'NoColor' + + # create a profile so instance history isn't saved + tmp_profile_dir = tempfile.mkdtemp(prefix='profile_') + profname = 'auto_profile_sphinx_build' + pdir = os.path.join(tmp_profile_dir,profname) + profile = ProfileDir.create_profile_dir(pdir) + + # Create and initialize global ipython, but don't start its mainloop. + # This will persist across different EmbededSphinxShell instances. + IP = InteractiveShell.instance(config=config, profile_dir=profile) + + # io.stdout redirect must be done after instantiating InteractiveShell + io.stdout = self.cout + io.stderr = self.cout + + # For debugging, so we can see normal output, use this: + #from IPython.utils.io import Tee + #io.stdout = Tee(self.cout, channel='stdout') # dbg + #io.stderr = Tee(self.cout, channel='stderr') # dbg + + # Store a few parts of IPython we'll need. + self.IP = IP + self.user_ns = self.IP.user_ns + self.user_global_ns = self.IP.user_global_ns + + self.input = '' + self.output = '' + + self.is_verbatim = False + self.is_doctest = False + self.is_suppress = False + + # Optionally, provide more detailed information to shell. + self.directive = None + + # on the first call to the savefig decorator, we'll import + # pyplot as plt so we can make a call to the plt.gcf().savefig + self._pyplot_imported = False + + # Prepopulate the namespace. + for line in exec_lines: + self.process_input_line(line, store_history=False) + + def clear_cout(self): + self.cout.seek(0) + self.cout.truncate(0) + + def process_input_line(self, line, store_history=True): + """process the input, capturing stdout""" + + stdout = sys.stdout + splitter = self.IP.input_splitter + try: + sys.stdout = self.cout + splitter.push(line) + more = splitter.push_accepts_more() + if not more: + try: + source_raw = splitter.source_raw_reset()[1] + except: + # recent ipython #4504 + source_raw = splitter.raw_reset() + self.IP.run_cell(source_raw, store_history=store_history) + finally: + sys.stdout = stdout + + def process_image(self, decorator): + """ + # build out an image directive like + # .. image:: somefile.png + # :width 4in + # + # from an input like + # savefig somefile.png width=4in + """ + savefig_dir = self.savefig_dir + source_dir = self.source_dir + saveargs = decorator.split(' ') + filename = saveargs[1] + # insert relative path to image file in source + outfile = os.path.relpath(os.path.join(savefig_dir,filename), + source_dir) + + imagerows = ['.. image:: %s'%outfile] + + for kwarg in saveargs[2:]: + arg, val = kwarg.split('=') + arg = arg.strip() + val = val.strip() + imagerows.append(' :%s: %s'%(arg, val)) + + image_file = os.path.basename(outfile) # only return file name + image_directive = '\n'.join(imagerows) + return image_file, image_directive + + # Callbacks for each type of token + def process_input(self, data, input_prompt, lineno): + """ + Process data block for INPUT token. + + """ + decorator, input, rest = data + image_file = None + image_directive = None + + is_verbatim = decorator=='@verbatim' or self.is_verbatim + is_doctest = (decorator is not None and \ + decorator.startswith('@doctest')) or self.is_doctest + is_suppress = decorator=='@suppress' or self.is_suppress + is_okexcept = decorator=='@okexcept' or self.is_okexcept + is_okwarning = decorator=='@okwarning' or self.is_okwarning + is_savefig = decorator is not None and \ + decorator.startswith('@savefig') + + # set the encodings to be used by DecodingStringIO + # to convert the execution output into unicode if + # needed. this attrib is set by IpythonDirective.run() + # based on the specified block options, defaulting to ['ut + self.cout.set_encodings(self.output_encoding) + + input_lines = input.split('\n') + + if len(input_lines) > 1: + if input_lines[-1] != "": + input_lines.append('') # make sure there's a blank line + # so splitter buffer gets reset + + continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) + + if is_savefig: + image_file, image_directive = self.process_image(decorator) + + ret = [] + is_semicolon = False + + # Hold the execution count, if requested to do so. + if is_suppress and self.hold_count: + store_history = False + else: + store_history = True + + # Note: catch_warnings is not thread safe + with warnings.catch_warnings(record=True) as ws: + for i, line in enumerate(input_lines): + if line.endswith(';'): + is_semicolon = True + + if i == 0: + # process the first input line + if is_verbatim: + self.process_input_line('') + self.IP.execution_count += 1 # increment it anyway + else: + # only submit the line in non-verbatim mode + self.process_input_line(line, store_history=store_history) + formatted_line = '%s %s'%(input_prompt, line) + else: + # process a continuation line + if not is_verbatim: + self.process_input_line(line, store_history=store_history) + + formatted_line = '%s %s'%(continuation, line) + + if not is_suppress: + ret.append(formatted_line) + + if not is_suppress and len(rest.strip()) and is_verbatim: + # the "rest" is the standard output of the + # input, which needs to be added in + # verbatim mode + ret.append(rest) + + self.cout.seek(0) + output = self.cout.read() + if not is_suppress and not is_semicolon: + ret.append(output) + elif is_semicolon: # get spacing right + ret.append('') + + # context information + filename = self.state.document.current_source + lineno = self.state.document.current_line + + # output any exceptions raised during execution to stdout + # unless :okexcept: has been specified. + if not is_okexcept and "Traceback" in output: + s = "\nException in %s at block ending on line %s\n" % (filename, lineno) + s += "Specify :okexcept: as an option in the ipython:: block to suppress this message\n" + sys.stdout.write('\n\n>>>' + ('-' * 73)) + sys.stdout.write(s) + sys.stdout.write(output) + sys.stdout.write('<<<' + ('-' * 73) + '\n\n') + + # output any warning raised during execution to stdout + # unless :okwarning: has been specified. + if not is_okwarning: + for w in ws: + s = "\nWarning in %s at block ending on line %s\n" % (filename, lineno) + s += "Specify :okwarning: as an option in the ipython:: block to suppress this message\n" + sys.stdout.write('\n\n>>>' + ('-' * 73)) + sys.stdout.write(s) + sys.stdout.write('-' * 76 + '\n') + s=warnings.formatwarning(w.message, w.category, + w.filename, w.lineno, w.line) + sys.stdout.write(s) + sys.stdout.write('<<<' + ('-' * 73) + '\n') + + self.cout.truncate(0) + return (ret, input_lines, output, is_doctest, decorator, image_file, + image_directive) + + + def process_output(self, data, output_prompt, + input_lines, output, is_doctest, decorator, image_file): + """ + Process data block for OUTPUT token. + + """ + TAB = ' ' * 4 + + if is_doctest and output is not None: + + found = output + found = found.strip() + submitted = data.strip() + + if self.directive is None: + source = 'Unavailable' + content = 'Unavailable' + else: + source = self.directive.state.document.current_source + content = self.directive.content + # Add tabs and join into a single string. + content = '\n'.join([TAB + line for line in content]) + + # Make sure the output contains the output prompt. + ind = found.find(output_prompt) + if ind < 0: + e = ('output does not contain output prompt\n\n' + 'Document source: {0}\n\n' + 'Raw content: \n{1}\n\n' + 'Input line(s):\n{TAB}{2}\n\n' + 'Output line(s):\n{TAB}{3}\n\n') + e = e.format(source, content, '\n'.join(input_lines), + repr(found), TAB=TAB) + raise RuntimeError(e) + found = found[len(output_prompt):].strip() + + # Handle the actual doctest comparison. + if decorator.strip() == '@doctest': + # Standard doctest + if found != submitted: + e = ('doctest failure\n\n' + 'Document source: {0}\n\n' + 'Raw content: \n{1}\n\n' + 'On input line(s):\n{TAB}{2}\n\n' + 'we found output:\n{TAB}{3}\n\n' + 'instead of the expected:\n{TAB}{4}\n\n') + e = e.format(source, content, '\n'.join(input_lines), + repr(found), repr(submitted), TAB=TAB) + raise RuntimeError(e) + else: + self.custom_doctest(decorator, input_lines, found, submitted) + + def process_comment(self, data): + """Process data fPblock for COMMENT token.""" + if not self.is_suppress: + return [data] + + def save_image(self, image_file): + """ + Saves the image file to disk. + """ + self.ensure_pyplot() + command = ('plt.gcf().savefig("%s", bbox_inches="tight", ' + 'dpi=100)' % image_file) + + #print 'SAVEFIG', command # dbg + self.process_input_line('bookmark ipy_thisdir', store_history=False) + self.process_input_line('cd -b ipy_savedir', store_history=False) + self.process_input_line(command, store_history=False) + self.process_input_line('cd -b ipy_thisdir', store_history=False) + self.process_input_line('bookmark -d ipy_thisdir', store_history=False) + self.clear_cout() + + def process_block(self, block): + """ + process block from the block_parser and return a list of processed lines + """ + ret = [] + output = None + input_lines = None + lineno = self.IP.execution_count + + input_prompt = self.promptin % lineno + output_prompt = self.promptout % lineno + image_file = None + image_directive = None + + for token, data in block: + if token == COMMENT: + out_data = self.process_comment(data) + elif token == INPUT: + (out_data, input_lines, output, is_doctest, decorator, + image_file, image_directive) = \ + self.process_input(data, input_prompt, lineno) + elif token == OUTPUT: + out_data = \ + self.process_output(data, output_prompt, + input_lines, output, is_doctest, + decorator, image_file) + if out_data: + ret.extend(out_data) + + # save the image files + if image_file is not None: + self.save_image(image_file) + + return ret, image_directive + + def ensure_pyplot(self): + """ + Ensures that pyplot has been imported into the embedded IPython shell. + + Also, makes sure to set the backend appropriately if not set already. + + """ + # We are here if the @figure pseudo decorator was used. Thus, it's + # possible that we could be here even if python_mplbackend were set to + # `None`. That's also strange and perhaps worthy of raising an + # exception, but for now, we just set the backend to 'agg'. + + if not self._pyplot_imported: + if 'matplotlib.backends' not in sys.modules: + # Then ipython_matplotlib was set to None but there was a + # call to the @figure decorator (and ipython_execlines did + # not set a backend). + #raise Exception("No backend was set, but @figure was used!") + import matplotlib + matplotlib.use('agg') + + # Always import pyplot into embedded shell. + self.process_input_line('import matplotlib.pyplot as plt', + store_history=False) + self._pyplot_imported = True + + def process_pure_python(self, content): + """ + content is a list of strings. it is unedited directive content + + This runs it line by line in the InteractiveShell, prepends + prompts as needed capturing stderr and stdout, then returns + the content as a list as if it were ipython code + """ + output = [] + savefig = False # keep up with this to clear figure + multiline = False # to handle line continuation + multiline_start = None + fmtin = self.promptin + + ct = 0 + + for lineno, line in enumerate(content): + + line_stripped = line.strip() + if not len(line): + output.append(line) + continue + + # handle decorators + if line_stripped.startswith('@'): + output.extend([line]) + if 'savefig' in line: + savefig = True # and need to clear figure + continue + + # handle comments + if line_stripped.startswith('#'): + output.extend([line]) + continue + + # deal with lines checking for multiline + continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2)) + if not multiline: + modified = u"%s %s" % (fmtin % ct, line_stripped) + output.append(modified) + ct += 1 + try: + ast.parse(line_stripped) + output.append(u'') + except Exception: # on a multiline + multiline = True + multiline_start = lineno + else: # still on a multiline + modified = u'%s %s' % (continuation, line) + output.append(modified) + + # if the next line is indented, it should be part of multiline + if len(content) > lineno + 1: + nextline = content[lineno + 1] + if len(nextline) - len(nextline.lstrip()) > 3: + continue + try: + mod = ast.parse( + '\n'.join(content[multiline_start:lineno+1])) + if isinstance(mod.body[0], ast.FunctionDef): + # check to see if we have the whole function + for element in mod.body[0].body: + if isinstance(element, ast.Return): + multiline = False + else: + output.append(u'') + multiline = False + except Exception: + pass + + if savefig: # clear figure if plotted + self.ensure_pyplot() + self.process_input_line('plt.clf()', store_history=False) + self.clear_cout() + savefig = False + + return output + + def custom_doctest(self, decorator, input_lines, found, submitted): + """ + Perform a specialized doctest. + + """ + from .custom_doctests import doctests + + args = decorator.split() + doctest_type = args[1] + if doctest_type in doctests: + doctests[doctest_type](self, args, input_lines, found, submitted) + else: + e = "Invalid option to @doctest: {0}".format(doctest_type) + raise Exception(e) + + +class IPythonDirective(Directive): + + has_content = True + required_arguments = 0 + optional_arguments = 4 # python, suppress, verbatim, doctest + final_argumuent_whitespace = True + option_spec = { 'python': directives.unchanged, + 'suppress' : directives.flag, + 'verbatim' : directives.flag, + 'doctest' : directives.flag, + 'okexcept': directives.flag, + 'okwarning': directives.flag, + 'output_encoding': directives.unchanged_required + } + + shell = None + + seen_docs = set() + + def get_config_options(self): + # contains sphinx configuration variables + config = self.state.document.settings.env.config + + # get config variables to set figure output directory + confdir = self.state.document.settings.env.app.confdir + savefig_dir = config.ipython_savefig_dir + source_dir = os.path.dirname(self.state.document.current_source) + if savefig_dir is None: + savefig_dir = config.html_static_path + if isinstance(savefig_dir, list): + savefig_dir = savefig_dir[0] # safe to assume only one path? + savefig_dir = os.path.join(confdir, savefig_dir) + + # get regex and prompt stuff + rgxin = config.ipython_rgxin + rgxout = config.ipython_rgxout + promptin = config.ipython_promptin + promptout = config.ipython_promptout + mplbackend = config.ipython_mplbackend + exec_lines = config.ipython_execlines + hold_count = config.ipython_holdcount + + return (savefig_dir, source_dir, rgxin, rgxout, + promptin, promptout, mplbackend, exec_lines, hold_count) + + def setup(self): + # Get configuration values. + (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout, + mplbackend, exec_lines, hold_count) = self.get_config_options() + + if self.shell is None: + # We will be here many times. However, when the + # EmbeddedSphinxShell is created, its interactive shell member + # is the same for each instance. + + if mplbackend and 'matplotlib.backends' not in sys.modules: + import matplotlib + # Repeated calls to use() will not hurt us since `mplbackend` + # is the same each time. + matplotlib.use(mplbackend) + + # Must be called after (potentially) importing matplotlib and + # setting its backend since exec_lines might import pylab. + self.shell = EmbeddedSphinxShell(exec_lines, self.state) + + # Store IPython directive to enable better error messages + self.shell.directive = self + + # reset the execution count if we haven't processed this doc + #NOTE: this may be borked if there are multiple seen_doc tmp files + #check time stamp? + if self.state.document.current_source not in self.seen_docs: + self.shell.IP.history_manager.reset() + self.shell.IP.execution_count = 1 + try: + self.shell.IP.prompt_manager.width = 0 + except AttributeError: + # GH14003: class promptManager has removed after IPython 5.x + pass + self.seen_docs.add(self.state.document.current_source) + + # and attach to shell so we don't have to pass them around + self.shell.rgxin = rgxin + self.shell.rgxout = rgxout + self.shell.promptin = promptin + self.shell.promptout = promptout + self.shell.savefig_dir = savefig_dir + self.shell.source_dir = source_dir + self.shell.hold_count = hold_count + + # setup bookmark for saving figures directory + self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir, + store_history=False) + self.shell.clear_cout() + + return rgxin, rgxout, promptin, promptout + + def teardown(self): + # delete last bookmark + self.shell.process_input_line('bookmark -d ipy_savedir', + store_history=False) + self.shell.clear_cout() + + def run(self): + debug = False + + #TODO, any reason block_parser can't be a method of embeddable shell + # then we wouldn't have to carry these around + rgxin, rgxout, promptin, promptout = self.setup() + + options = self.options + self.shell.is_suppress = 'suppress' in options + self.shell.is_doctest = 'doctest' in options + self.shell.is_verbatim = 'verbatim' in options + self.shell.is_okexcept = 'okexcept' in options + self.shell.is_okwarning = 'okwarning' in options + + self.shell.output_encoding = [options.get('output_encoding', 'utf8')] + + # handle pure python code + if 'python' in self.arguments: + content = self.content + self.content = self.shell.process_pure_python(content) + + parts = '\n'.join(self.content).split('\n\n') + + lines = ['.. code-block:: ipython', ''] + figures = [] + + for part in parts: + block = block_parser(part, rgxin, rgxout, promptin, promptout) + if len(block): + rows, figure = self.shell.process_block(block) + for row in rows: + lines.extend([' %s'%line for line in row.split('\n')]) + + if figure is not None: + figures.append(figure) + + for figure in figures: + lines.append('') + lines.extend(figure.split('\n')) + lines.append('') + + if len(lines)>2: + if debug: + print('\n'.join(lines)) + else: + # This has to do with input, not output. But if we comment + # these lines out, then no IPython code will appear in the + # final output. + self.state_machine.insert_input( + lines, self.state_machine.input_lines.source(0)) + + # cleanup + self.teardown() + + return [] + +# Enable as a proper Sphinx directive +def setup(app): + setup.app = app + + app.add_directive('ipython', IPythonDirective) + app.add_config_value('ipython_savefig_dir', None, 'env') + app.add_config_value('ipython_rgxin', + re.compile('In \[(\d+)\]:\s?(.*)\s*'), 'env') + app.add_config_value('ipython_rgxout', + re.compile('Out\[(\d+)\]:\s?(.*)\s*'), 'env') + app.add_config_value('ipython_promptin', 'In [%d]:', 'env') + app.add_config_value('ipython_promptout', 'Out[%d]:', 'env') + + # We could just let matplotlib pick whatever is specified as the default + # backend in the matplotlibrc file, but this would cause issues if the + # backend didn't work in headless environments. For this reason, 'agg' + # is a good default backend choice. + app.add_config_value('ipython_mplbackend', 'agg', 'env') + + # If the user sets this config value to `None`, then EmbeddedSphinxShell's + # __init__ method will treat it as []. + execlines = ['import numpy as np', 'import matplotlib.pyplot as plt'] + app.add_config_value('ipython_execlines', execlines, 'env') + + app.add_config_value('ipython_holdcount', True, 'env') + +# Simple smoke test, needs to be converted to a proper automatic test. +def test(): + + examples = [ + r""" +In [9]: pwd +Out[9]: '/home/jdhunter/py4science/book' + +In [10]: cd bookdata/ +/home/jdhunter/py4science/book/bookdata + +In [2]: from pylab import * + +In [2]: ion() + +In [3]: im = imread('stinkbug.png') + +@savefig mystinkbug.png width=4in +In [4]: imshow(im) +Out[4]: <matplotlib.image.AxesImage object at 0x39ea850> + +""", + r""" + +In [1]: x = 'hello world' + +# string methods can be +# used to alter the string +@doctest +In [2]: x.upper() +Out[2]: 'HELLO WORLD' + +@verbatim +In [3]: x.st<TAB> +x.startswith x.strip +""", + r""" + +In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\ + .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv' + +In [131]: print url.split('&') +['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv'] + +In [60]: import urllib + +""", + r"""\ + +In [133]: import numpy.random + +@suppress +In [134]: numpy.random.seed(2358) + +@doctest +In [135]: numpy.random.rand(10,2) +Out[135]: +array([[ 0.64524308, 0.59943846], + [ 0.47102322, 0.8715456 ], + [ 0.29370834, 0.74776844], + [ 0.99539577, 0.1313423 ], + [ 0.16250302, 0.21103583], + [ 0.81626524, 0.1312433 ], + [ 0.67338089, 0.72302393], + [ 0.7566368 , 0.07033696], + [ 0.22591016, 0.77731835], + [ 0.0072729 , 0.34273127]]) + +""", + + r""" +In [106]: print x +jdh + +In [109]: for i in range(10): + .....: print i + .....: + .....: +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +""", + + r""" + +In [144]: from pylab import * + +In [145]: ion() + +# use a semicolon to suppress the output +@savefig test_hist.png width=4in +In [151]: hist(np.random.randn(10000), 100); + + +@savefig test_plot.png width=4in +In [151]: plot(np.random.randn(10000), 'o'); + """, + + r""" +# use a semicolon to suppress the output +In [151]: plt.clf() + +@savefig plot_simple.png width=4in +In [151]: plot([1,2,3]) + +@savefig hist_simple.png width=4in +In [151]: hist(np.random.randn(10000), 100); + +""", + r""" +# update the current fig +In [151]: ylabel('number') + +In [152]: title('normal distribution') + + +@savefig hist_with_text.png +In [153]: grid(True) + +@doctest float +In [154]: 0.1 + 0.2 +Out[154]: 0.3 + +@doctest float +In [155]: np.arange(16).reshape(4,4) +Out[155]: +array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11], + [12, 13, 14, 15]]) + +In [1]: x = np.arange(16, dtype=float).reshape(4,4) + +In [2]: x[0,0] = np.inf + +In [3]: x[0,1] = np.nan + +@doctest float +In [4]: x +Out[4]: +array([[ inf, nan, 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [ 12., 13., 14., 15.]]) + + + """, + ] + # skip local-file depending first example: + examples = examples[1:] + + #ipython_directive.DEBUG = True # dbg + #options = dict(suppress=True) # dbg + options = dict() + for example in examples: + content = example.split('\n') + IPythonDirective('debug', arguments=None, options=options, + content=content, lineno=0, + content_offset=None, block_text=None, + state=None, state_machine=None, + ) + +# Run test suite as a script +if __name__=='__main__': + if not os.path.isdir('_static'): + os.mkdir('_static') + test() + print('All OK? Check figures in _static/')
This reverts commit ca737aca8b73b10b617f7fcc7da35545f9ec0a89. This reverts https://github.com/pandas-dev/pandas/pull/18193. The problem is there is something wrong with the upstream version such that errors in the code don't get reported.
https://api.github.com/repos/pandas-dev/pandas/pulls/18320
2017-11-16T08:39:46Z
2017-11-17T09:02:26Z
2017-11-17T09:02:26Z
2018-02-12T12:39:47Z
MAINT: Blacklist np.array_equal in tests
diff --git a/ci/lint.sh b/ci/lint.sh index c26b5f00d5a48..71d8c5c7e1621 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -72,7 +72,13 @@ if [ "$LINT" ]; then echo "Linting *.c and *.h DONE" echo "Check for invalid testing" - grep -r -E --include '*.py' --exclude testing.py '(numpy|np)\.testing' pandas + + # Check for the following code in testing: + # + # np.testing + # np.array_equal + grep -r -E --include '*.py' --exclude testing.py '(numpy|np)(\.testing|\.array_equal)' pandas/tests/ + if [ $? = "0" ]; then RET=1 fi diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index c182db35c0c89..4c0c7d8598a8e 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -286,29 +286,6 @@ def test_delete(self): with pytest.raises(Exception): newb.delete(3) - def test_split_block_at(self): - - # with dup column support this method was taken out - # GH3679 - pytest.skip("skipping for now") - - bs = list(self.fblock.split_block_at('a')) - assert len(bs) == 1 - assert np.array_equal(bs[0].items, ['c', 'e']) - - bs = list(self.fblock.split_block_at('c')) - assert len(bs) == 2 - assert np.array_equal(bs[0].items, ['a']) - assert np.array_equal(bs[1].items, ['e']) - - bs = list(self.fblock.split_block_at('e')) - assert len(bs) == 1 - assert np.array_equal(bs[0].items, ['a', 'c']) - - # bblock = get_bool_ex(['f']) - # bs = list(bblock.split_block_at('f')) - # assert len(bs), 0) - class TestDatetimeBlock(object):
Follow-up to #18087.
https://api.github.com/repos/pandas-dev/pandas/pulls/18318
2017-11-16T05:33:39Z
2017-11-16T18:42:41Z
2017-11-16T18:42:41Z
2017-11-17T04:54:39Z
DOC: ecosystem: dask-ml
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index ac8216d572ddd..f7d1edff15cfb 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -225,7 +225,13 @@ Out-of-core ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dask is a flexible parallel computing library for analytics. Dask -allow a familiar ``DataFrame`` interface to out-of-core, parallel and distributed computing. +provides a familiar ``DataFrame`` interface for out-of-core, parallel and distributed computing. + +`Dask-ML <https://dask-ml.readthedocs.io/en/latest/>`__ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Dask-ML enables parallel and distributed machine learning using Dask alongside existing machine learning libraries like Scikit-Learn, XGBoost, and TensorFlow. + `Blaze <http://blaze.pydata.org/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
### Dask-ml > Dask-ML enables parallel and distributed machine learning using Dask alongside existing machine learning libraries like Scikit-Learn. - Src: https://github.com/dask/dask-ml - Docs: https://dask-ml.readthedocs.io/en/latest/ ... - XGBoost, TensorFlow, scikit-learn
https://api.github.com/repos/pandas-dev/pandas/pulls/18317
2017-11-16T02:44:37Z
2017-11-16T11:15:41Z
2017-11-16T11:15:41Z
2017-12-11T20:23:34Z
CLN: replace %s syntax with .format in core.panel
diff --git a/pandas/core/panel.py b/pandas/core/panel.py index d2b513367fc78..327180b6a6e84 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -42,9 +42,9 @@ klass="Panel", axes_single_arg="{0, 1, 2, 'items', 'major_axis', 'minor_axis'}", optional_mapper='', optional_axis='', optional_labels='') -_shared_doc_kwargs['args_transpose'] = ("three positional arguments: each one" - "of\n%s" % - _shared_doc_kwargs['axes_single_arg']) +_shared_doc_kwargs['args_transpose'] = ( + "three positional arguments: each one of\n{ax_single}".format( + ax_single=_shared_doc_kwargs['axes_single_arg'])) def _ensure_like_indices(time, panels): @@ -311,7 +311,8 @@ def _init_matrix(self, data, axes, dtype=None, copy=False): try: values = values.astype(dtype) except Exception: - raise ValueError('failed to cast to %s' % dtype) + raise ValueError('failed to cast to ' + '{datatype}'.format(datatype=dtype)) shape = values.shape fixed_axes = [] @@ -352,18 +353,18 @@ def __unicode__(self): class_name = str(self.__class__) - shape = self.shape - dims = u('Dimensions: %s') % ' x '.join( - ["%d (%s)" % (s, a) for a, s in zip(self._AXIS_ORDERS, shape)]) + dims = u('Dimensions: {dimensions}'.format(dimensions=' x '.join( + ["{shape} ({axis})".format(shape=shape, axis=axis) for axis, shape + in zip(self._AXIS_ORDERS, self.shape)]))) def axis_pretty(a): v = getattr(self, a) if len(v) > 0: - return u('%s axis: %s to %s') % (a.capitalize(), - pprint_thing(v[0]), - pprint_thing(v[-1])) + return u('{ax} axis: {x} to {y}'.format(ax=a.capitalize(), + x=pprint_thing(v[0]), + y=pprint_thing(v[-1]))) else: - return u('%s axis: None') % a.capitalize() + return u('{ax} axis: None'.format(ax=a.capitalize())) output = '\n'.join( [class_name, dims] + [axis_pretty(a) for a in self._AXIS_ORDERS]) @@ -610,7 +611,8 @@ def __setitem__(self, key, value): elif is_scalar(value): mat = cast_scalar_to_array(shape[1:], value) else: - raise TypeError('Cannot set item of type: %s' % str(type(value))) + raise TypeError('Cannot set item of ' + 'type: {dtype!s}'.format(dtype=type(value))) mat = mat.reshape(tuple([1]) + shape[1:]) NDFrame._set_item(self, key, mat) @@ -739,9 +741,9 @@ def _combine(self, other, func, axis=0): elif is_scalar(other): return self._combine_const(other, func) else: - raise NotImplementedError("%s is not supported in combine " - "operation with %s" % - (str(type(other)), str(type(self)))) + raise NotImplementedError( + "{otype!s} is not supported in combine operation with " + "{selftype!s}".format(otype=type(other), selftype=type(self))) def _combine_const(self, other, func, try_cast=True): with np.errstate(all='ignore'): @@ -1188,8 +1190,8 @@ def _construct_return_type(self, result, axes=None): return self._constructor_sliced( result, **self._extract_axes_for_slice(self, axes)) - raise ValueError('invalid _construct_return_type [self->%s] ' - '[result->%s]' % (self, result)) + raise ValueError('invalid _construct_return_type [self->{self}] ' + '[result->{result}]'.format(self=self, result=result)) def _wrap_result(self, result, axis): axis = self._get_axis_name(axis) @@ -1508,7 +1510,8 @@ def _extract_axis(self, data, axis=0, intersect=False): if have_raw_arrays: lengths = list(set(raw_lengths)) if len(lengths) > 1: - raise ValueError('ndarrays must match shape on axis %d' % axis) + raise ValueError('ndarrays must match shape on ' + 'axis {ax}'.format(ax=axis)) if have_frames: if lengths[0] != len(index): @@ -1525,20 +1528,6 @@ def _extract_axis(self, data, axis=0, intersect=False): def _add_aggregate_operations(cls, use_numexpr=True): """ add the operations to the cls; evaluate the doc strings again """ - # doc strings substitors - _agg_doc = """ -Wrapper method for %%s - -Parameters ----------- -other : %s or %s""" % (cls._constructor_sliced.__name__, cls.__name__) + """ -axis : {""" + ', '.join(cls._AXIS_ORDERS) + "}" + """ - Axis to broadcast over - -Returns -------- -""" + cls.__name__ + "\n" - def _panel_arith_method(op, name, str_rep=None, default_axis=None, fill_zeros=None, **eval_kwargs): def na_op(x, y): @@ -1566,27 +1555,45 @@ def na_op(x, y): equiv = 'panel ' + op_desc['op'] + ' other' _op_doc = """ - %%s of series and other, element-wise (binary operator `%%s`). - Equivalent to ``%%s``. +{desc} of series and other, element-wise (binary operator `{op_name}`). +Equivalent to ``{equiv}``. + +Parameters +---------- +other : {construct} or {cls_name} +axis : {{{axis_order}}} + Axis to broadcast over + +Returns +------- +{cls_name} + +See also +-------- +{cls_name}.{reverse}\n""" + doc = _op_doc.format( + desc=op_desc['desc'], op_name=op_name, equiv=equiv, + construct=cls._constructor_sliced.__name__, + cls_name=cls.__name__, reverse=op_desc['reverse'], + axis_order=', '.join(cls._AXIS_ORDERS)) + else: + # doc strings substitors + _agg_doc = """ + Wrapper method for {wrp_method} Parameters ---------- - other : %s or %s""" % (cls._constructor_sliced.__name__, - cls.__name__) + """ - axis : {""" + ', '.join(cls._AXIS_ORDERS) + "}" + """ + other : {construct} or {cls_name} + axis : {{{axis_order}}} Axis to broadcast over Returns ------- - """ + cls.__name__ + """ - - See also - -------- - """ + cls.__name__ + ".%s\n" - doc = _op_doc % (op_desc['desc'], op_name, equiv, - op_desc['reverse']) - else: - doc = _agg_doc % name + {cls_name}\n""" + doc = _agg_doc.format( + construct=cls._constructor_sliced.__name__, + cls_name=cls.__name__, wrp_method=name, + axis_order=', '.join(cls._AXIS_ORDERS)) @Appender(doc) def f(self, other, axis=0):
- [x] Progress towards #16130 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Note, there's still a couple usages in this file in the `Appender` decorators, I'm planning on going through all `appender`/`shared_docs` usages in the near future to clean these up too.
https://api.github.com/repos/pandas-dev/pandas/pulls/18315
2017-11-16T00:13:44Z
2017-11-16T11:34:28Z
2017-11-16T11:34:28Z
2017-11-16T11:36:09Z
BUG: #12815 Always use np.nan for missing values of object dtypes
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 6dc730cae37f7..ed8d41738c62c 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -48,6 +48,7 @@ Other API Changes - :class:`CacheableOffset` and :class:`WeekDay` are no longer available in the ``pandas.tseries.offsets`` module (:issue:`17830`) - `tseries.frequencies.get_freq_group()` and `tseries.frequencies.DAYS` are removed from the public API (:issue:`18034`) - :func:`Series.truncate` and :func:`DataFrame.truncate` will raise a ``ValueError`` if the index is not sorted instead of an unhelpful ``KeyError`` (:issue:`17935`) +- :func:`Dataframe.unstack` will now default to filling with ``np.nan`` for ``object`` columns. (:issue:`12815`) .. _whatsnew_0220.deprecations: diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index eae283e9bc00d..f91624bae7af8 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -320,6 +320,7 @@ def maybe_promote(dtype, fill_value=np.nan): fill_value = iNaT else: dtype = np.object_ + fill_value = np.nan else: dtype = np.object_ diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index d795aa835b00a..04dcea2b9d533 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -783,3 +783,26 @@ def test_stack_preserve_categorical_dtype(self): expected = Series([10, 11, 12], index=midx) tm.assert_series_equal(result, expected) + + +def test_unstack_fill_frame_object(): + # GH12815 Test unstacking with object. + data = pd.Series(['a', 'b', 'c', 'a'], dtype='object') + data.index = pd.MultiIndex.from_tuples( + [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')]) + + # By default missing values will be NaN + result = data.unstack() + expected = pd.DataFrame( + {'a': ['a', np.nan, 'a'], 'b': ['b', 'c', np.nan]}, + index=list('xyz') + ) + assert_frame_equal(result, expected) + + # Fill with any value replaces missing values as expected + result = data.unstack(fill_value='d') + expected = pd.DataFrame( + {'a': ['a', 'd', 'a'], 'b': ['b', 'c', 'd']}, + index=list('xyz') + ) + assert_frame_equal(result, expected)
- [x] closes #12815 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Handles the issue of unstacked object columns filling missing values with `None` instead of `np.nan` by modifying `pd.core.dtypes.cast.maybe_promote()` to use a `fill_value` of `np.nan` (or `pd.NaT`) when the original `fill_value` is `None`. Let me know if you'd like me to clarify anything!
https://api.github.com/repos/pandas-dev/pandas/pulls/18313
2017-11-15T20:19:51Z
2017-11-21T00:41:13Z
2017-11-21T00:41:12Z
2017-11-21T03:10:26Z
import from np_datetime instead of src/datetime
diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx index bd21fb97ede20..272e6f7d38d87 100644 --- a/pandas/_libs/period.pyx +++ b/pandas/_libs/period.pyx @@ -19,31 +19,29 @@ from pandas.compat import PY2 cimport cython from tslibs.np_datetime cimport (pandas_datetimestruct, - dtstruct_to_dt64, dt64_to_dtstruct) -from datetime cimport is_leapyear + dtstruct_to_dt64, dt64_to_dtstruct, + is_leapyear) cimport util from util cimport is_period_object, is_string_object, INT32_MIN from lib cimport is_null_datetimelike -from pandas._libs import tslib -from pandas._libs.tslib import Timestamp, iNaT +from pandas._libs.tslib import Timestamp from tslibs.timezones cimport ( - is_utc, is_tzlocal, get_utcoffset, get_dst_info, maybe_get_tz) + is_utc, is_tzlocal, get_utcoffset, get_dst_info) from tslibs.timedeltas cimport delta_to_nanoseconds from tslibs.parsing import (parse_time_string, NAT_SENTINEL, _get_rule_month, _MONTH_NUMBERS) from tslibs.frequencies cimport get_freq_code from tslibs.resolution import resolution, Resolution -from tslibs.nattype import nat_strings, NaT -from tslibs.nattype cimport _nat_scalar_rules +from tslibs.nattype import nat_strings, NaT, iNaT +from tslibs.nattype cimport _nat_scalar_rules, NPY_NAT from pandas.tseries import offsets from pandas.tseries import frequencies -cdef int64_t NPY_NAT = util.get_nat() cdef extern from "period_helper.h": ctypedef struct date_info: diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 540a081bdda2e..88a859375c1e3 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -38,14 +38,7 @@ from cpython.datetime cimport (PyDelta_Check, PyTZInfo_Check, # import datetime C API PyDateTime_IMPORT # this is our datetime.pxd -from datetime cimport ( - pandas_datetime_to_datetimestruct, - days_per_month_table, - PANDAS_DATETIMEUNIT, - _string_to_dts, - is_leapyear, - dayofweek, - PANDAS_FR_ns) +from datetime cimport pandas_datetime_to_datetimestruct, _string_to_dts # stdlib datetime imports from datetime import time as datetime_time @@ -55,11 +48,14 @@ from tslibs.np_datetime cimport (check_dts_bounds, reverse_ops, cmp_scalar, pandas_datetimestruct, + PANDAS_DATETIMEUNIT, PANDAS_FR_ns, dt64_to_dtstruct, dtstruct_to_dt64, pydatetime_to_dt64, pydate_to_dt64, npy_datetime, get_datetime64_unit, get_datetime64_value, - get_timedelta64_value) + get_timedelta64_value, + days_per_month_table, + dayofweek, is_leapyear) from tslibs.np_datetime import OutOfBoundsDatetime from .tslibs.parsing import parse_datetime_string @@ -75,9 +71,6 @@ UTC = pytz.utc import_array() -cdef int64_t NPY_NAT = util.get_nat() -iNaT = NPY_NAT - from tslibs.timedeltas cimport cast_from_unit, delta_to_nanoseconds from tslibs.timedeltas import Timedelta from tslibs.timezones cimport ( @@ -95,8 +88,8 @@ from tslibs.conversion cimport (tz_convert_single, _TSObject, from tslibs.conversion import (tz_localize_to_utc, tz_convert_single, date_normalize) -from tslibs.nattype import NaT, nat_strings -from tslibs.nattype cimport _checknull_with_nat +from tslibs.nattype import NaT, nat_strings, iNaT +from tslibs.nattype cimport _checknull_with_nat, NPY_NAT cdef inline object create_timestamp_from_ts( diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index c175769dc725e..2a55180b53498 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -20,15 +20,14 @@ PyDateTime_IMPORT from np_datetime cimport (check_dts_bounds, pandas_datetimestruct, + PANDAS_DATETIMEUNIT, PANDAS_FR_ns, + npy_datetime, dt64_to_dtstruct, dtstruct_to_dt64, + get_datetime64_unit, get_datetime64_value, pydatetime_to_dt64) -from datetime cimport (pandas_datetime_to_datetimestruct, - PANDAS_DATETIMEUNIT, PANDAS_FR_ns, npy_datetime, - _string_to_dts, - get_datetime64_unit, get_datetime64_value) +from datetime cimport pandas_datetime_to_datetimestruct, _string_to_dts -cimport util from util cimport (is_string_object, is_datetime64_object, is_integer_object, is_float_object) @@ -41,10 +40,10 @@ from timezones cimport ( from parsing import parse_datetime_string from nattype import nat_strings, NaT +from nattype cimport NPY_NAT # ---------------------------------------------------------------------- # Constants -cdef int64_t NPY_NAT = util.get_nat() cdef int64_t DAY_NS = 86400000000000LL diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx index 3ab84853dfc4a..e813fad1d3fa7 100644 --- a/pandas/_libs/tslibs/fields.pyx +++ b/pandas/_libs/tslibs/fields.pyx @@ -18,16 +18,9 @@ np.import_array() from np_datetime cimport (pandas_datetimestruct, pandas_timedeltastruct, - dt64_to_dtstruct, td64_to_tdstruct) - -from datetime cimport ( - days_per_month_table, - is_leapyear, - dayofweek) - -cimport util - -cdef int64_t NPY_NAT = util.get_nat() + dt64_to_dtstruct, td64_to_tdstruct, + days_per_month_table, is_leapyear, dayofweek) +from nattype cimport NPY_NAT def build_field_sarray(ndarray[int64_t] dtindex): diff --git a/pandas/_libs/tslibs/nattype.pxd b/pandas/_libs/tslibs/nattype.pxd index 7ded36bb1bdc0..34fa1e70305e7 100644 --- a/pandas/_libs/tslibs/nattype.pxd +++ b/pandas/_libs/tslibs/nattype.pxd @@ -1,6 +1,9 @@ # -*- coding: utf-8 -*- # cython: profile=False +from numpy cimport int64_t +cdef int64_t NPY_NAT + cdef bint _nat_scalar_rules[6] cdef bint _checknull_with_nat(object val) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index a5861f5865a39..736eeee5e1130 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -26,6 +26,7 @@ from util cimport (get_nat, nat_strings = set(['NaT', 'nat', 'NAT', 'nan', 'NaN', 'NAN']) cdef int64_t NPY_NAT = get_nat() +iNaT = NPY_NAT # python-visible constant cdef bint _nat_scalar_rules[6] _nat_scalar_rules[Py_EQ] = False diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd index 3692822ada135..8d9a812654ab0 100644 --- a/pandas/_libs/tslibs/np_datetime.pxd +++ b/pandas/_libs/tslibs/np_datetime.pxd @@ -50,6 +50,11 @@ cdef extern from "../src/datetime/np_datetime.h": PANDAS_FR_fs PANDAS_FR_as + int days_per_month_table[2][12] + int dayofweek(int y, int m, int d) nogil + int is_leapyear(int64_t year) nogil + + cdef int reverse_ops[6] cdef bint cmp_scalar(int64_t lhs, int64_t rhs, int op) except -1 diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 214d7c0f2b432..64a972dacbaf0 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -36,11 +36,9 @@ from cpython.datetime cimport datetime from np_datetime cimport (check_dts_bounds, dtstruct_to_dt64, pandas_datetimestruct) -from util cimport is_string_object, get_nat +from util cimport is_string_object -cdef int64_t NPY_NAT = get_nat() - -from nattype cimport _checknull_with_nat +from nattype cimport _checknull_with_nat, NPY_NAT from nattype import nat_strings diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index aba213122ea31..4d55c8add6757 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -30,13 +30,11 @@ from np_datetime cimport (cmp_scalar, reverse_ops, td64_to_tdstruct, pandas_timedeltastruct) from nattype import nat_strings, NaT -from nattype cimport _checknull_with_nat +from nattype cimport _checknull_with_nat, NPY_NAT # ---------------------------------------------------------------------- # Constants -cdef int64_t NPY_NAT = util.get_nat() - cdef int64_t DAY_NS = 86400000000000LL # components named tuple @@ -872,7 +870,7 @@ class Timedelta(_Timedelta): if isinstance(value, Timedelta): value = value.value - elif util.is_string_object(value): + elif is_string_object(value): value = np.timedelta64(parse_timedelta_string(value)) elif PyDelta_Check(value): value = convert_to_timedelta64(value, 'ns') @@ -882,7 +880,7 @@ class Timedelta(_Timedelta): value = value.astype('timedelta64[ns]') elif hasattr(value, 'delta'): value = np.timedelta64(delta_to_nanoseconds(value.delta), 'ns') - elif is_integer_object(value) or util.is_float_object(value): + elif is_integer_object(value) or is_float_object(value): # unit=None is de-facto 'ns' value = convert_to_timedelta64(value, unit) elif _checknull_with_nat(value): diff --git a/setup.py b/setup.py index c3e0c037625da..76847e66b8bd5 100755 --- a/setup.py +++ b/setup.py @@ -553,13 +553,14 @@ def pxd(name): '_libs.tslibs.conversion': { 'pyxfile': '_libs/tslibs/conversion', 'pxdfiles': ['_libs/src/util', + '_libs/tslibs/nattype', '_libs/tslibs/timezones', '_libs/tslibs/timedeltas'], 'depends': tseries_depends, 'sources': np_datetime_sources}, '_libs.tslibs.fields': { 'pyxfile': '_libs/tslibs/fields', - 'pxdfiles': ['_libs/src/util'], + 'pxdfiles': ['_libs/tslibs/nattype'], 'depends': tseries_depends, 'sources': np_datetime_sources}, '_libs.tslibs.frequencies': {
There are a handful of things where there is an option to cimport from either tslibs.np_datetime or src/datetime.pxd. This PR updates imports use tslibs.np_datetime where possible. Exposes NPY_NAT in nattype.pxd so other modules can cimport it from there instead of using util.get_nat(). Thematically `nattype` is the appropriate place for this to come from. I don't think this has any overlaps with #18298. - [ ] 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/18312
2017-11-15T20:12:28Z
2017-11-16T00:01:24Z
2017-11-16T00:01:24Z
2017-11-16T01:01:18Z
BUG: cast to correct dtype in Index.drop()
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 24f3e4433411e..0fc862210fc6e 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -301,6 +301,7 @@ Indexing - Bug in :func:`MultiIndex.remove_unused_levels` which would fill nan values (:issue:`18417`) - Bug in :func:`MultiIndex.from_tuples`` which would fail to take zipped tuples in python3 (:issue:`18434`) - Bug in :class:`Index` construction from list of mixed type tuples (:issue:`18505`) +- Bug in :func:`Index.drop` when passing a list of both tuples and non-tuples (:issue:`18304`) - Bug in :class:`IntervalIndex` where empty and purely NA data was constructed inconsistently depending on the construction method (:issue:`18421`) - Bug in :func:`IntervalIndex.symmetric_difference` where the symmetric difference with a non-``IntervalIndex`` did not raise (:issue:`18475`) - Bug in indexing a datetimelike ``Index`` that raised ``ValueError`` instead of ``IndexError`` (:issue:`18386`). diff --git a/pandas/core/common.py b/pandas/core/common.py index 35696be5b2a03..775ecc32b0f3c 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -398,7 +398,19 @@ def _asarray_tuplesafe(values, dtype=None): return result -def _index_labels_to_array(labels): +def _index_labels_to_array(labels, dtype=None): + """ + Transform label or iterable of labels to array, for use in Index. + + Parameters + ---------- + dtype : dtype + If specified, use as dtype of the resulting array, otherwise infer. + + Returns + ------- + array + """ if isinstance(labels, (compat.string_types, tuple)): labels = [labels] @@ -408,7 +420,7 @@ def _index_labels_to_array(labels): except TypeError: # non-iterable labels = [labels] - labels = _asarray_tuplesafe(labels) + labels = _asarray_tuplesafe(labels, dtype=dtype) return labels diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 78c7cb7b1d30c..04b8ade7e5253 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3761,7 +3761,8 @@ def drop(self, labels, errors='raise'): ------- dropped : Index """ - labels = _index_labels_to_array(labels) + arr_dtype = 'object' if self.dtype == 'object' else None + labels = _index_labels_to_array(labels, dtype=arr_dtype) indexer = self.get_indexer(labels) mask = indexer == -1 if mask.any(): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index e09f4ad360843..e33fd1e0f4c1e 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1429,6 +1429,27 @@ def test_drop(self): expected = Index([1, 2]) tm.assert_index_equal(dropped, expected) + @pytest.mark.parametrize("values", [['a', 'b', ('c', 'd')], + ['a', ('c', 'd'), 'b'], + [('c', 'd'), 'a', 'b']]) + @pytest.mark.parametrize("to_drop", [[('c', 'd'), 'a'], ['a', ('c', 'd')]]) + def test_drop_tuple(self, values, to_drop): + # GH 18304 + index = pd.Index(values) + expected = pd.Index(['b']) + + result = index.drop(to_drop) + tm.assert_index_equal(result, expected) + + removed = index.drop(to_drop[0]) + for drop_me in to_drop[1], [to_drop[1]]: + result = removed.drop(drop_me) + tm.assert_index_equal(result, expected) + + removed = index.drop(to_drop[1]) + for drop_me in to_drop[1], [to_drop[1]]: + pytest.raises(ValueError, removed.drop, drop_me) + def test_tuple_union_bug(self): import pandas import numpy as np diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 6b44a339fad73..5b64f62527da4 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1631,3 +1631,15 @@ def test_crosstab_dup_index_names(self): index=expected_index, columns=expected_index) tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("names", [['a', ('b', 'c')], + [('a', 'b'), 'c']]) + def test_crosstab_tuple_name(self, names): + s1 = pd.Series(range(3), name=names[0]) + s2 = pd.Series(range(1, 4), name=names[1]) + + mi = pd.MultiIndex.from_arrays([range(3), range(1, 4)], names=names) + expected = pd.Series(1, index=mi).unstack(1, fill_value=0) + + result = pd.crosstab(s1, s2) + tm.assert_frame_equal(result, expected)
- [x] closes #18304 - [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/18309
2017-11-15T15:53:00Z
2017-12-29T00:53:35Z
2017-12-29T00:53:35Z
2017-12-29T08:35:01Z
API: Restore implicit converter registration
diff --git a/ci/check_imports.py b/ci/check_imports.py index a83436e7d258c..d6f24ebcc4d3e 100644 --- a/ci/check_imports.py +++ b/ci/check_imports.py @@ -9,7 +9,6 @@ 'ipython', 'jinja2' 'lxml', - 'matplotlib', 'numexpr', 'openpyxl', 'py', diff --git a/doc/source/api.rst b/doc/source/api.rst index f3405fcdee608..5044d35de703b 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -2375,6 +2375,17 @@ Style Export and Import Styler.use Styler.to_excel +Plotting +~~~~~~~~ + +.. currentmodule:: pandas + +.. autosummary:: + :toctree: generated/ + + plotting.register_matplotlib_converters + plotting.deregister_matplotlib_converters + .. currentmodule:: pandas General utility functions diff --git a/doc/source/options.rst b/doc/source/options.rst index 2da55a5a658a4..be3a3d9a55534 100644 --- a/doc/source/options.rst +++ b/doc/source/options.rst @@ -273,164 +273,166 @@ Options are 'right', and 'left'. Available Options ----------------- -=================================== ============ ================================== -Option Default Function -=================================== ============ ================================== -display.chop_threshold None If set to a float value, all float - values smaller then the given - threshold will be displayed as - exactly 0 by repr and friends. -display.colheader_justify right Controls the justification of - column headers. used by DataFrameFormatter. -display.column_space 12 No description available. -display.date_dayfirst False When True, prints and parses dates - with the day first, eg 20/01/2005 -display.date_yearfirst False When True, prints and parses dates - with the year first, eg 2005/01/20 -display.encoding UTF-8 Defaults to the detected encoding - of the console. Specifies the encoding - to be used for strings returned by - to_string, these are generally strings - meant to be displayed on the console. -display.expand_frame_repr True Whether to print out the full DataFrame - repr for wide DataFrames across - multiple lines, `max_columns` is - still respected, but the output will - wrap-around across multiple "pages" - if its width exceeds `display.width`. -display.float_format None The callable should accept a floating - point number and return a string with - the desired format of the number. - This is used in some places like - SeriesFormatter. - See core.format.EngFormatter for an example. -display.large_repr truncate For DataFrames exceeding max_rows/max_cols, - the repr (and HTML repr) can show - a truncated table (the default), - or switch to the view from df.info() - (the behaviour in earlier versions of pandas). - allowable settings, ['truncate', 'info'] -display.latex.repr False Whether to produce a latex DataFrame - representation for jupyter frontends - that support it. -display.latex.escape True Escapes special characters in DataFrames, when - using the to_latex method. -display.latex.longtable False Specifies if the to_latex method of a DataFrame - uses the longtable format. -display.latex.multicolumn True Combines columns when using a MultiIndex -display.latex.multicolumn_format 'l' Alignment of multicolumn labels -display.latex.multirow False Combines rows when using a MultiIndex. - Centered instead of top-aligned, - separated by clines. -display.max_columns 20 max_rows and max_columns are used - in __repr__() methods to decide if - to_string() or info() is used to - render an object to a string. In - case python/IPython is running in - a terminal this can be set to 0 and - pandas will correctly auto-detect - the width the terminal and swap to - a smaller format in case all columns - would not fit vertically. The IPython - notebook, IPython qtconsole, or IDLE - do not run in a terminal and hence - it is not possible to do correct - auto-detection. 'None' value means - unlimited. -display.max_colwidth 50 The maximum width in characters of - a column in the repr of a pandas - data structure. When the column overflows, - a "..." placeholder is embedded in - the output. -display.max_info_columns 100 max_info_columns is used in DataFrame.info - method to decide if per column information - will be printed. -display.max_info_rows 1690785 df.info() will usually show null-counts - for each column. For large frames - this can be quite slow. max_info_rows - and max_info_cols limit this null - check only to frames with smaller - dimensions then specified. -display.max_rows 60 This sets the maximum number of rows - pandas should output when printing - out various output. For example, - this value determines whether the - repr() for a dataframe prints out - fully or just a summary repr. - 'None' value means unlimited. -display.max_seq_items 100 when pretty-printing a long sequence, - no more then `max_seq_items` will - be printed. If items are omitted, - they will be denoted by the addition - of "..." to the resulting string. - If set to None, the number of items - to be printed is unlimited. -display.memory_usage True This specifies if the memory usage of - a DataFrame should be displayed when the - df.info() method is invoked. -display.multi_sparse True "Sparsify" MultiIndex display (don't - display repeated elements in outer - levels within groups) -display.notebook_repr_html True When True, IPython notebook will - use html representation for - pandas objects (if it is available). -display.pprint_nest_depth 3 Controls the number of nested levels - to process when pretty-printing -display.precision 6 Floating point output precision in - terms of number of places after the - decimal, for regular formatting as well - as scientific notation. Similar to - numpy's ``precision`` print option -display.show_dimensions truncate Whether to print out dimensions - at the end of DataFrame repr. - If 'truncate' is specified, only - print out the dimensions if the - frame is truncated (e.g. not display - all rows and/or columns) -display.width 80 Width of the display in characters. - In case python/IPython is running in - a terminal this can be set to None - and pandas will correctly auto-detect - the width. Note that the IPython notebook, - IPython qtconsole, or IDLE do not run in a - terminal and hence it is not possible - to correctly detect the width. -display.html.table_schema False Whether to publish a Table Schema - representation for frontends that - support it. -display.html.border 1 A ``border=value`` attribute is - inserted in the ``<table>`` tag - for the DataFrame HTML repr. -io.excel.xls.writer xlwt The default Excel writer engine for - 'xls' files. -io.excel.xlsm.writer openpyxl The default Excel writer engine for - 'xlsm' files. Available options: - 'openpyxl' (the default). -io.excel.xlsx.writer openpyxl The default Excel writer engine for - 'xlsx' files. -io.hdf.default_format None default format writing format, if - None, then put will default to - 'fixed' and append will default to - 'table' -io.hdf.dropna_table True drop ALL nan rows when appending - to a table -io.parquet.engine None The engine to use as a default for - parquet reading and writing. If None - then try 'pyarrow' and 'fastparquet' -mode.chained_assignment warn Raise an exception, warn, or no - action if trying to use chained - assignment, The default is warn -mode.sim_interactive False Whether to simulate interactive mode - for purposes of testing. -mode.use_inf_as_na False True means treat None, NaN, -INF, - INF as NA (old way), False means - None and NaN are null, but INF, -INF - are not NA (new way). -compute.use_bottleneck True Use the bottleneck library to accelerate - computation if it is installed. -compute.use_numexpr True Use the numexpr library to accelerate - computation if it is installed. -=================================== ============ ================================== +======================================= ============ ================================== +Option Default Function +======================================= ============ ================================== +display.chop_threshold None If set to a float value, all float + values smaller then the given + threshold will be displayed as + exactly 0 by repr and friends. +display.colheader_justify right Controls the justification of + column headers. used by DataFrameFormatter. +display.column_space 12 No description available. +display.date_dayfirst False When True, prints and parses dates + with the day first, eg 20/01/2005 +display.date_yearfirst False When True, prints and parses dates + with the year first, eg 2005/01/20 +display.encoding UTF-8 Defaults to the detected encoding + of the console. Specifies the encoding + to be used for strings returned by + to_string, these are generally strings + meant to be displayed on the console. +display.expand_frame_repr True Whether to print out the full DataFrame + repr for wide DataFrames across + multiple lines, `max_columns` is + still respected, but the output will + wrap-around across multiple "pages" + if its width exceeds `display.width`. +display.float_format None The callable should accept a floating + point number and return a string with + the desired format of the number. + This is used in some places like + SeriesFormatter. + See core.format.EngFormatter for an example. +display.large_repr truncate For DataFrames exceeding max_rows/max_cols, + the repr (and HTML repr) can show + a truncated table (the default), + or switch to the view from df.info() + (the behaviour in earlier versions of pandas). + allowable settings, ['truncate', 'info'] +display.latex.repr False Whether to produce a latex DataFrame + representation for jupyter frontends + that support it. +display.latex.escape True Escapes special characters in DataFrames, when + using the to_latex method. +display.latex.longtable False Specifies if the to_latex method of a DataFrame + uses the longtable format. +display.latex.multicolumn True Combines columns when using a MultiIndex +display.latex.multicolumn_format 'l' Alignment of multicolumn labels +display.latex.multirow False Combines rows when using a MultiIndex. + Centered instead of top-aligned, + separated by clines. +display.max_columns 20 max_rows and max_columns are used + in __repr__() methods to decide if + to_string() or info() is used to + render an object to a string. In + case python/IPython is running in + a terminal this can be set to 0 and + pandas will correctly auto-detect + the width the terminal and swap to + a smaller format in case all columns + would not fit vertically. The IPython + notebook, IPython qtconsole, or IDLE + do not run in a terminal and hence + it is not possible to do correct + auto-detection. 'None' value means + unlimited. +display.max_colwidth 50 The maximum width in characters of + a column in the repr of a pandas + data structure. When the column overflows, + a "..." placeholder is embedded in + the output. +display.max_info_columns 100 max_info_columns is used in DataFrame.info + method to decide if per column information + will be printed. +display.max_info_rows 1690785 df.info() will usually show null-counts + for each column. For large frames + this can be quite slow. max_info_rows + and max_info_cols limit this null + check only to frames with smaller + dimensions then specified. +display.max_rows 60 This sets the maximum number of rows + pandas should output when printing + out various output. For example, + this value determines whether the + repr() for a dataframe prints out + fully or just a summary repr. + 'None' value means unlimited. +display.max_seq_items 100 when pretty-printing a long sequence, + no more then `max_seq_items` will + be printed. If items are omitted, + they will be denoted by the addition + of "..." to the resulting string. + If set to None, the number of items + to be printed is unlimited. +display.memory_usage True This specifies if the memory usage of + a DataFrame should be displayed when the + df.info() method is invoked. +display.multi_sparse True "Sparsify" MultiIndex display (don't + display repeated elements in outer + levels within groups) +display.notebook_repr_html True When True, IPython notebook will + use html representation for + pandas objects (if it is available). +display.pprint_nest_depth 3 Controls the number of nested levels + to process when pretty-printing +display.precision 6 Floating point output precision in + terms of number of places after the + decimal, for regular formatting as well + as scientific notation. Similar to + numpy's ``precision`` print option +display.show_dimensions truncate Whether to print out dimensions + at the end of DataFrame repr. + If 'truncate' is specified, only + print out the dimensions if the + frame is truncated (e.g. not display + all rows and/or columns) +display.width 80 Width of the display in characters. + In case python/IPython is running in + a terminal this can be set to None + and pandas will correctly auto-detect + the width. Note that the IPython notebook, + IPython qtconsole, or IDLE do not run in a + terminal and hence it is not possible + to correctly detect the width. +display.html.table_schema False Whether to publish a Table Schema + representation for frontends that + support it. +display.html.border 1 A ``border=value`` attribute is + inserted in the ``<table>`` tag + for the DataFrame HTML repr. +io.excel.xls.writer xlwt The default Excel writer engine for + 'xls' files. +io.excel.xlsm.writer openpyxl The default Excel writer engine for + 'xlsm' files. Available options: + 'openpyxl' (the default). +io.excel.xlsx.writer openpyxl The default Excel writer engine for + 'xlsx' files. +io.hdf.default_format None default format writing format, if + None, then put will default to + 'fixed' and append will default to + 'table' +io.hdf.dropna_table True drop ALL nan rows when appending + to a table +io.parquet.engine None The engine to use as a default for + parquet reading and writing. If None + then try 'pyarrow' and 'fastparquet' +mode.chained_assignment warn Raise an exception, warn, or no + action if trying to use chained + assignment, The default is warn +mode.sim_interactive False Whether to simulate interactive mode + for purposes of testing. +mode.use_inf_as_na False True means treat None, NaN, -INF, + INF as NA (old way), False means + None and NaN are null, but INF, -INF + are not NA (new way). +compute.use_bottleneck True Use the bottleneck library to accelerate + computation if it is installed. +compute.use_numexpr True Use the numexpr library to accelerate + computation if it is installed. +plotting.matplotlib.register_converters True Register custom converters with + matplotlib. Set to False to de-register. +======================================= ============ ======================================== .. _basics.console_output: diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index e307e605687bf..55efbae68d8ef 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -7,6 +7,36 @@ This is a minor release from 0.21.1 and includes a number of deprecations, new features, enhancements, and performance improvements along with a large number of bug fixes. We recommend that all users upgrade to this version. +.. _whatsnew_0211.special: + +Restore Matplotlib datetime Converter Registration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Pandas implements some matplotlib converters for nicely formatting the axis +labels on plots with ``datetime`` or ``Period`` values. Prior to pandas 0.21.0, +these were implicitly registered with matplotlib, as a side effect of ``import +pandas``. + +In pandas 0.21.0, we required users to explicitly register the +converter. This caused problems for some users who relied on those converters +being present for regular ``matplotlib.pyplot`` plotting methods, so we're +temporarily reverting that change; pandas will again register the converters on +import. + +We've added a new option to control the converters: +``pd.options.plotting.matplotlib.register_converters``. By default, they are +registered. Toggling this to ``False`` removes pandas' formatters and restore +any converters we overwrote when registering them (:issue:`18301`). + +We're working with the matplotlib developers to make this easier. We're trying +to balance user convenience (automatically registering the converters) with +import performance and best practices (importing pandas shouldn't have the side +effect of overwriting any custom converters you've already set). In the future +we hope to have most of the datetime formatting functionality in matplotlib, +with just the pandas-specific converters in pandas. We'll then gracefully +deprecate the automatic registration of converters in favor of users explicitly +registering them when they want them. + .. _whatsnew_0211.enhancements: New features @@ -30,9 +60,8 @@ Other Enhancements Deprecations ~~~~~~~~~~~~ -- -- -- +- ``pandas.tseries.register`` has been renamed to + :func:`pandas.plotting.register_matplotlib_converters`` (:issue:`18301`) .. _whatsnew_0211.performance: diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 59578b96807e1..c3307c60b8ed9 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -480,3 +480,29 @@ def use_inf_as_na_cb(key): cf.register_option( 'engine', 'auto', parquet_engine_doc, validator=is_one_of_factory(['auto', 'pyarrow', 'fastparquet'])) + +# -------- +# Plotting +# --------- + +register_converter_doc = """ +: bool + Whether to register converters with matplotlib's units registry for + dates, times, datetimes, and Periods. Toggling to False will remove + the converters, restoring any converters that pandas overwrote. +""" + + +def register_converter_cb(key): + from pandas.plotting import register_matplotlib_converters + from pandas.plotting import deregister_matplotlib_converters + + if cf.get_option(key): + register_matplotlib_converters() + else: + deregister_matplotlib_converters() + + +with cf.config_prefix("plotting.matplotlib"): + cf.register_option("register_converters", True, register_converter_doc, + validator=bool, cb=register_converter_cb) diff --git a/pandas/plotting/__init__.py b/pandas/plotting/__init__.py index 8f98e297e3e66..385d4d7f047c7 100644 --- a/pandas/plotting/__init__.py +++ b/pandas/plotting/__init__.py @@ -11,3 +11,10 @@ from pandas.plotting._core import boxplot from pandas.plotting._style import plot_params from pandas.plotting._tools import table +try: + from pandas.plotting._converter import \ + register as register_matplotlib_converters + from pandas.plotting._converter import \ + deregister as deregister_matplotlib_converters +except ImportError: + pass diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index 9daee918b9f30..10b1d26a5aa77 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -1,3 +1,4 @@ +import warnings from datetime import datetime, timedelta import datetime as pydt import numpy as np @@ -45,14 +46,96 @@ MUSEC_PER_DAY = 1e6 * SEC_PER_DAY +_WARN = True # Global for whether pandas has registered the units explicitly +_mpl_units = {} # Cache for units overwritten by us -def register(): - units.registry[lib.Timestamp] = DatetimeConverter() - units.registry[Period] = PeriodConverter() - units.registry[pydt.datetime] = DatetimeConverter() - units.registry[pydt.date] = DatetimeConverter() - units.registry[pydt.time] = TimeConverter() - units.registry[np.datetime64] = DatetimeConverter() + +def get_pairs(): + pairs = [ + (lib.Timestamp, DatetimeConverter), + (Period, PeriodConverter), + (pydt.datetime, DatetimeConverter), + (pydt.date, DatetimeConverter), + (pydt.time, TimeConverter), + (np.datetime64, DatetimeConverter), + ] + return pairs + + +def register(explicit=True): + """Register Pandas Formatters and Converters with matplotlib + + This function modifies the global ``matplotlib.units.registry`` + dictionary. Pandas adds custom converters for + + * pd.Timestamp + * pd.Period + * np.datetime64 + * datetime.datetime + * datetime.date + * datetime.time + + See Also + -------- + deregister_matplotlib_converter + """ + # Renamed in pandas.plotting.__init__ + global _WARN + + if explicit: + _WARN = False + + pairs = get_pairs() + for type_, cls in pairs: + converter = cls() + if type_ in units.registry: + previous = units.registry[type_] + _mpl_units[type_] = previous + units.registry[type_] = converter + + +def deregister(): + """Remove pandas' formatters and converters + + Removes the custom converters added by :func:`register`. This + attempts to set the state of the registry back to the state before + pandas registered its own units. Converters for pandas' own types like + Timestamp and Period are removed completely. Converters for types + pandas overwrites, like ``datetime.datetime``, are restored to their + original value. + + See Also + -------- + deregister_matplotlib_converters + """ + # Renamed in pandas.plotting.__init__ + for type_, cls in get_pairs(): + # We use type to catch our classes directly, no inheritance + if type(units.registry.get(type_)) is cls: + units.registry.pop(type_) + + # restore the old keys + for unit, formatter in _mpl_units.items(): + if type(formatter) not in {DatetimeConverter, PeriodConverter, + TimeConverter}: + # make it idempotent by excluding ours. + units.registry[unit] = formatter + + +def _check_implicitly_registered(): + global _WARN + + if _WARN: + msg = ("Using an implicitly registered datetime converter for a " + "matplotlib plotting method. The converter was registered " + "by pandas on import. Future versions of pandas will require " + "you to explicitly register matplotlib converters.\n\n" + "To register the converters:\n\t" + ">>> from pandas.plotting import register_matplotlib_converters" + "\n\t" + ">>> register_matplotlib_converters()") + warnings.warn(msg, FutureWarning) + _WARN = False def _to_ordinalf(tm): @@ -190,6 +273,7 @@ class DatetimeConverter(dates.DateConverter): @staticmethod def convert(values, unit, axis): # values might be a 1-d array, or a list-like of arrays. + _check_implicitly_registered() if is_nested_list_like(values): values = [DatetimeConverter._convert_1d(v, unit, axis) for v in values] @@ -274,6 +358,7 @@ class PandasAutoDateLocator(dates.AutoDateLocator): def get_locator(self, dmin, dmax): 'Pick the best locator based on a distance.' + _check_implicitly_registered() delta = relativedelta(dmax, dmin) num_days = (delta.years * 12.0 + delta.months) * 31.0 + delta.days @@ -315,6 +400,7 @@ def get_unit_generic(freq): def __call__(self): # if no data have been set, this will tank with a ValueError + _check_implicitly_registered() try: dmin, dmax = self.viewlim_to_dt() except ValueError: @@ -917,6 +1003,8 @@ def _get_default_locs(self, vmin, vmax): def __call__(self): 'Return the locations of the ticks.' # axis calls Locator.set_axis inside set_m<xxxx>_formatter + _check_implicitly_registered() + vi = tuple(self.axis.get_view_interval()) if vi != self.plot_obj.view_interval: self.plot_obj.date_axis_info = None @@ -1001,6 +1089,8 @@ def set_locs(self, locs): 'Sets the locations of the ticks' # don't actually use the locs. This is just needed to work with # matplotlib. Force to use vmin, vmax + _check_implicitly_registered() + self.locs = locs (vmin, vmax) = vi = tuple(self.axis.get_view_interval()) @@ -1012,6 +1102,8 @@ def set_locs(self, locs): self._set_default_format(vmin, vmax) def __call__(self, x, pos=0): + _check_implicitly_registered() + if self.formatdict is None: return '' else: @@ -1042,6 +1134,7 @@ def format_timedelta_ticks(x, pos, n_decimals): return s def __call__(self, x, pos=0): + _check_implicitly_registered() (vmin, vmax) = tuple(self.axis.get_view_interval()) n_decimals = int(np.ceil(np.log10(100 * 1e9 / (vmax - vmin)))) if n_decimals > 9: diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index af8fc78f7d4a7..adaaa206edadd 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -11,6 +11,7 @@ from pandas.util._decorators import cache_readonly from pandas.core.base import PandasObject +from pandas.core.config import get_option from pandas.core.dtypes.missing import isna, notna, remove_na_arraylike from pandas.core.dtypes.common import ( is_list_like, @@ -40,16 +41,13 @@ _get_xlim, _set_ticks_props, format_date_labels) -_registered = False - - -def _setup(): - # delay the import of matplotlib until nescessary - global _registered - if not _registered: - from pandas.plotting import _converter - _converter.register() - _registered = True +try: + from pandas.plotting import _converter +except ImportError: + pass +else: + if get_option('plotting.matplotlib.register_converters'): + _converter.register(explicit=True) def _get_standard_kind(kind): @@ -99,7 +97,7 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=None, secondary_y=False, colormap=None, table=False, layout=None, **kwds): - _setup() + _converter._WARN = False self.data = data self.by = by @@ -2064,7 +2062,7 @@ def boxplot_frame(self, column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, layout=None, return_type=None, **kwds): import matplotlib.pyplot as plt - _setup() + _converter._WARN = False ax = boxplot(self, column=column, by=by, ax=ax, fontsize=fontsize, grid=grid, rot=rot, figsize=figsize, layout=layout, return_type=return_type, **kwds) @@ -2160,7 +2158,7 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, `**kwds` : other plotting keyword arguments To be passed to hist function """ - _setup() + _converter._WARN = False if by is not None: axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, figsize=figsize, sharex=sharex, sharey=sharey, @@ -2294,6 +2292,8 @@ def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None, ------- axes: collection of Matplotlib Axes """ + _converter._WARN = False + def plot_group(group, ax): ax.hist(group.dropna().values, bins=bins, **kwargs) @@ -2358,7 +2358,7 @@ def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, >>> grouped = df.unstack(level='lvl1').groupby(level=0, axis=1) >>> boxplot_frame_groupby(grouped, subplots=False) """ - _setup() + _converter._WARN = False if subplots is True: naxes = len(grouped) fig, axes = _subplots(naxes=naxes, squeeze=False, diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py index e1f64bed5598d..3818c04649366 100644 --- a/pandas/tests/plotting/test_converter.py +++ b/pandas/tests/plotting/test_converter.py @@ -1,20 +1,144 @@ +import subprocess import pytest from datetime import datetime, date import numpy as np -from pandas import Timestamp, Period, Index +from pandas import Timestamp, Period, Index, date_range, Series from pandas.compat import u +import pandas.core.config as cf import pandas.util.testing as tm from pandas.tseries.offsets import Second, Milli, Micro, Day from pandas.compat.numpy import np_datetime64_compat converter = pytest.importorskip('pandas.plotting._converter') +from pandas.plotting import (register_matplotlib_converters, + deregister_matplotlib_converters) def test_timtetonum_accepts_unicode(): assert (converter.time2num("00:01") == converter.time2num(u("00:01"))) +class TestRegistration(object): + + def test_register_by_default(self): + # Run in subprocess to ensure a clean state + code = ("'import matplotlib.units; " + "import pandas as pd; " + "units = dict(matplotlib.units.registry); " + "assert pd.Timestamp in units)'") + call = ['python', '-c', code] + assert subprocess.check_call(call) == 0 + + def test_warns(self): + plt = pytest.importorskip("matplotlib.pyplot") + s = Series(range(12), index=date_range('2017', periods=12)) + _, ax = plt.subplots() + + # Set to the "warning" state, in case this isn't the first test run + converter._WARN = True + with tm.assert_produces_warning(FutureWarning, + check_stacklevel=False) as w: + ax.plot(s.index, s.values) + plt.close() + + assert len(w) == 1 + assert "Using an implicitly registered datetime converter" in str(w[0]) + + def test_registering_no_warning(self): + plt = pytest.importorskip("matplotlib.pyplot") + s = Series(range(12), index=date_range('2017', periods=12)) + _, ax = plt.subplots() + + # Set to the "warn" state, in case this isn't the first test run + converter._WARN = True + register_matplotlib_converters() + with tm.assert_produces_warning(None) as w: + ax.plot(s.index, s.values) + + assert len(w) == 0 + + def test_pandas_plots_register(self): + pytest.importorskip("matplotlib.pyplot") + s = Series(range(12), index=date_range('2017', periods=12)) + # Set to the "warn" state, in case this isn't the first test run + converter._WARN = True + with tm.assert_produces_warning(None) as w: + s.plot() + + assert len(w) == 0 + + def test_matplotlib_formatters(self): + units = pytest.importorskip("matplotlib.units") + assert Timestamp in units.registry + + ctx = cf.option_context("plotting.matplotlib.register_converters", + False) + with ctx: + assert Timestamp not in units.registry + + assert Timestamp in units.registry + + def test_option_no_warning(self): + pytest.importorskip("matplotlib.pyplot") + ctx = cf.option_context("plotting.matplotlib.register_converters", + False) + plt = pytest.importorskip("matplotlib.pyplot") + s = Series(range(12), index=date_range('2017', periods=12)) + _, ax = plt.subplots() + + converter._WARN = True + # Test without registering first, no warning + with ctx: + with tm.assert_produces_warning(None) as w: + ax.plot(s.index, s.values) + + assert len(w) == 0 + + # Now test with registering + converter._WARN = True + register_matplotlib_converters() + with ctx: + with tm.assert_produces_warning(None) as w: + ax.plot(s.index, s.values) + + assert len(w) == 0 + + def test_registry_resets(self): + units = pytest.importorskip("matplotlib.units") + dates = pytest.importorskip("matplotlib.dates") + + # make a copy, to reset to + original = dict(units.registry) + + try: + # get to a known state + units.registry.clear() + date_converter = dates.DateConverter() + units.registry[datetime] = date_converter + units.registry[date] = date_converter + + register_matplotlib_converters() + assert units.registry[date] is not date_converter + deregister_matplotlib_converters() + assert units.registry[date] is date_converter + + finally: + # restore original stater + units.registry.clear() + for k, v in original.items(): + units.registry[k] = v + + def test_old_import_warns(self): + with tm.assert_produces_warning(FutureWarning) as w: + from pandas.tseries import converter + converter.register() + + assert len(w) + assert ('pandas.plotting.register_matplotlib_converters' in + str(w[0].message)) + + class TestDateTimeConverter(object): def setup_method(self, method): diff --git a/pandas/tseries/converter.py b/pandas/tseries/converter.py index df603c4d880d8..26d3f3cb85edc 100644 --- a/pandas/tseries/converter.py +++ b/pandas/tseries/converter.py @@ -1,6 +1,7 @@ # flake8: noqa +import warnings -from pandas.plotting._converter import (register, time2num, +from pandas.plotting._converter import (time2num, TimeConverter, TimeFormatter, PeriodConverter, get_datevalue, DatetimeConverter, @@ -9,3 +10,11 @@ MilliSecondLocator, get_finder, TimeSeries_DateLocator, TimeSeries_DateFormatter) + + +def register(): + from pandas.plotting._converter import register as register_ + msg = ("'pandas.tseries.converter.register' has been moved and renamed to " + "'pandas.plotting.register_matplotlib_converters'. ") + warnings.warn(msg, FutureWarning, stacklevel=2) + register_()
Closes #18301 TODO: - [ ] find best home for the import - [ ] update deprecation message
https://api.github.com/repos/pandas-dev/pandas/pulls/18307
2017-11-15T14:48:12Z
2017-12-07T15:04:36Z
2017-12-07T15:04:35Z
2017-12-11T00:18:23Z
BUG: Fix IntervalIndex.insert to allow inserting NaN
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 5549ba4e8f735..09c8367ff9747 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -77,6 +77,7 @@ Other API Changes - :func:`Series.truncate` and :func:`DataFrame.truncate` will raise a ``ValueError`` if the index is not sorted instead of an unhelpful ``KeyError`` (:issue:`17935`) - :func:`Dataframe.unstack` will now default to filling with ``np.nan`` for ``object`` columns. (:issue:`12815`) - :class:`IntervalIndex` constructor will raise if the ``closed`` parameter conflicts with how the input data is inferred to be closed (:issue:`18421`) +- Inserting missing values into indexes will work for all types of indexes and automatically insert the correct type of missing value (``NaN``, ``NaT``, etc.) regardless of the type passed in (:issue:`18295`) .. _whatsnew_0220.deprecations: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index af9e29a84b472..d0356fa78f13b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3734,6 +3734,10 @@ def insert(self, loc, item): ------- new_index : Index """ + if is_scalar(item) and isna(item): + # GH 18295 + item = self._na_value + _self = np.asarray(self) item = self._coerce_scalar_to_index(item)._values idx = np.concatenate((_self[:loc], item, _self[loc:])) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index d09e5447431ce..26ffb01b9577f 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -12,7 +12,7 @@ is_scalar) from pandas.core.common import (_asarray_tuplesafe, _values_from_object) -from pandas.core.dtypes.missing import array_equivalent +from pandas.core.dtypes.missing import array_equivalent, isna from pandas.core.algorithms import take_1d @@ -690,7 +690,7 @@ def insert(self, loc, item): """ code = self.categories.get_indexer([item]) - if (code == -1): + if (code == -1) and not (is_scalar(item) and isna(item)): raise TypeError("cannot insert an item into a CategoricalIndex " "that is not already an existing category") diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 111ba0c92aa9b..ee6263a9f0aad 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1757,6 +1757,9 @@ def insert(self, loc, item): ------- new_index : Index """ + if is_scalar(item) and isna(item): + # GH 18295 + item = self._na_value freq = None @@ -1773,6 +1776,7 @@ def insert(self, loc, item): elif (loc == len(self)) and item - self.freq == self[-1]: freq = self.freq item = _to_m8(item, tz=self.tz) + try: new_dates = np.concatenate((self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8)) @@ -1780,7 +1784,6 @@ def insert(self, loc, item): new_dates = conversion.tz_convert(new_dates, 'UTC', self.tz) return DatetimeIndex(new_dates, name=self.name, freq=freq, tz=self.tz) - except (AttributeError, TypeError): # fall back to object index diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index c7c739b766a9f..06843150bf46a 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1001,14 +1001,21 @@ def delete(self, loc): return self._shallow_copy(new_left, new_right) def insert(self, loc, item): - if not isinstance(item, Interval): - raise ValueError('can only insert Interval objects into an ' - 'IntervalIndex') - if not item.closed == self.closed: - raise ValueError('inserted item must be closed on the same side ' - 'as the index') - new_left = self.left.insert(loc, item.left) - new_right = self.right.insert(loc, item.right) + if isinstance(item, Interval): + if item.closed != self.closed: + raise ValueError('inserted item must be closed on the same ' + 'side as the index') + left_insert = item.left + right_insert = item.right + elif is_scalar(item) and isna(item): + # GH 18295 + left_insert = right_insert = item + else: + raise ValueError('can only insert Interval objects and NA into ' + 'an IntervalIndex') + + new_left = self.left.insert(loc, left_insert) + new_right = self.right.insert(loc, right_insert) return self._shallow_copy(new_left, new_right) def _as_like_interval_index(self, other, error_msg): diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 22fb7c255b12c..97f6ca2e5d642 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -852,16 +852,18 @@ def insert(self, loc, item): ------- new_index : Index """ - # try to convert if possible if _is_convertible_to_td(item): try: item = Timedelta(item) except Exception: pass + elif is_scalar(item) and isna(item): + # GH 18295 + item = self._na_value freq = None - if isinstance(item, Timedelta) or item is NaT: + if isinstance(item, Timedelta) or (is_scalar(item) and isna(item)): # check freq can be preserved on edge cases if self.freq is not None: diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 4ce9441d87970..b3ce22962d5d4 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -145,6 +145,13 @@ def test_insert(self): assert result.tz == expected.tz assert result.freq is None + # GH 18295 (test missing) + expected = DatetimeIndex( + ['20170101', pd.NaT, '20170102', '20170103', '20170104']) + for na in (np.nan, pd.NaT, None): + result = date_range('20170101', periods=4).insert(1, na) + tm.assert_index_equal(result, expected) + def test_delete(self): idx = date_range(start='2000-01-01', periods=5, freq='M', name='idx') diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 52558c27ce707..5bb143c5a3cc6 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -697,3 +697,11 @@ def test_join_self(self, how): index = period_range('1/1/2000', periods=10) joined = index.join(index, how=how) assert index is joined + + def test_insert(self): + # GH 18295 (test missing) + expected = PeriodIndex( + ['2017Q1', pd.NaT, '2017Q2', '2017Q3', '2017Q4'], freq='Q') + for na in (np.nan, pd.NaT, None): + result = period_range('2017Q1', periods=4, freq='Q').insert(1, na) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 99a99cc5cc3eb..0a6fa97d12170 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -457,6 +457,12 @@ def test_insert(self): null_index = Index([]) tm.assert_index_equal(Index(['a']), null_index.insert(0, 'a')) + # GH 18295 (test missing) + expected = Index(['a', np.nan, 'b', 'c']) + for na in (np.nan, pd.NaT, None): + result = Index(list('abc')).insert(1, na) + tm.assert_index_equal(result, expected) + def test_delete(self): idx = Index(['a', 'b', 'c', 'd'], name='idx') diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index 5e6898f9c8711..a04ea036b2862 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -344,6 +344,12 @@ def test_insert(self): # invalid pytest.raises(TypeError, lambda: ci.insert(0, 'd')) + # GH 18295 (test missing) + expected = CategoricalIndex(['a', np.nan, 'a', 'b', 'c', 'b']) + for na in (np.nan, pd.NaT, None): + result = CategoricalIndex(list('aabcb')).insert(1, na) + tm.assert_index_equal(result, expected) + def test_delete(self): ci = self.create_index() diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index 7d6f544f6d533..7df189113247b 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -366,14 +366,50 @@ def test_delete(self, closed): result = self.create_index(closed=closed).delete(0) tm.assert_index_equal(result, expected) - def test_insert(self): - expected = IntervalIndex.from_breaks(range(4)) - actual = self.index.insert(2, Interval(2, 3)) - assert expected.equals(actual) + @pytest.mark.parametrize('data', [ + interval_range(0, periods=10, closed='neither'), + interval_range(1.7, periods=8, freq=2.5, closed='both'), + interval_range(Timestamp('20170101'), periods=12, closed='left'), + interval_range(Timedelta('1 day'), periods=6, closed='right'), + IntervalIndex.from_tuples([('a', 'd'), ('e', 'j'), ('w', 'z')]), + IntervalIndex.from_tuples([(1, 2), ('a', 'z'), (3.14, 6.28)])]) + def test_insert(self, data): + item = data[0] + idx_item = IntervalIndex([item]) + + # start + expected = idx_item.append(data) + result = data.insert(0, item) + tm.assert_index_equal(result, expected) + + # end + expected = data.append(idx_item) + result = data.insert(len(data), item) + tm.assert_index_equal(result, expected) + + # mid + expected = data[:3].append(idx_item).append(data[3:]) + result = data.insert(3, item) + tm.assert_index_equal(result, expected) + + # invalid type + msg = 'can only insert Interval objects and NA into an IntervalIndex' + with tm.assert_raises_regex(ValueError, msg): + data.insert(1, 'foo') - pytest.raises(ValueError, self.index.insert, 0, 1) - pytest.raises(ValueError, self.index.insert, 0, - Interval(2, 3, closed='left')) + # invalid closed + msg = 'inserted item must be closed on the same side as the index' + for closed in {'left', 'right', 'both', 'neither'} - {item.closed}: + with tm.assert_raises_regex(ValueError, msg): + bad_item = Interval(item.left, item.right, closed=closed) + data.insert(1, bad_item) + + # GH 18295 (test missing) + na_idx = IntervalIndex([np.nan], closed=data.closed) + for na in (np.nan, pd.NaT, None): + expected = data[:1].append(na_idx).append(data[1:]) + result = data.insert(1, na) + tm.assert_index_equal(result, expected) def test_take(self, closed): index = self.create_index(closed=closed) diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 030d688f510b0..cbd819fa9cfb7 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -187,6 +187,13 @@ def test_where(self, klass): result = i.where(klass(cond)) tm.assert_index_equal(result, expected) + def test_insert(self): + # GH 18295 (test missing) + expected = Float64Index([0, np.nan, 1, 2, 3, 4]) + for na in (np.nan, pd.NaT, None): + result = self.create_index().insert(1, na) + tm.assert_index_equal(result, expected) + class TestFloat64Index(Numeric): _holder = Float64Index diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index b4d1c3760f25a..96d5981abc1bb 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -295,6 +295,12 @@ def test_insert(self): # test 0th element tm.assert_index_equal(idx[0:4], result.insert(0, idx[0])) + # GH 18295 (test missing) + expected = Float64Index([0, np.nan, 1, 2, 3, 4]) + for na in (np.nan, pd.NaT, None): + result = RangeIndex(5).insert(1, na) + tm.assert_index_equal(result, expected) + def test_delete(self): idx = RangeIndex(5, name='Foo') diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py index cb88bac6386f7..e64c4e6ac54a5 100644 --- a/pandas/tests/indexes/timedeltas/test_indexing.py +++ b/pandas/tests/indexes/timedeltas/test_indexing.py @@ -57,6 +57,12 @@ def test_insert(self): assert result.name == expected.name assert result.freq == expected.freq + # GH 18295 (test missing) + expected = TimedeltaIndex(['1day', pd.NaT, '2day', '3day']) + for na in (np.nan, pd.NaT, None): + result = timedelta_range('1day', '3day').insert(1, na) + tm.assert_index_equal(result, expected) + def test_delete(self): idx = timedelta_range(start='1 Days', periods=5, freq='D', name='idx')
- [X] closes #18295 - [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/18300
2017-11-15T07:12:41Z
2017-11-25T14:45:34Z
2017-11-25T14:45:34Z
2017-11-25T19:14:49Z
update imports; remove unused
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index f5d8a0da0112b..d74673b17c8d9 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -22,14 +22,11 @@ from pandas._libs.tslib import Timestamp, Timedelta from datetime import datetime, timedelta, date from cpython cimport PyTuple_Check, PyList_Check +from cpython.slice cimport PySlice_Check cdef int64_t iNaT = util.get_nat() -cdef extern from "Python.h": - int PySlice_Check(object) - - cdef inline is_definitely_invalid_key(object val): if PyTuple_Check(val): try: diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx index bd21fb97ede20..c1163bdc09221 100644 --- a/pandas/_libs/period.pyx +++ b/pandas/_libs/period.pyx @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- # cython: profile=False from datetime import datetime, date, timedelta -import operator from cpython cimport ( PyUnicode_Check, @@ -203,7 +202,7 @@ def period_asfreq_arr(ndarray[int64_t] arr, int freq1, int freq2, bint end): Py_ssize_t i, n freq_conv_func func asfreq_info finfo - int64_t val, ordinal + int64_t val char relation n = len(arr) @@ -238,9 +237,6 @@ def period_asfreq_arr(ndarray[int64_t] arr, int freq1, int freq2, bint end): def period_ordinal(int y, int m, int d, int h, int min, int s, int us, int ps, int freq): - cdef: - int64_t ordinal - return get_period_ordinal(y, m, d, h, min, s, us, ps, freq) diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 540a081bdda2e..a12d3eca10e39 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -5,7 +5,7 @@ # distutils: define_macros=CYTHON_TRACE_NOGIL=0 cimport numpy as np -from numpy cimport (int8_t, int32_t, int64_t, import_array, ndarray, +from numpy cimport (int32_t, int64_t, import_array, ndarray, float64_t, NPY_DATETIME, NPY_TIMEDELTA) import numpy as np @@ -24,8 +24,6 @@ from cpython cimport ( cdef extern from "Python.h": cdef PyTypeObject *Py_TYPE(object) -from libc.stdlib cimport free - from util cimport (is_integer_object, is_float_object, is_string_object, is_datetime64_object, is_timedelta64_object, INT64_MAX) @@ -57,7 +55,6 @@ from tslibs.np_datetime cimport (check_dts_bounds, pandas_datetimestruct, dt64_to_dtstruct, dtstruct_to_dt64, pydatetime_to_dt64, pydate_to_dt64, - npy_datetime, get_datetime64_unit, get_datetime64_value, get_timedelta64_value) from tslibs.np_datetime import OutOfBoundsDatetime @@ -82,12 +79,10 @@ from tslibs.timedeltas cimport cast_from_unit, delta_to_nanoseconds from tslibs.timedeltas import Timedelta from tslibs.timezones cimport ( is_utc, is_tzlocal, is_fixed_offset, - treat_tz_as_dateutil, treat_tz_as_pytz, - get_timezone, get_utcoffset, maybe_get_tz, + treat_tz_as_pytz, + get_timezone, maybe_get_tz, get_dst_info) -from tslibs.fields import ( - get_date_name_field, get_start_end_field, get_date_field, - build_field_sarray) +from tslibs.fields import get_start_end_field, get_date_field from tslibs.conversion cimport (tz_convert_single, _TSObject, convert_to_tsobject, convert_datetime_to_tsobject, @@ -1744,13 +1739,6 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', return oresult -cdef PyTypeObject* td_type = <PyTypeObject*> Timedelta - - -cdef inline bint is_timedelta(object o): - return Py_TYPE(o) == td_type # isinstance(o, Timedelta) - - # ---------------------------------------------------------------------- # Conversion routines diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 2e022cb151008..3fbc54982f99e 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -55,7 +55,7 @@ from pandas._libs import (lib, index as libindex, tslib as libts, algos as libalgos, join as libjoin, Timestamp, period as libperiod) -from pandas._libs.tslibs import timezones, conversion +from pandas._libs.tslibs import timezones, conversion, fields # -------- some conversion wrapper functions @@ -75,20 +75,20 @@ def f(self): self.freq.kwds.get('month', 12)) if self.freq else 12) - result = libts.get_start_end_field(values, field, self.freqstr, - month_kw) + result = fields.get_start_end_field(values, field, + self.freqstr, month_kw) else: - result = libts.get_date_field(values, field) + result = fields.get_date_field(values, field) # these return a boolean by-definition return result if field in self._object_ops: - result = libts.get_date_name_field(values, field) + result = fields.get_date_name_field(values, field) result = self._maybe_mask_results(result) else: - result = libts.get_date_field(values, field) + result = fields.get_date_field(values, field) result = self._maybe_mask_results(result, convert='float64') return Index(result, name=self.name)
General cleanup. flake8 doesn't catch unused cimports. - [ ] 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/18298
2017-11-15T06:26:00Z
2017-11-17T00:37:10Z
2017-11-17T00:37:10Z
2017-12-08T19:38:40Z
BUG: Accept dict or Series in fillna for categorical Series
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index e868c73914b6e..d5a136c5ab0c7 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -28,13 +28,14 @@ Other Enhancements - :class:`pandas.io.formats.style.Styler` now has method ``hide_index()`` to determine whether the index will be rendered in ouptut (:issue:`14194`) - :class:`pandas.io.formats.style.Styler` now has method ``hide_columns()`` to determine whether columns will be hidden in output (:issue:`14194`) - Improved wording of ``ValueError`` raised in :func:`to_datetime` when ``unit=`` is passed with a non-convertible value (:issue:`14350`) +- :func:`Series.fillna` now accepts a Series or a dict as a ``value`` for a categorical dtype (:issue:`17033`) .. _whatsnew_0220.api_breaking: Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- +- :func:`Series.fillna` now raises a ``TypeError`` instead of a ``ValueError`` when passed a list, tuple or DataFrame as a ``value`` (:issue:`18293`) - - diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index d0851e3ab4f96..03bf09352862b 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -1623,8 +1623,12 @@ def fillna(self, value=None, method=None, limit=None): Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap - value : scalar - Value to use to fill holes (e.g. 0) + value : scalar, dict, Series + If a scalar value is passed it is used to fill all missing values. + Alternatively, a Series or dict can be used to fill in different + values for each index. The value should not be a list. The + value(s) passed should either be in the categories or should be + NaN. limit : int, default None (Not implemented yet for Categorical!) If method is specified, this is the maximum number of consecutive @@ -1665,16 +1669,33 @@ def fillna(self, value=None, method=None, limit=None): else: - if not isna(value) and value not in self.categories: - raise ValueError("fill value must be in categories") + # If value is a dict or a Series (a dict value has already + # been converted to a Series) + if isinstance(value, ABCSeries): + if not value[~value.isin(self.categories)].isna().all(): + raise ValueError("fill value must be in categories") + + values_codes = _get_codes_for_values(value, self.categories) + indexer = np.where(values_codes != -1) + values[indexer] = values_codes[values_codes != -1] + + # If value is not a dict or Series it should be a scalar + elif is_scalar(value): + if not isna(value) and value not in self.categories: + raise ValueError("fill value must be in categories") + + mask = values == -1 + if mask.any(): + values = values.copy() + if isna(value): + values[mask] = -1 + else: + values[mask] = self.categories.get_loc(value) - mask = values == -1 - if mask.any(): - values = values.copy() - if isna(value): - values[mask] = -1 - else: - values[mask] = self.categories.get_loc(value) + else: + raise TypeError('"value" parameter must be a scalar, dict ' + 'or Series, but you passed a ' + '"{0}"'.format(type(value).__name__)) return self._constructor(values, categories=self.categories, ordered=self.ordered, fastpath=True) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d93fe52d5ca9c..e497679e2f3d9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4304,8 +4304,9 @@ def fillna(self, value=None, method=None, axis=None, inplace=False, elif not is_list_like(value): pass else: - raise ValueError("invalid fill value with a %s" % - type(value)) + raise TypeError('"value" parameter must be a scalar, dict ' + 'or Series, but you passed a ' + '"{0}"'.format(type(value).__name__)) new_data = self._data.fillna(value=value, limit=limit, inplace=inplace, diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index ebd15b3180a33..d566c92e7738e 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -10,7 +10,7 @@ from pandas.compat import lrange from pandas import (DataFrame, Series, Timestamp, - date_range) + date_range, Categorical) import pandas as pd from pandas.util.testing import assert_series_equal, assert_frame_equal @@ -270,6 +270,81 @@ def test_fillna(self): pd.Timestamp('2012-11-11 00:00:00+01:00')]}) assert_frame_equal(df.fillna(method='bfill'), exp) + def test_na_actions_categorical(self): + + cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) + vals = ["a", "b", np.nan, "d"] + df = DataFrame({"cats": cat, "vals": vals}) + cat2 = Categorical([1, 2, 3, 3], categories=[1, 2, 3]) + vals2 = ["a", "b", "b", "d"] + df_exp_fill = DataFrame({"cats": cat2, "vals": vals2}) + cat3 = Categorical([1, 2, 3], categories=[1, 2, 3]) + vals3 = ["a", "b", np.nan] + df_exp_drop_cats = DataFrame({"cats": cat3, "vals": vals3}) + cat4 = Categorical([1, 2], categories=[1, 2, 3]) + vals4 = ["a", "b"] + df_exp_drop_all = DataFrame({"cats": cat4, "vals": vals4}) + + # fillna + res = df.fillna(value={"cats": 3, "vals": "b"}) + tm.assert_frame_equal(res, df_exp_fill) + + with tm.assert_raises_regex(ValueError, "fill value must be " + "in categories"): + df.fillna(value={"cats": 4, "vals": "c"}) + + res = df.fillna(method='pad') + tm.assert_frame_equal(res, df_exp_fill) + + # dropna + res = df.dropna(subset=["cats"]) + tm.assert_frame_equal(res, df_exp_drop_cats) + + res = df.dropna() + tm.assert_frame_equal(res, df_exp_drop_all) + + # make sure that fillna takes missing values into account + c = Categorical([np.nan, "b", np.nan], categories=["a", "b"]) + df = pd.DataFrame({"cats": c, "vals": [1, 2, 3]}) + + cat_exp = Categorical(["a", "b", "a"], categories=["a", "b"]) + df_exp = DataFrame({"cats": cat_exp, "vals": [1, 2, 3]}) + + res = df.fillna("a") + tm.assert_frame_equal(res, df_exp) + + def test_fillna_categorical_nan(self): + # GH 14021 + # np.nan should always be a valid filler + cat = Categorical([np.nan, 2, np.nan]) + val = Categorical([np.nan, np.nan, np.nan]) + df = DataFrame({"cats": cat, "vals": val}) + res = df.fillna(df.median()) + v_exp = [np.nan, np.nan, np.nan] + df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp}, + dtype='category') + tm.assert_frame_equal(res, df_exp) + + result = df.cats.fillna(np.nan) + tm.assert_series_equal(result, df.cats) + result = df.vals.fillna(np.nan) + tm.assert_series_equal(result, df.vals) + + idx = pd.DatetimeIndex(['2011-01-01 09:00', '2016-01-01 23:45', + '2011-01-01 09:00', pd.NaT, pd.NaT]) + df = DataFrame({'a': Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + + idx = pd.PeriodIndex(['2011-01', '2011-01', '2011-01', + pd.NaT, pd.NaT], freq='M') + df = DataFrame({'a': Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + + idx = pd.TimedeltaIndex(['1 days', '2 days', + '1 days', pd.NaT, pd.NaT]) + df = DataFrame({'a': Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + def test_fillna_downcast(self): # GH 15277 # infer int64 from float64 @@ -489,7 +564,7 @@ def test_fillna_invalid_value(self): # tuple pytest.raises(TypeError, self.frame.fillna, (1, 2)) # frame with series - pytest.raises(ValueError, self.frame.iloc[:, 0].fillna, self.frame) + pytest.raises(TypeError, self.frame.iloc[:, 0].fillna, self.frame) def test_fillna_col_reordering(self): cols = ["COL." + str(i) for i in range(5, 0, -1)] diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 5ca4eba4da13b..2dbce45317639 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -12,7 +12,8 @@ import pandas as pd from pandas import (Series, DataFrame, isna, date_range, - MultiIndex, Index, Timestamp, NaT, IntervalIndex) + MultiIndex, Index, Timestamp, NaT, IntervalIndex, + Categorical) from pandas.compat import range from pandas._libs.tslib import iNaT from pandas.core.series import remove_na @@ -363,6 +364,55 @@ def test_fillna_raise(self): with pytest.raises(ValueError): s.fillna(1, limit=limit, method=method) + @pytest.mark.parametrize('fill_value, expected_output', [ + ('a', ['a', 'a', 'b', 'a', 'a']), + ({1: 'a', 3: 'b', 4: 'b'}, ['a', 'a', 'b', 'b', 'b']), + ({1: 'a'}, ['a', 'a', 'b', np.nan, np.nan]), + ({1: 'a', 3: 'b'}, ['a', 'a', 'b', 'b', np.nan]), + (Series('a'), ['a', np.nan, 'b', np.nan, np.nan]), + (Series('a', index=[1]), ['a', 'a', 'b', np.nan, np.nan]), + (Series({1: 'a', 3: 'b'}), ['a', 'a', 'b', 'b', np.nan]), + (Series(['a', 'b'], index=[3, 4]), ['a', np.nan, 'b', 'a', 'b']) + ]) + def test_fillna_categorical(self, fill_value, expected_output): + # GH 17033 + # Test fillna for a Categorical series + data = ['a', np.nan, 'b', np.nan, np.nan] + s = Series(Categorical(data, categories=['a', 'b'])) + exp = Series(Categorical(expected_output, categories=['a', 'b'])) + tm.assert_series_equal(s.fillna(fill_value), exp) + + def test_fillna_categorical_raise(self): + data = ['a', np.nan, 'b', np.nan, np.nan] + s = Series(Categorical(data, categories=['a', 'b'])) + + with tm.assert_raises_regex(ValueError, + "fill value must be in categories"): + s.fillna('d') + + with tm.assert_raises_regex(ValueError, + "fill value must be in categories"): + s.fillna(Series('d')) + + with tm.assert_raises_regex(ValueError, + "fill value must be in categories"): + s.fillna({1: 'd', 3: 'a'}) + + with tm.assert_raises_regex(TypeError, + '"value" parameter must be a scalar or ' + 'dict, but you passed a "list"'): + s.fillna(['a', 'b']) + + with tm.assert_raises_regex(TypeError, + '"value" parameter must be a scalar or ' + 'dict, but you passed a "tuple"'): + s.fillna(('a', 'b')) + + with tm.assert_raises_regex(TypeError, + '"value" parameter must be a scalar, dict ' + 'or Series, but you passed a "DataFrame"'): + s.fillna(DataFrame({1: ['a'], 3: ['b']})) + def test_fillna_nat(self): series = Series([0, 1, 2, iNaT], dtype='M8[ns]') diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 7988d9ca72568..b570672124976 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -4496,79 +4496,6 @@ def test_numpy_reshape(self): tm.assert_raises_regex(ValueError, msg, np.reshape, cat, cat.shape, order='F') - def test_na_actions(self): - - cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) - vals = ["a", "b", np.nan, "d"] - df = DataFrame({"cats": cat, "vals": vals}) - cat2 = Categorical([1, 2, 3, 3], categories=[1, 2, 3]) - vals2 = ["a", "b", "b", "d"] - df_exp_fill = DataFrame({"cats": cat2, "vals": vals2}) - cat3 = Categorical([1, 2, 3], categories=[1, 2, 3]) - vals3 = ["a", "b", np.nan] - df_exp_drop_cats = DataFrame({"cats": cat3, "vals": vals3}) - cat4 = Categorical([1, 2], categories=[1, 2, 3]) - vals4 = ["a", "b"] - df_exp_drop_all = DataFrame({"cats": cat4, "vals": vals4}) - - # fillna - res = df.fillna(value={"cats": 3, "vals": "b"}) - tm.assert_frame_equal(res, df_exp_fill) - - def f(): - df.fillna(value={"cats": 4, "vals": "c"}) - - pytest.raises(ValueError, f) - - res = df.fillna(method='pad') - tm.assert_frame_equal(res, df_exp_fill) - - res = df.dropna(subset=["cats"]) - tm.assert_frame_equal(res, df_exp_drop_cats) - - res = df.dropna() - tm.assert_frame_equal(res, df_exp_drop_all) - - # make sure that fillna takes missing values into account - c = Categorical([np.nan, "b", np.nan], categories=["a", "b"]) - df = DataFrame({"cats": c, "vals": [1, 2, 3]}) - - cat_exp = Categorical(["a", "b", "a"], categories=["a", "b"]) - df_exp = DataFrame({"cats": cat_exp, "vals": [1, 2, 3]}) - - res = df.fillna("a") - tm.assert_frame_equal(res, df_exp) - - # GH 14021 - # np.nan should always be a is a valid filler - cat = Categorical([np.nan, 2, np.nan]) - val = Categorical([np.nan, np.nan, np.nan]) - df = DataFrame({"cats": cat, "vals": val}) - res = df.fillna(df.median()) - v_exp = [np.nan, np.nan, np.nan] - df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp}, - dtype='category') - tm.assert_frame_equal(res, df_exp) - - result = df.cats.fillna(np.nan) - tm.assert_series_equal(result, df.cats) - result = df.vals.fillna(np.nan) - tm.assert_series_equal(result, df.vals) - - idx = DatetimeIndex(['2011-01-01 09:00', '2016-01-01 23:45', - '2011-01-01 09:00', NaT, NaT]) - df = DataFrame({'a': Categorical(idx)}) - tm.assert_frame_equal(df.fillna(value=NaT), df) - - idx = PeriodIndex( - ['2011-01', '2011-01', '2011-01', NaT, NaT], freq='M') - df = DataFrame({'a': Categorical(idx)}) - tm.assert_frame_equal(df.fillna(value=NaT), df) - - idx = TimedeltaIndex(['1 days', '2 days', '1 days', NaT, NaT]) - df = DataFrame({'a': Categorical(idx)}) - tm.assert_frame_equal(df.fillna(value=NaT), df) - def test_astype_to_other(self): s = self.cat['value_group']
- [ ] closes #17033 - [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/18293
2017-11-14T21:57:39Z
2017-11-22T02:33:56Z
2017-11-22T02:33:56Z
2017-11-27T14:50:10Z
#18285 parquet io docs
diff --git a/doc/source/io.rst b/doc/source/io.rst index 36f216601b491..c94d5bc75d4fc 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -4427,8 +4427,10 @@ Several caveats. - This is a newer library, and the format, though stable, is not guaranteed to be backward compatible to the earlier versions. -- The format will NOT write an ``Index``, or ``MultiIndex`` for the ``DataFrame`` and will raise an - error if a non-default one is provided. You can simply ``.reset_index()`` in order to store the index. +- The format will NOT write an ``Index``, or ``MultiIndex`` for the + ``DataFrame`` and will raise an error if a non-default one is provided. You + can ``.reset_index()`` to store the index or ``.reset_index(drop=True)`` to + ignore it. - Duplicate column names and non-string columns names are not supported - Non supported types include ``Period`` and actual python object types. These will raise a helpful error message on an attempt at serialization. @@ -4491,8 +4493,10 @@ dtypes, including extension dtypes such as datetime with tz. Several caveats. -- The format will NOT write an ``Index``, or ``MultiIndex`` for the ``DataFrame`` and will raise an - error if a non-default one is provided. You can simply ``.reset_index(drop=True)`` in order to store the index. +- The format will NOT write an ``Index``, or ``MultiIndex`` for the + ``DataFrame`` and will raise an error if a non-default one is provided. You + can ``.reset_index()`` to store the index or ``.reset_index(drop=True)`` to + ignore it. - Duplicate column names and non-string columns names are not supported - Categorical dtypes can be serialized to parquet, but will de-serialize as ``object`` dtype. - Non supported types include ``Period`` and actual python object types. These will raise a helpful error message @@ -4538,7 +4542,7 @@ Read from a parquet file. result.dtypes -Read only certain columns of a parquet file. +Read only certain columns of a parquet file. .. ipython:: python
- [x] closes #18285 - [x] tests ~added /~ passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] ~whatsnew entry~ (N/A)
https://api.github.com/repos/pandas-dev/pandas/pulls/18292
2017-11-14T21:05:49Z
2017-11-14T22:50:58Z
2017-11-14T22:50:58Z
2017-11-15T18:10:33Z
simplify algebra in Year offset apply methods
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 2d8ce4c59fedc..54f3f16700b65 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -428,3 +428,105 @@ cpdef datetime shift_month(datetime stamp, int months, object day_opt=None): else: raise ValueError(day_opt) return stamp.replace(year=year, month=month, day=day) + + +cdef int get_day_of_month(datetime other, day_opt) except? -1: + """ + Find the day in `other`'s month that satisfies a DateOffset's onOffset + policy, as described by the `day_opt` argument. + + Parameters + ---------- + other : datetime or Timestamp + day_opt : 'start', 'end' + 'start': returns 1 + 'end': returns last day of the month + + Returns + ------- + day_of_month : int + + Examples + ------- + >>> other = datetime(2017, 11, 14) + >>> get_day_of_month(other, 'start') + 1 + >>> get_day_of_month(other, 'end') + 30 + + """ + if day_opt == 'start': + return 1 + elif day_opt == 'end': + return monthrange(other.year, other.month)[1] + else: + raise ValueError(day_opt) + + +cpdef int roll_yearday(other, n, month, day_opt='start') except? -1: + """ + Possibly increment or decrement the number of periods to shift + based on rollforward/rollbackward conventions. + + Parameters + ---------- + other : datetime or Timestamp + n : number of periods to increment, before adjusting for rolling + day_opt : 'start', 'end' + 'start': returns 1 + 'end': returns last day of the month + + Returns + ------- + n : int number of periods to increment + + Notes + ----- + * Mirrors `roll_check` in tslib.shift_months + + Examples + ------- + >>> month = 3 + >>> day_opt = 'start' # `other` will be compared to March 1 + >>> other = datetime(2017, 2, 10) # before March 1 + >>> roll_yearday(other, 2, month, day_opt) + 1 + >>> roll_yearday(other, -7, month, day_opt) + -7 + >>> + >>> other = Timestamp('2014-03-15', tz='US/Eastern') # after March 1 + >>> roll_yearday(other, 2, month, day_opt) + 2 + >>> roll_yearday(other, -7, month, day_opt) + -6 + + >>> month = 6 + >>> day_opt = 'end' # `other` will be compared to June 30 + >>> other = datetime(1999, 6, 29) # before June 30 + >>> roll_yearday(other, 5, month, day_opt) + 4 + >>> roll_yearday(other, -7, month, day_opt) + -7 + >>> + >>> other = Timestamp(2072, 8, 24, 6, 17, 18) # after June 30 + >>> roll_yearday(other, 5, month, day_opt) + 5 + >>> roll_yearday(other, -7, month, day_opt) + -6 + + """ + # Note: The other.day < ... condition will never hold when day_opt=='start' + # and the other.day > ... condition will never hold when day_opt=='end'. + # At some point these extra checks may need to be optimized away. + # But that point isn't today. + if n > 0: + if other.month < month or (other.month == month and + other.day < get_day_of_month(other, + day_opt)): + n -= 1 + elif n <= 0: + if other.month > month or (other.month == month and + other.day > get_day_of_month(other, + day_opt)): + n += 1 + return n diff --git a/pandas/tests/tseries/offsets/test_liboffsets.py b/pandas/tests/tseries/offsets/test_liboffsets.py new file mode 100644 index 0000000000000..e3ec6fdf2fbcc --- /dev/null +++ b/pandas/tests/tseries/offsets/test_liboffsets.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +""" +Tests for helper functions in the cython tslibs.offsets +""" +from datetime import datetime + +import pytest + +import pandas as pd + +import pandas._libs.tslibs.offsets as liboffsets + + +def test_shift_month(): + dt = datetime(2017, 11, 15) + + assert liboffsets.shift_month(dt, 0, day_opt=None) == dt + assert liboffsets.shift_month(dt, 0, day_opt=15) == dt + + assert liboffsets.shift_month(dt, 1, + day_opt='start') == datetime(2017, 12, 1) + + assert liboffsets.shift_month(dt, -145, + day_opt='end') == datetime(2005, 10, 31) + + with pytest.raises(ValueError): + liboffsets.shift_month(dt, 3, day_opt='this should raise') + + +def test_get_day_of_month(): + # get_day_of_month is not directly exposed; we test it via roll_yearday + dt = datetime(2017, 11, 15) + + with pytest.raises(ValueError): + # To hit the raising case we need month == dt.month and n > 0 + liboffsets.roll_yearday(dt, n=3, month=11, day_opt='foo') + + +def test_roll_yearday(): + # Copied from doctest examples + month = 3 + day_opt = 'start' # `other` will be compared to March 1 + other = datetime(2017, 2, 10) # before March 1 + assert liboffsets.roll_yearday(other, 2, month, day_opt) == 1 + assert liboffsets.roll_yearday(other, -7, month, day_opt) == -7 + assert liboffsets.roll_yearday(other, 0, month, day_opt) == 0 + + other = pd.Timestamp('2014-03-15', tz='US/Eastern') # after March 1 + assert liboffsets.roll_yearday(other, 2, month, day_opt) == 2 + assert liboffsets.roll_yearday(other, -7, month, day_opt) == -6 + assert liboffsets.roll_yearday(other, 0, month, day_opt) == 1 + + month = 6 + day_opt = 'end' # `other` will be compared to June 30 + other = datetime(1999, 6, 29) # before June 30 + assert liboffsets.roll_yearday(other, 5, month, day_opt) == 4 + assert liboffsets.roll_yearday(other, -7, month, day_opt) == -7 + assert liboffsets.roll_yearday(other, 0, month, day_opt) == 0 + + other = pd.Timestamp(2072, 8, 24, 6, 17, 18) # after June 30 + assert liboffsets.roll_yearday(other, 5, month, day_opt) == 5 + assert liboffsets.roll_yearday(other, -7, month, day_opt) == -6 + assert liboffsets.roll_yearday(other, 0, month, day_opt) == 1 diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 5f94c0cf5a638..5dd1098bbeb37 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -22,6 +22,7 @@ _int_to_weekday, _weekday_to_int, _determine_offset, apply_index_wraps, + roll_yearday, shift_month, BeginMixin, EndMixin, BaseOffset) @@ -1905,49 +1906,12 @@ class YearEnd(EndMixin, YearOffset): @apply_wraps def apply(self, other): - def _increment(date): - if date.month == self.month: - _, days_in_month = tslib.monthrange(date.year, self.month) - if date.day != days_in_month: - year = date.year - else: - year = date.year + 1 - elif date.month < self.month: - year = date.year - else: - year = date.year + 1 - _, days_in_month = tslib.monthrange(year, self.month) - return datetime(year, self.month, days_in_month, - date.hour, date.minute, date.second, - date.microsecond) - - def _decrement(date): - year = date.year if date.month > self.month else date.year - 1 - _, days_in_month = tslib.monthrange(year, self.month) - return datetime(year, self.month, days_in_month, - date.hour, date.minute, date.second, - date.microsecond) - - def _rollf(date): - if date.month != self.month or\ - date.day < tslib.monthrange(date.year, date.month)[1]: - date = _increment(date) - return date - - n = self.n - result = other - if n > 0: - while n > 0: - result = _increment(result) - n -= 1 - elif n < 0: - while n < 0: - result = _decrement(result) - n += 1 - else: - # n == 0, roll forward - result = _rollf(result) - return result + n = roll_yearday(other, self.n, self.month, 'end') + year = other.year + n + days_in_month = tslib.monthrange(year, self.month)[1] + return datetime(year, self.month, days_in_month, + other.hour, other.minute, other.second, + other.microsecond) @apply_index_wraps def apply_index(self, i): @@ -1968,36 +1932,9 @@ class YearBegin(BeginMixin, YearOffset): @apply_wraps def apply(self, other): - def _increment(date, n): - year = date.year + n - 1 - if date.month >= self.month: - year += 1 - return datetime(year, self.month, 1, date.hour, date.minute, - date.second, date.microsecond) - - def _decrement(date, n): - year = date.year + n + 1 - if date.month < self.month or (date.month == self.month and - date.day == 1): - year -= 1 - return datetime(year, self.month, 1, date.hour, date.minute, - date.second, date.microsecond) - - def _rollf(date): - if (date.month != self.month) or date.day > 1: - date = _increment(date, 1) - return date - - n = self.n - result = other - if n > 0: - result = _increment(result, n) - elif n < 0: - result = _decrement(result, n) - else: - # n == 0, roll forward - result = _rollf(result) - return result + n = roll_yearday(other, self.n, self.month, 'start') + year = other.year + n + return other.replace(year=year, month=self.month, day=1) @apply_index_wraps def apply_index(self, i):
This PR is careful to only touch YearEnd and YearBegin classes, so should not overlap with #18263 or #18278. But like 18278, once the algebra is simplified, it looks an awful lot like 18263. The bad news is that the process of simplifying the dynamically-defined `_increment, `_decrement, `_rollf` functions is no fun, and I'm not aware of any good way to "show your work" to walk through the in-between steps. - [ ] closes #xxxx - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/18280
2017-11-14T05:39:35Z
2017-11-16T00:21:41Z
2017-11-16T00:21:41Z
2017-11-16T00:52:23Z
Simplify algebra in Week and SemiMonth offsets
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 4dc26f4dd69e2..5f94c0cf5a638 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -1093,10 +1093,7 @@ def _apply(self, n, other): n -= 1 elif other.day > self.day_of_month: other = other.replace(day=self.day_of_month) - if n == 0: - n = 1 - else: - n += 1 + n += 1 months = n // 2 day = 31 if n % 2 else self.day_of_month @@ -1146,15 +1143,10 @@ def _apply(self, n, other): # if other.day is not day_of_month move to day_of_month and update n if other.day < self.day_of_month: other = other.replace(day=self.day_of_month) - if n == 0: - n = -1 - else: - n -= 1 + n -= 1 elif other.day > self.day_of_month: other = other.replace(day=self.day_of_month) - if n == 0: - n = 1 - elif n < 0: + if n <= 0: n += 1 months = n // 2 + n % 2 @@ -1414,29 +1406,17 @@ def isAnchored(self): @apply_wraps def apply(self, other): - base = other if self.weekday is None: return other + self.n * self._inc - if self.n > 0: - k = self.n - otherDay = other.weekday() - if otherDay != self.weekday: - other = other + timedelta((self.weekday - otherDay) % 7) - k = k - 1 - for i in range(k): - other = other + self._inc - else: - k = self.n - otherDay = other.weekday() - if otherDay != self.weekday: - other = other + timedelta((self.weekday - otherDay) % 7) - for i in range(-k): - other = other - self._inc + k = self.n + otherDay = other.weekday() + if otherDay != self.weekday: + other = other + timedelta((self.weekday - otherDay) % 7) + if k > 0: + k -= 1 - other = datetime(other.year, other.month, other.day, - base.hour, base.minute, base.second, base.microsecond) - return other + return other + timedelta(weeks=k) @apply_index_wraps def apply_index(self, i): @@ -1511,18 +1491,11 @@ def apply(self, other): base = other offsetOfMonth = self.getOffsetOfMonth(other) - if offsetOfMonth > other: - if self.n > 0: - months = self.n - 1 - else: - months = self.n - elif offsetOfMonth == other: - months = self.n - else: - if self.n > 0: - months = self.n - else: - months = self.n + 1 + months = self.n + if months > 0 and offsetOfMonth > other: + months -= 1 + elif months <= 0 and offsetOfMonth < other: + months += 1 other = self.getOffsetOfMonth(shift_month(other, months, 'start')) other = datetime(other.year, other.month, other.day, base.hour, @@ -1533,11 +1506,7 @@ def getOffsetOfMonth(self, dt): w = Week(weekday=self.weekday) d = datetime(dt.year, dt.month, 1, tzinfo=dt.tzinfo) d = w.rollforward(d) - - for i in range(self.week): - d = w.apply(d) - - return d + return d + timedelta(weeks=self.week) def onOffset(self, dt): if self.normalize and not _is_normalized(dt): @@ -1602,18 +1571,11 @@ def __init__(self, n=1, normalize=False, weekday=None): def apply(self, other): offsetOfMonth = self.getOffsetOfMonth(other) - if offsetOfMonth > other: - if self.n > 0: - months = self.n - 1 - else: - months = self.n - elif offsetOfMonth == other: - months = self.n - else: - if self.n > 0: - months = self.n - else: - months = self.n + 1 + months = self.n + if months > 0 and offsetOfMonth > other: + months -= 1 + elif months <= 0 and offsetOfMonth < other: + months += 1 return self.getOffsetOfMonth(shift_month(other, months, 'start'))
This PR is careful to only touch Week-base and SemiMonth-based offsets, i.e. has no overlap with #18263. It does, however, simplify the algebra such that the end result looks a lot like 18263. - [ ] closes #xxxx - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/18278
2017-11-14T05:31:15Z
2017-11-15T11:26:26Z
2017-11-15T11:26:26Z
2017-12-08T19:38:41Z
CLN: Remove unnecessary uses of pd. in tests
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 25e572ee09a6b..d76c53e7f36db 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -318,9 +318,9 @@ def random_text(nobs=100): def test_setting_with_copy_bug(self): # operating on a copy - df = pd.DataFrame({'a': list(range(4)), - 'b': list('ab..'), - 'c': ['a', 'b', np.nan, 'd']}) + df = DataFrame({'a': list(range(4)), + 'b': list('ab..'), + 'c': ['a', 'b', np.nan, 'd']}) mask = pd.isna(df.c) def f(): diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index 617757c888eb5..a5c12e4152c90 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -11,8 +11,8 @@ def test_setitem_with_datetime_tz(self): # support .loc with alignment and tz-aware DatetimeIndex mask = np.array([True, False, True, False]) - idx = pd.date_range('20010101', periods=4, tz='UTC') - df = pd.DataFrame({'a': np.arange(4)}, index=idx).astype('float64') + idx = date_range('20010101', periods=4, tz='UTC') + df = DataFrame({'a': np.arange(4)}, index=idx).astype('float64') result = df.copy() result.loc[mask, :] = df.loc[mask, :] @@ -22,8 +22,8 @@ def test_setitem_with_datetime_tz(self): result.loc[mask] = df.loc[mask] tm.assert_frame_equal(result, df) - idx = pd.date_range('20010101', periods=4) - df = pd.DataFrame({'a': np.arange(4)}, index=idx).astype('float64') + idx = date_range('20010101', periods=4) + df = DataFrame({'a': np.arange(4)}, index=idx).astype('float64') result = df.copy() result.loc[mask, :] = df.loc[mask, :] @@ -127,10 +127,9 @@ def test_indexing_with_datetimeindex_tz(self): # GH 12050 # indexing on a series with a datetimeindex with tz - index = pd.date_range('2015-01-01', periods=2, tz='utc') + index = date_range('2015-01-01', periods=2, tz='utc') - ser = pd.Series(range(2), index=index, - dtype='int64') + ser = Series(range(2), index=index, dtype='int64') # list-like indexing @@ -141,7 +140,7 @@ def test_indexing_with_datetimeindex_tz(self): # setitem result = ser.copy() result[sel] = 1 - expected = pd.Series(1, index=index) + expected = Series(1, index=index) tm.assert_series_equal(result, expected) # .loc getitem @@ -150,7 +149,7 @@ def test_indexing_with_datetimeindex_tz(self): # .loc setitem result = ser.copy() result.loc[sel] = 1 - expected = pd.Series(1, index=index) + expected = Series(1, index=index) tm.assert_series_equal(result, expected) # single element indexing @@ -161,7 +160,7 @@ def test_indexing_with_datetimeindex_tz(self): # setitem result = ser.copy() result[index[1]] = 5 - expected = pd.Series([0, 5], index=index) + expected = Series([0, 5], index=index) tm.assert_series_equal(result, expected) # .loc getitem @@ -170,16 +169,15 @@ def test_indexing_with_datetimeindex_tz(self): # .loc setitem result = ser.copy() result.loc[index[1]] = 5 - expected = pd.Series([0, 5], index=index) + expected = Series([0, 5], index=index) tm.assert_series_equal(result, expected) def test_partial_setting_with_datetimelike_dtype(self): # GH9478 # a datetimeindex alignment issue with partial setting - df = pd.DataFrame(np.arange(6.).reshape(3, 2), columns=list('AB'), - index=pd.date_range('1/1/2000', periods=3, - freq='1H')) + df = DataFrame(np.arange(6.).reshape(3, 2), columns=list('AB'), + index=date_range('1/1/2000', periods=3, freq='1H')) expected = df.copy() expected['C'] = [expected.index[0]] + [pd.NaT, pd.NaT] @@ -196,7 +194,7 @@ def test_loc_setitem_datetime(self): for conv in [lambda x: x, lambda x: x.to_datetime64(), lambda x: x.to_pydatetime(), lambda x: np.datetime64(x)]: - df = pd.DataFrame() + df = DataFrame() df.loc[conv(dt1), 'one'] = 100 df.loc[conv(dt2), 'one'] = 200 diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index c8e320f9d9c77..a5506abe8f355 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -173,7 +173,7 @@ def test_iloc_getitem_neg_int_can_reach_first_index(self): tm.assert_series_equal(result, expected) # check the length 1 Series case highlighted in GH10547 - expected = pd.Series(['a'], index=['A']) + expected = Series(['a'], index=['A']) result = expected.iloc[[-1]] tm.assert_series_equal(result, expected) @@ -285,9 +285,7 @@ def test_iloc_setitem(self): def test_iloc_setitem_int_multiindex_series( self, data, indexes, values, expected_k): # GH17148 - df = pd.DataFrame( - data=data, - columns=['i', 'j', 'k']) + df = DataFrame(data=data, columns=['i', 'j', 'k']) df = df.set_index(['i', 'j']) series = df.k.copy() @@ -597,13 +595,13 @@ def test_iloc_non_unique_indexing(self): idx = np.array(lrange(30)) * 99 expected = df.iloc[idx] - df3 = pd.concat([df, 2 * df, 3 * df]) + df3 = concat([df, 2 * df, 3 * df]) result = df3.iloc[idx] tm.assert_frame_equal(result, expected) df2 = DataFrame({'A': [0.1] * 1000, 'B': [1] * 1000}) - df2 = pd.concat([df2, 2 * df2, 3 * df2]) + df2 = concat([df2, 2 * df2, 3 * df2]) sidx = df2.index.to_series() expected = df2.iloc[idx[idx <= sidx.max()]] @@ -615,8 +613,7 @@ def test_iloc_non_unique_indexing(self): new_list.append(s * 3) expected = DataFrame(new_list) - expected = pd.concat([expected, DataFrame(index=idx[idx > sidx.max()]) - ]) + expected = concat([expected, DataFrame(index=idx[idx > sidx.max()])]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = df2.loc[idx] tm.assert_frame_equal(result, expected, check_index_type=False) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 43c1b8e97fde6..0e66c15760653 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -70,7 +70,7 @@ def test_inf_upcast(self): # np.inf should cause an index to convert to float # Test with np.inf in rows - df = pd.DataFrame(columns=[0]) + df = DataFrame(columns=[0]) df.loc[1] = 1 df.loc[2] = 2 df.loc[np.inf] = 3 @@ -83,7 +83,7 @@ def test_inf_upcast(self): tm.assert_index_equal(result, expected) # Test with np.inf in columns - df = pd.DataFrame() + df = DataFrame() df.loc[0, 0] = 1 df.loc[1, 1] = 2 df.loc[0, np.inf] = 3 @@ -274,8 +274,8 @@ def test_indexing_mixed_frame_bug(self): def test_multitype_list_index_access(self): # GH 10610 - df = pd.DataFrame(np.random.random((10, 5)), - columns=["a"] + [20, 21, 22, 23]) + df = DataFrame(np.random.random((10, 5)), + columns=["a"] + [20, 21, 22, 23]) with pytest.raises(KeyError): df[[22, 26, -8]] @@ -469,8 +469,7 @@ def test_string_slice(self): # GH 14424 # string indexing against datetimelike with object # dtype should properly raises KeyError - df = pd.DataFrame([1], pd.Index([pd.Timestamp('2011-01-01')], - dtype=object)) + df = DataFrame([1], Index([pd.Timestamp('2011-01-01')], dtype=object)) assert df.index.is_all_dates with pytest.raises(KeyError): df['2011'] @@ -478,7 +477,7 @@ def test_string_slice(self): with pytest.raises(KeyError): df.loc['2011', 0] - df = pd.DataFrame() + df = DataFrame() assert not df.index.is_all_dates with pytest.raises(KeyError): df['2011'] @@ -571,7 +570,7 @@ def test_astype_assignment_with_dups(self): # GH 4686 # assignment with dups that has a dtype change - cols = pd.MultiIndex.from_tuples([('A', '1'), ('B', '1'), ('A', '2')]) + cols = MultiIndex.from_tuples([('A', '1'), ('B', '1'), ('A', '2')]) df = DataFrame(np.arange(3).reshape((1, 3)), columns=cols, dtype=object) index = df.index.copy() @@ -584,23 +583,23 @@ def test_astype_assignment_with_dups(self): # expected = Series({'float64': 2, 'object': 1}).sort_index() @pytest.mark.parametrize("index,val", [ - (pd.Index([0, 1, 2]), 2), - (pd.Index([0, 1, '2']), '2'), - (pd.Index([0, 1, 2, np.inf, 4]), 4), - (pd.Index([0, 1, 2, np.nan, 4]), 4), - (pd.Index([0, 1, 2, np.inf]), np.inf), - (pd.Index([0, 1, 2, np.nan]), np.nan), + (Index([0, 1, 2]), 2), + (Index([0, 1, '2']), '2'), + (Index([0, 1, 2, np.inf, 4]), 4), + (Index([0, 1, 2, np.nan, 4]), 4), + (Index([0, 1, 2, np.inf]), np.inf), + (Index([0, 1, 2, np.nan]), np.nan), ]) def test_index_contains(self, index, val): assert val in index @pytest.mark.parametrize("index,val", [ - (pd.Index([0, 1, 2]), '2'), - (pd.Index([0, 1, '2']), 2), - (pd.Index([0, 1, 2, np.inf]), 4), - (pd.Index([0, 1, 2, np.nan]), 4), - (pd.Index([0, 1, 2, np.inf]), np.nan), - (pd.Index([0, 1, 2, np.nan]), np.inf), + (Index([0, 1, 2]), '2'), + (Index([0, 1, '2']), 2), + (Index([0, 1, 2, np.inf]), 4), + (Index([0, 1, 2, np.nan]), 4), + (Index([0, 1, 2, np.inf]), np.nan), + (Index([0, 1, 2, np.nan]), np.inf), # Checking if np.inf in Int64Index should not cause an OverflowError # Related to GH 16957 (pd.Int64Index([0, 1, 2]), np.inf), @@ -705,7 +704,7 @@ def test_float_index_non_scalar_assignment(self): tm.assert_frame_equal(df, df2) def test_float_index_at_iat(self): - s = pd.Series([1, 2, 3], index=[0.1, 0.2, 0.3]) + s = Series([1, 2, 3], index=[0.1, 0.2, 0.3]) for el, item in s.iteritems(): assert s.at[el] == item for i in range(len(s)): @@ -744,7 +743,7 @@ def run_tests(df, rhs, right): xs = np.arange(20).reshape(5, 4) cols = ['jim', 'joe', 'jolie', 'joline'] - df = pd.DataFrame(xs, columns=cols, index=list('abcde')) + df = DataFrame(xs, columns=cols, index=list('abcde')) # right hand side; permute the indices and multiplpy by -2 rhs = -2 * df.iloc[3:0:-1, 2:0:-1] @@ -795,9 +794,9 @@ def test_slice_with_zero_step_raises(self): lambda: s.ix[::0]) def test_indexing_assignment_dict_already_exists(self): - df = pd.DataFrame({'x': [1, 2, 6], - 'y': [2, 2, 8], - 'z': [-5, 0, 5]}).set_index('z') + df = DataFrame({'x': [1, 2, 6], + 'y': [2, 2, 8], + 'z': [-5, 0, 5]}).set_index('z') expected = df.copy() rhs = dict(x=9, y=99) df.loc[5] = rhs @@ -819,7 +818,7 @@ def test_range_in_series_indexing(self): # range can cause an indexing error # GH 11652 for x in [5, 999999, 1000000]: - s = pd.Series(index=range(x)) + s = Series(index=range(x)) s.loc[range(1)] = 42 tm.assert_series_equal(s.loc[range(1)], Series(42.0, index=[0])) @@ -827,7 +826,7 @@ def test_range_in_series_indexing(self): tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1])) def test_non_reducing_slice(self): - df = pd.DataFrame([[0, 1], [2, 3]]) + df = DataFrame([[0, 1], [2, 3]]) slices = [ # pd.IndexSlice[:, :], @@ -841,7 +840,7 @@ def test_non_reducing_slice(self): slice(None, None, None), [0, 1], np.array([0, 1]), - pd.Series([0, 1]) + Series([0, 1]) ] for slice_ in slices: tslice_ = _non_reducing_slice(slice_) @@ -849,15 +848,15 @@ def test_non_reducing_slice(self): def test_list_slice(self): # like dataframe getitem - slices = [['A'], pd.Series(['A']), np.array(['A'])] - df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['A', 'B']) + slices = [['A'], Series(['A']), np.array(['A'])] + df = DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['A', 'B']) expected = pd.IndexSlice[:, ['A']] for subset in slices: result = _non_reducing_slice(subset) tm.assert_frame_equal(df.loc[result], df.loc[expected]) def test_maybe_numeric_slice(self): - df = pd.DataFrame({'A': [1, 2], 'B': ['c', 'd'], 'C': [True, False]}) + df = DataFrame({'A': [1, 2], 'B': ['c', 'd'], 'C': [True, False]}) result = _maybe_numeric_slice(df, slice_=None) expected = pd.IndexSlice[:, ['A']] assert result == expected @@ -870,20 +869,19 @@ def test_maybe_numeric_slice(self): def test_partial_boolean_frame_indexing(self): # GH 17170 - df = pd.DataFrame(np.arange(9.).reshape(3, 3), - index=list('abc'), - columns=list('ABC')) - index_df = pd.DataFrame(1, index=list('ab'), columns=list('AB')) + df = DataFrame(np.arange(9.).reshape(3, 3), + index=list('abc'), columns=list('ABC')) + index_df = DataFrame(1, index=list('ab'), columns=list('AB')) result = df[index_df.notnull()] - expected = pd.DataFrame(np.array([[0., 1., np.nan], - [3., 4., np.nan], - [np.nan] * 3]), - index=list('abc'), - columns=list('ABC')) + expected = DataFrame(np.array([[0., 1., np.nan], + [3., 4., np.nan], + [np.nan] * 3]), + index=list('abc'), + columns=list('ABC')) tm.assert_frame_equal(result, expected) def test_no_reference_cycle(self): - df = pd.DataFrame({'a': [0, 1], 'b': [2, 3]}) + df = DataFrame({'a': [0, 1], 'b': [2, 3]}) for name in ('loc', 'iloc', 'at', 'iat'): getattr(df, name) with catch_warnings(record=True): diff --git a/pandas/tests/indexing/test_indexing_slow.py b/pandas/tests/indexing/test_indexing_slow.py index 1b3fb18d9ff1d..f4d581f450363 100644 --- a/pandas/tests/indexing/test_indexing_slow.py +++ b/pandas/tests/indexing/test_indexing_slow.py @@ -70,7 +70,7 @@ def loop(mi, df, keys): keys += list(map(lambda t: t[:-1], vals[::n // m])) # covers both unique index and non-unique index - df = pd.DataFrame(vals, columns=cols) + df = DataFrame(vals, columns=cols) a, b = pd.concat([df, df]), df.drop_duplicates(subset=cols[:-1]) for frame in a, b: diff --git a/pandas/tests/indexing/test_interval.py b/pandas/tests/indexing/test_interval.py index 31a94abcd99a5..3792293f48b99 100644 --- a/pandas/tests/indexing/test_interval.py +++ b/pandas/tests/indexing/test_interval.py @@ -179,7 +179,7 @@ def test_non_unique(self): idx = IntervalIndex.from_tuples([(1, 3), (3, 7)]) - s = pd.Series(range(len(idx)), index=idx) + s = Series(range(len(idx)), index=idx) result = s.loc[Interval(1, 3)] assert result == 0 diff --git a/pandas/tests/indexing/test_ix.py b/pandas/tests/indexing/test_ix.py index dc9a591ee3101..568dd7cec5ecb 100644 --- a/pandas/tests/indexing/test_ix.py +++ b/pandas/tests/indexing/test_ix.py @@ -87,7 +87,7 @@ def compare(result, expected): assert expected.equals(result) # failure cases for .loc, but these work for .ix - df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD')) + df = DataFrame(np.random.randn(5, 4), columns=list('ABCD')) for key in [slice(1, 3), tuple([slice(0, 2), slice(0, 2)]), tuple([slice(0, 2), df.columns[0:2]])]: @@ -100,8 +100,8 @@ def compare(result, expected): pytest.raises(TypeError, lambda: df.loc[key]) - df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'), - index=pd.date_range('2012-01-01', periods=5)) + df = DataFrame(np.random.randn(5, 4), columns=list('ABCD'), + index=pd.date_range('2012-01-01', periods=5)) for key in ['2012-01-03', '2012-01-31', @@ -227,7 +227,7 @@ def test_ix_assign_column_mixed(self): expected = DataFrame({'a': [1, 2, 3], 'b': [100, 1, -100]}) tm.assert_frame_equal(df, expected) - df = pd.DataFrame({'a': lrange(4)}) + df = DataFrame({'a': lrange(4)}) df['b'] = np.nan df.loc[[1, 3], 'b'] = [100, -100] expected = DataFrame({'a': [0, 1, 2, 3], @@ -237,7 +237,7 @@ def test_ix_assign_column_mixed(self): # ok, but chained assignments are dangerous # if we turn off chained assignement it will work with option_context('chained_assignment', None): - df = pd.DataFrame({'a': lrange(4)}) + df = DataFrame({'a': lrange(4)}) df['b'] = np.nan df['b'].loc[[1, 3]] = [100, -100] tm.assert_frame_equal(df, expected) @@ -296,14 +296,14 @@ def test_ix_slicing_strings(self): tm.assert_frame_equal(df, expected) def test_ix_setitem_out_of_bounds_axis_0(self): - df = pd.DataFrame( + df = DataFrame( np.random.randn(2, 5), index=["row%s" % i for i in range(2)], columns=["col%s" % i for i in range(5)]) with catch_warnings(record=True): pytest.raises(ValueError, df.ix.__setitem__, (2, 0), 100) def test_ix_setitem_out_of_bounds_axis_1(self): - df = pd.DataFrame( + df = DataFrame( np.random.randn(5, 2), index=["row%s" % i for i in range(5)], columns=["col%s" % i for i in range(2)]) with catch_warnings(record=True): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index c6f38aeba9e87..6f0d8b1f29b77 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -8,8 +8,7 @@ import pandas as pd from pandas.compat import lrange, StringIO -from pandas import (Series, DataFrame, Timestamp, - date_range, MultiIndex) +from pandas import Series, DataFrame, Timestamp, date_range, MultiIndex from pandas.util import testing as tm from pandas.tests.indexing.common import Base @@ -165,13 +164,13 @@ def test_loc_getitem_label_list_with_missing(self): typs=['ints', 'uints'], axes=2, fails=KeyError) def test_getitem_label_list_with_missing(self): - s = pd.Series(range(3), index=['a', 'b', 'c']) + s = Series(range(3), index=['a', 'b', 'c']) # consistency with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): s[['a', 'd']] - s = pd.Series(range(3)) + s = Series(range(3)) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): s[[0, 3]] @@ -552,7 +551,7 @@ def test_loc_setitem_frame_multiples(self): def test_loc_coerceion(self): # 12411 - df = DataFrame({'date': [pd.Timestamp('20130101').tz_localize('UTC'), + df = DataFrame({'date': [Timestamp('20130101').tz_localize('UTC'), pd.NaT]}) expected = df.dtypes diff --git a/pandas/tests/indexing/test_multiindex.py b/pandas/tests/indexing/test_multiindex.py index c12bb8910ffc9..d89c64fc5b9f8 100644 --- a/pandas/tests/indexing/test_multiindex.py +++ b/pandas/tests/indexing/test_multiindex.py @@ -61,9 +61,9 @@ def check(target, indexers, value, compare_fn, expected=None): expected = value compare_fn(result, expected) # GH7190 - index = pd.MultiIndex.from_product([np.arange(0, 100), - np.arange(0, 80)], - names=['time', 'firm']) + index = MultiIndex.from_product([np.arange(0, 100), + np.arange(0, 80)], + names=['time', 'firm']) t, n = 0, 2 df = DataFrame(np.nan, columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], @@ -94,14 +94,14 @@ def check(target, indexers, value, compare_fn, expected=None): expected=3, ) # GH5206 - df = pd.DataFrame(np.arange(25).reshape(5, 5), - columns='A,B,C,D,E'.split(','), dtype=float) + df = DataFrame(np.arange(25).reshape(5, 5), + columns='A,B,C,D,E'.split(','), dtype=float) df['F'] = 99 row_selection = df['A'] % 2 == 0 col_selection = ['B', 'C'] with catch_warnings(record=True): df.ix[row_selection, col_selection] = df['F'] - output = pd.DataFrame(99., index=[0, 2, 4], columns=['B', 'C']) + output = DataFrame(99., index=[0, 2, 4], columns=['B', 'C']) with catch_warnings(record=True): tm.assert_frame_equal(df.ix[row_selection, col_selection], output) @@ -112,31 +112,31 @@ def check(target, indexers, value, compare_fn, expected=None): expected=output, ) # GH11372 - idx = pd.MultiIndex.from_product([ + idx = MultiIndex.from_product([ ['A', 'B', 'C'], - pd.date_range('2015-01-01', '2015-04-01', freq='MS')]) - cols = pd.MultiIndex.from_product([ + date_range('2015-01-01', '2015-04-01', freq='MS')]) + cols = MultiIndex.from_product([ ['foo', 'bar'], - pd.date_range('2016-01-01', '2016-02-01', freq='MS')]) + date_range('2016-01-01', '2016-02-01', freq='MS')]) - df = pd.DataFrame(np.random.random((12, 4)), - index=idx, columns=cols) + df = DataFrame(np.random.random((12, 4)), + index=idx, columns=cols) - subidx = pd.MultiIndex.from_tuples( - [('A', pd.Timestamp('2015-01-01')), - ('A', pd.Timestamp('2015-02-01'))]) - subcols = pd.MultiIndex.from_tuples( - [('foo', pd.Timestamp('2016-01-01')), - ('foo', pd.Timestamp('2016-02-01'))]) + subidx = MultiIndex.from_tuples( + [('A', Timestamp('2015-01-01')), + ('A', Timestamp('2015-02-01'))]) + subcols = MultiIndex.from_tuples( + [('foo', Timestamp('2016-01-01')), + ('foo', Timestamp('2016-02-01'))]) - vals = pd.DataFrame(np.random.random((2, 2)), - index=subidx, columns=subcols) + vals = DataFrame(np.random.random((2, 2)), + index=subidx, columns=subcols) check(target=df, indexers=(subidx, subcols), value=vals, compare_fn=tm.assert_frame_equal, ) # set all columns - vals = pd.DataFrame( + vals = DataFrame( np.random.random((2, 4)), index=subidx, columns=cols) check(target=df, indexers=(subidx, slice(None, None, None)), @@ -284,7 +284,7 @@ def test_getitem_partial_int(self): l1 = [10, 20] l2 = ['a', 'b'] df = DataFrame(index=range(2), - columns=pd.MultiIndex.from_product([l1, l2])) + columns=MultiIndex.from_product([l1, l2])) expected = DataFrame(index=range(2), columns=l2) result = df[20] @@ -292,7 +292,7 @@ def test_getitem_partial_int(self): # with list expected = DataFrame(index=range(2), - columns=pd.MultiIndex.from_product([l1[1:], l2])) + columns=MultiIndex.from_product([l1[1:], l2])) result = df[[20]] tm.assert_frame_equal(result, expected) @@ -318,8 +318,8 @@ def test_loc_multiindex_indexer_none(self): # GH 7349 # loc with a multi-index seems to be doing fallback df = DataFrame(np.arange(12).reshape(-1, 1), - index=pd.MultiIndex.from_product([[1, 2, 3, 4], - [1, 2, 3]])) + index=MultiIndex.from_product([[1, 2, 3, 4], + [1, 2, 3]])) expected = df.loc[([1, 2], ), :] result = df.loc[[1, 2]] @@ -329,8 +329,8 @@ def test_loc_multiindex_incomplete(self): # GH 7399 # incomplete indexers - s = pd.Series(np.arange(15, dtype='int64'), - MultiIndex.from_product([range(5), ['a', 'b', 'c']])) + s = Series(np.arange(15, dtype='int64'), + MultiIndex.from_product([range(5), ['a', 'b', 'c']])) expected = s.loc[:, 'a':'c'] result = s.loc[0:4, 'a':'c'] @@ -347,8 +347,8 @@ def test_loc_multiindex_incomplete(self): # GH 7400 # multiindexer gettitem with list of indexers skips wrong element - s = pd.Series(np.arange(15, dtype='int64'), - MultiIndex.from_product([range(5), ['a', 'b', 'c']])) + s = Series(np.arange(15, dtype='int64'), + MultiIndex.from_product([range(5), ['a', 'b', 'c']])) expected = s.iloc[[6, 7, 8, 12, 13, 14]] result = s.loc[2:4:2, 'a':'c'] tm.assert_series_equal(result, expected) @@ -436,9 +436,8 @@ def test_multiindex_setitem(self): np.array(['one', 'two', 'one', 'one', 'two', 'one']), np.arange(0, 6, 1)] - df_orig = pd.DataFrame(np.random.randn(6, 3), - index=arrays, - columns=['A', 'B', 'C']).sort_index() + df_orig = DataFrame(np.random.randn(6, 3), index=arrays, + columns=['A', 'B', 'C']).sort_index() expected = df_orig.loc[['bar']] * 2 df = df_orig.copy() @@ -521,15 +520,15 @@ def f(): # GH 7866 # multi-index slicing with missing indexers - idx = pd.MultiIndex.from_product([['A', 'B', 'C'], - ['foo', 'bar', 'baz']], - names=['one', 'two']) - s = pd.Series(np.arange(9, dtype='int64'), index=idx).sort_index() + idx = MultiIndex.from_product([['A', 'B', 'C'], + ['foo', 'bar', 'baz']], + names=['one', 'two']) + s = Series(np.arange(9, dtype='int64'), index=idx).sort_index() - exp_idx = pd.MultiIndex.from_product([['A'], ['foo', 'bar', 'baz']], - names=['one', 'two']) - expected = pd.Series(np.arange(3, dtype='int64'), - index=exp_idx).sort_index() + exp_idx = MultiIndex.from_product([['A'], ['foo', 'bar', 'baz']], + names=['one', 'two']) + expected = Series(np.arange(3, dtype='int64'), + index=exp_idx).sort_index() result = s.loc[['A']] tm.assert_series_equal(result, expected) @@ -545,7 +544,7 @@ def f(): tm.assert_series_equal(result, expected) idx = pd.IndexSlice - expected = pd.Series([0, 3, 6], index=pd.MultiIndex.from_product( + expected = Series([0, 3, 6], index=MultiIndex.from_product( [['A', 'B', 'C'], ['foo']], names=['one', 'two'])).sort_index() result = s.loc[idx[:, ['foo']]] @@ -555,8 +554,8 @@ def f(): # GH 8737 # empty indexer - multi_index = pd.MultiIndex.from_product((['foo', 'bar', 'baz'], - ['alpha', 'beta'])) + multi_index = MultiIndex.from_product((['foo', 'bar', 'baz'], + ['alpha', 'beta'])) df = DataFrame( np.random.randn(5, 6), index=range(5), columns=multi_index) df = df.sort_index(level=0, axis=1) @@ -683,18 +682,16 @@ def assert_slices_equivalent(l_slc, i_slc): def test_multiindex_slice_first_level(self): # GH 12697 freq = ['a', 'b', 'c', 'd'] - idx = pd.MultiIndex.from_product([freq, np.arange(500)]) - df = pd.DataFrame(list(range(2000)), index=idx, columns=['Test']) + idx = MultiIndex.from_product([freq, np.arange(500)]) + df = DataFrame(list(range(2000)), index=idx, columns=['Test']) df_slice = df.loc[pd.IndexSlice[:, 30:70], :] result = df_slice.loc['a'] - expected = pd.DataFrame(list(range(30, 71)), - columns=['Test'], - index=range(30, 71)) + expected = DataFrame(list(range(30, 71)), + columns=['Test'], index=range(30, 71)) tm.assert_frame_equal(result, expected) result = df_slice.loc['d'] - expected = pd.DataFrame(list(range(1530, 1571)), - columns=['Test'], - index=range(30, 71)) + expected = DataFrame(list(range(1530, 1571)), + columns=['Test'], index=range(30, 71)) tm.assert_frame_equal(result, expected) def test_multiindex_symmetric_difference(self): @@ -1216,10 +1213,10 @@ def test_iloc_getitem_panel_multiindex(self): # GH 7199 # Panel with multi-index - multi_index = pd.MultiIndex.from_tuples([('ONE', 'one'), - ('TWO', 'two'), - ('THREE', 'three')], - names=['UPPER', 'lower']) + multi_index = MultiIndex.from_tuples([('ONE', 'one'), + ('TWO', 'two'), + ('THREE', 'three')], + names=['UPPER', 'lower']) simple_index = [x[0] for x in multi_index] wd1 = Panel(items=['First', 'Second'], @@ -1278,21 +1275,21 @@ def test_panel_setitem_with_multiindex(self): tm.assert_panel_equal(p1, expected) # multi-indexes - axes['items'] = pd.MultiIndex.from_tuples( + axes['items'] = MultiIndex.from_tuples( [('A', 'a'), ('B', 'b')]) p2 = Panel(0., **axes) p2.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p2, expected) - axes['major_axis'] = pd.MultiIndex.from_tuples( + axes['major_axis'] = MultiIndex.from_tuples( [('A', 1), ('A', 2)]) p3 = Panel(0., **axes) p3.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p3, expected) - axes['minor_axis'] = pd.MultiIndex.from_product( + axes['minor_axis'] = MultiIndex.from_product( [['X'], range(3)]) p4 = Panel(0., **axes) p4.iloc[0, 0, :] = [1, 2, 3] diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 0e4957da5478c..f95f493c66043 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -440,10 +440,9 @@ def f(): df = orig.copy() with catch_warnings(record=True): df.loc['a', :] = df.ix[0] - exp = orig.append(pd.Series(df.ix[0], name='a')) + exp = orig.append(Series(df.ix[0], name='a')) tm.assert_frame_equal(df, exp) - tm.assert_index_equal(df.index, - pd.Index(orig.index.tolist() + ['a'])) + tm.assert_index_equal(df.index, Index(orig.index.tolist() + ['a'])) assert df.index.dtype == 'object' def test_partial_set_empty_series(self): @@ -495,8 +494,7 @@ def f(): # these work as they don't really change # anything but the index # GH5632 - expected = DataFrame(columns=['foo'], index=pd.Index( - [], dtype='int64')) + expected = DataFrame(columns=['foo'], index=Index([], dtype='int64')) def f(): df = DataFrame() @@ -519,8 +517,7 @@ def f(): tm.assert_frame_equal(f(), expected) - expected = DataFrame(columns=['foo'], - index=pd.Index([], dtype='int64')) + expected = DataFrame(columns=['foo'], index=Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') def f(): @@ -539,17 +536,16 @@ def f(): def f(): df = DataFrame() - tm.assert_index_equal(df.index, pd.Index([], dtype='object')) + tm.assert_index_equal(df.index, Index([], dtype='object')) df['foo'] = range(len(df)) return df - expected = DataFrame(columns=['foo'], - index=pd.Index([], dtype='int64')) + expected = DataFrame(columns=['foo'], index=Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') tm.assert_frame_equal(f(), expected) df = DataFrame() - tm.assert_index_equal(df.columns, pd.Index([], dtype=object)) + tm.assert_index_equal(df.columns, Index([], dtype=object)) df2 = DataFrame() df2[1] = Series([1], index=['foo']) df.loc[:, 1] = Series([1], index=['foo']) @@ -576,7 +572,7 @@ def test_partial_set_empty_frame_row(self): # GH5720, GH5744 # don't create rows when empty expected = DataFrame(columns=['A', 'B', 'New'], - index=pd.Index([], dtype='int64')) + index=Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['New'] = expected['New'].astype('float64') @@ -599,7 +595,7 @@ def test_partial_set_empty_frame_row(self): y = df[df.A > 5] result = y.reindex(columns=['A', 'B', 'C']) expected = DataFrame(columns=['A', 'B', 'C'], - index=pd.Index([], dtype='int64')) + index=Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['C'] = expected['C'].astype('float64') diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 240a7ad4b22f9..bf244deec9ffc 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -8,8 +8,7 @@ from datetime import datetime from itertools import permutations from pandas import (Series, Categorical, CategoricalIndex, - Timestamp, DatetimeIndex, - Index, IntervalIndex) + Timestamp, DatetimeIndex, Index, IntervalIndex) import pandas as pd from pandas import compat @@ -109,13 +108,13 @@ def test_mixed(self): exp = np.array([0, 0, -1, 1, 2, 3], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) - exp = pd.Index(['A', 'B', 3.14, np.inf]) + exp = Index(['A', 'B', 3.14, np.inf]) tm.assert_index_equal(uniques, exp) labels, uniques = algos.factorize(x, sort=True) exp = np.array([2, 2, -1, 3, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) - exp = pd.Index([3.14, np.inf, 'A', 'B']) + exp = Index([3.14, np.inf, 'A', 'B']) tm.assert_index_equal(uniques, exp) def test_datelike(self): @@ -310,24 +309,22 @@ def test_categorical(self): # we are expecting to return in the order # of appearance - expected = pd.Categorical(list('bac'), - categories=list('bac')) + expected = Categorical(list('bac'), categories=list('bac')) # we are expecting to return in the order # of the categories - expected_o = pd.Categorical(list('bac'), - categories=list('abc'), - ordered=True) + expected_o = Categorical( + list('bac'), categories=list('abc'), ordered=True) # GH 15939 - c = pd.Categorical(list('baabc')) + c = Categorical(list('baabc')) result = c.unique() tm.assert_categorical_equal(result, expected) result = algos.unique(c) tm.assert_categorical_equal(result, expected) - c = pd.Categorical(list('baabc'), ordered=True) + c = Categorical(list('baabc'), ordered=True) result = c.unique() tm.assert_categorical_equal(result, expected_o) @@ -335,7 +332,7 @@ def test_categorical(self): tm.assert_categorical_equal(result, expected_o) # Series of categorical dtype - s = Series(pd.Categorical(list('baabc')), name='foo') + s = Series(Categorical(list('baabc')), name='foo') result = s.unique() tm.assert_categorical_equal(result, expected) @@ -343,9 +340,9 @@ def test_categorical(self): tm.assert_categorical_equal(result, expected) # CI -> return CI - ci = pd.CategoricalIndex(pd.Categorical(list('baabc'), - categories=list('bac'))) - expected = pd.CategoricalIndex(expected) + ci = CategoricalIndex(Categorical(list('baabc'), + categories=list('bac'))) + expected = CategoricalIndex(expected) result = ci.unique() tm.assert_index_equal(result, expected) @@ -356,27 +353,27 @@ def test_datetime64tz_aware(self): # GH 15939 result = Series( - pd.Index([Timestamp('20160101', tz='US/Eastern'), - Timestamp('20160101', tz='US/Eastern')])).unique() + Index([Timestamp('20160101', tz='US/Eastern'), + Timestamp('20160101', tz='US/Eastern')])).unique() expected = np.array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object) tm.assert_numpy_array_equal(result, expected) - result = pd.Index([Timestamp('20160101', tz='US/Eastern'), - Timestamp('20160101', tz='US/Eastern')]).unique() + result = Index([Timestamp('20160101', tz='US/Eastern'), + Timestamp('20160101', tz='US/Eastern')]).unique() expected = DatetimeIndex(['2016-01-01 00:00:00'], dtype='datetime64[ns, US/Eastern]', freq=None) tm.assert_index_equal(result, expected) result = pd.unique( - Series(pd.Index([Timestamp('20160101', tz='US/Eastern'), - Timestamp('20160101', tz='US/Eastern')]))) + Series(Index([Timestamp('20160101', tz='US/Eastern'), + Timestamp('20160101', tz='US/Eastern')]))) expected = np.array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object) tm.assert_numpy_array_equal(result, expected) - result = pd.unique(pd.Index([Timestamp('20160101', tz='US/Eastern'), - Timestamp('20160101', tz='US/Eastern')])) + result = pd.unique(Index([Timestamp('20160101', tz='US/Eastern'), + Timestamp('20160101', tz='US/Eastern')])) expected = DatetimeIndex(['2016-01-01 00:00:00'], dtype='datetime64[ns, US/Eastern]', freq=None) tm.assert_index_equal(result, expected) @@ -399,7 +396,7 @@ def test_order_of_appearance(self): dtype='datetime64[ns]') tm.assert_numpy_array_equal(result, expected) - result = pd.unique(pd.Index( + result = pd.unique(Index( [Timestamp('20160101', tz='US/Eastern'), Timestamp('20160101', tz='US/Eastern')])) expected = DatetimeIndex(['2016-01-01 00:00:00'], @@ -411,8 +408,8 @@ def test_order_of_appearance(self): expected = np.array(['a', 'b', 'c'], dtype=object) tm.assert_numpy_array_equal(result, expected) - result = pd.unique(Series(pd.Categorical(list('aabc')))) - expected = pd.Categorical(list('abc')) + result = pd.unique(Series(Categorical(list('aabc')))) + expected = Categorical(list('abc')) tm.assert_categorical_equal(result, expected) @pytest.mark.parametrize("arg ,expected", [ @@ -512,16 +509,16 @@ def test_categorical_from_codes(self): # GH 16639 vals = np.array([0, 1, 2, 0]) cats = ['a', 'b', 'c'] - Sd = pd.Series(pd.Categorical(1).from_codes(vals, cats)) - St = pd.Series(pd.Categorical(1).from_codes(np.array([0, 1]), cats)) + Sd = Series(Categorical(1).from_codes(vals, cats)) + St = Series(Categorical(1).from_codes(np.array([0, 1]), cats)) expected = np.array([True, True, False, True]) result = algos.isin(Sd, St) tm.assert_numpy_array_equal(expected, result) - @pytest.mark.parametrize("empty", [[], pd.Series(), np.array([])]) + @pytest.mark.parametrize("empty", [[], Series(), np.array([])]) def test_empty(self, empty): # see gh-16991 - vals = pd.Index(["a", "b"]) + vals = Index(["a", "b"]) expected = np.array([False, False]) result = algos.isin(vals, empty) @@ -540,10 +537,8 @@ def test_value_counts(self): # assert isinstance(factor, n) result = algos.value_counts(factor) breaks = [-1.194, -0.535, 0.121, 0.777, 1.433] - expected_index = pd.IntervalIndex.from_breaks( - breaks).astype('category') - expected = Series([1, 1, 1, 1], - index=expected_index) + expected_index = IntervalIndex.from_breaks(breaks).astype('category') + expected = Series([1, 1, 1, 1], index=expected_index) tm.assert_series_equal(result.sort_index(), expected.sort_index()) def test_value_counts_bins(self): @@ -593,8 +588,8 @@ def test_value_counts_datetime_outofbounds(self): datetime(3000, 1, 1), datetime(3000, 1, 1)]) res = s.value_counts() - exp_index = pd.Index([datetime(3000, 1, 1), datetime(5000, 1, 1), - datetime(6000, 1, 1)], dtype=object) + exp_index = Index([datetime(3000, 1, 1), datetime(5000, 1, 1), + datetime(6000, 1, 1)], dtype=object) exp = Series([3, 2, 1], index=exp_index) tm.assert_series_equal(res, exp) @@ -605,10 +600,9 @@ def test_value_counts_datetime_outofbounds(self): tm.assert_series_equal(res, exp) def test_categorical(self): - s = Series(pd.Categorical(list('aaabbc'))) + s = Series(Categorical(list('aaabbc'))) result = s.value_counts() - expected = Series([3, 2, 1], - index=pd.CategoricalIndex(['a', 'b', 'c'])) + expected = Series([3, 2, 1], index=CategoricalIndex(['a', 'b', 'c'])) tm.assert_series_equal(result, expected, check_index_type=True) @@ -619,11 +613,10 @@ def test_categorical(self): tm.assert_series_equal(result, expected, check_index_type=True) def test_categorical_nans(self): - s = Series(pd.Categorical(list('aaaaabbbcc'))) # 4,3,2,1 (nan) + s = Series(Categorical(list('aaaaabbbcc'))) # 4,3,2,1 (nan) s.iloc[1] = np.nan result = s.value_counts() - expected = Series([4, 3, 2], index=pd.CategoricalIndex( - + expected = Series([4, 3, 2], index=CategoricalIndex( ['a', 'b', 'c'], categories=['a', 'b', 'c'])) tm.assert_series_equal(result, expected, check_index_type=True) result = s.value_counts(dropna=False) @@ -633,25 +626,25 @@ def test_categorical_nans(self): tm.assert_series_equal(result, expected, check_index_type=True) # out of order - s = Series(pd.Categorical( + s = Series(Categorical( list('aaaaabbbcc'), ordered=True, categories=['b', 'a', 'c'])) s.iloc[1] = np.nan result = s.value_counts() - expected = Series([4, 3, 2], index=pd.CategoricalIndex( + expected = Series([4, 3, 2], index=CategoricalIndex( ['a', 'b', 'c'], categories=['b', 'a', 'c'], ordered=True)) tm.assert_series_equal(result, expected, check_index_type=True) result = s.value_counts(dropna=False) - expected = Series([4, 3, 2, 1], index=pd.CategoricalIndex( + expected = Series([4, 3, 2, 1], index=CategoricalIndex( ['a', 'b', 'c', np.nan], categories=['b', 'a', 'c'], ordered=True)) tm.assert_series_equal(result, expected, check_index_type=True) def test_categorical_zeroes(self): # keep the `d` category with 0 - s = Series(pd.Categorical( + s = Series(Categorical( list('bbbaac'), categories=list('abcd'), ordered=True)) result = s.value_counts() - expected = Series([3, 2, 1, 0], index=pd.Categorical( + expected = Series([3, 2, 1, 0], index=Categorical( ['b', 'a', 'c', 'd'], categories=list('abcd'), ordered=True)) tm.assert_series_equal(result, expected, check_index_type=True) @@ -767,7 +760,7 @@ def test_duplicated_with_nas(self): 2.2, 4.4, 1.1, np.nan, 6.6]), pytest.mark.xfail(reason="Complex bug. GH 16399")( np.array([1 + 1j, 2 + 2j, 1 + 1j, 5 + 5j, 3 + 3j, - 2 + 2j, 4 + 4j, 1 + 1j, 5 + 5j, 6 + 6j]) + 2 + 2j, 4 + 4j, 1 + 1j, 5 + 5j, 6 + 6j]) ), np.array(['a', 'b', 'a', 'e', 'c', 'b', 'd', 'a', 'e', 'f'], dtype=object), @@ -791,7 +784,7 @@ def test_numeric_object_likes(self, case): tm.assert_numpy_array_equal(res_false, exp_false) # index - for idx in [pd.Index(case), pd.Index(case, dtype='category')]: + for idx in [Index(case), Index(case, dtype='category')]: res_first = idx.duplicated(keep='first') tm.assert_numpy_array_equal(res_first, exp_first) @@ -842,8 +835,8 @@ def test_datetime_likes(self): tm.assert_numpy_array_equal(res_false, exp_false) # index - for idx in [pd.Index(case), pd.Index(case, dtype='category'), - pd.Index(case, dtype=object)]: + for idx in [Index(case), Index(case, dtype='category'), + Index(case, dtype=object)]: res_first = idx.duplicated(keep='first') tm.assert_numpy_array_equal(res_first, exp_first) @@ -866,7 +859,7 @@ def test_datetime_likes(self): tm.assert_series_equal(res_false, Series(exp_false)) def test_unique_index(self): - cases = [pd.Index([1, 2, 3]), pd.RangeIndex(0, 3)] + cases = [Index([1, 2, 3]), pd.RangeIndex(0, 3)] for case in cases: assert case.is_unique tm.assert_numpy_array_equal(case.duplicated(), diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 5bfd8eb7eae24..31f4ca146040e 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -406,12 +406,12 @@ def test_value_counts_unique_nunique(self): if isinstance(o, Index) and o.is_boolean(): continue elif isinstance(o, Index): - expected_index = pd.Index(o[::-1]) + expected_index = Index(o[::-1]) expected_index.name = None o = o.repeat(range(1, len(o) + 1)) o.name = 'a' else: - expected_index = pd.Index(values[::-1]) + expected_index = Index(values[::-1]) idx = o.index.repeat(range(1, len(o) + 1)) rep = np.repeat(values, range(1, len(o) + 1)) o = klass(rep, index=idx, name='a') @@ -487,7 +487,7 @@ def test_value_counts_unique_nunique_null(self): if is_datetimetz(o): expected_index = orig._values._shallow_copy(values) else: - expected_index = pd.Index(values) + expected_index = Index(values) expected_index.name = None o = o.repeat(range(1, len(o) + 1)) o.name = 'a' @@ -500,7 +500,7 @@ def test_value_counts_unique_nunique_null(self): if isinstance(o, Index): tm.assert_numpy_array_equal(pd.isna(o), nanloc) else: - exp = pd.Series(nanloc, o.index, name='a') + exp = Series(nanloc, o.index, name='a') tm.assert_series_equal(pd.isna(o), exp) expected_s_na = Series(list(range(10, 2, -1)) + [3], @@ -1139,36 +1139,36 @@ def test_categorial_datetimelike(self, method): assert isinstance(result, Timestamp) def test_iter_box(self): - vals = [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')] - s = pd.Series(vals) + vals = [Timestamp('2011-01-01'), Timestamp('2011-01-02')] + s = Series(vals) assert s.dtype == 'datetime64[ns]' for res, exp in zip(s, vals): - assert isinstance(res, pd.Timestamp) + assert isinstance(res, Timestamp) assert res.tz is None assert res == exp - vals = [pd.Timestamp('2011-01-01', tz='US/Eastern'), - pd.Timestamp('2011-01-02', tz='US/Eastern')] - s = pd.Series(vals) + vals = [Timestamp('2011-01-01', tz='US/Eastern'), + Timestamp('2011-01-02', tz='US/Eastern')] + s = Series(vals) assert s.dtype == 'datetime64[ns, US/Eastern]' for res, exp in zip(s, vals): - assert isinstance(res, pd.Timestamp) + assert isinstance(res, Timestamp) assert res.tz == exp.tz assert res == exp # timedelta - vals = [pd.Timedelta('1 days'), pd.Timedelta('2 days')] - s = pd.Series(vals) + vals = [Timedelta('1 days'), Timedelta('2 days')] + s = Series(vals) assert s.dtype == 'timedelta64[ns]' for res, exp in zip(s, vals): - assert isinstance(res, pd.Timedelta) + assert isinstance(res, Timedelta) assert res == exp # period (object dtype, not boxed) vals = [pd.Period('2011-01-01', freq='M'), pd.Period('2011-01-02', freq='M')] - s = pd.Series(vals) + s = Series(vals) assert s.dtype == 'object' for res, exp in zip(s, vals): assert isinstance(res, pd.Period) diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index f062da02b2493..7988d9ca72568 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -18,12 +18,10 @@ import pandas as pd import pandas.compat as compat import pandas.util.testing as tm -from pandas import (Categorical, Index, Series, DataFrame, - Timestamp, CategoricalIndex, isna, - date_range, DatetimeIndex, - period_range, PeriodIndex, - timedelta_range, TimedeltaIndex, NaT, - Interval, IntervalIndex) +from pandas import (Categorical, Index, Series, DataFrame, Timestamp, + CategoricalIndex, isna, date_range, DatetimeIndex, + period_range, PeriodIndex, timedelta_range, + TimedeltaIndex, NaT, Interval, IntervalIndex) from pandas.compat import range, lrange, u, PY3, PYPY from pandas.core.config import option_context from pandas.core.categorical import _recode_for_categories @@ -71,7 +69,7 @@ def test_getitem_listlike(self): ]) def test_getname_categorical_accessor(self, method): # GH 17509 - s = pd.Series([1, 2, 3], name='A').astype('category') + s = Series([1, 2, 3], name='A').astype('category') expected = 'A' result = method(s).name assert result == expected @@ -80,21 +78,21 @@ def test_getitem_category_type(self): # GH 14580 # test iloc() on Series with Categorical data - s = pd.Series([1, 2, 3]).astype('category') + s = Series([1, 2, 3]).astype('category') # get slice result = s.iloc[0:2] - expected = pd.Series([1, 2]).astype(CategoricalDtype([1, 2, 3])) + expected = Series([1, 2]).astype(CategoricalDtype([1, 2, 3])) tm.assert_series_equal(result, expected) # get list of indexes result = s.iloc[[0, 1]] - expected = pd.Series([1, 2]).astype(CategoricalDtype([1, 2, 3])) + expected = Series([1, 2]).astype(CategoricalDtype([1, 2, 3])) tm.assert_series_equal(result, expected) # get boolean array result = s.iloc[[True, False, False]] - expected = pd.Series([1]).astype(CategoricalDtype([1, 2, 3])) + expected = Series([1]).astype(CategoricalDtype([1, 2, 3])) tm.assert_series_equal(result, expected) def test_setitem(self): @@ -265,18 +263,18 @@ def f(): tm.assert_categorical_equal(c1, c2) # This should result in integer categories, not float! - cat = pd.Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) + cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) assert is_integer_dtype(cat.categories) # https://github.com/pandas-dev/pandas/issues/3678 - cat = pd.Categorical([np.nan, 1, 2, 3]) + cat = Categorical([np.nan, 1, 2, 3]) assert is_integer_dtype(cat.categories) # this should result in floats - cat = pd.Categorical([np.nan, 1, 2., 3]) + cat = Categorical([np.nan, 1, 2., 3]) assert is_float_dtype(cat.categories) - cat = pd.Categorical([np.nan, 1., 2., 3.]) + cat = Categorical([np.nan, 1., 2., 3.]) assert is_float_dtype(cat.categories) # This doesn't work -> this would probably need some kind of "remember @@ -287,20 +285,20 @@ def f(): # assert is_integer_dtype(vals) # corner cases - cat = pd.Categorical([1]) + cat = Categorical([1]) assert len(cat.categories) == 1 assert cat.categories[0] == 1 assert len(cat.codes) == 1 assert cat.codes[0] == 0 - cat = pd.Categorical(["a"]) + cat = Categorical(["a"]) assert len(cat.categories) == 1 assert cat.categories[0] == "a" assert len(cat.codes) == 1 assert cat.codes[0] == 0 # Scalars should be converted to lists - cat = pd.Categorical(1) + cat = Categorical(1) assert len(cat.categories) == 1 assert cat.categories[0] == 1 assert len(cat.codes) == 1 @@ -336,16 +334,16 @@ def test_constructor_with_null(self): # Cannot have NaN in categories with pytest.raises(ValueError): - pd.Categorical([np.nan, "a", "b", "c"], - categories=[np.nan, "a", "b", "c"]) + Categorical([np.nan, "a", "b", "c"], + categories=[np.nan, "a", "b", "c"]) with pytest.raises(ValueError): - pd.Categorical([None, "a", "b", "c"], - categories=[None, "a", "b", "c"]) + Categorical([None, "a", "b", "c"], + categories=[None, "a", "b", "c"]) with pytest.raises(ValueError): - pd.Categorical(DatetimeIndex(['nat', '20160101']), - categories=[NaT, Timestamp('20160101')]) + Categorical(DatetimeIndex(['nat', '20160101']), + categories=[NaT, Timestamp('20160101')]) def test_constructor_with_index(self): ci = CategoricalIndex(list('aabbca'), categories=list('cab')) @@ -372,9 +370,9 @@ def test_constructor_with_generator(self): MultiIndex.from_product([range(5), ['a', 'b', 'c']]) # check that categories accept generators and sequences - cat = pd.Categorical([0, 1, 2], categories=(x for x in [0, 1, 2])) + cat = Categorical([0, 1, 2], categories=(x for x in [0, 1, 2])) tm.assert_categorical_equal(cat, exp) - cat = pd.Categorical([0, 1, 2], categories=xrange(3)) + cat = Categorical([0, 1, 2], categories=xrange(3)) tm.assert_categorical_equal(cat, exp) def test_constructor_with_datetimelike(self): @@ -382,11 +380,10 @@ def test_constructor_with_datetimelike(self): # 12077 # constructor wwth a datetimelike and NaT - for dtl in [pd.date_range('1995-01-01 00:00:00', - periods=5, freq='s'), - pd.date_range('1995-01-01 00:00:00', - periods=5, freq='s', tz='US/Eastern'), - pd.timedelta_range('1 day', periods=5, freq='s')]: + for dtl in [date_range('1995-01-01 00:00:00', periods=5, freq='s'), + date_range('1995-01-01 00:00:00', periods=5, + freq='s', tz='US/Eastern'), + timedelta_range('1 day', periods=5, freq='s')]: s = Series(dtl) c = Categorical(s) @@ -397,7 +394,7 @@ def test_constructor_with_datetimelike(self): # with NaT s2 = s.copy() - s2.iloc[-1] = pd.NaT + s2.iloc[-1] = NaT c = Categorical(s2) expected = type(dtl)(s2.dropna()) expected.freq = None @@ -410,28 +407,28 @@ def test_constructor_with_datetimelike(self): assert 'NaT' in result def test_constructor_from_index_series_datetimetz(self): - idx = pd.date_range('2015-01-01 10:00', freq='D', periods=3, - tz='US/Eastern') - result = pd.Categorical(idx) + idx = date_range('2015-01-01 10:00', freq='D', periods=3, + tz='US/Eastern') + result = Categorical(idx) tm.assert_index_equal(result.categories, idx) - result = pd.Categorical(pd.Series(idx)) + result = Categorical(Series(idx)) tm.assert_index_equal(result.categories, idx) def test_constructor_from_index_series_timedelta(self): - idx = pd.timedelta_range('1 days', freq='D', periods=3) - result = pd.Categorical(idx) + idx = timedelta_range('1 days', freq='D', periods=3) + result = Categorical(idx) tm.assert_index_equal(result.categories, idx) - result = pd.Categorical(pd.Series(idx)) + result = Categorical(Series(idx)) tm.assert_index_equal(result.categories, idx) def test_constructor_from_index_series_period(self): - idx = pd.period_range('2015-01-01', freq='D', periods=3) - result = pd.Categorical(idx) + idx = period_range('2015-01-01', freq='D', periods=3) + result = Categorical(idx) tm.assert_index_equal(result.categories, idx) - result = pd.Categorical(pd.Series(idx)) + result = Categorical(Series(idx)) tm.assert_index_equal(result.categories, idx) def test_constructor_invariant(self): @@ -440,10 +437,10 @@ def test_constructor_invariant(self): np.array([1., 1.2, 1.8, np.nan]), np.array([1, 2, 3], dtype='int64'), ['a', 'b', 'c', np.nan], - [pd.Period('2014-01'), pd.Period('2014-02'), pd.NaT], - [pd.Timestamp('2014-01-01'), pd.Timestamp('2014-01-02'), pd.NaT], - [pd.Timestamp('2014-01-01', tz='US/Eastern'), - pd.Timestamp('2014-01-02', tz='US/Eastern'), pd.NaT], + [pd.Period('2014-01'), pd.Period('2014-02'), NaT], + [Timestamp('2014-01-01'), Timestamp('2014-01-02'), NaT], + [Timestamp('2014-01-01', tz='US/Eastern'), + Timestamp('2014-01-02', tz='US/Eastern'), NaT], ] for val in vals: c = Categorical(val) @@ -454,9 +451,9 @@ def test_constructor_invariant(self): def test_constructor_with_dtype(self, ordered): categories = ['b', 'a', 'c'] dtype = CategoricalDtype(categories, ordered=ordered) - result = pd.Categorical(['a', 'b', 'a', 'c'], dtype=dtype) - expected = pd.Categorical(['a', 'b', 'a', 'c'], categories=categories, - ordered=ordered) + result = Categorical(['a', 'b', 'a', 'c'], dtype=dtype) + expected = Categorical(['a', 'b', 'a', 'c'], categories=categories, + ordered=ordered) tm.assert_categorical_equal(result, expected) assert result.ordered is ordered @@ -568,7 +565,7 @@ def f(): # Not available in earlier numpy versions if hasattr(np.random, "choice"): codes = np.random.choice([0, 1], 5, p=[0.9, 0.1]) - pd.Categorical.from_codes(codes, categories=["train", "test"]) + Categorical.from_codes(codes, categories=["train", "test"]) def test_from_codes_with_categorical_categories(self): # GH17884 @@ -673,13 +670,13 @@ def test_comparisons(self): tm.assert_numpy_array_equal(result, expected) # comparisons with categoricals - cat_rev = pd.Categorical(["a", "b", "c"], categories=["c", "b", "a"], - ordered=True) - cat_rev_base = pd.Categorical( + cat_rev = Categorical( + ["a", "b", "c"], categories=["c", "b", "a"], ordered=True) + cat_rev_base = Categorical( ["b", "b", "b"], categories=["c", "b", "a"], ordered=True) - cat = pd.Categorical(["a", "b", "c"], ordered=True) - cat_base = pd.Categorical(["b", "b", "b"], categories=cat.categories, - ordered=True) + cat = Categorical(["a", "b", "c"], ordered=True) + cat_base = Categorical( + ["b", "b", "b"], categories=cat.categories, ordered=True) # comparisons need to take categories ordering into account res_rev = cat_rev > cat_rev_base @@ -700,7 +697,7 @@ def f(): pytest.raises(TypeError, f) - cat_rev_base2 = pd.Categorical( + cat_rev_base2 = Categorical( ["b", "b", "b"], categories=["c", "b", "a", "d"]) def f(): @@ -738,7 +735,7 @@ def f(): # Make sure that unequal comparison take the categories order in # account - cat_rev = pd.Categorical( + cat_rev = Categorical( list("abc"), categories=list("cba"), ordered=True) exp = np.array([True, False, False]) res = cat_rev > "b" @@ -793,7 +790,7 @@ def test_categories_none(self): def test_set_categories_inplace(self): cat = self.factor.copy() cat.set_categories(['a', 'b', 'c', 'd'], inplace=True) - tm.assert_index_equal(cat.categories, pd.Index(['a', 'b', 'c', 'd'])) + tm.assert_index_equal(cat.categories, Index(['a', 'b', 'c', 'd'])) @pytest.mark.parametrize( "dtype", @@ -890,8 +887,8 @@ def test_describe(self): # string type desc = self.factor.describe() assert self.factor.ordered - exp_index = pd.CategoricalIndex(['a', 'b', 'c'], name='categories', - ordered=self.factor.ordered) + exp_index = CategoricalIndex(['a', 'b', 'c'], name='categories', + ordered=self.factor.ordered) expected = DataFrame({'counts': [3, 2, 3], 'freqs': [3 / 8., 2 / 8., 3 / 8.]}, index=exp_index) @@ -902,9 +899,8 @@ def test_describe(self): cat.set_categories(["a", "b", "c", "d"], inplace=True) desc = cat.describe() - exp_index = pd.CategoricalIndex(['a', 'b', 'c', 'd'], - ordered=self.factor.ordered, - name='categories') + exp_index = CategoricalIndex( + list('abcd'), ordered=self.factor.ordered, name='categories') expected = DataFrame({'counts': [3, 2, 3, 0], 'freqs': [3 / 8., 2 / 8., 3 / 8., 0]}, index=exp_index) @@ -913,8 +909,8 @@ def test_describe(self): # check an integer one cat = Categorical([1, 2, 3, 1, 2, 3, 3, 2, 1, 1, 1]) desc = cat.describe() - exp_index = pd.CategoricalIndex([1, 2, 3], ordered=cat.ordered, - name='categories') + exp_index = CategoricalIndex([1, 2, 3], ordered=cat.ordered, + name='categories') expected = DataFrame({'counts': [5, 3, 3], 'freqs': [5 / 11., 3 / 11., 3 / 11.]}, index=exp_index) @@ -922,13 +918,13 @@ def test_describe(self): # https://github.com/pandas-dev/pandas/issues/3678 # describe should work with NaN - cat = pd.Categorical([np.nan, 1, 2, 2]) + cat = Categorical([np.nan, 1, 2, 2]) desc = cat.describe() expected = DataFrame({'counts': [1, 2, 1], 'freqs': [1 / 4., 2 / 4., 1 / 4.]}, - index=pd.CategoricalIndex([1, 2, np.nan], - categories=[1, 2], - name='categories')) + index=CategoricalIndex([1, 2, np.nan], + categories=[1, 2], + name='categories')) tm.assert_frame_equal(desc, expected) def test_print(self): @@ -968,7 +964,7 @@ def test_empty_print(self): def test_print_none_width(self): # GH10087 - a = pd.Series(pd.Categorical([1, 2, 3, 4])) + a = Series(Categorical([1, 2, 3, 4])) exp = u("0 1\n1 2\n2 3\n3 4\n" + "dtype: category\nCategories (4, int64): [1, 2, 3, 4]") @@ -981,7 +977,7 @@ def test_unicode_print(self): else: _rep = unicode # noqa - c = pd.Categorical(['aaaaa', 'bb', 'cccc'] * 20) + c = Categorical(['aaaaa', 'bb', 'cccc'] * 20) expected = u"""\ [aaaaa, bb, cccc, aaaaa, bb, ..., bb, cccc, aaaaa, bb, cccc] Length: 60 @@ -989,7 +985,7 @@ def test_unicode_print(self): assert _rep(c) == expected - c = pd.Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20) + c = Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20) expected = u"""\ [ああああ, いいいいい, ううううううう, ああああ, いいいいい, ..., いいいいい, ううううううう, ああああ, いいいいい, ううううううう] Length: 60 @@ -1001,7 +997,7 @@ def test_unicode_print(self): # the repr width with option_context('display.unicode.east_asian_width', True): - c = pd.Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20) + c = Categorical([u'ああああ', u'いいいいい', u'ううううううう'] * 20) expected = u"""[ああああ, いいいいい, ううううううう, ああああ, いいいいい, ..., いいいいい, ううううううう, ああああ, いいいいい, ううううううう] Length: 60 Categories (3, object): [ああああ, いいいいい, ううううううう]""" # noqa @@ -1013,7 +1009,7 @@ def test_tab_complete_warning(self, ip): pytest.importorskip('IPython', minversion="6.0.0") from IPython.core.completer import provisionalcompleter - code = "import pandas as pd; c = pd.Categorical([])" + code = "import pandas as pd; c = Categorical([])" ip.run_code(code) with tm.assert_produces_warning(None): with provisionalcompleter('ignore'): @@ -1049,7 +1045,7 @@ def test_periodindex(self): tm.assert_index_equal(cat3.categories, exp_idx) def test_categories_assigments(self): - s = pd.Categorical(["a", "b", "c", "a"]) + s = Categorical(["a", "b", "c", "a"]) exp = np.array([1, 2, 3, 1], dtype=np.int64) s.categories = [1, 2, 3] tm.assert_numpy_array_equal(s.__array__(), exp) @@ -1078,21 +1074,19 @@ def test_construction_with_ordered(self): def test_ordered_api(self): # GH 9347 - cat1 = pd.Categorical(["a", "c", "b"], ordered=False) + cat1 = Categorical(list('acb'), ordered=False) tm.assert_index_equal(cat1.categories, Index(['a', 'b', 'c'])) assert not cat1.ordered - cat2 = pd.Categorical(["a", "c", "b"], categories=['b', 'c', 'a'], - ordered=False) + cat2 = Categorical(list('acb'), categories=list('bca'), ordered=False) tm.assert_index_equal(cat2.categories, Index(['b', 'c', 'a'])) assert not cat2.ordered - cat3 = pd.Categorical(["a", "c", "b"], ordered=True) + cat3 = Categorical(list('acb'), ordered=True) tm.assert_index_equal(cat3.categories, Index(['a', 'b', 'c'])) assert cat3.ordered - cat4 = pd.Categorical(["a", "c", "b"], categories=['b', 'c', 'a'], - ordered=True) + cat4 = Categorical(list('acb'), categories=list('bca'), ordered=True) tm.assert_index_equal(cat4.categories, Index(['b', 'c', 'a'])) assert cat4.ordered @@ -1103,10 +1097,9 @@ def test_set_dtype_same(self): def test_set_dtype_new_categories(self): c = Categorical(['a', 'b', 'c']) - result = c._set_dtype(CategoricalDtype(['a', 'b', 'c', 'd'])) + result = c._set_dtype(CategoricalDtype(list('abcd'))) tm.assert_numpy_array_equal(result.codes, c.codes) - tm.assert_index_equal(result.dtype.categories, - pd.Index(['a', 'b', 'c', 'd'])) + tm.assert_index_equal(result.dtype.categories, Index(list('abcd'))) def test_set_dtype_nans(self): c = Categorical(['a', 'b', np.nan]) @@ -1263,7 +1256,7 @@ def test_set_categories(self): tm.assert_numpy_array_equal(c.get_values(), c2.get_values()) def test_rename_categories(self): - cat = pd.Categorical(["a", "b", "c", "a"]) + cat = Categorical(["a", "b", "c", "a"]) # inplace=False: the old one must not be changed res = cat.rename_categories([1, 2, 3]) @@ -1294,19 +1287,19 @@ def test_rename_categories(self): def test_rename_categories_series(self): # https://github.com/pandas-dev/pandas/issues/17981 - c = pd.Categorical(['a', 'b']) + c = Categorical(['a', 'b']) xpr = "Treating Series 'new_categories' as a list-like " with tm.assert_produces_warning(FutureWarning) as rec: - result = c.rename_categories(pd.Series([0, 1])) + result = c.rename_categories(Series([0, 1])) assert len(rec) == 1 assert xpr in str(rec[0].message) - expected = pd.Categorical([0, 1]) + expected = Categorical([0, 1]) tm.assert_categorical_equal(result, expected) def test_rename_categories_dict(self): # GH 17336 - cat = pd.Categorical(['a', 'b', 'c', 'd']) + cat = Categorical(['a', 'b', 'c', 'd']) res = cat.rename_categories({'a': 4, 'b': 3, 'c': 2, 'd': 1}) expected = Index([4, 3, 2, 1]) tm.assert_index_equal(res.categories, expected) @@ -1318,21 +1311,21 @@ def test_rename_categories_dict(self): tm.assert_index_equal(cat.categories, expected) # Test for dicts of smaller length - cat = pd.Categorical(['a', 'b', 'c', 'd']) + cat = Categorical(['a', 'b', 'c', 'd']) res = cat.rename_categories({'a': 1, 'c': 3}) expected = Index([1, 'b', 3, 'd']) tm.assert_index_equal(res.categories, expected) # Test for dicts with bigger length - cat = pd.Categorical(['a', 'b', 'c', 'd']) + cat = Categorical(['a', 'b', 'c', 'd']) res = cat.rename_categories({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}) expected = Index([1, 2, 3, 4]) tm.assert_index_equal(res.categories, expected) # Test for dicts with no items from old categories - cat = pd.Categorical(['a', 'b', 'c', 'd']) + cat = Categorical(['a', 'b', 'c', 'd']) res = cat.rename_categories({'f': 1, 'g': 3}) expected = Index(['a', 'b', 'c', 'd']) @@ -1530,7 +1523,7 @@ def test_remove_unused_categories(self): tm.assert_index_equal(c.categories, exp_categories_all) val = ['F', np.nan, 'D', 'B', 'D', 'F', np.nan] - cat = pd.Categorical(values=val, categories=list('ABCDEFG')) + cat = Categorical(values=val, categories=list('ABCDEFG')) out = cat.remove_unused_categories() tm.assert_index_equal(out.categories, Index(['B', 'D', 'F'])) exp_codes = np.array([2, -1, 1, 0, 1, 2, -1], dtype=np.int8) @@ -1541,7 +1534,7 @@ def test_remove_unused_categories(self): val = np.random.choice(alpha[::2], 10000).astype('object') val[np.random.choice(len(val), 100)] = np.nan - cat = pd.Categorical(values=val, categories=alpha) + cat = Categorical(values=val, categories=alpha) out = cat.remove_unused_categories() assert out.get_values().tolist() == val.tolist() @@ -1708,13 +1701,13 @@ def test_unique_index_series(self): tm.assert_categorical_equal(c.unique(), exp) tm.assert_index_equal(Index(c).unique(), Index(exp)) - tm.assert_categorical_equal(pd.Series(c).unique(), exp) + tm.assert_categorical_equal(Series(c).unique(), exp) c = Categorical([1, 1, 2, 2], categories=[3, 2, 1]) exp = Categorical([1, 2], categories=[1, 2]) tm.assert_categorical_equal(c.unique(), exp) tm.assert_index_equal(Index(c).unique(), Index(exp)) - tm.assert_categorical_equal(pd.Series(c).unique(), exp) + tm.assert_categorical_equal(Series(c).unique(), exp) c = Categorical([3, 1, 2, 2, 1], categories=[3, 2, 1], ordered=True) # Categorical.unique keeps categories order if ordered=True @@ -1722,7 +1715,7 @@ def test_unique_index_series(self): tm.assert_categorical_equal(c.unique(), exp) tm.assert_index_equal(Index(c).unique(), Index(exp)) - tm.assert_categorical_equal(pd.Series(c).unique(), exp) + tm.assert_categorical_equal(Series(c).unique(), exp) def test_mode(self): s = Categorical([1, 1, 2, 4, 5, 5, 5], categories=[5, 4, 3, 2, 1], @@ -1853,26 +1846,26 @@ def test_slicing_directly(self): tm.assert_index_equal(sliced.categories, expected.categories) def test_set_item_nan(self): - cat = pd.Categorical([1, 2, 3]) + cat = Categorical([1, 2, 3]) cat[1] = np.nan - exp = pd.Categorical([1, np.nan, 3], categories=[1, 2, 3]) + exp = Categorical([1, np.nan, 3], categories=[1, 2, 3]) tm.assert_categorical_equal(cat, exp) def test_shift(self): # GH 9416 - cat = pd.Categorical(['a', 'b', 'c', 'd', 'a']) + cat = Categorical(['a', 'b', 'c', 'd', 'a']) # shift forward sp1 = cat.shift(1) - xp1 = pd.Categorical([np.nan, 'a', 'b', 'c', 'd']) + xp1 = Categorical([np.nan, 'a', 'b', 'c', 'd']) tm.assert_categorical_equal(sp1, xp1) tm.assert_categorical_equal(cat[:-1], sp1[1:]) # shift back sn2 = cat.shift(-2) - xp2 = pd.Categorical(['c', 'd', 'a', np.nan, np.nan], - categories=['a', 'b', 'c', 'd']) + xp2 = Categorical(['c', 'd', 'a', np.nan, np.nan], + categories=['a', 'b', 'c', 'd']) tm.assert_categorical_equal(sn2, xp2) tm.assert_categorical_equal(cat[2:], sn2[:-2]) @@ -1880,18 +1873,18 @@ def test_shift(self): tm.assert_categorical_equal(cat, cat.shift(0)) def test_nbytes(self): - cat = pd.Categorical([1, 2, 3]) + cat = Categorical([1, 2, 3]) exp = 3 + 3 * 8 # 3 int8s for values + 3 int64s for categories assert cat.nbytes == exp def test_memory_usage(self): - cat = pd.Categorical([1, 2, 3]) + cat = Categorical([1, 2, 3]) # .categories is an index, so we include the hashtable assert 0 < cat.nbytes <= cat.memory_usage() assert 0 < cat.nbytes <= cat.memory_usage(deep=True) - cat = pd.Categorical(['foo', 'foo', 'bar']) + cat = Categorical(['foo', 'foo', 'bar']) assert cat.memory_usage(deep=True) > cat.nbytes if not PYPY: @@ -1904,14 +1897,14 @@ def test_searchsorted(self): # https://github.com/pandas-dev/pandas/issues/8420 # https://github.com/pandas-dev/pandas/issues/14522 - c1 = pd.Categorical(['cheese', 'milk', 'apple', 'bread', 'bread'], - categories=['cheese', 'milk', 'apple', 'bread'], - ordered=True) - s1 = pd.Series(c1) - c2 = pd.Categorical(['cheese', 'milk', 'apple', 'bread', 'bread'], - categories=['cheese', 'milk', 'apple', 'bread'], - ordered=False) - s2 = pd.Series(c2) + c1 = Categorical(['cheese', 'milk', 'apple', 'bread', 'bread'], + categories=['cheese', 'milk', 'apple', 'bread'], + ordered=True) + s1 = Series(c1) + c2 = Categorical(['cheese', 'milk', 'apple', 'bread', 'bread'], + categories=['cheese', 'milk', 'apple', 'bread'], + ordered=False) + s2 = Series(c2) # Searching for single item argument, side='left' (default) res_cat = c1.searchsorted('apple') @@ -1956,7 +1949,7 @@ def test_searchsorted(self): def test_deprecated_labels(self): # TODO: labels is deprecated and should be removed in 0.18 or 2017, # whatever is earlier - cat = pd.Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) + cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) exp = cat.codes with tm.assert_produces_warning(FutureWarning): res = cat.labels @@ -1968,8 +1961,7 @@ def test_deprecated_from_array(self): Categorical.from_array([0, 1]) def test_datetime_categorical_comparison(self): - dt_cat = pd.Categorical( - pd.date_range('2014-01-01', periods=3), ordered=True) + dt_cat = Categorical(date_range('2014-01-01', periods=3), ordered=True) tm.assert_numpy_array_equal(dt_cat > dt_cat[0], np.array([False, True, True])) tm.assert_numpy_array_equal(dt_cat[0] < dt_cat, @@ -1977,7 +1969,7 @@ def test_datetime_categorical_comparison(self): def test_reflected_comparison_with_scalars(self): # GH8658 - cat = pd.Categorical([1, 2, 3], ordered=True) + cat = Categorical([1, 2, 3], ordered=True) tm.assert_numpy_array_equal(cat > cat[0], np.array([False, True, True])) tm.assert_numpy_array_equal(cat[0] < cat, @@ -1987,7 +1979,7 @@ def test_comparison_with_unknown_scalars(self): # https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057 # and following comparisons with scalars not in categories should raise # for unequal comps, but not for equal/not equal - cat = pd.Categorical([1, 2, 3], ordered=True) + cat = Categorical([1, 2, 3], ordered=True) pytest.raises(TypeError, lambda: cat < 4) pytest.raises(TypeError, lambda: cat > 4) @@ -2000,18 +1992,14 @@ def test_comparison_with_unknown_scalars(self): np.array([True, True, True])) def test_map(self): - c = pd.Categorical(list('ABABC'), categories=list('CBA'), - ordered=True) + c = Categorical(list('ABABC'), categories=list('CBA'), ordered=True) result = c.map(lambda x: x.lower()) - exp = pd.Categorical(list('ababc'), categories=list('cba'), - ordered=True) + exp = Categorical(list('ababc'), categories=list('cba'), ordered=True) tm.assert_categorical_equal(result, exp) - c = pd.Categorical(list('ABABC'), categories=list('ABC'), - ordered=False) + c = Categorical(list('ABABC'), categories=list('ABC'), ordered=False) result = c.map(lambda x: x.lower()) - exp = pd.Categorical(list('ababc'), categories=list('abc'), - ordered=False) + exp = Categorical(list('ababc'), categories=list('abc'), ordered=False) tm.assert_categorical_equal(result, exp) result = c.map(lambda x: 1) @@ -2058,8 +2046,8 @@ def test_validate_inplace(self): @pytest.mark.xfail(reason="Imaginary values not supported in Categorical") def test_imaginary(self): values = [1, 2, 3 + 1j] - c1 = pd.Categorical(values) - tm.assert_index_equal(c1.categories, pd.Index(values)) + c1 = Categorical(values) + tm.assert_index_equal(c1.categories, Index(values)) tm.assert_numpy_array_equal(np.array(c1), np.array(values)) @@ -2081,10 +2069,10 @@ def test_dtypes(self): # GH8143 index = ['cat', 'obj', 'num'] - cat = pd.Categorical(['a', 'b', 'c']) - obj = pd.Series(['a', 'b', 'c']) - num = pd.Series([1, 2, 3]) - df = pd.concat([pd.Series(cat), obj, num], axis=1, keys=index) + cat = Categorical(['a', 'b', 'c']) + obj = Series(['a', 'b', 'c']) + num = Series([1, 2, 3]) + df = pd.concat([Series(cat), obj, num], axis=1, keys=index) result = df.dtypes == 'object' expected = Series([False, True, False], index=index) @@ -2158,11 +2146,11 @@ def test_basic(self): str(df) # GH8623 - x = pd.DataFrame([[1, 'John P. Doe'], [2, 'Jane Dove'], - [1, 'John P. Doe']], - columns=['person_id', 'person_name']) - x['person_name'] = pd.Categorical(x.person_name - ) # doing this breaks transform + x = DataFrame([[1, 'John P. Doe'], [2, 'Jane Dove'], + [1, 'John P. Doe']], + columns=['person_id', 'person_name']) + x['person_name'] = Categorical(x.person_name + ) # doing this breaks transform expected = x.iloc[0].person_name result = x.person_name.iloc[0] @@ -2176,40 +2164,39 @@ def test_basic(self): def test_creation_astype(self): l = ["a", "b", "c", "a"] - s = pd.Series(l) - exp = pd.Series(Categorical(l)) + s = Series(l) + exp = Series(Categorical(l)) res = s.astype('category') tm.assert_series_equal(res, exp) l = [1, 2, 3, 1] - s = pd.Series(l) - exp = pd.Series(Categorical(l)) + s = Series(l) + exp = Series(Categorical(l)) res = s.astype('category') tm.assert_series_equal(res, exp) - df = pd.DataFrame({"cats": [1, 2, 3, 4, 5, 6], - "vals": [1, 2, 3, 4, 5, 6]}) + df = DataFrame({"cats": [1, 2, 3, 4, 5, 6], + "vals": [1, 2, 3, 4, 5, 6]}) cats = Categorical([1, 2, 3, 4, 5, 6]) - exp_df = pd.DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) + exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) df["cats"] = df["cats"].astype("category") tm.assert_frame_equal(exp_df, df) - df = pd.DataFrame({"cats": ['a', 'b', 'b', 'a', 'a', 'd'], - "vals": [1, 2, 3, 4, 5, 6]}) + df = DataFrame({"cats": ['a', 'b', 'b', 'a', 'a', 'd'], + "vals": [1, 2, 3, 4, 5, 6]}) cats = Categorical(['a', 'b', 'b', 'a', 'a', 'd']) - exp_df = pd.DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) + exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) df["cats"] = df["cats"].astype("category") tm.assert_frame_equal(exp_df, df) # with keywords l = ["a", "b", "c", "a"] - s = pd.Series(l) - exp = pd.Series(Categorical(l, ordered=True)) + s = Series(l) + exp = Series(Categorical(l, ordered=True)) res = s.astype(CategoricalDtype(None, ordered=True)) tm.assert_series_equal(res, exp) - exp = pd.Series(Categorical( - l, categories=list('abcdef'), ordered=True)) + exp = Series(Categorical(l, categories=list('abcdef'), ordered=True)) res = s.astype(CategoricalDtype(list('abcdef'), ordered=True)) tm.assert_series_equal(res, exp) @@ -2234,7 +2221,7 @@ def test_construction_series(self): # insert into frame with different index # GH 8076 - index = pd.date_range('20000101', periods=3) + index = date_range('20000101', periods=3) expected = Series(Categorical(values=[np.nan, np.nan, np.nan], categories=['a', 'b', 'c'])) expected.index = index @@ -2268,32 +2255,30 @@ def test_construction_frame(self): tm.assert_series_equal(df[0], expected) # ndim != 1 - df = DataFrame([pd.Categorical(list('abc'))]) + df = DataFrame([Categorical(list('abc'))]) expected = DataFrame({0: Series(list('abc'), dtype='category')}) tm.assert_frame_equal(df, expected) - df = DataFrame([pd.Categorical(list('abc')), pd.Categorical(list( - 'abd'))]) + df = DataFrame([Categorical(list('abc')), Categorical(list('abd'))]) expected = DataFrame({0: Series(list('abc'), dtype='category'), 1: Series(list('abd'), dtype='category')}, columns=[0, 1]) tm.assert_frame_equal(df, expected) # mixed - df = DataFrame([pd.Categorical(list('abc')), list('def')]) + df = DataFrame([Categorical(list('abc')), list('def')]) expected = DataFrame({0: Series(list('abc'), dtype='category'), 1: list('def')}, columns=[0, 1]) tm.assert_frame_equal(df, expected) # invalid (shape) - pytest.raises( - ValueError, - lambda: DataFrame([pd.Categorical(list('abc')), - pd.Categorical(list('abdefg'))])) + pytest.raises(ValueError, + lambda: DataFrame([Categorical(list('abc')), + Categorical(list('abdefg'))])) # ndim > 1 pytest.raises(NotImplementedError, - lambda: pd.Categorical(np.array([list('abcd')]))) + lambda: Categorical(np.array([list('abcd')]))) def test_reshaping(self): @@ -2316,7 +2301,7 @@ def test_reshaping(self): def test_reindex(self): - index = pd.date_range('20000101', periods=3) + index = date_range('20000101', periods=3) # reindexing to an invalid Categorical s = Series(['a', 'b', 'c'], dtype='category') @@ -2344,7 +2329,7 @@ def test_sideeffects_free(self): # the series or the categorical should not change the values in the # other one, IF you specify copy! cat = Categorical(["a", "b", "c", "a"]) - s = pd.Series(cat, copy=True) + s = Series(cat, copy=True) assert s.cat is not cat s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) @@ -2361,7 +2346,7 @@ def test_sideeffects_free(self): # however, copy is False by default # so this WILL change values cat = Categorical(["a", "b", "c", "a"]) - s = pd.Series(cat) + s = Series(cat) assert s.values is cat s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) @@ -2480,7 +2465,7 @@ def f(): # right: s.cat.set_categories([4,3,2,1]) def test_series_functions_no_warnings(self): - df = pd.DataFrame({'value': np.random.randint(0, 100, 20)}) + df = DataFrame({'value': np.random.randint(0, 100, 20)}) labels = ["{0} - {1}".format(i, i + 9) for i in range(0, 100, 10)] with tm.assert_produces_warning(False): df['group'] = pd.cut(df.value, range(0, 105, 10), right=False, @@ -2524,8 +2509,8 @@ def test_assignment_to_dataframe(self): s.name = 'E' tm.assert_series_equal(result2.sort_index(), s.sort_index()) - cat = pd.Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) - df = pd.DataFrame(pd.Series(cat)) + cat = Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) + df = DataFrame(Series(cat)) def test_describe(self): @@ -2544,52 +2529,51 @@ def test_describe(self): index=['count', 'unique', 'top', 'freq']) tm.assert_series_equal(result, expected) - cat = pd.Series(pd.Categorical(["a", "b", "c", "c"])) - df3 = pd.DataFrame({"cat": cat, "s": ["a", "b", "c", "c"]}) + cat = Series(Categorical(["a", "b", "c", "c"])) + df3 = DataFrame({"cat": cat, "s": ["a", "b", "c", "c"]}) res = df3.describe() tm.assert_numpy_array_equal(res["cat"].values, res["s"].values) def test_repr(self): - a = pd.Series(pd.Categorical([1, 2, 3, 4])) + a = Series(Categorical([1, 2, 3, 4])) exp = u("0 1\n1 2\n2 3\n3 4\n" + "dtype: category\nCategories (4, int64): [1, 2, 3, 4]") assert exp == a.__unicode__() - a = pd.Series(pd.Categorical(["a", "b"] * 25)) + a = Series(Categorical(["a", "b"] * 25)) exp = u("0 a\n1 b\n" + " ..\n" + "48 a\n49 b\n" + "Length: 50, dtype: category\nCategories (2, object): [a, b]") with option_context("display.max_rows", 5): assert exp == repr(a) levs = list("abcdefghijklmnopqrstuvwxyz") - a = pd.Series(pd.Categorical( - ["a", "b"], categories=levs, ordered=True)) + a = Series(Categorical(["a", "b"], categories=levs, ordered=True)) exp = u("0 a\n1 b\n" + "dtype: category\n" "Categories (26, object): [a < b < c < d ... w < x < y < z]") assert exp == a.__unicode__() def test_categorical_repr(self): - c = pd.Categorical([1, 2, 3]) + c = Categorical([1, 2, 3]) exp = """[1, 2, 3] Categories (3, int64): [1, 2, 3]""" assert repr(c) == exp - c = pd.Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3]) + c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3]) exp = """[1, 2, 3, 1, 2, 3] Categories (3, int64): [1, 2, 3]""" assert repr(c) == exp - c = pd.Categorical([1, 2, 3, 4, 5] * 10) + c = Categorical([1, 2, 3, 4, 5] * 10) exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5] Length: 50 Categories (5, int64): [1, 2, 3, 4, 5]""" assert repr(c) == exp - c = pd.Categorical(np.arange(20)) + c = Categorical(np.arange(20)) exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19] Length: 20 Categories (20, int64): [0, 1, 2, 3, ..., 16, 17, 18, 19]""" @@ -2597,27 +2581,26 @@ def test_categorical_repr(self): assert repr(c) == exp def test_categorical_repr_ordered(self): - c = pd.Categorical([1, 2, 3], ordered=True) + c = Categorical([1, 2, 3], ordered=True) exp = """[1, 2, 3] Categories (3, int64): [1 < 2 < 3]""" assert repr(c) == exp - c = pd.Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3], - ordered=True) + c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3], ordered=True) exp = """[1, 2, 3, 1, 2, 3] Categories (3, int64): [1 < 2 < 3]""" assert repr(c) == exp - c = pd.Categorical([1, 2, 3, 4, 5] * 10, ordered=True) + c = Categorical([1, 2, 3, 4, 5] * 10, ordered=True) exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5] Length: 50 Categories (5, int64): [1 < 2 < 3 < 4 < 5]""" assert repr(c) == exp - c = pd.Categorical(np.arange(20), ordered=True) + c = Categorical(np.arange(20), ordered=True) exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19] Length: 20 Categories (20, int64): [0 < 1 < 2 < 3 ... 16 < 17 < 18 < 19]""" @@ -2625,8 +2608,8 @@ def test_categorical_repr_ordered(self): assert repr(c) == exp def test_categorical_repr_datetime(self): - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5) - c = pd.Categorical(idx) + idx = date_range('2011-01-01 09:00', freq='H', periods=5) + c = Categorical(idx) # TODO(wesm): exceeding 80 characters in the console is not good # behavior @@ -2639,7 +2622,7 @@ def test_categorical_repr_datetime(self): "2011-01-01 13:00:00]""") assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx) + c = Categorical(idx.append(idx), categories=idx) exp = ( "[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, " "2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, " @@ -2652,9 +2635,9 @@ def test_categorical_repr_datetime(self): assert repr(c) == exp - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5, - tz='US/Eastern') - c = pd.Categorical(idx) + idx = date_range('2011-01-01 09:00', freq='H', periods=5, + tz='US/Eastern') + c = Categorical(idx) exp = ( "[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, " "2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, " @@ -2668,7 +2651,7 @@ def test_categorical_repr_datetime(self): assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx) + c = Categorical(idx.append(idx), categories=idx) exp = ( "[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, " "2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, " @@ -2685,24 +2668,24 @@ def test_categorical_repr_datetime(self): assert repr(c) == exp def test_categorical_repr_datetime_ordered(self): - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5) - c = pd.Categorical(idx, ordered=True) + idx = date_range('2011-01-01 09:00', freq='H', periods=5) + c = Categorical(idx, ordered=True) exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00] Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 < 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx, ordered=True) + c = Categorical(idx.append(idx), categories=idx, ordered=True) exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00] Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 < 2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa assert repr(c) == exp - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5, - tz='US/Eastern') - c = pd.Categorical(idx, ordered=True) + idx = date_range('2011-01-01 09:00', freq='H', periods=5, + tz='US/Eastern') + c = Categorical(idx, ordered=True) exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00] Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 < 2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 < @@ -2710,7 +2693,7 @@ def test_categorical_repr_datetime_ordered(self): assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx, ordered=True) + c = Categorical(idx.append(idx), categories=idx, ordered=True) exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00] Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 < 2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 < @@ -2719,79 +2702,79 @@ def test_categorical_repr_datetime_ordered(self): assert repr(c) == exp def test_categorical_repr_period(self): - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=5) - c = pd.Categorical(idx) + idx = period_range('2011-01-01 09:00', freq='H', periods=5) + c = Categorical(idx) exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00] Categories (5, period[H]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]""" # noqa assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx) + c = Categorical(idx.append(idx), categories=idx) exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00] Categories (5, period[H]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]""" # noqa assert repr(c) == exp - idx = pd.period_range('2011-01', freq='M', periods=5) - c = pd.Categorical(idx) + idx = period_range('2011-01', freq='M', periods=5) + c = Categorical(idx) exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05] Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx) + c = Categorical(idx.append(idx), categories=idx) exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05] Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" # noqa assert repr(c) == exp def test_categorical_repr_period_ordered(self): - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=5) - c = pd.Categorical(idx, ordered=True) + idx = period_range('2011-01-01 09:00', freq='H', periods=5) + c = Categorical(idx, ordered=True) exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00] Categories (5, period[H]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 < 2011-01-01 13:00]""" # noqa assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx, ordered=True) + c = Categorical(idx.append(idx), categories=idx, ordered=True) exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00] Categories (5, period[H]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 < 2011-01-01 13:00]""" # noqa assert repr(c) == exp - idx = pd.period_range('2011-01', freq='M', periods=5) - c = pd.Categorical(idx, ordered=True) + idx = period_range('2011-01', freq='M', periods=5) + c = Categorical(idx, ordered=True) exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05] Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx, ordered=True) + c = Categorical(idx.append(idx), categories=idx, ordered=True) exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05] Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" # noqa assert repr(c) == exp def test_categorical_repr_timedelta(self): - idx = pd.timedelta_range('1 days', periods=5) - c = pd.Categorical(idx) + idx = timedelta_range('1 days', periods=5) + c = Categorical(idx) exp = """[1 days, 2 days, 3 days, 4 days, 5 days] Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx) + c = Categorical(idx.append(idx), categories=idx) exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days] Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa assert repr(c) == exp - idx = pd.timedelta_range('1 hours', periods=20) - c = pd.Categorical(idx) + idx = timedelta_range('1 hours', periods=20) + c = Categorical(idx) exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00] Length: 20 Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, @@ -2800,7 +2783,7 @@ def test_categorical_repr_timedelta(self): assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx) + c = Categorical(idx.append(idx), categories=idx) exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00] Length: 40 Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, @@ -2810,21 +2793,21 @@ def test_categorical_repr_timedelta(self): assert repr(c) == exp def test_categorical_repr_timedelta_ordered(self): - idx = pd.timedelta_range('1 days', periods=5) - c = pd.Categorical(idx, ordered=True) + idx = timedelta_range('1 days', periods=5) + c = Categorical(idx, ordered=True) exp = """[1 days, 2 days, 3 days, 4 days, 5 days] Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx, ordered=True) + c = Categorical(idx.append(idx), categories=idx, ordered=True) exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days] Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa assert repr(c) == exp - idx = pd.timedelta_range('1 hours', periods=20) - c = pd.Categorical(idx, ordered=True) + idx = timedelta_range('1 hours', periods=20) + c = Categorical(idx, ordered=True) exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00] Length: 20 Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 < @@ -2833,7 +2816,7 @@ def test_categorical_repr_timedelta_ordered(self): assert repr(c) == exp - c = pd.Categorical(idx.append(idx), categories=idx, ordered=True) + c = Categorical(idx.append(idx), categories=idx, ordered=True) exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00] Length: 40 Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 < @@ -2843,7 +2826,7 @@ def test_categorical_repr_timedelta_ordered(self): assert repr(c) == exp def test_categorical_series_repr(self): - s = pd.Series(pd.Categorical([1, 2, 3])) + s = Series(Categorical([1, 2, 3])) exp = """0 1 1 2 2 3 @@ -2852,7 +2835,7 @@ def test_categorical_series_repr(self): assert repr(s) == exp - s = pd.Series(pd.Categorical(np.arange(10))) + s = Series(Categorical(np.arange(10))) exp = """0 0 1 1 2 2 @@ -2869,7 +2852,7 @@ def test_categorical_series_repr(self): assert repr(s) == exp def test_categorical_series_repr_ordered(self): - s = pd.Series(pd.Categorical([1, 2, 3], ordered=True)) + s = Series(Categorical([1, 2, 3], ordered=True)) exp = """0 1 1 2 2 3 @@ -2878,7 +2861,7 @@ def test_categorical_series_repr_ordered(self): assert repr(s) == exp - s = pd.Series(pd.Categorical(np.arange(10), ordered=True)) + s = Series(Categorical(np.arange(10), ordered=True)) exp = """0 0 1 1 2 2 @@ -2895,8 +2878,8 @@ def test_categorical_series_repr_ordered(self): assert repr(s) == exp def test_categorical_series_repr_datetime(self): - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5) - s = pd.Series(pd.Categorical(idx)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5) + s = Series(Categorical(idx)) exp = """0 2011-01-01 09:00:00 1 2011-01-01 10:00:00 2 2011-01-01 11:00:00 @@ -2908,9 +2891,9 @@ def test_categorical_series_repr_datetime(self): assert repr(s) == exp - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5, - tz='US/Eastern') - s = pd.Series(pd.Categorical(idx)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5, + tz='US/Eastern') + s = Series(Categorical(idx)) exp = """0 2011-01-01 09:00:00-05:00 1 2011-01-01 10:00:00-05:00 2 2011-01-01 11:00:00-05:00 @@ -2924,8 +2907,8 @@ def test_categorical_series_repr_datetime(self): assert repr(s) == exp def test_categorical_series_repr_datetime_ordered(self): - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5) - s = pd.Series(pd.Categorical(idx, ordered=True)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5) + s = Series(Categorical(idx, ordered=True)) exp = """0 2011-01-01 09:00:00 1 2011-01-01 10:00:00 2 2011-01-01 11:00:00 @@ -2937,9 +2920,9 @@ def test_categorical_series_repr_datetime_ordered(self): assert repr(s) == exp - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5, - tz='US/Eastern') - s = pd.Series(pd.Categorical(idx, ordered=True)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5, + tz='US/Eastern') + s = Series(Categorical(idx, ordered=True)) exp = """0 2011-01-01 09:00:00-05:00 1 2011-01-01 10:00:00-05:00 2 2011-01-01 11:00:00-05:00 @@ -2953,8 +2936,8 @@ def test_categorical_series_repr_datetime_ordered(self): assert repr(s) == exp def test_categorical_series_repr_period(self): - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=5) - s = pd.Series(pd.Categorical(idx)) + idx = period_range('2011-01-01 09:00', freq='H', periods=5) + s = Series(Categorical(idx)) exp = """0 2011-01-01 09:00 1 2011-01-01 10:00 2 2011-01-01 11:00 @@ -2966,8 +2949,8 @@ def test_categorical_series_repr_period(self): assert repr(s) == exp - idx = pd.period_range('2011-01', freq='M', periods=5) - s = pd.Series(pd.Categorical(idx)) + idx = period_range('2011-01', freq='M', periods=5) + s = Series(Categorical(idx)) exp = """0 2011-01 1 2011-02 2 2011-03 @@ -2979,8 +2962,8 @@ def test_categorical_series_repr_period(self): assert repr(s) == exp def test_categorical_series_repr_period_ordered(self): - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=5) - s = pd.Series(pd.Categorical(idx, ordered=True)) + idx = period_range('2011-01-01 09:00', freq='H', periods=5) + s = Series(Categorical(idx, ordered=True)) exp = """0 2011-01-01 09:00 1 2011-01-01 10:00 2 2011-01-01 11:00 @@ -2992,8 +2975,8 @@ def test_categorical_series_repr_period_ordered(self): assert repr(s) == exp - idx = pd.period_range('2011-01', freq='M', periods=5) - s = pd.Series(pd.Categorical(idx, ordered=True)) + idx = period_range('2011-01', freq='M', periods=5) + s = Series(Categorical(idx, ordered=True)) exp = """0 2011-01 1 2011-02 2 2011-03 @@ -3005,8 +2988,8 @@ def test_categorical_series_repr_period_ordered(self): assert repr(s) == exp def test_categorical_series_repr_timedelta(self): - idx = pd.timedelta_range('1 days', periods=5) - s = pd.Series(pd.Categorical(idx)) + idx = timedelta_range('1 days', periods=5) + s = Series(Categorical(idx)) exp = """0 1 days 1 2 days 2 3 days @@ -3017,8 +3000,8 @@ def test_categorical_series_repr_timedelta(self): assert repr(s) == exp - idx = pd.timedelta_range('1 hours', periods=10) - s = pd.Series(pd.Categorical(idx)) + idx = timedelta_range('1 hours', periods=10) + s = Series(Categorical(idx)) exp = """0 0 days 01:00:00 1 1 days 01:00:00 2 2 days 01:00:00 @@ -3037,8 +3020,8 @@ def test_categorical_series_repr_timedelta(self): assert repr(s) == exp def test_categorical_series_repr_timedelta_ordered(self): - idx = pd.timedelta_range('1 days', periods=5) - s = pd.Series(pd.Categorical(idx, ordered=True)) + idx = timedelta_range('1 days', periods=5) + s = Series(Categorical(idx, ordered=True)) exp = """0 1 days 1 2 days 2 3 days @@ -3049,8 +3032,8 @@ def test_categorical_series_repr_timedelta_ordered(self): assert repr(s) == exp - idx = pd.timedelta_range('1 hours', periods=10) - s = pd.Series(pd.Categorical(idx, ordered=True)) + idx = timedelta_range('1 hours', periods=10) + s = Series(Categorical(idx, ordered=True)) exp = """0 0 days 01:00:00 1 1 days 01:00:00 2 2 days 01:00:00 @@ -3069,26 +3052,26 @@ def test_categorical_series_repr_timedelta_ordered(self): assert repr(s) == exp def test_categorical_index_repr(self): - idx = pd.CategoricalIndex(pd.Categorical([1, 2, 3])) + idx = CategoricalIndex(Categorical([1, 2, 3])) exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category')""" # noqa assert repr(idx) == exp - i = pd.CategoricalIndex(pd.Categorical(np.arange(10))) + i = CategoricalIndex(Categorical(np.arange(10))) exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, 4, 5, 6, 7, ...], ordered=False, dtype='category')""" # noqa assert repr(i) == exp def test_categorical_index_repr_ordered(self): - i = pd.CategoricalIndex(pd.Categorical([1, 2, 3], ordered=True)) + i = CategoricalIndex(Categorical([1, 2, 3], ordered=True)) exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=True, dtype='category')""" # noqa assert repr(i) == exp - i = pd.CategoricalIndex(pd.Categorical(np.arange(10), ordered=True)) + i = CategoricalIndex(Categorical(np.arange(10), ordered=True)) exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, 4, 5, 6, 7, ...], ordered=True, dtype='category')""" # noqa assert repr(i) == exp def test_categorical_index_repr_datetime(self): - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00', '2011-01-01 11:00:00', '2011-01-01 12:00:00', '2011-01-01 13:00:00'], @@ -3096,9 +3079,9 @@ def test_categorical_index_repr_datetime(self): assert repr(i) == exp - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5, - tz='US/Eastern') - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5, + tz='US/Eastern') + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00'], @@ -3107,8 +3090,8 @@ def test_categorical_index_repr_datetime(self): assert repr(i) == exp def test_categorical_index_repr_datetime_ordered(self): - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx, ordered=True)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5) + i = CategoricalIndex(Categorical(idx, ordered=True)) exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00', '2011-01-01 11:00:00', '2011-01-01 12:00:00', '2011-01-01 13:00:00'], @@ -3116,9 +3099,9 @@ def test_categorical_index_repr_datetime_ordered(self): assert repr(i) == exp - idx = pd.date_range('2011-01-01 09:00', freq='H', periods=5, - tz='US/Eastern') - i = pd.CategoricalIndex(pd.Categorical(idx, ordered=True)) + idx = date_range('2011-01-01 09:00', freq='H', periods=5, + tz='US/Eastern') + i = CategoricalIndex(Categorical(idx, ordered=True)) exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00'], @@ -3126,7 +3109,7 @@ def test_categorical_index_repr_datetime_ordered(self): assert repr(i) == exp - i = pd.CategoricalIndex(pd.Categorical(idx.append(idx), ordered=True)) + i = CategoricalIndex(Categorical(idx.append(idx), ordered=True)) exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00', '2011-01-01 09:00:00-05:00', @@ -3138,30 +3121,30 @@ def test_categorical_index_repr_datetime_ordered(self): def test_categorical_index_repr_period(self): # test all length - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=1) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = period_range('2011-01-01 09:00', freq='H', periods=1) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['2011-01-01 09:00'], categories=[2011-01-01 09:00], ordered=False, dtype='category')""" # noqa assert repr(i) == exp - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=2) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = period_range('2011-01-01 09:00', freq='H', periods=2) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00], ordered=False, dtype='category')""" # noqa assert repr(i) == exp - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=3) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = period_range('2011-01-01 09:00', freq='H', periods=3) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00], ordered=False, dtype='category')""" # noqa assert repr(i) == exp - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = period_range('2011-01-01 09:00', freq='H', periods=5) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00', '2011-01-01 13:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa assert repr(i) == exp - i = pd.CategoricalIndex(pd.Categorical(idx.append(idx))) + i = CategoricalIndex(Categorical(idx.append(idx))) exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00', '2011-01-01 13:00', '2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00', @@ -3170,33 +3153,33 @@ def test_categorical_index_repr_period(self): assert repr(i) == exp - idx = pd.period_range('2011-01', freq='M', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = period_range('2011-01', freq='M', periods=5) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=False, dtype='category')""" # noqa assert repr(i) == exp def test_categorical_index_repr_period_ordered(self): - idx = pd.period_range('2011-01-01 09:00', freq='H', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx, ordered=True)) + idx = period_range('2011-01-01 09:00', freq='H', periods=5) + i = CategoricalIndex(Categorical(idx, ordered=True)) exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00', '2011-01-01 13:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=True, dtype='category')""" # noqa assert repr(i) == exp - idx = pd.period_range('2011-01', freq='M', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx, ordered=True)) + idx = period_range('2011-01', freq='M', periods=5) + i = CategoricalIndex(Categorical(idx, ordered=True)) exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=True, dtype='category')""" # noqa assert repr(i) == exp def test_categorical_index_repr_timedelta(self): - idx = pd.timedelta_range('1 days', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = timedelta_range('1 days', periods=5) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days 00:00:00, 2 days 00:00:00, 3 days 00:00:00, 4 days 00:00:00, 5 days 00:00:00], ordered=False, dtype='category')""" # noqa assert repr(i) == exp - idx = pd.timedelta_range('1 hours', periods=10) - i = pd.CategoricalIndex(pd.Categorical(idx)) + idx = timedelta_range('1 hours', periods=10) + i = CategoricalIndex(Categorical(idx)) exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00', '3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00', '6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00', @@ -3206,13 +3189,13 @@ def test_categorical_index_repr_timedelta(self): assert repr(i) == exp def test_categorical_index_repr_timedelta_ordered(self): - idx = pd.timedelta_range('1 days', periods=5) - i = pd.CategoricalIndex(pd.Categorical(idx, ordered=True)) + idx = timedelta_range('1 days', periods=5) + i = CategoricalIndex(Categorical(idx, ordered=True)) exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days 00:00:00, 2 days 00:00:00, 3 days 00:00:00, 4 days 00:00:00, 5 days 00:00:00], ordered=True, dtype='category')""" # noqa assert repr(i) == exp - idx = pd.timedelta_range('1 hours', periods=10) - i = pd.CategoricalIndex(pd.Categorical(idx, ordered=True)) + idx = timedelta_range('1 hours', periods=10) + i = CategoricalIndex(Categorical(idx, ordered=True)) exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00', '3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00', '6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00', @@ -3223,10 +3206,10 @@ def test_categorical_index_repr_timedelta_ordered(self): def test_categorical_frame(self): # normal DataFrame - dt = pd.date_range('2011-01-01 09:00', freq='H', periods=5, - tz='US/Eastern') - p = pd.period_range('2011-01', freq='M', periods=5) - df = pd.DataFrame({'dt': dt, 'p': p}) + dt = date_range('2011-01-01 09:00', freq='H', periods=5, + tz='US/Eastern') + p = period_range('2011-01', freq='M', periods=5) + df = DataFrame({'dt': dt, 'p': p}) exp = """ dt p 0 2011-01-01 09:00:00-05:00 2011-01 1 2011-01-01 10:00:00-05:00 2011-02 @@ -3234,7 +3217,7 @@ def test_categorical_frame(self): 3 2011-01-01 12:00:00-05:00 2011-04 4 2011-01-01 13:00:00-05:00 2011-05""" - df = pd.DataFrame({'dt': pd.Categorical(dt), 'p': pd.Categorical(p)}) + df = DataFrame({'dt': Categorical(dt), 'p': Categorical(p)}) assert repr(df) == exp def test_info(self): @@ -3261,7 +3244,7 @@ def test_groupby_sort(self): res = self.cat.groupby(['value_group'])['value_group'].count() exp = res[sorted(res.index, key=lambda x: float(x.split()[0]))] - exp.index = pd.CategoricalIndex(exp.index, name=exp.index.name) + exp.index = CategoricalIndex(exp.index, name=exp.index.name) tm.assert_series_equal(res, exp) def test_min_max(self): @@ -3320,26 +3303,23 @@ def test_mode(self): def test_value_counts(self): # GH 12835 - cats = pd.Categorical(["a", "b", "c", "c", "c", "b"], - categories=["c", "a", "b", "d"]) - s = pd.Series(cats, name='xxx') + cats = Categorical(list('abcccb'), categories=list('cabd')) + s = Series(cats, name='xxx') res = s.value_counts(sort=False) - exp_index = pd.CategoricalIndex(["c", "a", "b", "d"], - categories=cats.categories) + exp_index = CategoricalIndex(list('cabd'), categories=cats.categories) exp = Series([3, 1, 2, 0], name='xxx', index=exp_index) tm.assert_series_equal(res, exp) res = s.value_counts(sort=True) - exp_index = pd.CategoricalIndex(["c", "b", "a", "d"], - categories=cats.categories) + exp_index = CategoricalIndex(list('cbad'), categories=cats.categories) exp = Series([3, 2, 1, 0], name='xxx', index=exp_index) tm.assert_series_equal(res, exp) # check object dtype handles the Series.name as the same # (tested in test_base.py) - s = pd.Series(["a", "b", "c", "c", "c", "b"], name='xxx') + s = Series(["a", "b", "c", "c", "c", "b"], name='xxx') res = s.value_counts() exp = Series([3, 2, 1], name='xxx', index=["c", "b", "a"]) tm.assert_series_equal(res, exp) @@ -3348,8 +3328,8 @@ def test_value_counts_with_nan(self): # see gh-9443 # sanity check - s = pd.Series(["a", "b", "a"], dtype="category") - exp = pd.Series([2, 1], index=pd.CategoricalIndex(["a", "b"])) + s = Series(["a", "b", "a"], dtype="category") + exp = Series([2, 1], index=CategoricalIndex(["a", "b"])) res = s.value_counts(dropna=True) tm.assert_series_equal(res, exp) @@ -3359,27 +3339,25 @@ def test_value_counts_with_nan(self): # same Series via two different constructions --> same behaviour series = [ - pd.Series(["a", "b", None, "a", None, None], dtype="category"), - pd.Series(pd.Categorical(["a", "b", None, "a", None, None], - categories=["a", "b"])) + Series(["a", "b", None, "a", None, None], dtype="category"), + Series(Categorical(["a", "b", None, "a", None, None], + categories=["a", "b"])) ] for s in series: # None is a NaN value, so we exclude its count here - exp = pd.Series([2, 1], index=pd.CategoricalIndex(["a", "b"])) + exp = Series([2, 1], index=CategoricalIndex(["a", "b"])) res = s.value_counts(dropna=True) tm.assert_series_equal(res, exp) # we don't exclude the count of None and sort by counts - exp = pd.Series( - [3, 2, 1], index=pd.CategoricalIndex([np.nan, "a", "b"])) + exp = Series([3, 2, 1], index=CategoricalIndex([np.nan, "a", "b"])) res = s.value_counts(dropna=False) tm.assert_series_equal(res, exp) # When we aren't sorting by counts, and np.nan isn't a # category, it should be last. - exp = pd.Series( - [2, 1, 3], index=pd.CategoricalIndex(["a", "b", np.nan])) + exp = Series([2, 1, 3], index=CategoricalIndex(["a", "b", np.nan])) res = s.value_counts(dropna=False, sort=False) tm.assert_series_equal(res, exp) @@ -3389,8 +3367,7 @@ def test_groupby(self): categories=["a", "b", "c", "d"], ordered=True) data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats}) - exp_index = pd.CategoricalIndex(['a', 'b', 'c', 'd'], name='b', - ordered=True) + exp_index = CategoricalIndex(list('abcd'), name='b', ordered=True) expected = DataFrame({'a': [1, 2, 4, np.nan]}, index=exp_index) result = data.groupby("b").mean() tm.assert_frame_equal(result, expected) @@ -3403,7 +3380,7 @@ def test_groupby(self): # single grouper gb = df.groupby("A") - exp_idx = pd.CategoricalIndex(['a', 'b', 'z'], name='A', ordered=True) + exp_idx = CategoricalIndex(['a', 'b', 'z'], name='A', ordered=True) expected = DataFrame({'values': Series([3, 7, np.nan], index=exp_idx)}) result = gb.sum() tm.assert_frame_equal(result, expected) @@ -3436,10 +3413,10 @@ def test_groupby(self): tm.assert_frame_equal(result, expected) # GH 8623 - x = pd.DataFrame([[1, 'John P. Doe'], [2, 'Jane Dove'], - [1, 'John P. Doe']], - columns=['person_id', 'person_name']) - x['person_name'] = pd.Categorical(x.person_name) + x = DataFrame([[1, 'John P. Doe'], [2, 'Jane Dove'], + [1, 'John P. Doe']], + columns=['person_id', 'person_name']) + x['person_name'] = Categorical(x.person_name) g = x.groupby(['person_id']) result = g.transform(lambda x: x) @@ -3490,13 +3467,13 @@ def f(x): df.groupby(c).transform(lambda xs: np.sum(xs)), df[['a']]) # GH 9603 - df = pd.DataFrame({'a': [1, 0, 0, 0]}) - c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=pd.Categorical(list('abcd'))) + df = DataFrame({'a': [1, 0, 0, 0]}) + c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=Categorical(list('abcd'))) result = df.groupby(c).apply(len) - exp_index = pd.CategoricalIndex(c.values.categories, - ordered=c.values.ordered) - expected = pd.Series([1, 0, 0, 0], index=exp_index) + exp_index = CategoricalIndex( + c.values.categories, ordered=c.values.ordered) + expected = Series([1, 0, 0, 0], index=exp_index) expected.index.name = 'a' tm.assert_series_equal(result, expected) @@ -3581,7 +3558,7 @@ def test_sort_values(self): # GH 7848 df = DataFrame({"id": [6, 5, 4, 3, 2, 1], "raw_grade": ['a', 'b', 'b', 'a', 'a', 'e']}) - df["grade"] = pd.Categorical(df["raw_grade"], ordered=True) + df["grade"] = Categorical(df["raw_grade"], ordered=True) df['grade'] = df['grade'].cat.set_categories(['b', 'e', 'a']) # sorts 'grade' according to the order of the categories @@ -3626,26 +3603,26 @@ def test_slicing_and_getting_ops(self): # - returning a row # - returning a single value - cats = pd.Categorical( + cats = Categorical( ["a", "c", "b", "c", "c", "c", "c"], categories=["a", "b", "c"]) - idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + idx = Index(["h", "i", "j", "k", "l", "m", "n"]) values = [1, 2, 3, 4, 5, 6, 7] - df = pd.DataFrame({"cats": cats, "values": values}, index=idx) + df = DataFrame({"cats": cats, "values": values}, index=idx) # the expected values - cats2 = pd.Categorical(["b", "c"], categories=["a", "b", "c"]) - idx2 = pd.Index(["j", "k"]) + cats2 = Categorical(["b", "c"], categories=["a", "b", "c"]) + idx2 = Index(["j", "k"]) values2 = [3, 4] # 2:4,: | "j":"k",: - exp_df = pd.DataFrame({"cats": cats2, "values": values2}, index=idx2) + exp_df = DataFrame({"cats": cats2, "values": values2}, index=idx2) # :,"cats" | :,0 - exp_col = pd.Series(cats, index=idx, name='cats') + exp_col = Series(cats, index=idx, name='cats') # "j",: | 2,: - exp_row = pd.Series(["b", 3], index=["cats", "values"], dtype="object", - name="j") + exp_row = Series(["b", 3], index=["cats", "values"], dtype="object", + name="j") # "j","cats | 2,0 exp_val = "b" @@ -3804,46 +3781,44 @@ def test_assigning_ops(self): # assign a part of a column with dtype != categorical -> # exp_parts_cats_col - cats = pd.Categorical(["a", "a", "a", "a", "a", "a", "a"], - categories=["a", "b"]) - idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], + categories=["a", "b"]) + idx = Index(["h", "i", "j", "k", "l", "m", "n"]) values = [1, 1, 1, 1, 1, 1, 1] - orig = pd.DataFrame({"cats": cats, "values": values}, index=idx) + orig = DataFrame({"cats": cats, "values": values}, index=idx) # the expected values # changed single row - cats1 = pd.Categorical(["a", "a", "b", "a", "a", "a", "a"], - categories=["a", "b"]) - idx1 = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], + categories=["a", "b"]) + idx1 = Index(["h", "i", "j", "k", "l", "m", "n"]) values1 = [1, 1, 2, 1, 1, 1, 1] - exp_single_row = pd.DataFrame({"cats": cats1, - "values": values1}, index=idx1) + exp_single_row = DataFrame({"cats": cats1, + "values": values1}, index=idx1) # changed multiple rows - cats2 = pd.Categorical(["a", "a", "b", "b", "a", "a", "a"], - categories=["a", "b"]) - idx2 = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], + categories=["a", "b"]) + idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) values2 = [1, 1, 2, 2, 1, 1, 1] - exp_multi_row = pd.DataFrame({"cats": cats2, - "values": values2}, index=idx2) + exp_multi_row = DataFrame({"cats": cats2, + "values": values2}, index=idx2) # changed part of the cats column - cats3 = pd.Categorical( + cats3 = Categorical( ["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) - idx3 = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + idx3 = Index(["h", "i", "j", "k", "l", "m", "n"]) values3 = [1, 1, 1, 1, 1, 1, 1] - exp_parts_cats_col = pd.DataFrame( - {"cats": cats3, - "values": values3}, index=idx3) + exp_parts_cats_col = DataFrame({"cats": cats3, + "values": values3}, index=idx3) # changed single value in cats col - cats4 = pd.Categorical( + cats4 = Categorical( ["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) - idx4 = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + idx4 = Index(["h", "i", "j", "k", "l", "m", "n"]) values4 = [1, 1, 1, 1, 1, 1, 1] - exp_single_cats_value = pd.DataFrame( - {"cats": cats4, - "values": values4}, index=idx4) + exp_single_cats_value = DataFrame({"cats": cats4, + "values": values4}, index=idx4) # iloc # ############### @@ -3889,20 +3864,18 @@ def f(): # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy() - df.iloc[2:4, 0] = pd.Categorical(["b", "b"], categories=["a", "b"]) + df.iloc[2:4, 0] = Categorical(["b", "b"], categories=["a", "b"]) tm.assert_frame_equal(df, exp_parts_cats_col) with pytest.raises(ValueError): # different categories -> not sure if this should fail or pass df = orig.copy() - df.iloc[2:4, 0] = pd.Categorical( - ["b", "b"], categories=["a", "b", "c"]) + df.iloc[2:4, 0] = Categorical(list('bb'), categories=list('abc')) with pytest.raises(ValueError): # different values df = orig.copy() - df.iloc[2:4, 0] = pd.Categorical( - ["c", "c"], categories=["a", "b", "c"]) + df.iloc[2:4, 0] = Categorical(list('cc'), categories=list('abc')) # assign a part of a column with dtype != categorical -> # exp_parts_cats_col @@ -3957,20 +3930,20 @@ def f(): # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy() - df.loc["j":"k", "cats"] = pd.Categorical( + df.loc["j":"k", "cats"] = Categorical( ["b", "b"], categories=["a", "b"]) tm.assert_frame_equal(df, exp_parts_cats_col) with pytest.raises(ValueError): # different categories -> not sure if this should fail or pass df = orig.copy() - df.loc["j":"k", "cats"] = pd.Categorical( + df.loc["j":"k", "cats"] = Categorical( ["b", "b"], categories=["a", "b", "c"]) with pytest.raises(ValueError): # different values df = orig.copy() - df.loc["j":"k", "cats"] = pd.Categorical( + df.loc["j":"k", "cats"] = Categorical( ["c", "c"], categories=["a", "b", "c"]) # assign a part of a column with dtype != categorical -> @@ -4026,20 +3999,20 @@ def f(): # assign a part of a column with dtype == categorical -> # exp_parts_cats_col df = orig.copy() - df.loc["j":"k", df.columns[0]] = pd.Categorical( + df.loc["j":"k", df.columns[0]] = Categorical( ["b", "b"], categories=["a", "b"]) tm.assert_frame_equal(df, exp_parts_cats_col) with pytest.raises(ValueError): # different categories -> not sure if this should fail or pass df = orig.copy() - df.loc["j":"k", df.columns[0]] = pd.Categorical( + df.loc["j":"k", df.columns[0]] = Categorical( ["b", "b"], categories=["a", "b", "c"]) with pytest.raises(ValueError): # different values df = orig.copy() - df.loc["j":"k", df.columns[0]] = pd.Categorical( + df.loc["j":"k", df.columns[0]] = Categorical( ["c", "c"], categories=["a", "b", "c"]) # assign a part of a column with dtype != categorical -> @@ -4077,11 +4050,11 @@ def f(): pytest.raises(ValueError, f) # fancy indexing - catsf = pd.Categorical(["a", "a", "c", "c", "a", "a", "a"], - categories=["a", "b", "c"]) - idxf = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) + catsf = Categorical(["a", "a", "c", "c", "a", "a", "a"], + categories=["a", "b", "c"]) + idxf = Index(["h", "i", "j", "k", "l", "m", "n"]) valuesf = [1, 1, 3, 3, 1, 1, 1] - df = pd.DataFrame({"cats": catsf, "values": valuesf}, index=idxf) + df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf) exp_fancy = exp_multi_row.copy() exp_fancy["cats"].cat.set_categories(["a", "b", "c"], inplace=True) @@ -4103,40 +4076,38 @@ def f(): # Assigning a Category to parts of a int/... column uses the values of # the Catgorical - df = pd.DataFrame({"a": [1, 1, 1, 1, 1], - "b": ["a", "a", "a", "a", "a"]}) - exp = pd.DataFrame({"a": [1, "b", "b", 1, 1], - "b": ["a", "a", "b", "b", "a"]}) - df.loc[1:2, "a"] = pd.Categorical(["b", "b"], categories=["a", "b"]) - df.loc[2:3, "b"] = pd.Categorical(["b", "b"], categories=["a", "b"]) + df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) + exp = DataFrame({"a": [1, "b", "b", 1, 1], "b": list("aabba")}) + df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"]) + df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"]) tm.assert_frame_equal(df, exp) # Series - orig = Series(pd.Categorical(["b", "b"], categories=["a", "b"])) + orig = Series(Categorical(["b", "b"], categories=["a", "b"])) s = orig.copy() s[:] = "a" - exp = Series(pd.Categorical(["a", "a"], categories=["a", "b"])) + exp = Series(Categorical(["a", "a"], categories=["a", "b"])) tm.assert_series_equal(s, exp) s = orig.copy() s[1] = "a" - exp = Series(pd.Categorical(["b", "a"], categories=["a", "b"])) + exp = Series(Categorical(["b", "a"], categories=["a", "b"])) tm.assert_series_equal(s, exp) s = orig.copy() s[s.index > 0] = "a" - exp = Series(pd.Categorical(["b", "a"], categories=["a", "b"])) + exp = Series(Categorical(["b", "a"], categories=["a", "b"])) tm.assert_series_equal(s, exp) s = orig.copy() s[[False, True]] = "a" - exp = Series(pd.Categorical(["b", "a"], categories=["a", "b"])) + exp = Series(Categorical(["b", "a"], categories=["a", "b"])) tm.assert_series_equal(s, exp) s = orig.copy() s.index = ["x", "y"] s["y"] = "a" - exp = Series(pd.Categorical(["b", "a"], categories=["a", "b"]), + exp = Series(Categorical(["b", "a"], categories=["a", "b"]), index=["x", "y"]) tm.assert_series_equal(s, exp) @@ -4150,13 +4121,13 @@ def test_comparisons(self): tests_data = [(list("abc"), list("cba"), list("bbb")), ([1, 2, 3], [3, 2, 1], [2, 2, 2])] for data, reverse, base in tests_data: - cat_rev = pd.Series(pd.Categorical(data, categories=reverse, - ordered=True)) - cat_rev_base = pd.Series(pd.Categorical(base, categories=reverse, - ordered=True)) - cat = pd.Series(pd.Categorical(data, ordered=True)) - cat_base = pd.Series(pd.Categorical( - base, categories=cat.cat.categories, ordered=True)) + cat_rev = Series( + Categorical(data, categories=reverse, ordered=True)) + cat_rev_base = Series( + Categorical(base, categories=reverse, ordered=True)) + cat = Series(Categorical(data, ordered=True)) + cat_base = Series( + Categorical(base, categories=cat.cat.categories, ordered=True)) s = Series(base) a = np.array(base) @@ -4327,24 +4298,24 @@ def test_compare_different_lengths(self): c1 == c2 def test_concat_append(self): - cat = pd.Categorical(["a", "b"], categories=["a", "b"]) + cat = Categorical(["a", "b"], categories=["a", "b"]) vals = [1, 2] - df = pd.DataFrame({"cats": cat, "vals": vals}) - cat2 = pd.Categorical(["a", "b", "a", "b"], categories=["a", "b"]) + df = DataFrame({"cats": cat, "vals": vals}) + cat2 = Categorical(["a", "b", "a", "b"], categories=["a", "b"]) vals2 = [1, 2, 1, 2] - exp = pd.DataFrame({"cats": cat2, - "vals": vals2}, index=pd.Index([0, 1, 0, 1])) + exp = DataFrame({"cats": cat2, "vals": vals2}, + index=Index([0, 1, 0, 1])) tm.assert_frame_equal(pd.concat([df, df]), exp) tm.assert_frame_equal(df.append(df), exp) # GH 13524 can concat different categories - cat3 = pd.Categorical(["a", "b"], categories=["a", "b", "c"]) + cat3 = Categorical(["a", "b"], categories=["a", "b", "c"]) vals3 = [1, 2] - df_different_categories = pd.DataFrame({"cats": cat3, "vals": vals3}) + df_different_categories = DataFrame({"cats": cat3, "vals": vals3}) res = pd.concat([df, df_different_categories], ignore_index=True) - exp = pd.DataFrame({"cats": list('abab'), "vals": [1, 2, 1, 2]}) + exp = DataFrame({"cats": list('abab'), "vals": [1, 2, 1, 2]}) tm.assert_frame_equal(res, exp) res = df.append(df_different_categories, ignore_index=True) @@ -4353,9 +4324,8 @@ def test_concat_append(self): def test_concat_append_gh7864(self): # GH 7864 # make sure ordering is preserverd - df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], - "raw_grade": ['a', 'b', 'b', 'a', 'a', 'e']}) - df["grade"] = pd.Categorical(df["raw_grade"]) + df = DataFrame({"id": [1, 2, 3, 4, 5, 6], "raw_grade": list('abbaae')}) + df["grade"] = Categorical(df["raw_grade"]) df['grade'].cat.set_categories(['e', 'a', 'b']) df1 = df[0:3] @@ -4421,8 +4391,7 @@ def test_categorical_index_preserver(self): tm.assert_frame_equal(result, expected) # wrong catgories - df3 = DataFrame({'A': a, - 'B': pd.Categorical(b, categories=list('abe')) + df3 = DataFrame({'A': a, 'B': Categorical(b, categories=list('abe')) }).set_index('B') pytest.raises(TypeError, lambda: pd.concat([df2, df3])) @@ -4479,47 +4448,47 @@ def test_merge(self): def test_repeat(self): # GH10183 - cat = pd.Categorical(["a", "b"], categories=["a", "b"]) - exp = pd.Categorical(["a", "a", "b", "b"], categories=["a", "b"]) + cat = Categorical(["a", "b"], categories=["a", "b"]) + exp = Categorical(["a", "a", "b", "b"], categories=["a", "b"]) res = cat.repeat(2) tm.assert_categorical_equal(res, exp) def test_numpy_repeat(self): - cat = pd.Categorical(["a", "b"], categories=["a", "b"]) - exp = pd.Categorical(["a", "a", "b", "b"], categories=["a", "b"]) + cat = Categorical(["a", "b"], categories=["a", "b"]) + exp = Categorical(["a", "a", "b", "b"], categories=["a", "b"]) tm.assert_categorical_equal(np.repeat(cat, 2), exp) msg = "the 'axis' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.repeat, cat, 2, axis=1) def test_reshape(self): - cat = pd.Categorical([], categories=["a", "b"]) + cat = Categorical([], categories=["a", "b"]) tm.assert_produces_warning(FutureWarning, cat.reshape, 0) with tm.assert_produces_warning(FutureWarning): - cat = pd.Categorical([], categories=["a", "b"]) + cat = Categorical([], categories=["a", "b"]) tm.assert_categorical_equal(cat.reshape(0), cat) with tm.assert_produces_warning(FutureWarning): - cat = pd.Categorical([], categories=["a", "b"]) + cat = Categorical([], categories=["a", "b"]) tm.assert_categorical_equal(cat.reshape((5, -1)), cat) with tm.assert_produces_warning(FutureWarning): - cat = pd.Categorical(["a", "b"], categories=["a", "b"]) + cat = Categorical(["a", "b"], categories=["a", "b"]) tm.assert_categorical_equal(cat.reshape(cat.shape), cat) with tm.assert_produces_warning(FutureWarning): - cat = pd.Categorical(["a", "b"], categories=["a", "b"]) + cat = Categorical(["a", "b"], categories=["a", "b"]) tm.assert_categorical_equal(cat.reshape(cat.size), cat) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): msg = "can only specify one unknown dimension" - cat = pd.Categorical(["a", "b"], categories=["a", "b"]) + cat = Categorical(["a", "b"], categories=["a", "b"]) tm.assert_raises_regex(ValueError, msg, cat.reshape, (-2, -1)) def test_numpy_reshape(self): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - cat = pd.Categorical(["a", "b"], categories=["a", "b"]) + cat = Categorical(["a", "b"], categories=["a", "b"]) tm.assert_categorical_equal(np.reshape(cat, cat.shape), cat) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): @@ -4529,18 +4498,18 @@ def test_numpy_reshape(self): def test_na_actions(self): - cat = pd.Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) + cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) vals = ["a", "b", np.nan, "d"] - df = pd.DataFrame({"cats": cat, "vals": vals}) - cat2 = pd.Categorical([1, 2, 3, 3], categories=[1, 2, 3]) + df = DataFrame({"cats": cat, "vals": vals}) + cat2 = Categorical([1, 2, 3, 3], categories=[1, 2, 3]) vals2 = ["a", "b", "b", "d"] - df_exp_fill = pd.DataFrame({"cats": cat2, "vals": vals2}) - cat3 = pd.Categorical([1, 2, 3], categories=[1, 2, 3]) + df_exp_fill = DataFrame({"cats": cat2, "vals": vals2}) + cat3 = Categorical([1, 2, 3], categories=[1, 2, 3]) vals3 = ["a", "b", np.nan] - df_exp_drop_cats = pd.DataFrame({"cats": cat3, "vals": vals3}) - cat4 = pd.Categorical([1, 2], categories=[1, 2, 3]) + df_exp_drop_cats = DataFrame({"cats": cat3, "vals": vals3}) + cat4 = Categorical([1, 2], categories=[1, 2, 3]) vals4 = ["a", "b"] - df_exp_drop_all = pd.DataFrame({"cats": cat4, "vals": vals4}) + df_exp_drop_all = DataFrame({"cats": cat4, "vals": vals4}) # fillna res = df.fillna(value={"cats": 3, "vals": "b"}) @@ -4562,10 +4531,10 @@ def f(): # make sure that fillna takes missing values into account c = Categorical([np.nan, "b", np.nan], categories=["a", "b"]) - df = pd.DataFrame({"cats": c, "vals": [1, 2, 3]}) + df = DataFrame({"cats": c, "vals": [1, 2, 3]}) cat_exp = Categorical(["a", "b", "a"], categories=["a", "b"]) - df_exp = pd.DataFrame({"cats": cat_exp, "vals": [1, 2, 3]}) + df_exp = DataFrame({"cats": cat_exp, "vals": [1, 2, 3]}) res = df.fillna("a") tm.assert_frame_equal(res, df_exp) @@ -4577,8 +4546,8 @@ def f(): df = DataFrame({"cats": cat, "vals": val}) res = df.fillna(df.median()) v_exp = [np.nan, np.nan, np.nan] - df_exp = pd.DataFrame({"cats": [2, 2, 2], "vals": v_exp}, - dtype='category') + df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp}, + dtype='category') tm.assert_frame_equal(res, df_exp) result = df.cats.fillna(np.nan) @@ -4586,20 +4555,19 @@ def f(): result = df.vals.fillna(np.nan) tm.assert_series_equal(result, df.vals) - idx = pd.DatetimeIndex(['2011-01-01 09:00', '2016-01-01 23:45', - '2011-01-01 09:00', pd.NaT, pd.NaT]) - df = DataFrame({'a': pd.Categorical(idx)}) - tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + idx = DatetimeIndex(['2011-01-01 09:00', '2016-01-01 23:45', + '2011-01-01 09:00', NaT, NaT]) + df = DataFrame({'a': Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) - idx = pd.PeriodIndex(['2011-01', '2011-01', '2011-01', - pd.NaT, pd.NaT], freq='M') - df = DataFrame({'a': pd.Categorical(idx)}) - tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + idx = PeriodIndex( + ['2011-01', '2011-01', '2011-01', NaT, NaT], freq='M') + df = DataFrame({'a': Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) - idx = pd.TimedeltaIndex(['1 days', '2 days', - '1 days', pd.NaT, pd.NaT]) - df = pd.DataFrame({'a': pd.Categorical(idx)}) - tm.assert_frame_equal(df.fillna(value=pd.NaT), df) + idx = TimedeltaIndex(['1 days', '2 days', '1 days', NaT, NaT]) + df = DataFrame({'a': Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) def test_astype_to_other(self): @@ -4643,8 +4611,8 @@ def cmp(a, b): tm.assert_series_equal(result, s, check_categorical=False) # invalid conversion (these are NOT a dtype) - for invalid in [lambda x: x.astype(pd.Categorical), - lambda x: x.astype('object').astype(pd.Categorical)]: + for invalid in [lambda x: x.astype(Categorical), + lambda x: x.astype('object').astype(Categorical)]: pytest.raises(TypeError, lambda: invalid(s)) def test_astype_categorical(self): @@ -4693,7 +4661,7 @@ def test_numeric_like_ops(self): # mad technically works because it takes always the numeric data # numpy ops - s = pd.Series(pd.Categorical([1, 2, 3, 4])) + s = Series(Categorical([1, 2, 3, 4])) pytest.raises(TypeError, lambda: np.sum(s)) # numeric ops on a Series @@ -4802,7 +4770,7 @@ def test_str_accessor_api_for_categorical(self): res = getattr(c.str, func)(*args, **kwargs) exp = getattr(s.str, func)(*args, **kwargs) - if isinstance(res, pd.DataFrame): + if isinstance(res, DataFrame): tm.assert_frame_equal(res, exp) else: tm.assert_series_equal(res, exp) @@ -4867,9 +4835,9 @@ def test_dt_accessor_api_for_categorical(self): res = getattr(c.dt, func)(*args, **kwargs) exp = getattr(s.dt, func)(*args, **kwargs) - if isinstance(res, pd.DataFrame): + if isinstance(res, DataFrame): tm.assert_frame_equal(res, exp) - elif isinstance(res, pd.Series): + elif isinstance(res, Series): tm.assert_series_equal(res, exp) else: tm.assert_almost_equal(res, exp) @@ -4882,9 +4850,9 @@ def test_dt_accessor_api_for_categorical(self): print(name, attr) raise e - if isinstance(res, pd.DataFrame): + if isinstance(res, DataFrame): tm.assert_frame_equal(res, exp) - elif isinstance(res, pd.Series): + elif isinstance(res, Series): tm.assert_series_equal(res, exp) else: tm.assert_almost_equal(res, exp) @@ -4897,21 +4865,21 @@ def test_dt_accessor_api_for_categorical(self): def test_concat_categorical(self): # See GH 10177 - df1 = pd.DataFrame(np.arange(18, dtype='int64').reshape(6, 3), - columns=["a", "b", "c"]) + df1 = DataFrame(np.arange(18, dtype='int64').reshape(6, 3), + columns=["a", "b", "c"]) - df2 = pd.DataFrame(np.arange(14, dtype='int64').reshape(7, 2), - columns=["a", "c"]) + df2 = DataFrame(np.arange(14, dtype='int64').reshape(7, 2), + columns=["a", "c"]) cat_values = ["one", "one", "two", "one", "two", "two", "one"] - df2['h'] = pd.Series(pd.Categorical(cat_values)) + df2['h'] = Series(Categorical(cat_values)) res = pd.concat((df1, df2), axis=0, ignore_index=True) - exp = pd.DataFrame({'a': [0, 3, 6, 9, 12, 15, 0, 2, 4, 6, 8, 10, 12], - 'b': [1, 4, 7, 10, 13, 16, np.nan, np.nan, - np.nan, np.nan, np.nan, np.nan, np.nan], - 'c': [2, 5, 8, 11, 14, 17, 1, 3, 5, 7, 9, 11, 13], - 'h': [None] * 6 + cat_values}) + exp = DataFrame({'a': [0, 3, 6, 9, 12, 15, 0, 2, 4, 6, 8, 10, 12], + 'b': [1, 4, 7, 10, 13, 16, np.nan, np.nan, np.nan, + np.nan, np.nan, np.nan, np.nan], + 'c': [2, 5, 8, 11, 14, 17, 1, 3, 5, 7, 9, 11, 13], + 'h': [None] * 6 + cat_values}) tm.assert_frame_equal(res, exp) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 785be71e236d7..592b069ef8bac 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -757,8 +757,7 @@ def _check_counts(frame, axis=0): self.frame['D'] = 'foo' result = self.frame.count(level=0, numeric_only=True) - tm.assert_index_equal(result.columns, - pd.Index(['A', 'B', 'C'], name='exp')) + tm.assert_index_equal(result.columns, Index(list('ABC'), name='exp')) def test_count_level_series(self): index = MultiIndex(levels=[['foo', 'bar', 'baz'], ['one', 'two', @@ -1052,7 +1051,7 @@ def test_unstack_period_series(self): idx2 = pd.PeriodIndex(['2013-12', '2013-11', '2013-10', '2013-09', '2013-08', '2013-07'], freq='M', name='period2') - idx = pd.MultiIndex.from_arrays([idx1, idx2]) + idx = MultiIndex.from_arrays([idx1, idx2]) s = Series(value, index=idx) result1 = s.unstack() @@ -1082,8 +1081,8 @@ def test_unstack_period_frame(self): '2013-10', '2014-02'], freq='M', name='period2') value = {'A': [1, 2, 3, 4, 5, 6], 'B': [6, 5, 4, 3, 2, 1]} - idx = pd.MultiIndex.from_arrays([idx1, idx2]) - df = pd.DataFrame(value, index=idx) + idx = MultiIndex.from_arrays([idx1, idx2]) + df = DataFrame(value, index=idx) result1 = df.unstack() result2 = df.unstack(level=1) @@ -1092,7 +1091,7 @@ def test_unstack_period_frame(self): e_1 = pd.PeriodIndex(['2014-01', '2014-02'], freq='M', name='period1') e_2 = pd.PeriodIndex(['2013-10', '2013-12', '2014-02', '2013-10', '2013-12', '2014-02'], freq='M', name='period2') - e_cols = pd.MultiIndex.from_arrays(['A A A B B B'.split(), e_2]) + e_cols = MultiIndex.from_arrays(['A A A B B B'.split(), e_2]) expected = DataFrame([[5, 1, 6, 2, 6, 1], [4, 2, 3, 3, 5, 4]], index=e_1, columns=e_cols) @@ -1103,7 +1102,7 @@ def test_unstack_period_frame(self): '2014-02'], freq='M', name='period1') e_2 = pd.PeriodIndex( ['2013-10', '2013-12', '2014-02'], freq='M', name='period2') - e_cols = pd.MultiIndex.from_arrays(['A A B B'.split(), e_1]) + e_cols = MultiIndex.from_arrays(['A A B B'.split(), e_1]) expected = DataFrame([[5, 4, 2, 3], [1, 2, 6, 5], [6, 3, 1, 4]], index=e_2, columns=e_cols) @@ -1129,7 +1128,7 @@ def test_stack_multiple_bug(self): def test_stack_dropna(self): # GH #3997 - df = pd.DataFrame({'A': ['a1', 'a2'], 'B': ['b1', 'b2'], 'C': [1, 1]}) + df = DataFrame({'A': ['a1', 'a2'], 'B': ['b1', 'b2'], 'C': [1, 1]}) df = df.set_index(['A', 'B']) stacked = df.unstack().stack(dropna=False) @@ -1865,7 +1864,7 @@ def test_drop_level(self): def test_drop_level_nonunique_datetime(self): # GH 12701 - idx = pd.Index([2, 3, 4, 4, 5], name='id') + idx = Index([2, 3, 4, 4, 5], name='id') idxdt = pd.to_datetime(['201603231400', '201603231500', '201603231600', @@ -1875,7 +1874,7 @@ def test_drop_level_nonunique_datetime(self): columns=list('ab'), index=idx) df['tstamp'] = idxdt df = df.set_index('tstamp', append=True) - ts = pd.Timestamp('201603231600') + ts = Timestamp('201603231600') assert not df.index.is_unique result = df.drop(ts, level='tstamp') @@ -2119,7 +2118,7 @@ def test_datetimeindex(self): for d1, d2 in itertools.product( [date1, date2, date3], [date1, date2, date3]): - index = pd.MultiIndex.from_product([[d1], [d2]]) + index = MultiIndex.from_product([[d1], [d2]]) assert isinstance(index.levels[0], pd.DatetimeIndex) assert isinstance(index.levels[1], pd.DatetimeIndex) @@ -2140,7 +2139,7 @@ def test_constructor_with_tz(self): def test_set_index_datetime(self): # GH 3950 - df = pd.DataFrame( + df = DataFrame( {'label': ['a', 'a', 'a', 'b', 'b', 'b'], 'datetime': ['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00', '2011-07-19 07:00:00', @@ -2157,11 +2156,11 @@ def test_set_index_datetime(self): df = df.set_index('label', append=True) tm.assert_index_equal(df.index.levels[0], expected) tm.assert_index_equal(df.index.levels[1], - pd.Index(['a', 'b'], name='label')) + Index(['a', 'b'], name='label')) df = df.swaplevel(0, 1) tm.assert_index_equal(df.index.levels[0], - pd.Index(['a', 'b'], name='label')) + Index(['a', 'b'], name='label')) tm.assert_index_equal(df.index.levels[1], expected) df = DataFrame(np.random.random(6)) @@ -2199,82 +2198,80 @@ def test_reset_index_datetime(self): for tz in ['UTC', 'Asia/Tokyo', 'US/Eastern']: idx1 = pd.date_range('1/1/2011', periods=5, freq='D', tz=tz, name='idx1') - idx2 = pd.Index(range(5), name='idx2', dtype='int64') - idx = pd.MultiIndex.from_arrays([idx1, idx2]) - df = pd.DataFrame( + idx2 = Index(range(5), name='idx2', dtype='int64') + idx = MultiIndex.from_arrays([idx1, idx2]) + df = DataFrame( {'a': np.arange(5, dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) - expected = pd.DataFrame({'idx1': [datetime.datetime(2011, 1, 1), - datetime.datetime(2011, 1, 2), - datetime.datetime(2011, 1, 3), - datetime.datetime(2011, 1, 4), - datetime.datetime(2011, 1, 5)], - 'idx2': np.arange(5, dtype='int64'), - 'a': np.arange(5, dtype='int64'), - 'b': ['A', 'B', 'C', 'D', 'E']}, - columns=['idx1', 'idx2', 'a', 'b']) + expected = DataFrame({'idx1': [datetime.datetime(2011, 1, 1), + datetime.datetime(2011, 1, 2), + datetime.datetime(2011, 1, 3), + datetime.datetime(2011, 1, 4), + datetime.datetime(2011, 1, 5)], + 'idx2': np.arange(5, dtype='int64'), + 'a': np.arange(5, dtype='int64'), + 'b': ['A', 'B', 'C', 'D', 'E']}, + columns=['idx1', 'idx2', 'a', 'b']) expected['idx1'] = expected['idx1'].apply( - lambda d: pd.Timestamp(d, tz=tz)) + lambda d: Timestamp(d, tz=tz)) tm.assert_frame_equal(df.reset_index(), expected) idx3 = pd.date_range('1/1/2012', periods=5, freq='MS', tz='Europe/Paris', name='idx3') - idx = pd.MultiIndex.from_arrays([idx1, idx2, idx3]) - df = pd.DataFrame( + idx = MultiIndex.from_arrays([idx1, idx2, idx3]) + df = DataFrame( {'a': np.arange(5, dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx) - expected = pd.DataFrame({'idx1': [datetime.datetime(2011, 1, 1), - datetime.datetime(2011, 1, 2), - datetime.datetime(2011, 1, 3), - datetime.datetime(2011, 1, 4), - datetime.datetime(2011, 1, 5)], - 'idx2': np.arange(5, dtype='int64'), - 'idx3': [datetime.datetime(2012, 1, 1), - datetime.datetime(2012, 2, 1), - datetime.datetime(2012, 3, 1), - datetime.datetime(2012, 4, 1), - datetime.datetime(2012, 5, 1)], - 'a': np.arange(5, dtype='int64'), - 'b': ['A', 'B', 'C', 'D', 'E']}, - columns=['idx1', 'idx2', 'idx3', 'a', 'b']) + expected = DataFrame({'idx1': [datetime.datetime(2011, 1, 1), + datetime.datetime(2011, 1, 2), + datetime.datetime(2011, 1, 3), + datetime.datetime(2011, 1, 4), + datetime.datetime(2011, 1, 5)], + 'idx2': np.arange(5, dtype='int64'), + 'idx3': [datetime.datetime(2012, 1, 1), + datetime.datetime(2012, 2, 1), + datetime.datetime(2012, 3, 1), + datetime.datetime(2012, 4, 1), + datetime.datetime(2012, 5, 1)], + 'a': np.arange(5, dtype='int64'), + 'b': ['A', 'B', 'C', 'D', 'E']}, + columns=['idx1', 'idx2', 'idx3', 'a', 'b']) expected['idx1'] = expected['idx1'].apply( - lambda d: pd.Timestamp(d, tz=tz)) + lambda d: Timestamp(d, tz=tz)) expected['idx3'] = expected['idx3'].apply( - lambda d: pd.Timestamp(d, tz='Europe/Paris')) + lambda d: Timestamp(d, tz='Europe/Paris')) tm.assert_frame_equal(df.reset_index(), expected) # GH 7793 - idx = pd.MultiIndex.from_product([['a', 'b'], pd.date_range( + idx = MultiIndex.from_product([['a', 'b'], pd.date_range( '20130101', periods=3, tz=tz)]) - df = pd.DataFrame( + df = DataFrame( np.arange(6, dtype='int64').reshape( 6, 1), columns=['a'], index=idx) - expected = pd.DataFrame({'level_0': 'a a a b b b'.split(), - 'level_1': [ - datetime.datetime(2013, 1, 1), - datetime.datetime(2013, 1, 2), - datetime.datetime(2013, 1, 3)] * 2, - 'a': np.arange(6, dtype='int64')}, - columns=['level_0', 'level_1', 'a']) + expected = DataFrame({'level_0': 'a a a b b b'.split(), + 'level_1': [ + datetime.datetime(2013, 1, 1), + datetime.datetime(2013, 1, 2), + datetime.datetime(2013, 1, 3)] * 2, + 'a': np.arange(6, dtype='int64')}, + columns=['level_0', 'level_1', 'a']) expected['level_1'] = expected['level_1'].apply( - lambda d: pd.Timestamp(d, freq='D', tz=tz)) + lambda d: Timestamp(d, freq='D', tz=tz)) tm.assert_frame_equal(df.reset_index(), expected) def test_reset_index_period(self): # GH 7746 - idx = pd.MultiIndex.from_product([pd.period_range('20130101', - periods=3, freq='M'), - ['a', 'b', 'c']], - names=['month', 'feature']) - - df = pd.DataFrame(np.arange(9, dtype='int64') - .reshape(-1, 1), - index=idx, columns=['a']) - expected = pd.DataFrame({ + idx = MultiIndex.from_product( + [pd.period_range('20130101', periods=3, freq='M'), list('abc')], + names=['month', 'feature']) + + df = DataFrame(np.arange(9, dtype='int64').reshape(-1, 1), + index=idx, columns=['a']) + expected = DataFrame({ 'month': ([pd.Period('2013-01', freq='M')] * 3 + [pd.Period('2013-02', freq='M')] * 3 + [pd.Period('2013-03', freq='M')] * 3), @@ -2285,8 +2282,8 @@ def test_reset_index_period(self): def test_reset_index_multiindex_columns(self): levels = [['A', ''], ['B', 'b']] - df = pd.DataFrame([[0, 2], [1, 3]], - columns=pd.MultiIndex.from_tuples(levels)) + df = DataFrame([[0, 2], [1, 3]], + columns=MultiIndex.from_tuples(levels)) result = df[['B']].rename_axis('A').reset_index() tm.assert_frame_equal(result, df) @@ -2301,9 +2298,8 @@ def test_reset_index_multiindex_columns(self): tm.assert_frame_equal(result, df) # with additional (unnamed) index level - idx_col = pd.DataFrame([[0], [1]], - columns=pd.MultiIndex.from_tuples([('level_0', - '')])) + idx_col = DataFrame([[0], [1]], + columns=MultiIndex.from_tuples([('level_0', '')])) expected = pd.concat([idx_col, df[[('B', 'b'), ('A', '')]]], axis=1) result = df.set_index([('B', 'b')], append=True).reset_index() tm.assert_frame_equal(result, expected) @@ -2316,12 +2312,10 @@ def test_reset_index_multiindex_columns(self): # or too short... levels = [['A', 'a', ''], ['B', 'b', 'i']] - df2 = pd.DataFrame([[0, 2], [1, 3]], - columns=pd.MultiIndex.from_tuples(levels)) - idx_col = pd.DataFrame([[0], [1]], - columns=pd.MultiIndex.from_tuples([('C', - 'c', - 'ii')])) + df2 = DataFrame([[0, 2], [1, 3]], + columns=MultiIndex.from_tuples(levels)) + idx_col = DataFrame([[0], [1]], + columns=MultiIndex.from_tuples([('C', 'c', 'ii')])) expected = pd.concat([idx_col, df2], axis=1) result = df2.rename_axis([('C', 'c')]).reset_index(col_fill='ii') tm.assert_frame_equal(result, expected) @@ -2364,36 +2358,26 @@ def test_set_index_period(self): def test_repeat(self): # GH 9361 # fixed by # GH 7891 - m_idx = pd.MultiIndex.from_tuples([(1, 2), (3, 4), (5, 6), (7, 8)]) + m_idx = MultiIndex.from_tuples([(1, 2), (3, 4), (5, 6), (7, 8)]) data = ['a', 'b', 'c', 'd'] - m_df = pd.Series(data, index=m_idx) + m_df = Series(data, index=m_idx) assert m_df.repeat(3).shape == (3 * len(data), ) def test_iloc_mi(self): # GH 13797 # Test if iloc can handle integer locations in MultiIndexed DataFrame - data = [ - ['str00', 'str01'], - ['str10', 'str11'], - ['str20', 'srt21'], - ['str30', 'str31'], - ['str40', 'str41'] - ] + data = [['str00', 'str01'], ['str10', 'str11'], ['str20', 'srt21'], + ['str30', 'str31'], ['str40', 'str41']] - mi = pd.MultiIndex.from_tuples( - [('CC', 'A'), - ('CC', 'B'), - ('CC', 'B'), - ('BB', 'a'), - ('BB', 'b') - ]) + mi = MultiIndex.from_tuples( + [('CC', 'A'), ('CC', 'B'), ('CC', 'B'), ('BB', 'a'), ('BB', 'b')]) - expected = pd.DataFrame(data) - df_mi = pd.DataFrame(data, index=mi) + expected = DataFrame(data) + df_mi = DataFrame(data, index=mi) - result = pd.DataFrame([[df_mi.iloc[r, c] for c in range(2)] - for r in range(5)]) + result = DataFrame([[df_mi.iloc[r, c] for c in range(2)] + for r in range(5)]) tm.assert_frame_equal(result, expected) @@ -2691,12 +2675,10 @@ def test_sort_index_and_reconstruction_doc_example(self): def test_sort_index_reorder_on_ops(self): # 15687 - df = pd.DataFrame( + df = DataFrame( np.random.randn(8, 2), index=MultiIndex.from_product( - [['a', 'b'], - ['big', 'small'], - ['red', 'blu']], + [['a', 'b'], ['big', 'small'], ['red', 'blu']], names=['letter', 'size', 'color']), columns=['near', 'far']) df = df.sort_index() @@ -2708,9 +2690,7 @@ def my_func(group): result = df.groupby(level=['letter', 'size']).apply( my_func).sort_index() expected = MultiIndex.from_product( - [['a', 'b'], - ['big', 'small'], - ['newa', 'newz']], + [['a', 'b'], ['big', 'small'], ['newa', 'newz']], names=['letter', 'size', None]) tm.assert_index_equal(result.index, expected) @@ -2806,10 +2786,9 @@ def test_sort_ascending_list(self): arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'], [4, 3, 2, 1, 4, 3, 2, 1]] - tuples = list(zip(*arrays)) - index = pd.MultiIndex.from_tuples(tuples, - names=['first', 'second', 'third']) - s = pd.Series(range(8), index=index) + tuples = lzip(*arrays) + mi = MultiIndex.from_tuples(tuples, names=['first', 'second', 'third']) + s = Series(range(8), index=mi) # Sort with boolean ascending result = s.sort_index(level=['third', 'first'], ascending=False) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 33fb6f1108bf2..42df2e26b301f 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -7,7 +7,6 @@ import pytest import numpy as np -import pandas as pd from pandas.core.dtypes.common import is_float_dtype from pandas.core.dtypes.missing import remove_na_arraylike @@ -367,7 +366,7 @@ def test_raise_when_not_implemented(self): with catch_warnings(record=True): p = Panel(np.arange(3 * 4 * 5).reshape(3, 4, 5), items=['ItemA', 'ItemB', 'ItemC'], - major_axis=pd.date_range('20130101', periods=4), + major_axis=date_range('20130101', periods=4), minor_axis=list('ABCDE')) d = p.sum(axis=1).iloc[0] ops = ['add', 'sub', 'mul', 'truediv', @@ -2112,10 +2111,10 @@ def test_round(self): evalues = [[[float(np.around(i)) for i in j] for j in k] for k in values] p = Panel(values, items=['Item1', 'Item2'], - major_axis=pd.date_range('1/1/2000', periods=5), + major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B']) expected = Panel(evalues, items=['Item1', 'Item2'], - major_axis=pd.date_range('1/1/2000', periods=5), + major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B']) result = p.round() assert_panel_equal(expected, result) @@ -2129,10 +2128,10 @@ def test_numpy_round(self): evalues = [[[float(np.around(i)) for i in j] for j in k] for k in values] p = Panel(values, items=['Item1', 'Item2'], - major_axis=pd.date_range('1/1/2000', periods=5), + major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B']) expected = Panel(evalues, items=['Item1', 'Item2'], - major_axis=pd.date_range('1/1/2000', periods=5), + major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B']) result = np.round(p) assert_panel_equal(expected, result) diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 61b2b689bffd6..5f8c69a8152ac 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -150,7 +150,7 @@ def f(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert isinstance(getattr(r, op)(2), pd.Series) + assert isinstance(getattr(r, op)(2), Series) # unary numeric ops for op in ['__pos__', '__neg__', '__abs__', '__inv__']: @@ -161,7 +161,7 @@ def f(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert isinstance(getattr(r, op)(), pd.Series) + assert isinstance(getattr(r, op)(), Series) # comparison ops for op in ['__lt__', '__le__', '__gt__', '__ge__', '__eq__', '__ne__']: @@ -169,7 +169,7 @@ def f(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert isinstance(getattr(r, op)(2), pd.Series) + assert isinstance(getattr(r, op)(2), Series) # IPython introspection shouldn't trigger warning GH 13618 for op in ['_repr_json', '_repr_latex', @@ -225,9 +225,9 @@ def test_groupby_resample_on_api(self): # GH 15021 # .groupby(...).resample(on=...) results in an unexpected # keyword warning. - df = pd.DataFrame({'key': ['A', 'B'] * 5, - 'dates': pd.date_range('2016-01-01', periods=10), - 'values': np.random.randn(10)}) + df = DataFrame({'key': ['A', 'B'] * 5, + 'dates': pd.date_range('2016-01-01', periods=10), + 'values': np.random.randn(10)}) expected = df.set_index('dates').groupby('key').resample('D').mean() @@ -300,7 +300,7 @@ def test_api_compat_before_use(self): # on these attributes for attr in ['groups', 'ngroups', 'indices']: rng = pd.date_range('1/1/2012', periods=100, freq='S') - ts = pd.Series(np.arange(len(rng)), index=rng) + ts = Series(np.arange(len(rng)), index=rng) rs = ts.resample('30s') # before use @@ -327,7 +327,7 @@ def test_downsample_but_actually_upsampling(self): # this is reindex / asfreq rng = pd.date_range('1/1/2012', periods=100, freq='S') - ts = pd.Series(np.arange(len(rng), dtype='int64'), index=rng) + ts = Series(np.arange(len(rng), dtype='int64'), index=rng) result = ts.resample('20s').asfreq() expected = Series([0, 20, 40, 60, 80], index=pd.date_range('2012-01-01 00:00:00', @@ -342,7 +342,7 @@ def test_combined_up_downsampling_of_irregular(self): # preserve these semantics rng = pd.date_range('1/1/2012', periods=100, freq='S') - ts = pd.Series(np.arange(len(rng)), index=rng) + ts = Series(np.arange(len(rng)), index=rng) ts2 = ts.iloc[[0, 1, 2, 3, 5, 7, 11, 15, 16, 25, 30]] with tm.assert_produces_warning(FutureWarning, @@ -363,7 +363,7 @@ def test_fillna(self): # need to upsample here rng = pd.date_range('1/1/2012', periods=10, freq='2S') - ts = pd.Series(np.arange(len(rng), dtype='int64'), index=rng) + ts = Series(np.arange(len(rng), dtype='int64'), index=rng) r = ts.resample('s') expected = r.ffill() @@ -412,9 +412,7 @@ def test_agg(self): index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq='D') index.name = 'date' - df = pd.DataFrame(np.random.rand(10, 2), - columns=list('AB'), - index=index) + df = DataFrame(np.random.rand(10, 2), columns=list('AB'), index=index) df_col = df.reset_index() df_mult = df_col.copy() df_mult.index = pd.MultiIndex.from_arrays([range(10), df.index], @@ -504,9 +502,7 @@ def test_agg_misc(self): index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq='D') index.name = 'date' - df = pd.DataFrame(np.random.rand(10, 2), - columns=list('AB'), - index=index) + df = DataFrame(np.random.rand(10, 2), columns=list('AB'), index=index) df_col = df.reset_index() df_mult = df_col.copy() df_mult.index = pd.MultiIndex.from_arrays([range(10), df.index], @@ -609,9 +605,7 @@ def test_agg_nested_dicts(self): index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq='D') index.name = 'date' - df = pd.DataFrame(np.random.rand(10, 2), - columns=list('AB'), - index=index) + df = DataFrame(np.random.rand(10, 2), columns=list('AB'), index=index) df_col = df.reset_index() df_mult = df_col.copy() df_mult.index = pd.MultiIndex.from_arrays([range(10), df.index], @@ -652,13 +646,12 @@ def test_selection_api_validation(self): # GH 13500 index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq='D') - df = pd.DataFrame({'date': index, - 'a': np.arange(len(index), dtype=np.int64)}, - index=pd.MultiIndex.from_arrays([ - np.arange(len(index), dtype=np.int64), - index], names=['v', 'd'])) - df_exp = pd.DataFrame({'a': np.arange(len(index), dtype=np.int64)}, - index=index) + + rng = np.arange(len(index), dtype=np.int64) + df = DataFrame({'date': index, 'a': rng}, + index=pd.MultiIndex.from_arrays([rng, index], + names=['v', 'd'])) + df_exp = DataFrame({'a': rng}, index=index) # non DatetimeIndex with pytest.raises(TypeError): @@ -831,7 +824,7 @@ def test_resample_empty_dtypes(self): for index in tm.all_timeseries_index_generator(0): for dtype in (np.float, np.int, np.object, 'datetime64[ns]'): for how in downsample_methods + upsample_methods: - empty_series = pd.Series([], index, dtype) + empty_series = Series([], index, dtype) try: getattr(empty_series.resample('d'), how)() except DataError: @@ -1036,7 +1029,7 @@ def test_resample_how_callables(self): # GH 7929 data = np.arange(5, dtype=np.int64) ind = pd.DatetimeIndex(start='2014-01-01', periods=len(data), freq='d') - df = pd.DataFrame({"A": data, "B": data}, index=ind) + df = DataFrame({"A": data, "B": data}, index=ind) def fn(x, a=1): return str(type(x)) @@ -1086,7 +1079,7 @@ def test_resample_timedelta_idempotency(self): # GH 12072 index = pd.timedelta_range('0', periods=9, freq='10L') - series = pd.Series(range(9), index=index) + series = Series(range(9), index=index) result = series.resample('10L').mean() expected = series assert_series_equal(result, expected) @@ -1298,7 +1291,7 @@ def test_resample_loffset_count(self): date_range(start_time, periods=10, freq='10S') + timedelta(seconds=1) ) - expected = pd.Series(10, index=expected_index) + expected = Series(10, index=expected_index) assert_series_equal(result, expected) @@ -1325,17 +1318,17 @@ def test_resample_upsample(self): def test_resample_how_method(self): # GH9915 - s = pd.Series([11, 22], - index=[Timestamp('2015-03-31 21:48:52.672000'), - Timestamp('2015-03-31 21:49:52.739000')]) - expected = pd.Series([11, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, 22], - index=[Timestamp('2015-03-31 21:48:50'), - Timestamp('2015-03-31 21:49:00'), - Timestamp('2015-03-31 21:49:10'), - Timestamp('2015-03-31 21:49:20'), - Timestamp('2015-03-31 21:49:30'), - Timestamp('2015-03-31 21:49:40'), - Timestamp('2015-03-31 21:49:50')]) + s = Series([11, 22], + index=[Timestamp('2015-03-31 21:48:52.672000'), + Timestamp('2015-03-31 21:49:52.739000')]) + expected = Series([11, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, 22], + index=[Timestamp('2015-03-31 21:48:50'), + Timestamp('2015-03-31 21:49:00'), + Timestamp('2015-03-31 21:49:10'), + Timestamp('2015-03-31 21:49:20'), + Timestamp('2015-03-31 21:49:30'), + Timestamp('2015-03-31 21:49:40'), + Timestamp('2015-03-31 21:49:50')]) assert_series_equal(s.resample("10S").mean(), expected) def test_resample_extra_index_point(self): @@ -1414,7 +1407,7 @@ def test_resample_ohlc_result(self): def test_resample_ohlc_dataframe(self): df = ( - pd.DataFrame({ + DataFrame({ 'PRICE': { Timestamp('2011-01-06 10:59:05', tz=None): 24990, Timestamp('2011-01-06 12:43:33', tz=None): 25499, @@ -1678,11 +1671,9 @@ def test_resample_to_period_monthly_buglet(self): def test_period_with_agg(self): # aggregate a period resampler with a lambda - s2 = pd.Series(np.random.randint(0, 5, 50), - index=pd.period_range('2012-01-01', - freq='H', - periods=50), - dtype='float64') + s2 = Series(np.random.randint(0, 5, 50), + index=pd.period_range('2012-01-01', freq='H', periods=50), + dtype='float64') expected = s2.to_timestamp().resample('D').mean().to_period() result = s2.resample('D').agg(lambda x: x.mean()) @@ -1697,9 +1688,9 @@ def test_resample_segfault(self): (2, datetime(2013, 10, 1, 18, 15), 1, 0), (2, datetime(2013, 10, 1, 16, 10, 31), 1, 0)] - df = pd.DataFrame.from_records(all_wins_and_wagers, - columns=("ID", "timestamp", "A", "B") - ).set_index("timestamp") + df = DataFrame.from_records(all_wins_and_wagers, + columns=("ID", "timestamp", "A", "B") + ).set_index("timestamp") result = df.groupby("ID").resample("5min").sum() expected = df.groupby("ID").apply(lambda x: x.resample("5min").sum()) assert_frame_equal(result, expected) @@ -1728,8 +1719,7 @@ def test_resample_dtype_coerceion(self): # GH 16361 df = {"a": [1, 3, 1, 4]} - df = pd.DataFrame( - df, index=pd.date_range("2017-01-01", "2017-01-04")) + df = DataFrame(df, index=pd.date_range("2017-01-01", "2017-01-04")) expected = (df.astype("float64") .resample("H") @@ -1770,7 +1760,7 @@ def test_nanosecond_resample_error(self): periods=10, freq='100n' ) - ts = pd.Series(range(len(indx)), index=indx) + ts = Series(range(len(indx)), index=indx) r = ts.resample(pd.tseries.offsets.Nano(100)) result = r.agg('mean') @@ -1779,7 +1769,7 @@ def test_nanosecond_resample_error(self): periods=10, freq='100n' ) - exp = pd.Series(range(len(exp_indx)), index=exp_indx) + exp = Series(range(len(exp_indx)), index=exp_indx) assert_series_equal(result, exp) @@ -1838,15 +1828,15 @@ def test_resample_anchored_multiday(self): ) | pd.date_range( '2014-10-15 23:00:00', periods=2, freq='2200L') - s = pd.Series(np.random.randn(5), index=index) + s = Series(np.random.randn(5), index=index) # Ensure left closing works result = s.resample('2200L').mean() - assert result.index[-1] == pd.Timestamp('2014-10-15 23:00:02.000') + assert result.index[-1] == Timestamp('2014-10-15 23:00:02.000') # Ensure right closing works result = s.resample('2200L', label='right').mean() - assert result.index[-1] == pd.Timestamp('2014-10-15 23:00:04.200') + assert result.index[-1] == Timestamp('2014-10-15 23:00:04.200') def test_corner_cases(self): # miscellaneous test coverage @@ -1952,7 +1942,7 @@ def test_resample_consistency(self): # resample with bfill / limit / reindex consistency i30 = pd.date_range('2002-02-02', periods=4, freq='30T') - s = pd.Series(np.arange(4.), index=i30) + s = Series(np.arange(4.), index=i30) s[2] = np.NaN # Upsample by factor 3 with reindex() and resample() methods: @@ -2005,10 +1995,10 @@ def test_resample_nunique(self): # GH 12352 df = DataFrame({ - 'ID': {pd.Timestamp('2015-06-05 00:00:00'): '0010100903', - pd.Timestamp('2015-06-08 00:00:00'): '0010150847'}, - 'DATE': {pd.Timestamp('2015-06-05 00:00:00'): '2015-06-05', - pd.Timestamp('2015-06-08 00:00:00'): '2015-06-08'}}) + 'ID': {Timestamp('2015-06-05 00:00:00'): '0010100903', + Timestamp('2015-06-08 00:00:00'): '0010150847'}, + 'DATE': {Timestamp('2015-06-05 00:00:00'): '2015-06-05', + Timestamp('2015-06-08 00:00:00'): '2015-06-08'}}) r = df.resample('D') g = df.groupby(pd.Grouper(freq='D')) expected = df.groupby(pd.Grouper(freq='D')).ID.apply(lambda x: @@ -2030,14 +2020,14 @@ def test_resample_nunique_with_date_gap(self): index = pd.date_range('1-1-2000', '2-15-2000', freq='h') index2 = pd.date_range('4-15-2000', '5-15-2000', freq='h') index3 = index.append(index2) - s = pd.Series(range(len(index3)), index=index3, dtype='int64') + s = Series(range(len(index3)), index=index3, dtype='int64') r = s.resample('M') # Since all elements are unique, these should all be the same results = [ r.count(), r.nunique(), - r.agg(pd.Series.nunique), + r.agg(Series.nunique), r.agg('nunique') ] @@ -2296,11 +2286,10 @@ def test_asfreq_fill_value(self): def test_selection(self, index, freq, kind): # This is a bug, these should be implemented # GH 14008 - df = pd.DataFrame({'date': index, - 'a': np.arange(len(index), dtype=np.int64)}, - index=pd.MultiIndex.from_arrays([ - np.arange(len(index), dtype=np.int64), - index], names=['v', 'd'])) + rng = np.arange(len(index), dtype=np.int64) + df = DataFrame({'date': index, 'a': rng}, + index=pd.MultiIndex.from_arrays([rng, index], + names=['v', 'd'])) with pytest.raises(NotImplementedError): df.resample(freq, on='date', kind=kind) with pytest.raises(NotImplementedError): @@ -2448,17 +2437,17 @@ def test_resample_basic(self): ('2M', [31 + 29, 31 + 9])]) def test_resample_count(self, freq, expected_vals): # GH12774 - series = pd.Series(1, index=pd.period_range(start='2000', periods=100)) + series = Series(1, index=pd.period_range(start='2000', periods=100)) result = series.resample(freq).count() expected_index = pd.period_range(start='2000', freq=freq, periods=len(expected_vals)) - expected = pd.Series(expected_vals, index=expected_index) + expected = Series(expected_vals, index=expected_index) assert_series_equal(result, expected) def test_resample_same_freq(self): # GH12770 - series = pd.Series(range(3), index=pd.period_range( + series = Series(range(3), index=pd.period_range( start='2000', periods=3, freq='M')) expected = series @@ -2469,7 +2458,7 @@ def test_resample_same_freq(self): def test_resample_incompat_freq(self): with pytest.raises(IncompatibleFrequency): - pd.Series(range(3), index=pd.period_range( + Series(range(3), index=pd.period_range( start='2000', periods=3, freq='M')).resample('W').mean() def test_with_local_timezone_pytz(self): @@ -2484,7 +2473,7 @@ def test_with_local_timezone_pytz(self): index = pd.date_range(start, end, freq='H') - series = pd.Series(1, index=index) + series = Series(1, index=index) series = series.tz_convert(local_timezone) result = series.resample('D', kind='period').mean() @@ -2492,7 +2481,7 @@ def test_with_local_timezone_pytz(self): # Index is moved back a day with the timezone conversion from UTC to # Pacific expected_index = (pd.period_range(start=start, end=end, freq='D') - 1) - expected = pd.Series(1, index=expected_index) + expected = Series(1, index=expected_index) assert_series_equal(result, expected) def test_with_local_timezone_dateutil(self): @@ -2507,7 +2496,7 @@ def test_with_local_timezone_dateutil(self): index = pd.date_range(start, end, freq='H', name='idx') - series = pd.Series(1, index=index) + series = Series(1, index=index) series = series.tz_convert(local_timezone) result = series.resample('D', kind='period').mean() @@ -2516,7 +2505,7 @@ def test_with_local_timezone_dateutil(self): # Pacific expected_index = (pd.period_range(start=start, end=end, freq='D', name='idx') - 1) - expected = pd.Series(1, index=expected_index) + expected = Series(1, index=expected_index) assert_series_equal(result, expected) def test_fill_method_and_how_upsample(self): @@ -2732,7 +2721,7 @@ def test_resample_weekly_bug_1726(self): def test_resample_bms_2752(self): # GH2753 - foo = pd.Series(index=pd.bdate_range('20000101', '20000201')) + foo = Series(index=pd.bdate_range('20000101', '20000201')) res1 = foo.resample("BMS").mean() res2 = foo.resample("BMS").mean().resample("B").mean() assert res1.index[0] == Timestamp('20000103') @@ -3012,15 +3001,15 @@ def test_getitem_multiple(self): # GH 13174 # multiple calls after selection causing an issue with aliasing data = [{'id': 1, 'buyer': 'A'}, {'id': 2, 'buyer': 'B'}] - df = pd.DataFrame(data, index=pd.date_range('2016-01-01', periods=2)) + df = DataFrame(data, index=pd.date_range('2016-01-01', periods=2)) r = df.groupby('id').resample('1D') result = r['buyer'].count() - expected = pd.Series([1, 1], - index=pd.MultiIndex.from_tuples( - [(1, pd.Timestamp('2016-01-01')), - (2, pd.Timestamp('2016-01-02'))], - names=['id', None]), - name='buyer') + expected = Series([1, 1], + index=pd.MultiIndex.from_tuples( + [(1, Timestamp('2016-01-01')), + (2, Timestamp('2016-01-02'))], + names=['id', None]), + name='buyer') assert_series_equal(result, expected) result = r['buyer'].count() @@ -3031,9 +3020,9 @@ def test_nearest(self): # GH 17496 # Resample nearest index = pd.date_range('1/1/2000', periods=3, freq='T') - result = pd.Series(range(3), index=index).resample('20s').nearest() + result = Series(range(3), index=index).resample('20s').nearest() - expected = pd.Series( + expected = Series( [0, 0, 1, 1, 1, 2, 2], index=pd.DatetimeIndex( ['2000-01-01 00:00:00', '2000-01-01 00:00:20', @@ -3107,11 +3096,10 @@ def f(x): def test_apply_with_mutated_index(self): # GH 15169 index = pd.date_range('1-1-2015', '12-31-15', freq='D') - df = pd.DataFrame(data={'col1': np.random.rand(len(index))}, - index=index) + df = DataFrame(data={'col1': np.random.rand(len(index))}, index=index) def f(x): - s = pd.Series([1, 2], index=['a', 'b']) + s = Series([1, 2], index=['a', 'b']) return s expected = df.groupby(pd.Grouper(freq='M')).apply(f) @@ -3160,10 +3148,9 @@ def test_consistency_with_window(self): def test_median_duplicate_columns(self): # GH 14233 - df = pd.DataFrame(np.random.randn(20, 3), - columns=list('aaa'), - index=pd.date_range('2012-01-01', - periods=20, freq='s')) + df = DataFrame(np.random.randn(20, 3), + columns=list('aaa'), + index=pd.date_range('2012-01-01', periods=20, freq='s')) df2 = df.copy() df2.columns = ['a', 'b', 'c'] expected = df2.resample('5s').median() diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py index 06c1fa1c0905a..57bd5e7b62fdf 100644 --- a/pandas/tests/test_sorting.py +++ b/pandas/tests/test_sorting.py @@ -6,9 +6,9 @@ import numpy as np from numpy import nan -import pandas as pd from pandas.core import common as com -from pandas import DataFrame, MultiIndex, merge, concat, Series, compat +from pandas import (DataFrame, MultiIndex, merge, concat, Series, compat, + _np_version_under1p10) from pandas.util import testing as tm from pandas.util.testing import assert_frame_equal, assert_series_equal from pandas.core.sorting import (is_int64_overflow_possible, @@ -63,10 +63,8 @@ def test_int64_overflow_moar(self): # GH9096 values = range(55109) - data = pd.DataFrame.from_dict({'a': values, - 'b': values, - 'c': values, - 'd': values}) + data = DataFrame.from_dict( + {'a': values, 'b': values, 'c': values, 'd': values}) grouped = data.groupby(['a', 'b', 'c', 'd']) assert len(grouped) == len(values) @@ -418,7 +416,7 @@ def test_mixed_integer_from_list(self): def test_unsortable(self): # GH 13714 arr = np.array([1, 2, datetime.now(), 0, 3], dtype=object) - if compat.PY2 and not pd._np_version_under1p10: + if compat.PY2 and not _np_version_under1p10: # RuntimeWarning: tp_compare didn't return -1 or -2 for exception with warnings.catch_warnings(): pytest.raises(TypeError, safe_sort, arr) diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 165813a89b5db..742b8a5ac9a55 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -97,7 +97,7 @@ def tests_skip_nuisance(self): columns=list('AB')) tm.assert_frame_equal(result, expected) - expected = pd.concat([r[['A', 'B']].sum(), df[['C']]], axis=1) + expected = concat([r[['A', 'B']].sum(), df[['C']]], axis=1) result = r.sum() tm.assert_frame_equal(result, expected, check_like=True) @@ -113,30 +113,30 @@ def test_agg(self): b_sum = r['B'].sum() result = r.aggregate([np.mean, np.std]) - expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) + expected = concat([a_mean, a_std, b_mean, b_std], axis=1) expected.columns = pd.MultiIndex.from_product([['A', 'B'], ['mean', 'std']]) tm.assert_frame_equal(result, expected) result = r.aggregate({'A': np.mean, 'B': np.std}) - expected = pd.concat([a_mean, b_std], axis=1) + expected = concat([a_mean, b_std], axis=1) tm.assert_frame_equal(result, expected, check_like=True) result = r.aggregate({'A': ['mean', 'std']}) - expected = pd.concat([a_mean, a_std], axis=1) + expected = concat([a_mean, a_std], axis=1) expected.columns = pd.MultiIndex.from_tuples([('A', 'mean'), ('A', 'std')]) tm.assert_frame_equal(result, expected) result = r['A'].aggregate(['mean', 'sum']) - expected = pd.concat([a_mean, a_sum], axis=1) + expected = concat([a_mean, a_sum], axis=1) expected.columns = ['mean', 'sum'] tm.assert_frame_equal(result, expected) with catch_warnings(record=True): result = r.aggregate({'A': {'mean': 'mean', 'sum': 'sum'}}) - expected = pd.concat([a_mean, a_sum], axis=1) + expected = concat([a_mean, a_sum], axis=1) expected.columns = pd.MultiIndex.from_tuples([('A', 'mean'), ('A', 'sum')]) tm.assert_frame_equal(result, expected, check_like=True) @@ -146,13 +146,13 @@ def test_agg(self): 'sum': 'sum'}, 'B': {'mean2': 'mean', 'sum2': 'sum'}}) - expected = pd.concat([a_mean, a_sum, b_mean, b_sum], axis=1) + expected = concat([a_mean, a_sum, b_mean, b_sum], axis=1) exp_cols = [('A', 'mean'), ('A', 'sum'), ('B', 'mean2'), ('B', 'sum2')] expected.columns = pd.MultiIndex.from_tuples(exp_cols) tm.assert_frame_equal(result, expected, check_like=True) result = r.aggregate({'A': ['mean', 'std'], 'B': ['mean', 'std']}) - expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) + expected = concat([a_mean, a_std, b_mean, b_std], axis=1) exp_cols = [('A', 'mean'), ('A', 'std'), ('B', 'mean'), ('B', 'std')] expected.columns = pd.MultiIndex.from_tuples(exp_cols) @@ -161,7 +161,7 @@ def test_agg(self): # passed lambda result = r.agg({'A': np.sum, 'B': lambda x: np.std(x, ddof=1)}) rcustom = r['B'].apply(lambda x: np.std(x, ddof=1)) - expected = pd.concat([a_sum, rcustom], axis=1) + expected = concat([a_sum, rcustom], axis=1) tm.assert_frame_equal(result, expected, check_like=True) def test_agg_consistency(self): @@ -193,8 +193,8 @@ def f(): pytest.raises(SpecificationError, f) - expected = pd.concat([r['A'].mean(), r['A'].std(), r['B'].mean(), - r['B'].std()], axis=1) + expected = concat([r['A'].mean(), r['A'].std(), + r['B'].mean(), r['B'].std()], axis=1) expected.columns = pd.MultiIndex.from_tuples([('ra', 'mean'), ( 'ra', 'std'), ('rb', 'mean'), ('rb', 'std')]) with catch_warnings(record=True): @@ -225,8 +225,8 @@ def test_count_nonnumeric_types(self): 'fl_inf': [1., 2., np.Inf], 'fl_nan': [1., 2., np.NaN], 'str_nan': ['aa', 'bb', np.NaN], - 'dt_nat': [pd.Timestamp('20170101'), pd.Timestamp('20170203'), - pd.Timestamp(None)], + 'dt_nat': [Timestamp('20170101'), Timestamp('20170203'), + Timestamp(None)], 'periods_nat': [pd.Period('2012-01'), pd.Period('2012-02'), pd.Period(None)]}, columns=cols) @@ -258,7 +258,7 @@ def test_window_with_args(self): # make sure that we are aggregating window functions correctly with arg r = Series(np.random.randn(100)).rolling(window=10, min_periods=1, win_type='gaussian') - expected = pd.concat([r.mean(std=10), r.mean(std=.01)], axis=1) + expected = concat([r.mean(std=10), r.mean(std=.01)], axis=1) expected.columns = ['<lambda>', '<lambda>'] result = r.aggregate([lambda x: x.mean(std=10), lambda x: x.mean(std=.01)]) @@ -270,7 +270,7 @@ def a(x): def b(x): return x.mean(std=0.01) - expected = pd.concat([r.mean(std=10), r.mean(std=.01)], axis=1) + expected = concat([r.mean(std=10), r.mean(std=.01)], axis=1) expected.columns = ['a', 'b'] result = r.aggregate([a, b]) tm.assert_frame_equal(result, expected) @@ -288,9 +288,8 @@ def test_how_compat(self): # in prior versions, we would allow how to be used in the resample # now that its deprecated, we need to handle this in the actual # aggregation functions - s = pd.Series( - np.random.randn(20), - index=pd.date_range('1/1/2000', periods=20, freq='12H')) + s = Series(np.random.randn(20), + index=pd.date_range('1/1/2000', periods=20, freq='12H')) for how in ['min', 'max', 'median']: for op in ['mean', 'sum', 'std', 'var', 'kurt', 'skew']: @@ -408,17 +407,14 @@ def test_constructor_with_win_type(self): def test_constructor_with_timedelta_window(self): # GH 15440 n = 10 - df = pd.DataFrame({'value': np.arange(n)}, - index=pd.date_range('2015-12-24', - periods=n, - freq="D")) + df = DataFrame({'value': np.arange(n)}, + index=pd.date_range('2015-12-24', periods=n, freq="D")) expected_data = np.append([0., 1.], np.arange(3., 27., 3)) for window in [timedelta(days=3), pd.Timedelta(days=3)]: result = df.rolling(window=window).sum() - expected = pd.DataFrame({'value': expected_data}, - index=pd.date_range('2015-12-24', - periods=n, - freq="D")) + expected = DataFrame({'value': expected_data}, + index=pd.date_range('2015-12-24', periods=n, + freq="D")) tm.assert_frame_equal(result, expected) expected = df.rolling('3D').sum() tm.assert_frame_equal(result, expected) @@ -428,15 +424,11 @@ def test_constructor_with_timedelta_window(self): def test_constructor_with_timedelta_window_and_minperiods(self, window): # GH 15305 n = 10 - df = pd.DataFrame({'value': np.arange(n)}, - index=pd.date_range('2017-08-08', - periods=n, - freq="D")) - expected = pd.DataFrame({'value': np.append([np.NaN, 1.], - np.arange(3., 27., 3))}, - index=pd.date_range('2017-08-08', - periods=n, - freq="D")) + df = DataFrame({'value': np.arange(n)}, + index=pd.date_range('2017-08-08', periods=n, freq="D")) + expected = DataFrame( + {'value': np.append([np.NaN, 1.], np.arange(3., 27., 3))}, + index=pd.date_range('2017-08-08', periods=n, freq="D")) result_roll_sum = df.rolling(window=window, min_periods=2).sum() result_roll_generic = df.rolling(window=window, min_periods=2).apply(sum) @@ -480,7 +472,7 @@ def test_multi_index_names(self): # GH 16789, 16825 cols = pd.MultiIndex.from_product([['A', 'B'], ['C', 'D', 'E']], names=['1', '2']) - df = pd.DataFrame(np.ones((10, 6)), columns=cols) + df = DataFrame(np.ones((10, 6)), columns=cols) result = df.rolling(3).cov() tm.assert_index_equal(result.columns, df.columns) @@ -1176,8 +1168,7 @@ def test_rolling_quantile_np_percentile(self): row = 10 col = 5 idx = pd.date_range('20100101', periods=row, freq='B') - df = pd.DataFrame(np.random.rand(row * col).reshape((row, -1)), - index=idx) + df = DataFrame(np.random.rand(row * col).reshape((row, -1)), index=idx) df_quantile = df.quantile([0.25, 0.5, 0.75], axis=0) np_percentile = np.percentile(df, [25, 50, 75], axis=0) @@ -1186,9 +1177,9 @@ def test_rolling_quantile_np_percentile(self): def test_rolling_quantile_series(self): # #16211: Tests that rolling window's quantile default behavior - # is analogus to pd.Series' quantile + # is analogus to Series' quantile arr = np.arange(100) - s = pd.Series(arr) + s = Series(arr) q1 = s.quantile(0.1) q2 = s.rolling(100).quantile(0.1).iloc[-1] @@ -2981,12 +2972,12 @@ def test_rolling_kurt_edge_cases(self): def test_rolling_skew_eq_value_fperr(self): # #18804 all rolling skew for all equal values should return Nan - a = pd.Series([1.1] * 15).rolling(window=10).skew() + a = Series([1.1] * 15).rolling(window=10).skew() assert np.isnan(a).all() def test_rolling_kurt_eq_value_fperr(self): # #18804 all rolling kurt for all equal values should return Nan - a = pd.Series([1.1] * 15).rolling(window=10).kurt() + a = Series([1.1] * 15).rolling(window=10).kurt() assert np.isnan(a).all() def _check_expanding_ndarray(self, func, static_comp, has_min_periods=True, @@ -3452,11 +3443,11 @@ def test_frame_on2(self): # using multiple aggregation columns df = DataFrame({'A': [0, 1, 2, 3, 4], 'B': [0, 1, 2, np.nan, 4], - 'C': pd.Index([pd.Timestamp('20130101 09:00:00'), - pd.Timestamp('20130101 09:00:02'), - pd.Timestamp('20130101 09:00:03'), - pd.Timestamp('20130101 09:00:05'), - pd.Timestamp('20130101 09:00:06')])}, + 'C': Index([Timestamp('20130101 09:00:00'), + Timestamp('20130101 09:00:02'), + Timestamp('20130101 09:00:03'), + Timestamp('20130101 09:00:05'), + Timestamp('20130101 09:00:06')])}, columns=['A', 'C', 'B']) expected1 = DataFrame({'A': [0., 1, 3, 3, 7], @@ -3517,11 +3508,11 @@ def test_closed(self): # xref GH13965 df = DataFrame({'A': [1] * 5}, - index=[pd.Timestamp('20130101 09:00:01'), - pd.Timestamp('20130101 09:00:02'), - pd.Timestamp('20130101 09:00:03'), - pd.Timestamp('20130101 09:00:04'), - pd.Timestamp('20130101 09:00:06')]) + index=[Timestamp('20130101 09:00:01'), + Timestamp('20130101 09:00:02'), + Timestamp('20130101 09:00:03'), + Timestamp('20130101 09:00:04'), + Timestamp('20130101 09:00:06')]) # closed must be 'right', 'left', 'both', 'neither' with pytest.raises(ValueError): @@ -3892,7 +3883,7 @@ def test_groupby_monotonic(self): ['Ryan', '3/31/2016', 50], ['Joe', '7/1/2015', 100], ['Joe', '9/9/2015', 500], ['Joe', '10/15/2015', 50]] - df = pd.DataFrame(data=data, columns=['name', 'date', 'amount']) + df = DataFrame(data=data, columns=['name', 'date', 'amount']) df['date'] = pd.to_datetime(df['date']) expected = df.set_index('date').groupby('name').apply( @@ -3905,9 +3896,9 @@ def test_non_monotonic(self): dates = pd.date_range(start='2016-01-01 09:30:00', periods=20, freq='s') - df = pd.DataFrame({'A': [1] * 20 + [2] * 12 + [3] * 8, - 'B': np.concatenate((dates, dates)), - 'C': np.arange(40)}) + df = DataFrame({'A': [1] * 20 + [2] * 12 + [3] * 8, + 'B': np.concatenate((dates, dates)), + 'C': np.arange(40)}) result = df.groupby('A').rolling('4s', on='B').C.mean() expected = df.set_index('B').groupby('A').apply( @@ -3922,20 +3913,17 @@ def test_rolling_cov_offset(self): # GH16058 idx = pd.date_range('2017-01-01', periods=24, freq='1h') - ss = pd.Series(np.arange(len(idx)), index=idx) + ss = Series(np.arange(len(idx)), index=idx) result = ss.rolling('2h').cov() - expected = pd.Series([np.nan] + [0.5 for _ in range(len(idx) - 1)], - index=idx) + expected = Series([np.nan] + [0.5] * (len(idx) - 1), index=idx) tm.assert_series_equal(result, expected) expected2 = ss.rolling(2, min_periods=1).cov() tm.assert_series_equal(result, expected2) result = ss.rolling('3h').cov() - expected = pd.Series([np.nan, 0.5] + - [1.0 for _ in range(len(idx) - 2)], - index=idx) + expected = Series([np.nan, 0.5] + [1.0] * (len(idx) - 2), index=idx) tm.assert_series_equal(result, expected) expected2 = ss.rolling(3, min_periods=1).cov()
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - Mostly edits along the lines of `pd.Series` -> `Series` for things that were already imported and had redundant uses of `pd`. - I cleaned some of the `import` statements, but I didn't import anything new, though that could be done in the future for further cleaning. - Was able to shorten some multi-line statements for a net deletion of ~100 lines without changing the content of any tests. - Only did the base level `tests` and `tests/indexing` so far.
https://api.github.com/repos/pandas-dev/pandas/pulls/18277
2017-11-14T05:12:50Z
2017-11-15T11:27:55Z
2017-11-15T11:27:55Z
2020-11-06T02:08:58Z
CLN: Use generators instead of lists in built-in Python functions
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index c8c5f86820b76..6a92815ef84de 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1484,7 +1484,7 @@ def get_blkno_indexers(int64_t[:] blknos, bint group=True): if len(slices) == 1: yield blkno, slice(slices[0][0], slices[0][1]) else: - tot_len = sum([stop - start for start, stop in slices]) + tot_len = sum(stop - start for start, stop in slices) result = np.empty(tot_len, dtype=np.int64) res_view = result diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 4a201d065c0b6..8a6a979ddd7c3 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -266,7 +266,7 @@ def east_asian_len(data, encoding=None, ambiguous_width=1): Calculate display width considering unicode East Asian Width """ if isinstance(data, text_type): - return sum([_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data]) + return sum(_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data) else: return len(data) @@ -318,7 +318,7 @@ def east_asian_len(data, encoding=None, ambiguous_width=1): data = data.decode(encoding) except UnicodeError: pass - return sum([_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data]) + return sum(_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data) else: return len(data) diff --git a/pandas/core/base.py b/pandas/core/base.py index 19f6728642645..90fe350848bf7 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -486,13 +486,13 @@ def _agg(arg, func): def is_any_series(): # return a boolean if we have *any* nested series - return any([isinstance(r, ABCSeries) - for r in compat.itervalues(result)]) + return any(isinstance(r, ABCSeries) + for r in compat.itervalues(result)) def is_any_frame(): # return a boolean if we have *any* nested series - return any([isinstance(r, ABCDataFrame) - for r in compat.itervalues(result)]) + return any(isinstance(r, ABCDataFrame) + for r in compat.itervalues(result)) if isinstance(result, list): return concat(result, keys=keys, axis=1), True diff --git a/pandas/core/config.py b/pandas/core/config.py index 2354b7ca04e7f..e71c3b6f58562 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -800,7 +800,7 @@ def inner(x): from pandas.io.formats.printing import pprint_thing as pp if x not in legal_values: - if not any([c(x) for c in callables]): + if not any(c(x) for c in callables): pp_values = pp("|".join(lmap(pp, legal_values))) msg = "Value must be one of {pp_values}" if len(callables): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f3137c1edf2af..4330ece124d2b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -601,7 +601,7 @@ def _repr_fits_horizontal_(self, ignore_width=False): d.to_string(buf=buf) value = buf.getvalue() - repr_width = max([len(l) for l in value.split('\n')]) + repr_width = max(len(l) for l in value.split('\n')) return repr_width < width @@ -1798,7 +1798,7 @@ def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None, def _verbose_repr(): lines.append('Data columns (total %d columns):' % len(self.columns)) - space = max([len(pprint_thing(k)) for k in self.columns]) + 4 + space = max(len(pprint_thing(k)) for k in self.columns) + 4 counts = None tmpl = "%s%s" @@ -6391,7 +6391,7 @@ def convert(arr): def _get_names_from_index(data): - has_some_name = any([getattr(s, 'name', None) is not None for s in data]) + has_some_name = any(getattr(s, 'name', None) is not None for s in data) if not has_some_name: return _default_index(len(data)) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 8b2a15e6d1666..9af4b889ac5a0 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1006,8 +1006,8 @@ def _set_axis_name(self, name, axis=0, inplace=False): # Comparisons def _indexed_same(self, other): - return all([self._get_axis(a).equals(other._get_axis(a)) - for a in self._AXIS_ORDERS]) + return all(self._get_axis(a).equals(other._get_axis(a)) + for a in self._AXIS_ORDERS) def __neg__(self): values = _values_from_object(self) @@ -2989,8 +2989,8 @@ def reindex(self, *args, **kwargs): # if all axes that are requested to reindex are equal, then only copy # if indicated must have index names equal here as well as values - if all([self._get_axis(axis).identical(ax) - for axis, ax in axes.items() if ax is not None]): + if all(self._get_axis(axis).identical(ax) + for axis, ax in axes.items() if ax is not None): if copy: return self.copy() return self @@ -5886,8 +5886,8 @@ def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None, # if we are NOT aligned, raise as we cannot where index if (axis is None and - not all([other._get_axis(i).equals(ax) - for i, ax in enumerate(self.axes)])): + not all(other._get_axis(i).equals(ax) + for i, ax in enumerate(self.axes))): raise InvalidIndexError # slice me out of the other diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 7a58b7d358fbb..8bd9b822ee62e 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -3890,8 +3890,7 @@ def first_not_none(values): # values are not series or array-like but scalars else: # only coerce dates if we find at least 1 datetime - coerce = True if any([isinstance(x, Timestamp) - for x in values]) else False + 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 @@ -4303,8 +4302,8 @@ def _reindex_output(self, result): return result elif len(groupings) == 1: return result - elif not any([isinstance(ping.grouper, (Categorical, CategoricalIndex)) - for ping in groupings]): + elif not any(isinstance(ping.grouper, (Categorical, CategoricalIndex)) + for ping in groupings): return result levels_list = [ping.group_index for ping in groupings] diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index eb96cbad70099..57454e6fce118 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -907,7 +907,7 @@ def _extend_line(s, line, value, display_width, next_line_prefix): def best_len(values): if values: - return max([adj.len(x) for x in values]) + return max(adj.len(x) for x in values) else: return 0 @@ -4246,7 +4246,7 @@ def _trim_front(strings): Trims zeros and decimal points """ trimmed = strings - while len(strings) > 0 and all([x[0] == ' ' for x in trimmed]): + while len(strings) > 0 and all(x[0] == ' ' for x in trimmed): trimmed = [x[1:] for x in trimmed] return trimmed diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index e6294f7d47aff..89a55add03f25 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -461,7 +461,7 @@ def _is_memory_usage_qualified(self): """ return a boolean if we need a qualified .info display """ def f(l): return 'mixed' in l or 'string' in l or 'unicode' in l - return any([f(l) for l in self._inferred_type_levels]) + return any(f(l) for l in self._inferred_type_levels) @Appender(Index.memory_usage.__doc__) def memory_usage(self, deep=False): @@ -489,9 +489,9 @@ def _nbytes(self, deep=False): # for implementations with no useful getsizeof (PyPy) objsize = 24 - level_nbytes = sum((i.memory_usage(deep=deep) for i in self.levels)) - label_nbytes = sum((i.nbytes for i in self.labels)) - names_nbytes = sum((getsizeof(i, objsize) for i in self.names)) + level_nbytes = sum(i.memory_usage(deep=deep) for i in self.levels) + label_nbytes = sum(i.nbytes for i in self.labels) + names_nbytes = sum(getsizeof(i, objsize) for i in self.names) result = level_nbytes + label_nbytes + names_nbytes # include our engine hashtable @@ -2214,12 +2214,12 @@ def partial_selection(key, indexer=None): # here we have a completely specified key, but are # using some partial string matching here # GH4758 - all_dates = [(l.is_all_dates and + all_dates = ((l.is_all_dates and not isinstance(k, compat.string_types)) - for k, l in zip(key, self.levels)] + for k, l in zip(key, self.levels)) can_index_exactly = any(all_dates) - if (any([l.is_all_dates - for k, l in zip(key, self.levels)]) and + if (any(l.is_all_dates + for k, l in zip(key, self.levels)) and not can_index_exactly): indexer = self.get_loc(key) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 9cb01896424f7..85a734190ff95 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -193,8 +193,8 @@ def nbytes(self): On implementations where this is undetermined (PyPy) assume 24 bytes for each value """ - return sum([getsizeof(getattr(self, v), 24) for v in - ['_start', '_stop', '_step']]) + return sum(getsizeof(getattr(self, v), 24) for v in + ['_start', '_stop', '_step']) def memory_usage(self, deep=False): """ @@ -613,8 +613,8 @@ def _evaluate_numeric_binop(self, other): # for compat with numpy / Int64Index # even if we can represent as a RangeIndex, return # as a Float64Index if we have float-like descriptors - if not all([is_integer(x) for x in - [rstart, rstop, rstep]]): + if not all(is_integer(x) for x in + [rstart, rstop, rstep]): result = result.astype('float64') return result diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index b2720078635a4..e242e928687ff 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -217,8 +217,8 @@ def _should_validate_iterable(self, axis=None): return True def _is_nested_tuple_indexer(self, tup): - if any([isinstance(ax, MultiIndex) for ax in self.obj.axes]): - return any([is_nested_tuple(tup, ax) for ax in self.obj.axes]) + if any(isinstance(ax, MultiIndex) for ax in self.obj.axes): + return any(is_nested_tuple(tup, ax) for ax in self.obj.axes) return False def _convert_tuple(self, key, is_setter=False): @@ -342,7 +342,7 @@ def _setitem_with_indexer(self, indexer, value): len(_ax) for _i, _ax in enumerate(self.obj.axes) if _i != i ] - if any([not l for l in len_non_info_axes]): + if any(not l for l in len_non_info_axes): if not is_list_like_indexer(value): raise ValueError("cannot set a frame with no " "defined index and a scalar") @@ -690,7 +690,7 @@ def _align_series(self, indexer, ser, multiindex_indexer=False): # we have a frame, with multiple indexers on both axes; and a # series, so need to broadcast (see GH5206) if (sum_aligners == self.ndim and - all([is_sequence(_) for _ in indexer])): + all(is_sequence(_) for _ in indexer)): ser = ser.reindex(obj.axes[0][indexer[0]], copy=True)._values # single indexer diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 045580d393b26..665f9ff8eb7a0 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3539,13 +3539,13 @@ def is_mixed_type(self): def is_numeric_mixed_type(self): # Warning, consolidation needs to get checked upstairs self._consolidate_inplace() - return all([block.is_numeric for block in self.blocks]) + return all(block.is_numeric for block in self.blocks) @property def is_datelike_mixed_type(self): # Warning, consolidation needs to get checked upstairs self._consolidate_inplace() - return any([block.is_datelike for block in self.blocks]) + return any(block.is_datelike for block in self.blocks) @property def is_view(self): @@ -4574,7 +4574,7 @@ def concat(self, to_concat, new_axis): if len(non_empties) > 0: blocks = [obj.blocks[0] for obj in non_empties] - if all([type(b) is type(blocks[0]) for b in blocks[1:]]): # noqa + if all(type(b) is type(blocks[0]) for b in blocks[1:]): # noqa new_block = blocks[0].concat_same_type(blocks) else: values = [x.values for x in blocks] @@ -5211,13 +5211,13 @@ def is_uniform_join_units(join_units): """ return ( # all blocks need to have the same type - all([type(ju.block) is type(join_units[0].block) for ju in join_units]) and # noqa + all(type(ju.block) is type(join_units[0].block) for ju in join_units) and # noqa # no blocks that would get missing values (can lead to type upcasts) - all([not ju.is_na for ju in join_units]) and + all(not ju.is_na for ju in join_units) and # no blocks with indexers (as then the dimensions do not fit) - all([not ju.indexers for ju in join_units]) and + all(not ju.indexers for ju in join_units) and # disregard Panels - all([ju.block.ndim <= 2 for ju in join_units]) and + all(ju.block.ndim <= 2 for ju in join_units) and # only use this path when there is something to concatenate len(join_units) > 1) diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index 1b45b180b8dc1..22a88264cad3e 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -347,8 +347,8 @@ def density(self): Ratio of non-sparse points to total (dense) data points represented in the frame """ - tot_nonsparse = sum([ser.sp_index.npoints - for _, ser in compat.iteritems(self)]) + tot_nonsparse = sum(ser.sp_index.npoints + for _, ser in compat.iteritems(self)) tot = len(self.index) * len(self.columns) return tot_nonsparse / float(tot) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 35a87fbe7b15b..09d6b37bae772 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -546,7 +546,7 @@ def _to_str_columns(self): minimum=header_colwidth, adj=self.adj) - max_len = max(np.max([self.adj.len(x) for x in fmt_values]), + max_len = max(max(self.adj.len(x) for x in fmt_values), header_colwidth) cheader = self.adj.justify(cheader, max_len, mode=self.justify) stringified.append(cheader + fmt_values) @@ -761,7 +761,7 @@ def _get_formatted_column_labels(self, frame): dtypes = self.frame.dtypes._values # if we have a Float level, they don't use leading space at all - restrict_formatting = any([l.is_floating for l in columns.levels]) + restrict_formatting = any(l.is_floating for l in columns.levels) need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes))) def space_format(x, y): @@ -2302,7 +2302,7 @@ def _make_fixed_width(strings, justify='right', minimum=None, adj=None): if adj is None: adj = _get_adjustment() - max_len = np.max([adj.len(x) for x in strings]) + max_len = max(adj.len(x) for x in strings) if minimum is not None: max_len = max(minimum, max_len) @@ -2330,8 +2330,8 @@ def _trim_zeros(str_floats, na_rep='NaN'): def _cond(values): non_na = [x for x in values if x != na_rep] - return (len(non_na) > 0 and all([x.endswith('0') for x in non_na]) and - not (any([('e' in x) or ('E' in x) for x in non_na]))) + return (len(non_na) > 0 and all(x.endswith('0') for x in non_na) and + not (any(('e' in x) or ('E' in x) for x in non_na))) while _cond(trimmed): trimmed = [x[:-1] if x != na_rep else x for x in trimmed] diff --git a/pandas/io/html.py b/pandas/io/html.py index e1636d8007345..f29062968bff1 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -359,7 +359,7 @@ def _parse_raw_thead(self, table): trs = self._parse_tr(thead[0]) for tr in trs: cols = lmap(self._text_getter, self._parse_td(tr)) - if any([col != '' for col in cols]): + if any(col != '' for col in cols): res.append(cols) return res @@ -606,7 +606,7 @@ def _parse_raw_thead(self, table): for tr in trs: cols = [_remove_whitespace(x.text_content()) for x in self._parse_td(tr)] - if any([col != '' for col in cols]): + if any(col != '' for col in cols): res.append(cols) return res diff --git a/pandas/io/json/normalize.py b/pandas/io/json/normalize.py index e811dd1eab142..d062e4f2830ff 100644 --- a/pandas/io/json/normalize.py +++ b/pandas/io/json/normalize.py @@ -189,7 +189,7 @@ def _pull_field(js, spec): data = [data] if record_path is None: - if any([isinstance(x, dict) for x in compat.itervalues(data[0])]): + if any(isinstance(x, dict) for x in compat.itervalues(data[0])): # naive normalization, this is idempotent for flat records # and potentially will inflate the data considerably for # deeply nested structures: diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index ae79d70d4cf0a..ee336dff000b2 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1121,7 +1121,7 @@ def _is_potential_multi_index(columns): boolean : Whether or not columns could become a MultiIndex """ return (len(columns) and not isinstance(columns, MultiIndex) and - all([isinstance(c, tuple) for c in columns])) + all(isinstance(c, tuple) for c in columns)) def _evaluate_usecols(usecols, names): @@ -1367,7 +1367,7 @@ def tostr(x): # if we find 'Unnamed' all of a single level, then our header was too # long for n in range(len(columns[0])): - if all(['Unnamed' in tostr(c[n]) for c in columns]): + if all('Unnamed' in tostr(c[n]) for c in columns): raise ParserError( "Passed header=[%s] are too many rows for this " "multi_index of columns" @@ -2017,7 +2017,7 @@ def TextParser(*args, **kwds): def count_empty_vals(vals): - return sum([1 for v in vals if v == '' or v is None]) + return sum(1 for v in vals if v == '' or v is None) class PythonParser(ParserBase): @@ -2524,7 +2524,7 @@ def _handle_usecols(self, columns, usecols_key): if self.usecols is not None: if callable(self.usecols): col_indices = _evaluate_usecols(self.usecols, usecols_key) - elif any([isinstance(u, string_types) for u in self.usecols]): + elif any(isinstance(u, string_types) for u in self.usecols): if len(columns) > 1: raise ValueError("If using multiple headers, usecols must " "be integers.") @@ -2888,7 +2888,7 @@ def _rows_to_cols(self, content): if self._implicit_index: col_len += len(self.index_col) - max_len = max([len(row) for row in content]) + max_len = max(len(row) for row in content) # Check that there are no rows with too many # elements in their row (rows with too few diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 40955c50f6b5f..5d8299ff1a2be 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1539,8 +1539,8 @@ def __unicode__(self): def __eq__(self, other): """ compare 2 col items """ - return all([getattr(self, a, None) == getattr(other, a, None) - for a in ['name', 'cname', 'axis', 'pos']]) + return all(getattr(self, a, None) == getattr(other, a, None) + for a in ['name', 'cname', 'axis', 'pos']) def __ne__(self, other): return not self.__eq__(other) @@ -1824,8 +1824,8 @@ def __unicode__(self): def __eq__(self, other): """ compare 2 col items """ - return all([getattr(self, a, None) == getattr(other, a, None) - for a in ['name', 'cname', 'dtype', 'pos']]) + return all(getattr(self, a, None) == getattr(other, a, None) + for a in ['name', 'cname', 'dtype', 'pos']) def set_data(self, data, dtype=None): self.data = data @@ -3094,7 +3094,7 @@ def axes(self): @property def ncols(self): """ the number of total columns in the values axes """ - return sum([len(a.values) for a in self.values_axes]) + return sum(len(a.values) for a in self.values_axes) @property def is_transposed(self): diff --git a/pandas/util/_doctools.py b/pandas/util/_doctools.py index d654c78b8b13f..667c5d9526563 100644 --- a/pandas/util/_doctools.py +++ b/pandas/util/_doctools.py @@ -28,10 +28,10 @@ def _get_cells(self, left, right, vertical): """ if vertical: - # calcurate required number of cells - vcells = max(sum([self._shape(l)[0] for l in left]), + # calculate required number of cells + vcells = max(sum(self._shape(l)[0] for l in left), self._shape(right)[0]) - hcells = (max([self._shape(l)[1] for l in left]) + + hcells = (max(self._shape(l)[1] for l in left) + self._shape(right)[1]) else: vcells = max([self._shape(l)[0] for l in left] + @@ -72,8 +72,8 @@ def plot(self, left, right, labels=None, vertical=True): if vertical: gs = gridspec.GridSpec(len(left), hcells) # left - max_left_cols = max([self._shape(l)[1] for l in left]) - max_left_rows = max([self._shape(l)[0] for l in left]) + max_left_cols = max(self._shape(l)[1] for l in left) + max_left_rows = max(self._shape(l)[0] for l in left) for i, (l, label) in enumerate(zip(left, labels)): ax = fig.add_subplot(gs[i, 0:max_left_cols]) self._make_table(ax, l, title=label, @@ -83,7 +83,7 @@ def plot(self, left, right, labels=None, vertical=True): self._make_table(ax, right, title='Result', height=1.05 / vcells) fig.subplots_adjust(top=0.9, bottom=0.05, left=0.05, right=0.95) else: - max_rows = max([self._shape(df)[0] for df in left + [right]]) + max_rows = max(self._shape(df)[0] for df in left + [right]) height = 1.0 / np.max(max_rows) gs = gridspec.GridSpec(1, hcells) # left diff --git a/pandas/util/testing.py b/pandas/util/testing.py index a13ecef5dd1bf..1c4c63acb436a 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1881,7 +1881,7 @@ def makeCustomIndex(nentries, nlevels, prefix='#', names=False, ndupe_l=None, ndupe_l.extend([1] * (nlevels - len(ndupe_l))) assert len(ndupe_l) == nlevels - assert all([x > 0 for x in ndupe_l]) + assert all(x > 0 for x in ndupe_l) tuples = [] for i in range(nlevels): @@ -2348,7 +2348,7 @@ def wrapper(*args, **kwargs): except Exception: e_str = str(e) - if any([m.lower() in e_str.lower() for m in _skip_on_messages]): + if any(m.lower() in e_str.lower() for m in _skip_on_messages): skip("Skipping test because exception " "message is known and error {error}".format(error=e))
- [x] tests passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Pass generators in built-in Python functions instead of passing in a list, e.g `any([value for value in iterator])` --> `any(value for value in iterator)`
https://api.github.com/repos/pandas-dev/pandas/pulls/18276
2017-11-14T03:35:04Z
2017-11-15T11:29:32Z
2017-11-15T11:29:32Z
2017-12-20T02:04:16Z
ASV/CLN: cleanup period benchmarks
diff --git a/asv_bench/benchmarks/period.py b/asv_bench/benchmarks/period.py index df3c2bf3e4b46..15d7655293ea3 100644 --- a/asv_bench/benchmarks/period.py +++ b/asv_bench/benchmarks/period.py @@ -3,141 +3,128 @@ class PeriodProperties(object): - def setup(self): - self.per = Period('2012-06-01', freq='M') + params = ['M', 'min'] + param_names = ['freq'] + + def setup(self, freq): + self.per = Period('2012-06-01', freq=freq) - def time_year(self): + def time_year(self, freq): self.per.year - def time_month(self): + def time_month(self, freq): self.per.month - def time_quarter(self): - self.per.quarter - - def time_day(self): + def time_day(self, freq): self.per.day - def time_hour(self): + def time_hour(self, freq): self.per.hour - def time_minute(self): - self.per.second + def time_minute(self, freq): + self.per.minute - def time_second(self): + def time_second(self, freq): self.per.second - def time_leap_year(self): - self.per.is_leapyear - - -class Constructor(object): - goal_time = 0.2 - - def setup(self): - self.rng = date_range('1985', periods=1000) - self.rng2 = date_range('1985', periods=1000).to_pydatetime() - - def time_from_date_range(self): - PeriodIndex(self.rng, freq='D') - - def time_from_pydatetime(self): - PeriodIndex(self.rng2, freq='D') + def time_is_leap_year(self, freq): + self.per.is_leap_year + def time_quarter(self, freq): + self.per.quarter -class DataFrame(object): - goal_time = 0.2 + def time_qyear(self, freq): + self.per.qyear - def setup(self): - self.rng = pd.period_range(start='1/1/1990', freq='S', periods=20000) - self.df = pd.DataFrame(index=range(len(self.rng))) + def time_week(self, freq): + self.per.week - def time_setitem_period_column(self): - self.df['col'] = self.rng + def time_daysinmonth(self, freq): + self.per.daysinmonth + def time_dayofweek(self, freq): + self.per.dayofweek -class Algorithms(object): - goal_time = 0.2 + def time_dayofyear(self, freq): + self.per.dayofyear - def setup(self): - data = [Period('2011-01', freq='M'), Period('2011-02', freq='M'), - Period('2011-03', freq='M'), Period('2011-04', freq='M')] - self.s = Series(data * 1000) - self.i = PeriodIndex(data, freq='M') + def time_start_time(self, freq): + self.per.start_time - def time_drop_duplicates_pseries(self): - self.s.drop_duplicates() + def time_end_time(self, freq): + self.per.end_time - def time_drop_duplicates_pindex(self): - self.i.drop_duplicates() - def time_value_counts_pseries(self): - self.s.value_counts() +class PeriodUnaryMethods(object): + params = ['M', 'min'] + param_names = ['freq'] - def time_value_counts_pindex(self): - self.i.value_counts() + def setup(self, freq): + self.per = Period('2012-06-01', freq=freq) + def time_to_timestamp(self, freq): + self.per.to_timestamp() -class Properties(object): - def setup(self): - self.per = Period('2017-09-06 08:28', freq='min') + def time_now(self, freq): + self.per.now(freq) - def time_year(self): - self.per.year + def time_asfreq(self, freq): + self.per.asfreq('A') - def time_month(self): - self.per.month - def time_day(self): - self.per.day +class PeriodIndexConstructor(object): + goal_time = 0.2 - def time_hour(self): - self.per.hour + params = ['D'] + param_names = ['freq'] - def time_minute(self): - self.per.minute + def setup(self, freq): + self.rng = date_range('1985', periods=1000) + self.rng2 = date_range('1985', periods=1000).to_pydatetime() - def time_second(self): - self.per.second + def time_from_date_range(self, freq): + PeriodIndex(self.rng, freq=freq) - def time_is_leap_year(self): - self.per.is_leap_year + def time_from_pydatetime(self, freq): + PeriodIndex(self.rng2, freq=freq) - def time_quarter(self): - self.per.quarter - def time_qyear(self): - self.per.qyear +class DataFramePeriodColumn(object): + goal_time = 0.2 - def time_week(self): - self.per.week + def setup_cache(self): + rng = pd.period_range(start='1/1/1990', freq='S', periods=20000) + df = pd.DataFrame(index=range(len(rng))) + return rng, df - def time_daysinmonth(self): - self.per.daysinmonth + def time_setitem_period_column(self, tup): + rng, df = tup + df['col'] = rng - def time_dayofweek(self): - self.per.dayofweek - def time_dayofyear(self): - self.per.dayofyear +class Algorithms(object): + goal_time = 0.2 - def time_start_time(self): - self.per.start_time + params = ['index', 'series'] + param_names = ['typ'] - def time_end_time(self): - self.per.end_time + def setup(self, typ): + data = [Period('2011-01', freq='M'), Period('2011-02', freq='M'), + Period('2011-03', freq='M'), Period('2011-04', freq='M')] - def time_to_timestamp(): - self.per.to_timestamp() + if typ == 'index': + self.vector = PeriodIndex(data * 1000, freq='M') + elif typ == 'series': + self.vector = Series(data * 1000) - def time_now(): - self.per.now() + def time_drop_duplicates(self, typ): + self.vector.drop_duplicates() - def time_asfreq(): - self.per.asfreq('A') + def time_value_counts(self, typ): + self.vector.value_counts() -class period_standard_indexing(object): +class Indexing(object): goal_time = 0.2 def setup(self): diff --git a/asv_bench/benchmarks/timedelta.py b/asv_bench/benchmarks/timedelta.py index 0f8c8458628b1..2d1ff3a24f787 100644 --- a/asv_bench/benchmarks/timedelta.py +++ b/asv_bench/benchmarks/timedelta.py @@ -31,14 +31,14 @@ def time_convert_ignore(self): to_timedelta(self.arr4, errors='ignore') -class Ops(object): +class TimedeltaOps(object): goal_time = 0.2 def setup(self): self.td = to_timedelta(np.arange(1000000)) self.ts = Timestamp('2000') - def test_add_td_ts(self): + def time_add_td_ts(self): self.td + self.ts diff --git a/asv_bench/benchmarks/timestamp.py b/asv_bench/benchmarks/timestamp.py index e8cb4c9d1c75b..b8ef309e6a464 100644 --- a/asv_bench/benchmarks/timestamp.py +++ b/asv_bench/benchmarks/timestamp.py @@ -7,8 +7,11 @@ class TimestampProperties(object): goal_time = 0.2 - def setup(self): - self.ts = Timestamp('2017-08-25 08:16:14') + params = [None, pytz.timezone('Europe/Amsterdam')] + param_names = ['tz'] + + def setup(self, tz): + self.ts = Timestamp('2017-08-25 08:16:14', tzinfo=tz) def time_tz(self): self.ts.tz @@ -65,25 +68,29 @@ def time_microsecond(self): class TimestampOps(object): goal_time = 0.2 - def setup(self): - self.ts = Timestamp('2017-08-25 08:16:14') - self.ts_tz = Timestamp('2017-08-25 08:16:14', tz='US/Eastern') + params = [None, 'US/Eastern'] + param_names = ['tz'] - dt = datetime.datetime(2016, 3, 27, 1) - self.tzinfo = pytz.timezone('CET').localize(dt, is_dst=False).tzinfo - self.ts2 = Timestamp(dt) + def setup(self, tz): + self.ts = Timestamp('2017-08-25 08:16:14', tz=tz) def time_replace_tz(self): self.ts.replace(tzinfo=pytz.timezone('US/Eastern')) - def time_replace_across_dst(self): - self.ts2.replace(tzinfo=self.tzinfo) - def time_replace_None(self): - self.ts_tz.replace(tzinfo=None) + self.ts.replace(tzinfo=None) def time_to_pydatetime(self): self.ts.to_pydatetime() - def time_to_pydatetime_tz(self): - self.ts_tz.to_pydatetime() + +class TimestampAcrossDst(object): + goal_time = 0.2 + + def setup(self): + dt = datetime.datetime(2016, 3, 27, 1) + self.tzinfo = pytz.timezone('CET').localize(dt, is_dst=False).tzinfo + self.ts2 = Timestamp(dt) + + def time_replace_across_dst(self): + self.ts2.replace(tzinfo=self.tzinfo)
Fix one benchmark that wasnt getting run because of a name typo Remove redundant Period benchmarks. Cleanup a few benchmarks using `params`. #noci (is that how that works?)
https://api.github.com/repos/pandas-dev/pandas/pulls/18275
2017-11-14T02:27:33Z
2017-11-23T08:43:10Z
2017-11-23T08:43:10Z
2017-12-08T19:40:05Z
DOC: add docstring for fillna (#18018)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 4cc59f5297058..a0f5472493344 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -809,9 +809,10 @@ def duplicated(self, keep='first'): return duplicated_int64(ids, keep) - @Appender(ibase._index_shared_docs['fillna']) def fillna(self, value=None, downcast=None): - # isna is not implemented for MultiIndex + """ + fillna is not implemented for MultiIndex + """ raise NotImplementedError('isna is not defined for MultiIndex') @Appender(_index_shared_docs['dropna'])
- [ ] closes #18018 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/18269
2017-11-13T20:20:11Z
2017-11-13T21:03:56Z
2017-11-13T21:03:56Z
2017-11-13T21:03:57Z
DOC: update Series.combine/DataFrame.combine doc strings
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f3137c1edf2af..a7f8049a53af8 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4029,6 +4029,8 @@ def combine(self, other, func, fill_value=None, overwrite=True): ---------- other : DataFrame func : function + Function that takes two series as inputs and return a Series or a + scalar fill_value : scalar value overwrite : boolean, default True If True then overwrite values for common keys in the calling frame @@ -4036,8 +4038,21 @@ def combine(self, other, func, fill_value=None, overwrite=True): Returns ------- result : DataFrame - """ + Examples + -------- + >>> df1 = DataFrame({'A': [0, 0], 'B': [4, 4]}) + >>> df2 = DataFrame({'A': [1, 1], 'B': [3, 3]}) + >>> df1.combine(df2, lambda s1, s2: s1 if s1.sum() < s2.sum() else s2) + A B + 0 0 3 + 1 0 3 + + See Also + -------- + DataFrame.combine_first : Combine two DataFrame objects and default to + non-null values in frame calling the method + """ other_idxlen = len(other.index) # save for compare this, other = self.align(other, copy=False) diff --git a/pandas/core/series.py b/pandas/core/series.py index c9a72bb688270..1cac35d58d888 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1731,11 +1731,26 @@ def combine(self, other, func, fill_value=np.nan): ---------- other : Series or scalar value func : function + Function that takes two scalars as inputs and return a scalar fill_value : scalar value Returns ------- result : Series + + Examples + -------- + >>> s1 = Series([1, 2]) + >>> s2 = Series([0, 3]) + >>> s1.combine(s2, lambda x1, x2: x1 if x1 < x2 else x2) + 0 0 + 1 2 + dtype: int64 + + See Also + -------- + Series.combine_first : Combine Series values, choosing the calling + Series's values first """ if isinstance(other, Series): new_index = self.index.union(other.index)
This PR updates ``Series.combine``/``DataFrame.combine`` doc strings. In particular, it adds some short examples to the doc strings.
https://api.github.com/repos/pandas-dev/pandas/pulls/18268
2017-11-13T20:16:11Z
2017-11-14T11:32:45Z
2017-11-14T11:32:45Z
2017-12-11T20:38:19Z
DOC: updated .combine_first doc strings
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f3137c1edf2af..b478b977a041b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4125,16 +4125,24 @@ def combine_first(self, other): ---------- other : DataFrame + Returns + ------- + combined : DataFrame + Examples -------- - a's values prioritized, use values from b to fill holes: - - >>> a.combine_first(b) + df1's values prioritized, use values from df2 to fill holes: + >>> df1 = pd.DataFrame([[1, np.nan]]) + >>> df2 = pd.DataFrame([[3, 4]]) + >>> df1.combine_first(df2) + 0 1 + 0 1 4.0 - Returns - ------- - combined : DataFrame + See Also + -------- + DataFrame.combine : Perform series-wise operation on two DataFrames + using a given function """ import pandas.core.computation.expressions as expressions diff --git a/pandas/core/series.py b/pandas/core/series.py index c9a72bb688270..acebec7733c0b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1764,7 +1764,21 @@ def combine_first(self, other): Returns ------- - y : Series + combined : Series + + Examples + -------- + >>> s1 = pd.Series([1, np.nan]) + >>> s2 = pd.Series([3, 4]) + >>> s1.combine_first(s2) + 0 1.0 + 1 4.0 + dtype: float64 + + See Also + -------- + Series.combine : Perform elementwise operation on two Series + using a given function """ new_index = self.index.union(other.index) this = self.reindex(new_index, copy=False)
This PR updates ``Series.combine_first``/``DataFrame.combine_first`` doc strings. In Particular, it add some short examples to the doc strings.
https://api.github.com/repos/pandas-dev/pandas/pulls/18266
2017-11-13T18:46:20Z
2017-11-14T09:43:09Z
2017-11-14T09:43:09Z
2017-12-11T08:09:19Z
cleaned up imports
diff --git a/pandas/core/api.py b/pandas/core/api.py index 1f46aaa40e9eb..8a624da362976 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -23,9 +23,9 @@ from pandas.core.frame import DataFrame from pandas.core.panel import Panel, WidePanel from pandas.core.panel4d import Panel4D -from pandas.core.reshape.reshape import ( - pivot_simple as pivot, get_dummies) -from pandas.core.reshape.melt import lreshape, wide_to_long + +# TODO: Remove import when statsmodels updates #18264 +from pandas.core.reshape.reshape import get_dummies from pandas.core.indexing import IndexSlice from pandas.core.tools.numeric import to_numeric diff --git a/pandas/core/reshape/api.py b/pandas/core/reshape/api.py index 99286d807a205..454a3965d74a6 100644 --- a/pandas/core/reshape/api.py +++ b/pandas/core/reshape/api.py @@ -1,7 +1,8 @@ # flake8: noqa from pandas.core.reshape.concat import concat -from pandas.core.reshape.melt import melt +from pandas.core.reshape.melt import melt, lreshape, wide_to_long +from pandas.core.reshape.reshape import pivot_simple as pivot, get_dummies from pandas.core.reshape.merge import ( merge, ordered_merge, merge_ordered, merge_asof) from pandas.core.reshape.pivot import pivot_table, crosstab diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 846d04221fe7f..36e52f1472f82 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -6,14 +6,12 @@ from pandas import compat from pandas.core.categorical import Categorical -from pandas.core.frame import DataFrame -from pandas.core.index import MultiIndex +from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.frame import _shared_docs from pandas.util._decorators import Appender import re -import pandas.core.dtypes.concat as _concat from pandas.core.dtypes.missing import notna @@ -27,7 +25,7 @@ def melt(frame, id_vars=None, value_vars=None, var_name=None, if id_vars is not None: if not is_list_like(id_vars): id_vars = [id_vars] - elif (isinstance(frame.columns, MultiIndex) and + elif (isinstance(frame.columns, ABCMultiIndex) and not isinstance(id_vars, list)): raise ValueError('id_vars must be a list of tuples when columns' ' are a MultiIndex') @@ -39,7 +37,7 @@ def melt(frame, id_vars=None, value_vars=None, var_name=None, if value_vars is not None: if not is_list_like(value_vars): value_vars = [value_vars] - elif (isinstance(frame.columns, MultiIndex) and + elif (isinstance(frame.columns, ABCMultiIndex) and not isinstance(value_vars, list)): raise ValueError('value_vars must be a list of tuples when' ' columns are a MultiIndex') @@ -54,7 +52,7 @@ def melt(frame, id_vars=None, value_vars=None, var_name=None, frame.columns = frame.columns.get_level_values(col_level) if var_name is None: - if isinstance(frame.columns, MultiIndex): + if isinstance(frame.columns, ABCMultiIndex): if len(frame.columns.names) == len(set(frame.columns.names)): var_name = frame.columns.names else: @@ -81,6 +79,7 @@ def melt(frame, id_vars=None, value_vars=None, var_name=None, mdata[col] = np.asanyarray(frame.columns ._get_level_values(i)).repeat(N) + from pandas import DataFrame return DataFrame(mdata, columns=mcolumns) @@ -137,6 +136,8 @@ def lreshape(data, groups, dropna=True, label=None): for target, names in zip(keys, values): to_concat = [data[col].values for col in names] + + import pandas.core.dtypes.concat as _concat mdata[target] = _concat._concat_compat(to_concat) pivot_cols.append(target) @@ -150,6 +151,7 @@ def lreshape(data, groups, dropna=True, label=None): if not mask.all(): mdata = dict((k, v[mask]) for k, v in compat.iteritems(mdata)) + from pandas import DataFrame return DataFrame(mdata, columns=id_cols + pivot_cols) diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index 2722c3e92d85a..28d53ed968246 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -11,8 +11,7 @@ from pandas.util.testing import assert_frame_equal -from pandas.core.reshape.reshape import get_dummies -from pandas.core.reshape.melt import melt, lreshape, wide_to_long +from pandas import melt, lreshape, wide_to_long, get_dummies import pandas.util.testing as tm from pandas.compat import range, u
This is a continuation of #18148 and does the following - puts the `reshape` imports from `pandas.core.api` to `pandas.core.reshape.api` - uses `pandas.core.dtypes.generic.ABCMultiIndex` inplace of `MultiIndex` in `melt.py` - uses `from pandas import DataFrame` in `melt.py` inside functions - imports directly from pandas in reshape tests There is one test failing. Statsmodels imports `get_dummies` from `pandas.core.api` which is no longer possible. It should import directly from pandas.
https://api.github.com/repos/pandas-dev/pandas/pulls/18264
2017-11-13T17:47:04Z
2017-11-23T15:50:38Z
2017-11-23T15:50:38Z
2017-11-23T16:19:37Z
simplify+unify offset.apply logic
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 2d8ce4c59fedc..6071241f98b9b 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -139,12 +139,45 @@ def apply_index_wraps(func): # --------------------------------------------------------------------- # Business Helpers -cpdef int _get_firstbday(int wkday): +cpdef int get_lastbday(int wkday, int days_in_month): """ - wkday is the result of monthrange(year, month) + Find the last day of the month that is a business day. - If it's a saturday or sunday, increment first business day to reflect this + (wkday, days_in_month) is the output from monthrange(year, month) + + Parameters + ---------- + wkday : int + days_in_month : int + + Returns + ------- + last_bday : int """ + return days_in_month - max(((wkday + days_in_month - 1) % 7) - 4, 0) + + +cpdef int get_firstbday(int wkday, int days_in_month=0): + """ + Find the first day of the month that is a business day. + + (wkday, days_in_month) is the output from monthrange(year, month) + + Parameters + ---------- + wkday : int + days_in_month : int, default 0 + + Returns + ------- + first_bday : int + + Notes + ----- + `days_in_month` arg is a dummy so that this has the same signature as + `get_lastbday`. + """ + cdef int first first = 1 if wkday == 5: # on Saturday first = 3 @@ -380,7 +413,6 @@ class BaseOffset(_BaseOffset): # ---------------------------------------------------------------------- # RelativeDelta Arithmetic - cpdef datetime shift_month(datetime stamp, int months, object day_opt=None): """ Given a datetime (or Timestamp) `stamp`, an integer `months` and an @@ -406,7 +438,7 @@ cpdef datetime shift_month(datetime stamp, int months, object day_opt=None): """ cdef: int year, month, day - int dim, dy + int wkday, days_in_month, dy dy = (stamp.month + months) // 12 month = (stamp.month + months) % 12 @@ -416,15 +448,21 @@ cpdef datetime shift_month(datetime stamp, int months, object day_opt=None): dy -= 1 year = stamp.year + dy - dim = monthrange(year, month)[1] + wkday, days_in_month = monthrange(year, month) if day_opt is None: - day = min(stamp.day, dim) + day = min(stamp.day, days_in_month) elif day_opt == 'start': day = 1 elif day_opt == 'end': - day = dim + day = days_in_month + elif day_opt == 'business_start': + # first business day of month + day = get_firstbday(wkday, days_in_month) + elif day_opt == 'business_end': + # last business day of month + day = get_lastbday(wkday, days_in_month) elif is_integer_object(day_opt): - day = min(day_opt, dim) + day = min(day_opt, days_in_month) else: raise ValueError(day_opt) return stamp.replace(year=year, month=month, day=day) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index b123fa127e29c..250e57c273603 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -34,7 +34,7 @@ to_datetime, DateParseError) import pandas.tseries.offsets as offsets from pandas.io.pickle import read_pickle -from pandas._libs.tslibs import timezones +from pandas._libs.tslibs import timezones, offsets as liboffsets from pandas._libs.tslib import normalize_date, NaT, Timestamp import pandas._libs.tslib as tslib import pandas.util.testing as tm @@ -4683,3 +4683,43 @@ def test_all_offset_classes(self, tup): first = Timestamp(test_values[0], tz='US/Eastern') + offset() second = Timestamp(test_values[1], tz='US/Eastern') assert first == second + + +def test_get_lastbday(): + dt = datetime(2017, 11, 30) + assert dt.weekday() == 3 # i.e. this is a business day + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_lastbday(wkday, days_in_month) == 30 + + dt = datetime(1993, 10, 31) + assert dt.weekday() == 6 # i.e. this is not a business day + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_lastbday(wkday, days_in_month) == 29 + + +def test_get_firstbday(): + dt = datetime(2017, 4, 1) + assert dt.weekday() == 5 # i.e. not a weekday + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_firstbday(wkday, days_in_month) == 3 + + dt = datetime(1993, 10, 1) + assert dt.weekday() == 4 # i.e. a business day + wkday, days_in_month = tslib.monthrange(dt.year, dt.month) + assert liboffsets.get_firstbday(wkday, days_in_month) == 1 + + +def test_shift_month(): + dt = datetime(2017, 11, 30) + assert liboffsets.shift_month(dt, 0, 'business_end') == dt + assert liboffsets.shift_month(dt, 0, + 'business_start') == datetime(2017, 11, 1) + + ts = Timestamp('1929-05-05') + assert liboffsets.shift_month(ts, 1, 'start') == Timestamp('1929-06-01') + assert liboffsets.shift_month(ts, -3, 'end') == Timestamp('1929-02-28') + + assert liboffsets.shift_month(ts, 25, None) == Timestamp('1931-06-5') + + # Try to shift to April 31, then shift back to Apr 30 to get a real date + assert liboffsets.shift_month(ts, -1, 31) == Timestamp('1929-04-30') diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 5f94c0cf5a638..ff6eb0d11a6f7 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -18,7 +18,8 @@ from pandas._libs.tslibs.offsets import ( ApplyTypeError, as_datetime, _is_normalized, - _get_firstbday, _get_calendar, _to_dt64, _validate_business_time, + get_firstbday, get_lastbday, + _get_calendar, _to_dt64, _validate_business_time, _int_to_weekday, _weekday_to_int, _determine_offset, apply_index_wraps, @@ -1180,18 +1181,14 @@ class BusinessMonthEnd(MonthOffset): def apply(self, other): n = self.n wkday, days_in_month = tslib.monthrange(other.year, other.month) - lastBDay = days_in_month - max(((wkday + days_in_month - 1) - % 7) - 4, 0) + lastBDay = get_lastbday(wkday, days_in_month) if n > 0 and not other.day >= lastBDay: n = n - 1 elif n <= 0 and other.day > lastBDay: n = n + 1 - other = shift_month(other, n, 'end') - if other.weekday() > 4: - other = other - BDay() - return other + return shift_month(other, n, 'business_end') class BusinessMonthBegin(MonthOffset): @@ -1202,7 +1199,7 @@ class BusinessMonthBegin(MonthOffset): def apply(self, other): n = self.n wkday, _ = tslib.monthrange(other.year, other.month) - first = _get_firstbday(wkday) + first = get_firstbday(wkday) if other.day > first and n <= 0: # as if rolled forward already @@ -1211,24 +1208,13 @@ def apply(self, other): other = other + timedelta(days=first - other.day) n -= 1 - other = shift_month(other, n, None) - wkday, _ = tslib.monthrange(other.year, other.month) - first = _get_firstbday(wkday) - result = datetime(other.year, other.month, first, - other.hour, other.minute, - other.second, other.microsecond) - return result + return shift_month(other, n, 'business_start') def onOffset(self, dt): if self.normalize and not _is_normalized(dt): return False first_weekday, _ = tslib.monthrange(dt.year, dt.month) - if first_weekday == 5: - return dt.day == 3 - elif first_weekday == 6: - return dt.day == 2 - else: - return dt.day == 1 + return dt.day == get_firstbday(first_weekday) class CustomBusinessMonthEnd(BusinessMixin, MonthOffset): @@ -1610,10 +1596,7 @@ def _from_name(cls, suffix=None): class QuarterOffset(DateOffset): """Quarter representation - doesn't call super""" - - #: default month for __init__ _default_startingMonth = None - #: default month in _from_name _from_name_startingMonth = None _adjust_dst = True # TODO: Consider combining QuarterOffset and YearOffset __init__ at some @@ -1655,21 +1638,15 @@ class BQuarterEnd(QuarterOffset): """ _outputName = 'BusinessQuarterEnd' _default_startingMonth = 3 - # 'BQ' _from_name_startingMonth = 12 _prefix = 'BQ' @apply_wraps def apply(self, other): n = self.n - base = other - other = datetime(other.year, other.month, other.day, - other.hour, other.minute, other.second, - other.microsecond) wkday, days_in_month = tslib.monthrange(other.year, other.month) - lastBDay = days_in_month - max(((wkday + days_in_month - 1) - % 7) - 4, 0) + lastBDay = get_lastbday(wkday, days_in_month) monthsToGo = 3 - ((other.month - self.startingMonth) % 3) if monthsToGo == 3: @@ -1680,11 +1657,7 @@ def apply(self, other): elif n <= 0 and other.day > lastBDay and monthsToGo == 0: n = n + 1 - other = shift_month(other, monthsToGo + 3 * n, 'end') - other = tslib._localize_pydatetime(other, base.tzinfo) - if other.weekday() > 4: - other = other - BDay() - return other + return shift_month(other, monthsToGo + 3 * n, 'business_end') def onOffset(self, dt): if self.normalize and not _is_normalized(dt): @@ -1710,7 +1683,7 @@ def apply(self, other): n = self.n wkday, _ = tslib.monthrange(other.year, other.month) - first = _get_firstbday(wkday) + first = get_firstbday(wkday) monthsSince = (other.month - self.startingMonth) % 3 @@ -1724,14 +1697,7 @@ def apply(self, other): elif n > 0 and (monthsSince == 0 and other.day < first): n = n - 1 - # get the first bday for result - other = shift_month(other, 3 * n - monthsSince, None) - wkday, _ = tslib.monthrange(other.year, other.month) - first = _get_firstbday(wkday) - result = datetime(other.year, other.month, first, - other.hour, other.minute, other.second, - other.microsecond) - return result + return shift_month(other, 3 * n - monthsSince, 'business_start') class QuarterEnd(EndMixin, QuarterOffset): @@ -1840,8 +1806,7 @@ class BYearEnd(YearOffset): def apply(self, other): n = self.n wkday, days_in_month = tslib.monthrange(other.year, self.month) - lastBDay = (days_in_month - - max(((wkday + days_in_month - 1) % 7) - 4, 0)) + lastBDay = get_lastbday(wkday, days_in_month) years = n if n > 0: @@ -1853,17 +1818,8 @@ def apply(self, other): (other.month == self.month and other.day > lastBDay)): years += 1 - other = shift_month(other, 12 * years, None) - - _, days_in_month = tslib.monthrange(other.year, self.month) - result = datetime(other.year, self.month, days_in_month, - other.hour, other.minute, other.second, - other.microsecond) - - if result.weekday() > 4: - result = result - BDay() - - return result + months = years * 12 + (self.month - other.month) + return shift_month(other, months, 'business_end') class BYearBegin(YearOffset): @@ -1877,7 +1833,7 @@ def apply(self, other): n = self.n wkday, days_in_month = tslib.monthrange(other.year, self.month) - first = _get_firstbday(wkday) + first = get_firstbday(wkday) years = n @@ -1891,11 +1847,8 @@ def apply(self, other): years += 1 # set first bday for result - other = shift_month(other, years * 12, None) - wkday, days_in_month = tslib.monthrange(other.year, self.month) - first = _get_firstbday(wkday) - return datetime(other.year, self.month, first, other.hour, - other.minute, other.second, other.microsecond) + months = years * 12 + (self.month - other.month) + return shift_month(other, months, 'business_start') class YearEnd(EndMixin, YearOffset):
Implement _get_lastbday mirroring _get_firstbday. Implement bstart and bend cases in shift month. Use these to simplify a bunch of the BusinessFoo offsets.
https://api.github.com/repos/pandas-dev/pandas/pulls/18263
2017-11-13T15:29:02Z
2017-11-16T11:13:56Z
2017-11-16T11:13:56Z
2017-12-08T19:38:39Z
DEPR: deprecate (Sparse)Series.from_array
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 943b6bb84fb47..f06a507c6318c 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -51,7 +51,7 @@ Other API Changes Deprecations ~~~~~~~~~~~~ -- +- ``Series.from_array`` and ``SparseSeries.from_array`` are deprecated. Use the normal constructor ``Series(..)`` and ``SparseSeries(..)`` instead (:issue:`18213`). - - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 70f1ff0a5380d..091da7ae4b43f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2099,10 +2099,8 @@ def _ixs(self, i, axis=0): if index_len and not len(values): values = np.array([np.nan] * index_len, dtype=object) - result = self._constructor_sliced.from_array(values, - index=self.index, - name=label, - fastpath=True) + result = self._constructor_sliced._from_array( + values, index=self.index, name=label, fastpath=True) # this is a cached value, mark it so result._set_as_cached(label, self) @@ -2496,8 +2494,8 @@ def _box_item_values(self, key, values): def _box_col_values(self, values, items): """ provide boxed values for a column """ - return self._constructor_sliced.from_array(values, index=self.index, - name=items, fastpath=True) + return self._constructor_sliced._from_array(values, index=self.index, + name=items, fastpath=True) def __setitem__(self, key, value): key = com._apply_if_callable(key, self) @@ -4915,8 +4913,8 @@ def _apply_standard(self, func, axis, ignore_failures=False, reduce=True): res_index = self.index res_columns = self.columns values = self.values - series_gen = (Series.from_array(arr, index=res_columns, name=name, - dtype=dtype) + series_gen = (Series._from_array(arr, index=res_columns, name=name, + dtype=dtype) for i, (arr, name) in enumerate(zip(values, res_index))) else: # pragma : no cover diff --git a/pandas/core/series.py b/pandas/core/series.py index 1c92c4b8850ee..0b41fe55dd70f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -273,6 +273,25 @@ def __init__(self, data=None, index=None, dtype=None, name=None, @classmethod def from_array(cls, arr, index=None, name=None, dtype=None, copy=False, fastpath=False): + """ + DEPRECATED: use the pd.Series(..) constructor instead. + + """ + warnings.warn("'from_array' is deprecated and will be removed in a " + "future version. Please use the pd.Series(..) " + "constructor instead.", FutureWarning, stacklevel=2) + return cls._from_array(arr, index=index, name=name, dtype=dtype, + copy=copy, fastpath=fastpath) + + @classmethod + def _from_array(cls, arr, index=None, name=None, dtype=None, copy=False, + fastpath=False): + """ + Internal method used in DataFrame.__setitem__/__getitem__. + Difference with Series(..) is that this method checks if a sparse + array is passed. + + """ # return a sparse series here if isinstance(arr, ABCSparseArray): from pandas.core.sparse.series import SparseSeries diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index 17d0737ba7c63..b5ce3efe9f85d 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -256,8 +256,18 @@ def npoints(self): def from_array(cls, arr, index=None, name=None, copy=False, fill_value=None, fastpath=False): """ - Simplified alternate constructor + DEPRECATED: use the pd.SparseSeries(..) constructor instead. + """ + warnings.warn("'from_array' is deprecated and will be removed in a " + "future version. Please use the pd.SparseSeries(..) " + "constructor instead.", FutureWarning, stacklevel=2) + return cls._from_array(arr, index=index, name=name, copy=copy, + fill_value=fill_value, fastpath=fastpath) + + @classmethod + def _from_array(cls, arr, index=None, name=None, copy=False, + fill_value=None, fastpath=False): return cls(arr, index=index, name=name, copy=copy, fill_value=fill_value, fastpath=fastpath) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index c1e4189283928..9aae40e1b8dbb 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -195,6 +195,11 @@ def test_constructor_dict_timedelta_index(self): ) self._assert_series_equal(result, expected) + def test_from_array_deprecated(self): + + with tm.assert_produces_warning(FutureWarning): + self.series_klass.from_array([1, 2, 3]) + class TestSeriesMisc(TestData, SharedWithSparse): diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 6018260708335..89029a35d73de 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -919,8 +919,9 @@ def test_from_M8_structured(self): assert isinstance(s[0], Timestamp) assert s[0] == dates[0][0] - s = Series.from_array(arr['Date'], Index([0])) - assert s[0] == dates[0][0] + with pytest.warns(FutureWarning): + s = Series.from_array(arr['Date'], Index([0])) + assert s[0] == dates[0][0] def test_get_level_values_box(self): from pandas import MultiIndex
Closes #18213. It's a bit annoying that I have to keep it as internal method. On the other hand this might signal that `from_array` actually has some use case ..
https://api.github.com/repos/pandas-dev/pandas/pulls/18258
2017-11-13T10:50:54Z
2017-11-17T01:11:44Z
2017-11-17T01:11:44Z
2018-02-23T07:50:22Z
CLN/DEPR: remove setter for MultiIndex levels/labels properties
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index ccaa408603333..8afdd1b2e22b3 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -62,7 +62,7 @@ Removal of prior version deprecations/changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Warnings against the obsolete usage ``Categorical(codes, categories)``, which were emitted for instance when the first two arguments to ``Categorical()`` had different dtypes, and recommended the use of ``Categorical.from_codes``, have now been removed (:issue:`8074`) -- +- The ``levels`` and ``labels`` attributes of a ``MultiIndex`` can no longer be set directly (:issue:`4039`). - .. _whatsnew_0220.performance: diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index f603a0eef36a5..ada6a39e7bbe4 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2,7 +2,6 @@ # pylint: disable=E1101,E1103,W0232 import datetime import warnings -from functools import partial from sys import getsizeof import numpy as np @@ -28,8 +27,7 @@ is_true_slices) import pandas.core.base as base -from pandas.util._decorators import (Appender, cache_readonly, - deprecate, deprecate_kwarg) +from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg import pandas.core.common as com import pandas.core.missing as missing import pandas.core.algorithms as algos @@ -177,7 +175,8 @@ def _verify_integrity(self, labels=None, levels=None): " inconsistent state" % (i, label.max(), len(level))) - def _get_levels(self): + @property + def levels(self): return self._levels def _set_levels(self, levels, level=None, copy=False, validate=True, @@ -279,14 +278,8 @@ def set_levels(self, levels, level=None, inplace=False, if not inplace: return idx - # remove me in 0.14 and change to read only property - __set_levels = deprecate("setting `levels` directly", - partial(set_levels, inplace=True, - verify_integrity=True), - alt_name="set_levels") - levels = property(fget=_get_levels, fset=__set_levels) - - def _get_labels(self): + @property + def labels(self): return self._labels def _set_labels(self, labels, level=None, copy=False, validate=True, @@ -379,13 +372,6 @@ def set_labels(self, labels, level=None, inplace=False, if not inplace: return idx - # remove me in 0.14 and change to readonly property - __set_labels = deprecate("setting labels directly", - partial(set_labels, inplace=True, - verify_integrity=True), - alt_name="set_labels") - labels = property(fget=_get_labels, fset=__set_labels) - def copy(self, names=None, dtype=None, levels=None, labels=None, deep=False, _set_identity=False, **kwargs): """ diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index b69b958d4e4ba..dbd18de16cebd 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -158,6 +158,24 @@ def test_set_name_methods(self): assert res is None assert ind.names == new_names2 + def test_set_levels_labels_directly(self): + # setting levels/labels directly raises AttributeError + + levels = self.index.levels + new_levels = [[lev + 'a' for lev in level] for level in levels] + + labels = self.index.labels + major_labels, minor_labels = labels + major_labels = [(x + 1) % 3 for x in major_labels] + minor_labels = [(x + 1) % 1 for x in minor_labels] + new_labels = [major_labels, minor_labels] + + with pytest.raises(AttributeError): + self.index.levels = new_levels + + with pytest.raises(AttributeError): + self.index.labels = new_labels + def test_set_levels(self): # side note - you probably wouldn't want to use levels and labels # directly like this - but it is possible. @@ -578,16 +596,6 @@ def test_constructor_mismatched_label_levels(self): with tm.assert_raises_regex(ValueError, label_error): self.index.copy().set_labels([[0, 0, 0, 0], [0, 0]]) - # deprecated properties - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - - with tm.assert_raises_regex(ValueError, length_error): - self.index.copy().levels = [['a'], ['b']] - - with tm.assert_raises_regex(ValueError, label_error): - self.index.copy().labels = [[0, 0, 0, 0], [0, 0]] - def assert_multiindex_copied(self, copy, original): # Levels should be (at least, shallow copied) tm.assert_copy(copy.levels, original.levels)
Noticed this in another PR, this doesn't seem to be listed in our deprecations master issue https://github.com/pandas-dev/pandas/issues/6581. But it is already deprecated since 0.13 (https://github.com/pandas-dev/pandas/pull/4039)
https://api.github.com/repos/pandas-dev/pandas/pulls/18256
2017-11-13T10:21:05Z
2017-11-13T23:31:21Z
2017-11-13T23:31:21Z
2017-11-13T23:31:21Z
TST: conform tests for datetutil > 2.6.1
diff --git a/pandas/conftest.py b/pandas/conftest.py index 90e5ac864e96f..b9d0087b50306 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1,8 +1,10 @@ import pytest +from distutils.version import LooseVersion import numpy import pandas import pandas.util.testing as tm +import dateutil def pytest_addoption(parser): @@ -65,3 +67,11 @@ def ip(): pytest.importorskip('IPython', minversion="6.0.0") from IPython.core.interactiveshell import InteractiveShell return InteractiveShell() + + +is_dateutil_le_261 = pytest.mark.skipif( + LooseVersion(dateutil.__version__) > '2.6.1', + reason="dateutil api change version") +is_dateutil_gt_261 = pytest.mark.skipif( + LooseVersion(dateutil.__version__) <= '2.6.1', + reason="dateutil stable version") diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index f53688fd5c84a..a1287c3102b77 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -12,6 +12,7 @@ from distutils.version import LooseVersion import pandas as pd +from pandas.conftest import is_dateutil_le_261, is_dateutil_gt_261 from pandas._libs import tslib from pandas._libs.tslibs import parsing from pandas.core.tools import datetimes as tools @@ -996,7 +997,7 @@ def test_dayfirst(self, cache): class TestGuessDatetimeFormat(object): - @pytest.mark.xfail(reason="GH18141 - dateutil > 2.6.1 broken") + @is_dateutil_le_261 def test_guess_datetime_format_for_array(self): tm._skip_if_not_us_locale() expected_format = '%Y-%m-%d %H:%M:%S.%f' @@ -1017,6 +1018,27 @@ def test_guess_datetime_format_for_array(self): [np.nan, np.nan, np.nan], dtype='O')) assert format_for_string_of_nans is None + @is_dateutil_gt_261 + def test_guess_datetime_format_for_array_gt_261(self): + tm._skip_if_not_us_locale() + expected_format = '%Y-%m-%d %H:%M:%S.%f' + dt_string = datetime(2011, 12, 30, 0, 0, 0).strftime(expected_format) + + test_arrays = [ + np.array([dt_string, dt_string, dt_string], dtype='O'), + np.array([np.nan, np.nan, dt_string], dtype='O'), + np.array([dt_string, 'random_string'], dtype='O'), + ] + + for test_array in test_arrays: + assert tools._guess_datetime_format_for_array( + test_array) is None + + format_for_string_of_nans = tools._guess_datetime_format_for_array( + np.array( + [np.nan, np.nan, np.nan], dtype='O')) + assert format_for_string_of_nans is None + class TestToDatetimeInferFormat(object): diff --git a/pandas/tests/scalar/test_parsing.py b/pandas/tests/scalar/test_parsing.py index 54ae84b678a94..70961755ceec9 100644 --- a/pandas/tests/scalar/test_parsing.py +++ b/pandas/tests/scalar/test_parsing.py @@ -3,14 +3,12 @@ Tests for Timestamp parsing, aimed at pandas/_libs/tslibs/parsing.pyx """ from datetime import datetime - import numpy as np import pytest from dateutil.parser import parse - +from pandas.conftest import is_dateutil_le_261, is_dateutil_gt_261 from pandas import compat from pandas.util import testing as tm - from pandas._libs.tslibs import parsing @@ -68,7 +66,7 @@ def test_parsers_monthfreq(self): class TestGuessDatetimeFormat(object): - @pytest.mark.xfail(reason="GH18141 - dateutil > 2.6.1 broken") + @is_dateutil_le_261 @pytest.mark.parametrize( "string, format", [ @@ -86,7 +84,20 @@ def test_guess_datetime_format_with_parseable_formats( result = parsing._guess_datetime_format(string) assert result == format - @pytest.mark.xfail(reason="GH18141 - dateutil > 2.6.1 broken") + @is_dateutil_gt_261 + @pytest.mark.parametrize( + "string", + ['20111230', '2011-12-30', '30-12-2011', + '2011-12-30 00:00:00', '2011-12-30T00:00:00', + '2011-12-30 00:00:00.000000']) + def test_guess_datetime_format_with_parseable_formats_gt_261( + self, string): + tm._skip_if_not_us_locale() + + result = parsing._guess_datetime_format(string) + assert result is None + + @is_dateutil_le_261 @pytest.mark.parametrize( "dayfirst, expected", [ @@ -98,7 +109,16 @@ def test_guess_datetime_format_with_dayfirst(self, dayfirst, expected): ambiguous_string, dayfirst=dayfirst) assert result == expected - @pytest.mark.xfail(reason="GH18141 - dateutil > 2.6.1 broken") + @is_dateutil_gt_261 + @pytest.mark.parametrize( + "dayfirst", [True, False]) + def test_guess_datetime_format_with_dayfirst_gt_261(self, dayfirst): + ambiguous_string = '01/01/2011' + result = parsing._guess_datetime_format( + ambiguous_string, dayfirst=dayfirst) + assert result is None + + @is_dateutil_le_261 @pytest.mark.parametrize( "string, format", [ @@ -114,6 +134,22 @@ def test_guess_datetime_format_with_locale_specific_formats( result = parsing._guess_datetime_format(string) assert result == format + @is_dateutil_gt_261 + @pytest.mark.parametrize( + "string", + [ + '30/Dec/2011', + '30/December/2011', + '30/Dec/2011 00:00:00']) + def test_guess_datetime_format_with_locale_specific_formats_gt_261( + self, string): + # The month names will vary depending on the locale, in which + # case these wont be parsed properly (dateutil can't parse them) + tm._skip_if_has_locale() + + result = parsing._guess_datetime_format(string) + assert result is None + def test_guess_datetime_format_invalid_inputs(self): # A datetime string must include a year, month and a day for it # to be guessable, in addition to being a string that looks like @@ -132,7 +168,7 @@ def test_guess_datetime_format_invalid_inputs(self): for invalid_dt in invalid_dts: assert parsing._guess_datetime_format(invalid_dt) is None - @pytest.mark.xfail(reason="GH18141 - dateutil > 2.6.1 broken") + @is_dateutil_le_261 @pytest.mark.parametrize( "string, format", [ @@ -147,6 +183,21 @@ def test_guess_datetime_format_nopadding(self, string, format): result = parsing._guess_datetime_format(string) assert result == format + @is_dateutil_gt_261 + @pytest.mark.parametrize( + "string", + [ + '2011-1-1', + '30-1-2011', + '1/1/2011', + '2011-1-1 00:00:00', + '2011-1-1 0:0:0', + '2011-1-3T00:00:0']) + def test_guess_datetime_format_nopadding_gt_261(self, string): + # GH 11142 + result = parsing._guess_datetime_format(string) + assert result is None + class TestArrayToDatetime(object): def test_try_parse_dates(self):
xref #18141
https://api.github.com/repos/pandas-dev/pandas/pulls/18253
2017-11-13T00:25:21Z
2017-11-13T11:08:44Z
2017-11-13T11:08:44Z
2017-11-13T11:08:44Z
COMPAT: avoid invalid buffer comparisions
diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index f2edf48a6b829..c432c40c8f6b3 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -613,7 +613,7 @@ cdef class Validator: self.dtype = dtype self.skipna = skipna - cdef bint validate(self, object[:] values) except -1: + cdef bint validate(self, ndarray values) except -1: if not self.n: return False @@ -629,7 +629,7 @@ cdef class Validator: @cython.wraparound(False) @cython.boundscheck(False) - cdef bint _validate(self, object[:] values) except -1: + cdef bint _validate(self, ndarray values) except -1: cdef: Py_ssize_t i Py_ssize_t n = self.n @@ -642,7 +642,7 @@ cdef class Validator: @cython.wraparound(False) @cython.boundscheck(False) - cdef bint _validate_skipna(self, object[:] values) except -1: + cdef bint _validate_skipna(self, ndarray values) except -1: cdef: Py_ssize_t i Py_ssize_t n = self.n @@ -852,7 +852,7 @@ cdef class DatetimeValidator(TemporalValidator): return is_null_datetime64(value) -cpdef bint is_datetime_array(ndarray[object] values): +cpdef bint is_datetime_array(ndarray values): cdef: DatetimeValidator validator = DatetimeValidator( len(values), @@ -876,7 +876,7 @@ cpdef bint is_datetime64_array(ndarray values): return validator.validate(values) -cpdef bint is_datetime_with_singletz_array(ndarray[object] values): +cpdef bint is_datetime_with_singletz_array(ndarray values): """ Check values have the same tzinfo attribute. Doesn't check values are datetime-like types. @@ -959,7 +959,7 @@ cdef class DateValidator(Validator): return is_date(value) -cpdef bint is_date_array(ndarray[object] values, bint skipna=False): +cpdef bint is_date_array(ndarray values, bint skipna=False): cdef DateValidator validator = DateValidator(len(values), skipna=skipna) return validator.validate(values) @@ -970,7 +970,7 @@ cdef class TimeValidator(Validator): return is_time(value) -cpdef bint is_time_array(ndarray[object] values, bint skipna=False): +cpdef bint is_time_array(ndarray values, bint skipna=False): cdef TimeValidator validator = TimeValidator(len(values), skipna=skipna) return validator.validate(values) @@ -984,7 +984,7 @@ cdef class PeriodValidator(TemporalValidator): return is_null_period(value) -cpdef bint is_period_array(ndarray[object] values): +cpdef bint is_period_array(ndarray values): cdef PeriodValidator validator = PeriodValidator(len(values), skipna=True) return validator.validate(values) @@ -995,7 +995,7 @@ cdef class IntervalValidator(Validator): return is_interval(value) -cpdef bint is_interval_array(ndarray[object] values): +cpdef bint is_interval_array(ndarray values): cdef: IntervalValidator validator = IntervalValidator( len(values), diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 7195cb43a70dc..34ed9d3142923 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -39,7 +39,7 @@ from pandas.util import testing as tm -@pytest.fixture(params=[True, False], ids=lambda val: str(val)) +@pytest.fixture(params=[True, False], ids=str) def coerce(request): return request.param @@ -60,16 +60,20 @@ def __getitem__(self): assert (not is_seq(A())) -def test_is_list_like(): - passes = ([], [1], (1, ), (1, 2), {'a': 1}, set([1, 'a']), Series([1]), - Series([]), Series(['a']).str) - fails = (1, '2', object(), str) +@pytest.mark.parametrize( + "ll", + [ + [], [1], (1, ), (1, 2), {'a': 1}, + set([1, 'a']), Series([1]), + Series([]), Series(['a']).str]) +def test_is_list_like_passes(ll): + assert inference.is_list_like(ll) - for p in passes: - assert inference.is_list_like(p) - for f in fails: - assert not inference.is_list_like(f) +@pytest.mark.parametrize( + "ll", [1, '2', object(), str]) +def test_is_list_like_fails(ll): + assert not inference.is_list_like(ll) @pytest.mark.parametrize('inner', [ @@ -93,15 +97,16 @@ def test_is_nested_list_like_fails(obj): assert not inference.is_nested_list_like(obj) -def test_is_dict_like(): - passes = [{}, {'A': 1}, Series([1])] - fails = ['1', 1, [1, 2], (1, 2), range(2), Index([1])] +@pytest.mark.parametrize( + "ll", [{}, {'A': 1}, Series([1])]) +def test_is_dict_like_passes(ll): + assert inference.is_dict_like(ll) - for p in passes: - assert inference.is_dict_like(p) - for f in fails: - assert not inference.is_dict_like(f) +@pytest.mark.parametrize( + "ll", ['1', 1, [1, 2], (1, 2), range(2), Index([1])]) +def test_is_dict_like_fails(ll): + assert not inference.is_dict_like(ll) def test_is_file_like(): @@ -148,15 +153,16 @@ class MockFile(object): assert not is_file(mock.Mock()) -def test_is_named_tuple(): - passes = (collections.namedtuple('Test', list('abc'))(1, 2, 3), ) - fails = ((1, 2, 3), 'a', Series({'pi': 3.14})) +@pytest.mark.parametrize( + "ll", [collections.namedtuple('Test', list('abc'))(1, 2, 3)]) +def test_is_names_tuple_passes(ll): + assert inference.is_named_tuple(ll) - for p in passes: - assert inference.is_named_tuple(p) - for f in fails: - assert not inference.is_named_tuple(f) +@pytest.mark.parametrize( + "ll", [(1, 2, 3), 'a', Series({'pi': 3.14})]) +def test_is_names_tuple_fails(ll): + assert not inference.is_named_tuple(ll) def test_is_hashable(): @@ -208,27 +214,32 @@ class OldStyleClass(): hash(c) # this will not raise -def test_is_re(): - passes = re.compile('ad'), - fails = 'x', 2, 3, object() +@pytest.mark.parametrize( + "ll", [re.compile('ad')]) +def test_is_re_passes(ll): + assert inference.is_re(ll) - for p in passes: - assert inference.is_re(p) - for f in fails: - assert not inference.is_re(f) +@pytest.mark.parametrize( + "ll", ['x', 2, 3, object()]) +def test_is_re_fails(ll): + assert not inference.is_re(ll) -def test_is_recompilable(): - passes = (r'a', u('x'), r'asdf', re.compile('adsf'), u(r'\u2233\s*'), - re.compile(r'')) - fails = 1, [], object() +@pytest.mark.parametrize( + "ll", [r'a', u('x'), + r'asdf', + re.compile('adsf'), + u(r'\u2233\s*'), + re.compile(r'')]) +def test_is_recompilable_passes(ll): + assert inference.is_re_compilable(ll) - for p in passes: - assert inference.is_re_compilable(p) - for f in fails: - assert not inference.is_re_compilable(f) +@pytest.mark.parametrize( + "ll", [1, [], object()]) +def test_is_recompilable_fails(ll): + assert not inference.is_re_compilable(ll) class TestInference(object): @@ -300,15 +311,14 @@ def test_maybe_convert_numeric_infinities(self): np.array(['foo_' + infinity], dtype=object), na_values, maybe_int) - def test_maybe_convert_numeric_post_floatify_nan(self): + def test_maybe_convert_numeric_post_floatify_nan(self, coerce): # see gh-13314 data = np.array(['1.200', '-999.000', '4.500'], dtype=object) expected = np.array([1.2, np.nan, 4.5], dtype=np.float64) nan_values = set([-999, -999.0]) - for coerce_type in (True, False): - out = lib.maybe_convert_numeric(data, nan_values, coerce_type) - tm.assert_numpy_array_equal(out, expected) + out = lib.maybe_convert_numeric(data, nan_values, coerce) + tm.assert_numpy_array_equal(out, expected) def test_convert_infs(self): arr = np.array(['inf', 'inf', 'inf'], dtype='O') @@ -739,6 +749,36 @@ def test_is_datetimelike_array_all_nan_nat_like(self): assert not lib.is_timedelta64_array(arr) assert not lib.is_timedelta_or_timedelta64_array(arr) + assert lib.is_datetime_with_singletz_array( + np.array([pd.Timestamp('20130101', tz='US/Eastern'), + pd.Timestamp('20130102', tz='US/Eastern')], + dtype=object)) + assert not lib.is_datetime_with_singletz_array( + np.array([pd.Timestamp('20130101', tz='US/Eastern'), + pd.Timestamp('20130102', tz='CET')], + dtype=object)) + + @pytest.mark.parametrize( + "func", + [ + 'is_datetime_array', + 'is_datetime64_array', + 'is_bool_array', + 'is_timedelta_array', + 'is_timedelta64_array', + 'is_timedelta_or_timedelta64_array', + 'is_date_array', + 'is_time_array', + 'is_interval_array', + 'is_period_array']) + def test_other_dtypes_for_array(self, func): + func = getattr(lib, func) + arr = np.array(['foo', 'bar']) + assert not func(arr) + + arr = np.array([1, 2]) + assert not func(arr) + def test_date(self): dates = [date(2012, 1, day) for day in range(1, 20)] @@ -752,6 +792,24 @@ def test_date(self): result = lib.infer_dtype(dates, skipna=True) assert result == 'date' + def test_is_numeric_array(self): + + assert lib.is_float_array(np.array([1, 2.0])) + assert lib.is_float_array(np.array([1, 2.0, np.nan])) + assert not lib.is_float_array(np.array([1, 2])) + + assert lib.is_integer_array(np.array([1, 2])) + assert not lib.is_integer_array(np.array([1, 2.0])) + + def test_is_string_array(self): + + assert lib.is_string_array(np.array(['foo', 'bar'])) + assert not lib.is_string_array( + np.array(['foo', 'bar', np.nan], dtype=object), skipna=False) + assert lib.is_string_array( + np.array(['foo', 'bar', np.nan], dtype=object), skipna=True) + assert not lib.is_string_array(np.array([1, 2])) + def test_to_object_array_tuples(self): r = (5, 6) values = [r]
closes #18064
https://api.github.com/repos/pandas-dev/pandas/pulls/18252
2017-11-12T23:45:43Z
2017-11-13T13:06:29Z
2017-11-13T13:06:29Z
2018-06-15T07:13:10Z
CI: move clipboard tests to an allowed-failure test
diff --git a/.travis.yml b/.travis.yml index 42b4ef0396fc8..0f43e4cf54faa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -52,10 +52,6 @@ matrix: - dist: trusty env: - JOB="3.5" TEST_ARGS="--skip-slow --skip-network" COVERAGE=true - addons: - apt: - packages: - - xsel - dist: trusty env: - JOB="3.6" TEST_ARGS="--skip-slow --skip-network" PANDAS_TESTING_MODE="deprecate" CONDA_FORGE=true @@ -66,7 +62,11 @@ matrix: # In allow_failures - dist: trusty env: - - JOB="2.7_BUILD_TEST" TEST_ARGS="--skip-slow" BUILD_TEST=true + - JOB="3.6_BUILD_TEST" TEST_ARGS="--skip-slow" BUILD_TEST=true + addons: + apt: + packages: + - xsel # In allow_failures - dist: trusty env: @@ -75,17 +75,17 @@ matrix: - dist: trusty env: - JOB="3.6_DOC" DOC=true - addons: - apt: - packages: - - xsel allow_failures: - dist: trusty env: - JOB="2.7_SLOW" SLOW=true - dist: trusty env: - - JOB="2.7_BUILD_TEST" TEST_ARGS="--skip-slow" BUILD_TEST=true + - JOB="3.6_BUILD_TEST" TEST_ARGS="--skip-slow" BUILD_TEST=true + addons: + apt: + packages: + - xsel - dist: trusty env: - JOB="3.6_NUMPY_DEV" TEST_ARGS="--skip-slow --skip-network" PANDAS_TESTING_MODE="deprecate" diff --git a/ci/requirements-2.7_BUILD_TEST.build b/ci/requirements-2.7_BUILD_TEST.build deleted file mode 100644 index aadec00cb7ebf..0000000000000 --- a/ci/requirements-2.7_BUILD_TEST.build +++ /dev/null @@ -1,6 +0,0 @@ -python=2.7* -dateutil -pytz -nomkl -numpy -cython diff --git a/ci/requirements-3.6_BUILD_TEST.build b/ci/requirements-3.6_BUILD_TEST.build new file mode 100644 index 0000000000000..1c4b46aea3865 --- /dev/null +++ b/ci/requirements-3.6_BUILD_TEST.build @@ -0,0 +1,6 @@ +python=3.6* +python-dateutil +pytz +nomkl +numpy +cython diff --git a/ci/requirements-2.7_BUILD_TEST.pip b/ci/requirements-3.6_BUILD_TEST.pip similarity index 100% rename from ci/requirements-2.7_BUILD_TEST.pip rename to ci/requirements-3.6_BUILD_TEST.pip diff --git a/ci/requirements-2.7_BUILD_TEST.sh b/ci/requirements-3.6_BUILD_TEST.sh old mode 100755 new mode 100644 similarity index 75% rename from ci/requirements-2.7_BUILD_TEST.sh rename to ci/requirements-3.6_BUILD_TEST.sh index 78941fd0944e5..84dd27c50d587 --- a/ci/requirements-2.7_BUILD_TEST.sh +++ b/ci/requirements-3.6_BUILD_TEST.sh @@ -2,6 +2,6 @@ source activate pandas -echo "install 27 BUILD_TEST" +echo "install 36 BUILD_TEST" conda install -n pandas -c conda-forge pyarrow dask diff --git a/ci/script_multi.sh b/ci/script_multi.sh index ee9fbcaad5ef5..863613e14af98 100755 --- a/ci/script_multi.sh +++ b/ci/script_multi.sh @@ -27,6 +27,11 @@ if [ "$BUILD_TEST" ]; then echo "[running]" cd /tmp unset PYTHONPATH + + echo "[build-test: single]" + python -c 'import pandas; pandas.test(["--skip-slow", "--skip-network", "-r xX", "-m single"])' + + echo "[build-test: not single]" python -c 'import pandas; pandas.test(["-n 2", "--skip-slow", "--skip-network", "-r xX", "-m not single"])' elif [ "$DOC" ]; then
CI: change 2.7-build_test -> 3.6-build_test
https://api.github.com/repos/pandas-dev/pandas/pulls/18251
2017-11-12T23:01:51Z
2017-11-13T11:02:46Z
2017-11-13T11:02:46Z
2017-11-13T11:03:46Z
DOC: Error msg using Python keyword in numexpr query #18221
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 61679b14a8592..9c44081b64134 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -158,6 +158,6 @@ Categorical Other ^^^^^ -- +- Improved error message when attempting to use a Python keyword as an identifier in a numexpr query (:issue:`18221`) - - diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index ae956bce11329..23abfa8b3fca1 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -307,7 +307,14 @@ def __init__(self, env, engine, parser, preparser=_preparse): def visit(self, node, **kwargs): if isinstance(node, string_types): clean = self.preparser(node) - node = ast.fix_missing_locations(ast.parse(clean)) + try: + node = ast.fix_missing_locations(ast.parse(clean)) + except SyntaxError as e: + from keyword import iskeyword + if any(iskeyword(x) for x in clean.split()): + e.msg = ("Python keyword not valid identifier" + " in numexpr query") + raise e method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 70f1ff0a5380d..9ca0d10cd0b1d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2267,7 +2267,8 @@ def query(self, expr, inplace=False, **kwargs): by default, which allows you to treat both the index and columns of the frame as a column in the frame. The identifier ``index`` is used for the frame index; you can also - use the name of the index to identify it in a query. + use the name of the index to identify it in a query. Please note that + Python keywords may not be used as identifiers. For further details and examples see the ``query`` documentation in :ref:`indexing <indexing.query>`. diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index d2874b1606e72..c2d1eb8ae1372 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -718,6 +718,18 @@ def test_float_truncation(self): expected = df.loc[[1], :] tm.assert_frame_equal(expected, result) + def test_disallow_python_keywords(self): + # GH 18221 + df = pd.DataFrame([[0, 0, 0]], columns=['foo', 'bar', 'class']) + msg = "Python keyword not valid identifier in numexpr query" + with tm.assert_raises_regex(SyntaxError, msg): + df.query('class == 0') + + df = pd.DataFrame() + df.index.name = 'lambda' + with tm.assert_raises_regex(SyntaxError, msg): + df.query('lambda == 0') + class TestEvalNumexprPython(TestEvalNumexprPandas):
- [X] closes #18221 - [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/18248
2017-11-12T21:11:07Z
2017-11-13T13:05:47Z
2017-11-13T13:05:47Z
2018-03-09T23:51:58Z
MAINT: asv with py3 on windows
diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json index 62f1c090a7462..59c05400d06b0 100644 --- a/asv_bench/asv.conf.json +++ b/asv_bench/asv.conf.json @@ -46,12 +46,14 @@ "numexpr": [], "pytables": [null, ""], // platform dependent, see excludes below "tables": [null, ""], - "libpython": [null, ""], "openpyxl": [], "xlsxwriter": [], "xlrd": [], "xlwt": [], "pytest": [], + // If using Windows with python 2.7 and want to build using the + // mingw toolchain (rather than MSVC), uncomment the following line. + // "libpython": [], }, // Combinations of libraries/python versions can be excluded/included @@ -80,10 +82,6 @@ {"environment_type": "conda", "pytables": null}, {"environment_type": "(?!conda).*", "tables": null}, {"environment_type": "(?!conda).*", "pytables": ""}, - // On conda&win32, install libpython - {"sys_platform": "(?!win32).*", "libpython": ""}, - {"environment_type": "conda", "sys_platform": "win32", "libpython": null}, - {"environment_type": "(?!conda).*", "libpython": ""} ], "include": [],
Since benchmarking on python 3, no longer want to install `libpython`
https://api.github.com/repos/pandas-dev/pandas/pulls/16139
2017-04-26T02:06:16Z
2017-04-26T13:20:36Z
2017-04-26T13:20:36Z
2017-04-26T13:25:41Z
Make various minor corrections to cheatsheet
diff --git a/doc/cheatsheet/Pandas_Cheat_Sheet.pdf b/doc/cheatsheet/Pandas_Cheat_Sheet.pdf index d504926d22580..0492805a1408b 100644 Binary files a/doc/cheatsheet/Pandas_Cheat_Sheet.pdf and b/doc/cheatsheet/Pandas_Cheat_Sheet.pdf differ diff --git a/doc/cheatsheet/Pandas_Cheat_Sheet.pptx b/doc/cheatsheet/Pandas_Cheat_Sheet.pptx index 76ae8f1e39d4e..6cca9ac4647f7 100644 Binary files a/doc/cheatsheet/Pandas_Cheat_Sheet.pptx and b/doc/cheatsheet/Pandas_Cheat_Sheet.pptx differ
Changes made: - Fixed SubHeading `Make New Variables` to `Make New Columns` -- because these operations create new columns. - Fixed # of distinct values in a column to use the pandas method `.nunique()` rather than `len(df['w'].unique())`. - For clarity, renamed the `Length` column selection to `w` under the Summarize Data -- can see this being misleading to someone thinking that to get "Count number of rows with each value of the variable" they might need to call `Length`. - For legibility/clarity removed the times that the example df was renamed (instances of `df=df.dropna()`); we should perhaps make a higher-level note that all of these operations are by default not done `inplace`, and either need to reassign or `inplace=True`. Updated .pptx and .pdf
https://api.github.com/repos/pandas-dev/pandas/pulls/16136
2017-04-25T23:24:42Z
2017-04-27T13:59:00Z
2017-04-27T13:59:00Z
2017-04-27T13:59:13Z
BUG: sefault in concat of CategoricalIndex
diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index c07760a94d3f1..c9c22de9141fe 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -1629,6 +1629,7 @@ Indexing - Bug in the display of ``.info()`` where a qualifier (+) would always be displayed with a ``MultiIndex`` that contains only non-strings (:issue:`15245`) - Bug in ``pd.concat()`` where the names of ``MultiIndex`` of resulting ``DataFrame`` are not handled correctly when ``None`` is presented in the names of ``MultiIndex`` of input ``DataFrame`` (:issue:`15787`) - Bug in ``DataFrame.sort_index()`` and ``Series.sort_index()`` where ``na_position`` doesn't work with a ``MultiIndex`` (:issue:`14784`, :issue:`16604`) + - Bug in in ``pd.concat()`` when combining objects with a ``CategoricalIndex`` (:issue:`16111`) I/O ^^^ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 257ca86947f2b..5f38b19742f71 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -12,6 +12,7 @@ is_scalar) from pandas.core.common import _asarray_tuplesafe from pandas.core.dtypes.missing import array_equivalent +from pandas.core.algorithms import take_1d from pandas.util.decorators import Appender, cache_readonly @@ -470,8 +471,10 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): codes = target.codes else: if isinstance(target, CategoricalIndex): - target = target.categories - codes = self.categories.get_indexer(target) + code_indexer = self.categories.get_indexer(target.categories) + codes = take_1d(code_indexer, target.codes, fill_value=-1) + else: + codes = self.categories.get_indexer(target) indexer, _ = self._engine.get_indexer_non_unique(codes) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index b877a9d181848..cc71cf6b1a4dc 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -1928,6 +1928,27 @@ def test_concat_multiindex_dfs_with_deepcopy(self): result_no_copy = pd.concat(example_dict, names=['testname']) tm.assert_frame_equal(result_no_copy, expected) + def test_concat_categoricalindex(self): + # GH 16111, categories that aren't lexsorted + categories = [9, 0, 1, 2, 3] + + a = pd.Series(1, index=pd.CategoricalIndex([9, 0], + categories=categories)) + b = pd.Series(2, index=pd.CategoricalIndex([0, 1], + categories=categories)) + c = pd.Series(3, index=pd.CategoricalIndex([1, 2], + categories=categories)) + + result = pd.concat([a, b, c], axis=1) + + exp_idx = pd.CategoricalIndex([0, 1, 2, 9]) + exp = pd.DataFrame({0: [1, np.nan, np.nan, 1], + 1: [2, 2, np.nan, np.nan], + 2: [np.nan, 3, 3, np.nan]}, + columns=[0, 1, 2], + index=exp_idx) + tm.assert_frame_equal(result, exp) + @pytest.mark.parametrize('pdt', [pd.Series, pd.DataFrame, pd.Panel]) @pytest.mark.parametrize('dt', np.sctypes['float'])
- [x] closes #16111 - [ ] tests added / passed - [ ] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16133
2017-04-25T19:04:23Z
2017-04-25T22:55:22Z
2017-04-25T22:55:22Z
2017-04-25T22:55:22Z
BUG/API: Catch exceptions in _ipython_display_
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 74d3053821e39..f078cbb435d25 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -43,6 +43,7 @@ import pandas.core.algorithms as algos import pandas.core.common as com import pandas.core.missing as missing +from pandas.errors import UnserializableWarning from pandas.io.formats.printing import pprint_thing from pandas.io.formats.format import format_percentiles from pandas.tseries.frequencies import to_offset @@ -138,7 +139,12 @@ def _ipython_display_(self): # Series doesn't define _repr_html_ or _repr_latex_ latex = self._repr_latex_() if hasattr(self, '_repr_latex_') else None html = self._repr_html_() if hasattr(self, '_repr_html_') else None - table_schema = self._repr_table_schema_() + try: + table_schema = self._repr_table_schema_() + except Exception as e: + warnings.warn("Cannot create table schema representation. " + "{}".format(e), UnserializableWarning) + table_schema = None # We need the inital newline since we aren't going through the # usual __repr__. See # https://github.com/pandas-dev/pandas/pull/14904#issuecomment-277829277 diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index f6719e7be421b..8540d8776fbaa 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -55,3 +55,11 @@ class ParserWarning(Warning): one specified by the user due to lack of support or functionality for parsing particular attributes of a CSV file with the requsted engine """ + + +class UnserializableWarning(Warning): + """ + Warnng that is raised when a DataFrame cannot be serialzed. + + .. versionadded:: 0.20.0 + """ diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index f9d911f523699..63cd08545610f 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -5,6 +5,7 @@ import pandas as pd from pandas import compat +from pandas.errors import UnserializableWarning import pandas.io.formats.printing as printing import pandas.io.formats.format as fmt import pandas.util.testing as tm @@ -177,9 +178,16 @@ def test_publishes_not_implemented(self): make_patch = self.mock.patch('IPython.display.display') opt = pd.option_context('display.html.table_schema', True) - with opt, make_patch as mock_display: # noqa - with pytest.raises(NotImplementedError): + with opt, make_patch as mock_display: + with pytest.warns(UnserializableWarning) as record: df._ipython_display_() + args, _ = mock_display.call_args + arg, = args # just one argument + + expected = {'text/plain', 'text/html'} + assert set(arg.keys()) == expected + assert "orient='table' is not supported for MultiIndex" in ( + record[-1].message.args[0]) def test_config_on(self): df = pd.DataFrame({"A": [1, 2]})
We raise an UnserializeableWarning when we fail to generate the table schema and do not publish a `table_schema` repr. closes https://github.com/pandas-dev/pandas/issues/15996
https://api.github.com/repos/pandas-dev/pandas/pulls/16132
2017-04-25T18:03:13Z
2017-04-25T23:55:20Z
2017-04-25T23:55:20Z
2017-05-01T15:50:28Z
PERF: use StringHashtable in data algos
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 3df82b6c13259..a745ec616eda8 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -216,10 +216,7 @@ def _get_data_algo(values, func_map): # its cheaper to use a String Hash Table than Object if lib.infer_dtype(values) in ['string']: - try: - f = func_map['string'] - except KeyError: - pass + ndtype = 'string' f = func_map.get(ndtype, func_map['object'])
xref #16107
https://api.github.com/repos/pandas-dev/pandas/pulls/16128
2017-04-25T10:26:52Z
2017-04-25T11:16:34Z
2017-04-25T11:16:34Z
2017-04-25T11:17:29Z
BUG: fix error for reset_index() with index.name in MultiIndex columns
diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index 945922b5f9ba8..c07760a94d3f1 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -1623,6 +1623,7 @@ Indexing - Bug in ``Series.iloc`` where a ``Categorical`` object for list-like indexes input was returned, where a ``Series`` was expected. (:issue:`14580`) - Bug in ``DataFrame.isin`` comparing datetimelike to empty frame (:issue:`15473`) - Bug in ``.reset_index()`` when an all ``NaN`` level of a ``MultiIndex`` would fail (:issue:`6322`) +- Bug in ``.reset_index()`` when raising error for index name already present in ``MultiIndex`` columns (:issue:`16120`) - Bug in creating a ``MultiIndex`` with tuples and not passing a list of names; this will now raise ``ValueError`` (:issue:`15110`) - Bug in the HTML display with with a ``MultiIndex`` and truncation (:issue:`14882`) - Bug in the display of ``.info()`` where a qualifier (+) would always be displayed with a ``MultiIndex`` that contains only non-strings (:issue:`15245`) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index f265f5f438280..840206977cf30 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3807,7 +3807,7 @@ def insert(self, loc, item, value, allow_duplicates=False): """ if not allow_duplicates and item in self.items: # Should this be a different kind of error?? - raise ValueError('cannot insert %s, already exists' % item) + raise ValueError('cannot insert {}, already exists'.format(item)) if not isinstance(loc, int): raise TypeError("loc must be int") diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 173ac97691b3b..e81e6e2d987c6 100755 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -2235,6 +2235,22 @@ def test_reset_index_period(self): }, columns=['month', 'feature', 'a']) tm.assert_frame_equal(df.reset_index(), expected) + def test_reset_index_multiindex_columns(self): + levels = [['A', ''], ['B', 'b']] + df = pd.DataFrame([[0, 2], [1, 3]], + columns=pd.MultiIndex.from_tuples(levels)) + expected = df.copy() + df.index.name = 'A' + result = df[['B']].reset_index() + tm.assert_frame_equal(result, expected) + + # GH 16120 + # already existing column + with tm.assertRaisesRegexp(ValueError, + ("cannot insert \('A', ''\), " + "already exists")): + df.reset_index() + def test_set_index_period(self): # GH 6631 df = DataFrame(np.random.random(6))
- [x] closes #16120 - [x] tests added / passed - [x] passes ``git diff upstream/master --name-only -- '*.py' | flake8 --diff`` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/16126
2017-04-25T09:17:15Z
2017-04-25T10:35:14Z
2017-04-25T10:35:14Z
2017-04-25T10:35:54Z
REGR: bug in moments when using bottleneck
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 5ce302967de24..e9be43b184537 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -381,6 +381,7 @@ def nanstd(values, axis=None, skipna=True, ddof=1): @bottleneck_switch(ddof=1) def nanvar(values, axis=None, skipna=True, ddof=1): + values = _values_from_object(values) dtype = values.dtype mask = isnull(values) if is_any_int_dtype(values): @@ -489,6 +490,7 @@ def nanskew(values, axis=None, skipna=True): """ + values = _values_from_object(values) mask = isnull(values) if not is_float_dtype(values.dtype): values = values.astype('f8') @@ -543,6 +545,7 @@ def nankurt(values, axis=None, skipna=True): central moment. """ + values = _values_from_object(values) mask = isnull(values) if not is_float_dtype(values.dtype): values = values.astype('f8') diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index cd98460d8609c..0941f0af6bec5 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -591,6 +591,23 @@ def test_numeric_only_flag(self): pytest.raises(TypeError, lambda: getattr(df2, meth)( axis=1, numeric_only=False)) + def test_mixed_ops(self): + # GH 16116 + df = DataFrame({'int': [1, 2, 3, 4], + 'float': [1., 2., 3., 4.], + 'str': ['a', 'b', 'c', 'd']}) + + for op in ['mean', 'std', 'var', 'skew', + 'kurt', 'sem']: + result = getattr(df, op)() + assert len(result) == 2 + + if nanops._USE_BOTTLENECK: + nanops._USE_BOTTLENECK = False + result = getattr(df, op)() + assert len(result) == 2 + nanops._USE_BOTTLENECK = True + def test_cumsum(self): self.tsframe.loc[5:10, 0] = nan self.tsframe.loc[10:15, 1] = nan
closes #16116
https://api.github.com/repos/pandas-dev/pandas/pulls/16124
2017-04-25T02:08:58Z
2017-04-25T07:56:35Z
2017-04-25T07:56:34Z
2017-04-25T07:57:44Z
REGR: Bug in indexing with a CategoricalIndex
diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index 0b66b90afec67..c46593d9fe6ac 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -1630,7 +1630,8 @@ Indexing - Bug in the display of ``.info()`` where a qualifier (+) would always be displayed with a ``MultiIndex`` that contains only non-strings (:issue:`15245`) - Bug in ``pd.concat()`` where the names of ``MultiIndex`` of resulting ``DataFrame`` are not handled correctly when ``None`` is presented in the names of ``MultiIndex`` of input ``DataFrame`` (:issue:`15787`) - Bug in ``DataFrame.sort_index()`` and ``Series.sort_index()`` where ``na_position`` doesn't work with a ``MultiIndex`` (:issue:`14784`, :issue:`16604`) - - Bug in in ``pd.concat()`` when combining objects with a ``CategoricalIndex`` (:issue:`16111`) +- Bug in in ``pd.concat()`` when combining objects with a ``CategoricalIndex`` (:issue:`16111`) +- Bug in indexing with a scalar and a ``CategoricalIndex`` (:issue:`16123`) I/O ^^^ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 5f38b19742f71..760db4ba20675 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -10,7 +10,8 @@ is_list_like, is_interval_dtype, is_scalar) -from pandas.core.common import _asarray_tuplesafe +from pandas.core.common import (_asarray_tuplesafe, + _values_from_object) from pandas.core.dtypes.missing import array_equivalent from pandas.core.algorithms import take_1d @@ -353,6 +354,22 @@ def get_loc(self, key, method=None): raise KeyError(key) return self._engine.get_loc(codes) + def get_value(self, series, key): + """ + Fast lookup of value from 1-dimensional ndarray. Only use this if you + know what you're doing + """ + try: + k = _values_from_object(key) + k = self._convert_scalar_indexer(k, kind='getitem') + indexer = self.get_loc(k) + return series.iloc[indexer] + except (KeyError, TypeError): + pass + + # we might be a positional inexer + return super(CategoricalIndex, self).get_value(series, key) + def _can_reindex(self, indexer): """ always allow reindexing """ pass @@ -507,7 +524,7 @@ def _convert_list_indexer(self, keyarr, kind=None): indexer = self.categories._convert_list_indexer(keyarr, kind=kind) return Index(self.codes).get_indexer_for(indexer) - indexer = self.categories.get_indexer(keyarr) + indexer = self.categories.get_indexer(np.asarray(keyarr)) if (indexer == -1).any(): raise KeyError( "a list-indexer must only " diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index fd5557dfcb99c..e0f95a1fd5c0d 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -4,7 +4,8 @@ import pandas as pd import numpy as np -from pandas import Series, DataFrame +from pandas import (Series, DataFrame, Timestamp, + Categorical, CategoricalIndex) from pandas.util.testing import assert_series_equal, assert_frame_equal from pandas.util import testing as tm @@ -66,6 +67,17 @@ def f(): pytest.raises(TypeError, f) + def test_getitem_scalar(self): + + cats = Categorical([Timestamp('12-31-1999'), + Timestamp('12-31-2000')]) + + s = Series([1, 2], index=cats) + + expected = s.iloc[0] + result = s[cats[0]] + assert result == expected + def test_loc_listlike(self): # list of labels @@ -74,7 +86,7 @@ def test_loc_listlike(self): assert_frame_equal(result, expected, check_index_type=True) result = self.df2.loc[['a', 'b', 'e']] - exp_index = pd.CategoricalIndex( + exp_index = CategoricalIndex( list('aaabbe'), categories=list('cabe'), name='B') expected = DataFrame({'A': [0, 1, 5, 2, 3, np.nan]}, index=exp_index) assert_frame_equal(result, expected, check_index_type=True) @@ -86,14 +98,14 @@ def test_loc_listlike(self): df = self.df2.copy() df.loc['e'] = 20 result = df.loc[['a', 'b', 'e']] - exp_index = pd.CategoricalIndex( + exp_index = CategoricalIndex( list('aaabbe'), categories=list('cabe'), name='B') expected = DataFrame({'A': [0, 1, 5, 2, 3, 20]}, index=exp_index) assert_frame_equal(result, expected) df = self.df2.copy() result = df.loc[['a', 'b', 'e']] - exp_index = pd.CategoricalIndex( + exp_index = CategoricalIndex( list('aaabbe'), categories=list('cabe'), name='B') expected = DataFrame({'A': [0, 1, 5, 2, 3, np.nan]}, index=exp_index) assert_frame_equal(result, expected, check_index_type=True) @@ -105,21 +117,21 @@ def test_loc_listlike_dtypes(self): # GH 11586 # unique categories and codes - index = pd.CategoricalIndex(['a', 'b', 'c']) + index = CategoricalIndex(['a', 'b', 'c']) df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=index) # unique slice res = df.loc[['a', 'b']] - exp_index = pd.CategoricalIndex(['a', 'b'], - categories=index.categories) + exp_index = CategoricalIndex(['a', 'b'], + categories=index.categories) exp = DataFrame({'A': [1, 2], 'B': [4, 5]}, index=exp_index) tm.assert_frame_equal(res, exp, check_index_type=True) # duplicated slice res = df.loc[['a', 'a', 'b']] - exp_index = pd.CategoricalIndex(['a', 'a', 'b'], - categories=index.categories) + exp_index = CategoricalIndex(['a', 'a', 'b'], + categories=index.categories) exp = DataFrame({'A': [1, 1, 2], 'B': [4, 4, 5]}, index=exp_index) tm.assert_frame_equal(res, exp, check_index_type=True) @@ -130,14 +142,14 @@ def test_loc_listlike_dtypes(self): df.loc[['a', 'x']] # duplicated categories and codes - index = pd.CategoricalIndex(['a', 'b', 'a']) + index = CategoricalIndex(['a', 'b', 'a']) df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=index) # unique slice res = df.loc[['a', 'b']] exp = DataFrame({'A': [1, 3, 2], 'B': [4, 6, 5]}, - index=pd.CategoricalIndex(['a', 'a', 'b'])) + index=CategoricalIndex(['a', 'a', 'b'])) tm.assert_frame_equal(res, exp, check_index_type=True) # duplicated slice @@ -145,7 +157,7 @@ def test_loc_listlike_dtypes(self): exp = DataFrame( {'A': [1, 3, 1, 3, 2], 'B': [4, 6, 4, 6, 5 - ]}, index=pd.CategoricalIndex(['a', 'a', 'a', 'a', 'b'])) + ]}, index=CategoricalIndex(['a', 'a', 'a', 'a', 'b'])) tm.assert_frame_equal(res, exp, check_index_type=True) with tm.assertRaisesRegexp( @@ -155,27 +167,27 @@ def test_loc_listlike_dtypes(self): df.loc[['a', 'x']] # contains unused category - index = pd.CategoricalIndex( + index = CategoricalIndex( ['a', 'b', 'a', 'c'], categories=list('abcde')) df = DataFrame({'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8]}, index=index) res = df.loc[['a', 'b']] - exp = DataFrame({'A': [1, 3, 2], - 'B': [5, 7, 6]}, index=pd.CategoricalIndex( - ['a', 'a', 'b'], categories=list('abcde'))) + exp = DataFrame({'A': [1, 3, 2], 'B': [5, 7, 6]}, + index=CategoricalIndex(['a', 'a', 'b'], + categories=list('abcde'))) tm.assert_frame_equal(res, exp, check_index_type=True) res = df.loc[['a', 'e']] exp = DataFrame({'A': [1, 3, np.nan], 'B': [5, 7, np.nan]}, - index=pd.CategoricalIndex(['a', 'a', 'e'], - categories=list('abcde'))) + index=CategoricalIndex(['a', 'a', 'e'], + categories=list('abcde'))) tm.assert_frame_equal(res, exp, check_index_type=True) # duplicated slice res = df.loc[['a', 'a', 'b']] exp = DataFrame({'A': [1, 3, 1, 3, 2], 'B': [5, 7, 5, 7, 6]}, - index=pd.CategoricalIndex(['a', 'a', 'a', 'a', 'b'], - categories=list('abcde'))) + index=CategoricalIndex(['a', 'a', 'a', 'a', 'b'], + categories=list('abcde'))) tm.assert_frame_equal(res, exp, check_index_type=True) with tm.assertRaisesRegexp( @@ -184,54 +196,77 @@ def test_loc_listlike_dtypes(self): 'that are in the categories'): df.loc[['a', 'x']] + def test_get_indexer_array(self): + arr = np.array([Timestamp('1999-12-31 00:00:00'), + Timestamp('2000-12-31 00:00:00')], dtype=object) + cats = [Timestamp('1999-12-31 00:00:00'), + Timestamp('2000-12-31 00:00:00')] + ci = CategoricalIndex(cats, + categories=cats, + ordered=False, dtype='category') + result = ci.get_indexer(arr) + expected = np.array([0, 1], dtype='intp') + tm.assert_numpy_array_equal(result, expected) + + def test_getitem_with_listlike(self): + # GH 16115 + cats = Categorical([Timestamp('12-31-1999'), + Timestamp('12-31-2000')]) + + expected = DataFrame([[1, 0], [0, 1]], dtype='uint8', + index=[0, 1], columns=cats) + dummies = pd.get_dummies(cats) + result = dummies[[c for c in dummies.columns]] + assert_frame_equal(result, expected) + def test_ix_categorical_index(self): # GH 12531 - df = pd.DataFrame(np.random.randn(3, 3), - index=list('ABC'), columns=list('XYZ')) + df = DataFrame(np.random.randn(3, 3), + index=list('ABC'), columns=list('XYZ')) cdf = df.copy() - cdf.index = pd.CategoricalIndex(df.index) - cdf.columns = pd.CategoricalIndex(df.columns) + cdf.index = CategoricalIndex(df.index) + cdf.columns = CategoricalIndex(df.columns) - expect = pd.Series(df.loc['A', :], index=cdf.columns, name='A') + expect = Series(df.loc['A', :], index=cdf.columns, name='A') assert_series_equal(cdf.loc['A', :], expect) - expect = pd.Series(df.loc[:, 'X'], index=cdf.index, name='X') + expect = Series(df.loc[:, 'X'], index=cdf.index, name='X') assert_series_equal(cdf.loc[:, 'X'], expect) - exp_index = pd.CategoricalIndex(list('AB'), categories=['A', 'B', 'C']) - expect = pd.DataFrame(df.loc[['A', 'B'], :], columns=cdf.columns, - index=exp_index) + exp_index = CategoricalIndex(list('AB'), categories=['A', 'B', 'C']) + expect = DataFrame(df.loc[['A', 'B'], :], columns=cdf.columns, + index=exp_index) assert_frame_equal(cdf.loc[['A', 'B'], :], expect) - exp_columns = pd.CategoricalIndex(list('XY'), - categories=['X', 'Y', 'Z']) - expect = pd.DataFrame(df.loc[:, ['X', 'Y']], index=cdf.index, - columns=exp_columns) + exp_columns = CategoricalIndex(list('XY'), + categories=['X', 'Y', 'Z']) + expect = DataFrame(df.loc[:, ['X', 'Y']], index=cdf.index, + columns=exp_columns) assert_frame_equal(cdf.loc[:, ['X', 'Y']], expect) # non-unique - df = pd.DataFrame(np.random.randn(3, 3), - index=list('ABA'), columns=list('XYX')) + df = DataFrame(np.random.randn(3, 3), + index=list('ABA'), columns=list('XYX')) cdf = df.copy() - cdf.index = pd.CategoricalIndex(df.index) - cdf.columns = pd.CategoricalIndex(df.columns) + cdf.index = CategoricalIndex(df.index) + cdf.columns = CategoricalIndex(df.columns) - exp_index = pd.CategoricalIndex(list('AA'), categories=['A', 'B']) - expect = pd.DataFrame(df.loc['A', :], columns=cdf.columns, - index=exp_index) + exp_index = CategoricalIndex(list('AA'), categories=['A', 'B']) + expect = DataFrame(df.loc['A', :], columns=cdf.columns, + index=exp_index) assert_frame_equal(cdf.loc['A', :], expect) - exp_columns = pd.CategoricalIndex(list('XX'), categories=['X', 'Y']) - expect = pd.DataFrame(df.loc[:, 'X'], index=cdf.index, - columns=exp_columns) + exp_columns = CategoricalIndex(list('XX'), categories=['X', 'Y']) + expect = DataFrame(df.loc[:, 'X'], index=cdf.index, + columns=exp_columns) assert_frame_equal(cdf.loc[:, 'X'], expect) - expect = pd.DataFrame(df.loc[['A', 'B'], :], columns=cdf.columns, - index=pd.CategoricalIndex(list('AAB'))) + expect = DataFrame(df.loc[['A', 'B'], :], columns=cdf.columns, + index=CategoricalIndex(list('AAB'))) assert_frame_equal(cdf.loc[['A', 'B'], :], expect) - expect = pd.DataFrame(df.loc[:, ['X', 'Y']], index=cdf.index, - columns=pd.CategoricalIndex(list('XXY'))) + expect = DataFrame(df.loc[:, ['X', 'Y']], index=cdf.index, + columns=CategoricalIndex(list('XXY'))) assert_frame_equal(cdf.loc[:, ['X', 'Y']], expect) def test_read_only_source(self): @@ -281,13 +316,13 @@ def test_reindexing(self): # then return a Categorical cats = list('cabe') - result = self.df2.reindex(pd.Categorical(['a', 'd'], categories=cats)) + result = self.df2.reindex(Categorical(['a', 'd'], categories=cats)) expected = DataFrame({'A': [0, 1, 5, np.nan], 'B': Series(list('aaad')).astype( 'category', categories=cats)}).set_index('B') assert_frame_equal(result, expected, check_index_type=True) - result = self.df2.reindex(pd.Categorical(['a'], categories=cats)) + result = self.df2.reindex(Categorical(['a'], categories=cats)) expected = DataFrame({'A': [0, 1, 5], 'B': Series(list('aaa')).astype( 'category', categories=cats)}).set_index('B') @@ -309,7 +344,7 @@ def test_reindexing(self): assert_frame_equal(result, expected, check_index_type=True) # give back the type of categorical that we received - result = self.df2.reindex(pd.Categorical( + result = self.df2.reindex(Categorical( ['a', 'd'], categories=cats, ordered=True)) expected = DataFrame( {'A': [0, 1, 5, np.nan], @@ -317,7 +352,7 @@ def test_reindexing(self): ordered=True)}).set_index('B') assert_frame_equal(result, expected, check_index_type=True) - result = self.df2.reindex(pd.Categorical( + result = self.df2.reindex(Categorical( ['a', 'd'], categories=['a', 'd'])) expected = DataFrame({'A': [0, 1, 5, np.nan], 'B': Series(list('aaad')).astype( diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index 8960ae610f8d7..f41c977cc03e1 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -490,8 +490,8 @@ def test_dataframe_dummies_with_categorical(self): 'cat_x', 'cat_y']] assert_frame_equal(result, expected) - # GH12402 Add a new parameter `drop_first` to avoid collinearity def test_basic_drop_first(self): + # GH12402 Add a new parameter `drop_first` to avoid collinearity # Basic case s_list = list('abc') s_series = Series(s_list)
closes #16115 closes #16131
https://api.github.com/repos/pandas-dev/pandas/pulls/16123
2017-04-25T01:53:51Z
2017-04-26T15:15:04Z
2017-04-26T15:15:04Z
2017-04-26T16:05:20Z
MAINT: Rename assertRaisesRegexp to assert_raises_regex
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 6ec06f75de06d..cc14282934f16 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -29,9 +29,8 @@ import pandas.core.computation.expr as expr import pandas.util.testing as tm from pandas.util.testing import (assert_frame_equal, randbool, - assertRaisesRegexp, assert_numpy_array_equal, - assert_produces_warning, assert_series_equal, - slow) + assert_numpy_array_equal, assert_series_equal, + assert_produces_warning, slow) from pandas.compat import PY3, reduce _series_frame_incompatible = _bool_ops_syms @@ -1677,17 +1676,17 @@ def test_result_types2(self): def test_undefined_func(self): df = DataFrame({'a': np.random.randn(10)}) - with tm.assertRaisesRegexp(ValueError, - "\"mysin\" is not a supported function"): + with tm.assert_raises_regex( + ValueError, "\"mysin\" is not a supported function"): df.eval("mysin(a)", engine=self.engine, parser=self.parser) def test_keyword_arg(self): df = DataFrame({'a': np.random.randn(10)}) - with tm.assertRaisesRegexp(TypeError, - "Function \"sin\" does not support " - "keyword arguments"): + with tm.assert_raises_regex(TypeError, + "Function \"sin\" does not support " + "keyword arguments"): df.eval("sin(x=a)", engine=self.engine, parser=self.parser) @@ -1748,16 +1747,16 @@ def test_no_new_globals(self, engine, parser): def test_invalid_engine(): tm.skip_if_no_ne() - assertRaisesRegexp(KeyError, 'Invalid engine \'asdf\' passed', - pd.eval, 'x + y', local_dict={'x': 1, 'y': 2}, - engine='asdf') + tm.assert_raises_regex(KeyError, 'Invalid engine \'asdf\' passed', + pd.eval, 'x + y', local_dict={'x': 1, 'y': 2}, + engine='asdf') def test_invalid_parser(): tm.skip_if_no_ne() - assertRaisesRegexp(KeyError, 'Invalid parser \'asdf\' passed', - pd.eval, 'x + y', local_dict={'x': 1, 'y': 2}, - parser='asdf') + tm.assert_raises_regex(KeyError, 'Invalid parser \'asdf\' passed', + pd.eval, 'x + y', local_dict={'x': 1, 'y': 2}, + parser='asdf') _parsers = {'python': PythonExprVisitor, 'pytables': pytables.ExprVisitor, @@ -1795,18 +1794,20 @@ def test_invalid_local_variable_reference(engine, parser): for _expr in exprs: if parser != 'pandas': - with tm.assertRaisesRegexp(SyntaxError, "The '@' prefix is only"): + with tm.assert_raises_regex(SyntaxError, + "The '@' prefix is only"): pd.eval(_expr, engine=engine, parser=parser) else: - with tm.assertRaisesRegexp(SyntaxError, "The '@' prefix is not"): + with tm.assert_raises_regex(SyntaxError, + "The '@' prefix is not"): pd.eval(_expr, engine=engine, parser=parser) def test_numexpr_builtin_raises(engine, parser): sin, dotted_line = 1, 2 if engine == 'numexpr': - with tm.assertRaisesRegexp(NumExprClobberingError, - 'Variables in expression .+'): + with tm.assert_raises_regex(NumExprClobberingError, + 'Variables in expression .+'): pd.eval('sin + dotted_line', engine=engine, parser=parser) else: res = pd.eval('sin + dotted_line', engine=engine, parser=parser) @@ -1815,20 +1816,21 @@ def test_numexpr_builtin_raises(engine, parser): def test_bad_resolver_raises(engine, parser): cannot_resolve = 42, 3.0 - with tm.assertRaisesRegexp(TypeError, 'Resolver of type .+'): + with tm.assert_raises_regex(TypeError, 'Resolver of type .+'): pd.eval('1 + 2', resolvers=cannot_resolve, engine=engine, parser=parser) def test_empty_string_raises(engine, parser): # GH 13139 - with tm.assertRaisesRegexp(ValueError, 'expr cannot be an empty string'): + with tm.assert_raises_regex(ValueError, + 'expr cannot be an empty string'): pd.eval('', engine=engine, parser=parser) def test_more_than_one_expression_raises(engine, parser): - with tm.assertRaisesRegexp(SyntaxError, - 'only a single expression is allowed'): + with tm.assert_raises_regex(SyntaxError, + 'only a single expression is allowed'): pd.eval('1 + 1; 2 + 2', engine=engine, parser=parser) diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index dd8f65a8e48ff..35720b32d756c 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -257,7 +257,7 @@ def test_maybe_convert_numeric_infinities(self): tm.assert_numpy_array_equal(out, pos) # too many characters - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): lib.maybe_convert_numeric( np.array(['foo_' + infinity], dtype=object), na_values, maybe_int) @@ -320,7 +320,7 @@ def test_convert_numeric_uint64_nan(self): for coerce in (True, False): for arr, na_values in cases: if coerce: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): lib.maybe_convert_numeric(arr, na_values, coerce_numeric=coerce) else: @@ -339,7 +339,7 @@ def test_convert_numeric_int64_uint64(self): for coerce in (True, False): for case in cases: if coerce: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): lib.maybe_convert_numeric(case, set(), coerce_numeric=coerce) else: diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index b4b86d8ea1907..0a00d7e018f33 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -18,9 +18,7 @@ is_interval_dtype) import pandas as pd -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_series_equal, assert_frame_equal import pandas.util.testing as tm @@ -36,7 +34,7 @@ def test_set_index(self): _ = self.mixed_frame['foo'] # noqa self.mixed_frame.index = idx assert self.mixed_frame['foo'].index is idx - with assertRaisesRegexp(ValueError, 'Length mismatch'): + with tm.assert_raises_regex(ValueError, 'Length mismatch'): self.mixed_frame.index = idx[::2] def test_set_index_cast(self): @@ -111,7 +109,8 @@ def test_set_index2(self): assert_frame_equal(df3, expected_nodrop) # corner case - with assertRaisesRegexp(ValueError, 'Index has duplicate keys'): + with tm.assert_raises_regex(ValueError, + 'Index has duplicate keys'): df.set_index('A', verify_integrity=True) # append @@ -136,7 +135,8 @@ def test_set_index_nonuniq(self): 'C': ['a', 'b', 'c', 'd', 'e'], 'D': np.random.randn(5), 'E': np.random.randn(5)}) - with assertRaisesRegexp(ValueError, 'Index has duplicate keys'): + with tm.assert_raises_regex(ValueError, + 'Index has duplicate keys'): df.set_index('A', verify_integrity=True, inplace=True) assert 'A' in df @@ -338,7 +338,7 @@ def test_set_index_empty_column(self): def test_set_columns(self): cols = Index(np.arange(len(self.mixed_frame.columns))) self.mixed_frame.columns = cols - with assertRaisesRegexp(ValueError, 'Length mismatch'): + with tm.assert_raises_regex(ValueError, 'Length mismatch'): self.mixed_frame.columns = cols[::2] def test_dti_set_index_reindex(self): diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 0941f0af6bec5..45d93c187e0b7 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -779,7 +779,7 @@ def wrapper(x): # assert_series_equal(result, comp) # bad axis - tm.assertRaisesRegexp(ValueError, 'No axis named 2', f, axis=2) + tm.assert_raises_regex(ValueError, 'No axis named 2', f, axis=2) # make sure works on mixed-type frame getattr(self.mixed_frame, name)(axis=0) getattr(self.mixed_frame, name)(axis=1) @@ -1749,7 +1749,7 @@ def test_numpy_round(self): tm.assert_frame_equal(out, expected) msg = "the 'out' parameter is not supported" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): np.round(df, decimals=0, out=df) def test_round_mixed_type(self): @@ -1897,7 +1897,8 @@ def test_dot(self): exp = a.dot(a.iloc[0]) tm.assert_series_equal(result, exp) - with tm.assertRaisesRegexp(ValueError, 'Dot product shape mismatch'): + with tm.assert_raises_regex(ValueError, + 'Dot product shape mismatch'): a.dot(row[:-1]) a = np.random.rand(1, 5) @@ -1914,7 +1915,7 @@ def test_dot(self): df = DataFrame(randn(3, 4), index=[1, 2, 3], columns=lrange(4)) df2 = DataFrame(randn(5, 3), index=lrange(5), columns=[1, 2, 3]) - with tm.assertRaisesRegexp(ValueError, 'aligned'): + with tm.assert_raises_regex(ValueError, 'aligned'): df.dot(df2) @@ -1986,7 +1987,7 @@ def test_n(self, df_strings, method, n, order): error_msg = self.dtype_error_msg_template.format( column='b', method=method, dtype='object') - with tm.assertRaisesRegexp(TypeError, error_msg): + with tm.assert_raises_regex(TypeError, error_msg): getattr(df, method)(n, order) else: ascending = method == 'nsmallest' @@ -2003,7 +2004,7 @@ def test_n_error(self, df_main_dtypes, method, columns): df = df_main_dtypes error_msg = self.dtype_error_msg_template.format( column=columns[1], method=method, dtype=df[columns[1]].dtype) - with tm.assertRaisesRegexp(TypeError, error_msg): + with tm.assert_raises_regex(TypeError, error_msg): getattr(df, method)(2, columns) def test_n_all_dtypes(self, df_main_dtypes): diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 9e16698bab39c..bd4abd6fcd822 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -20,8 +20,7 @@ from pandas.util.testing import (assert_almost_equal, assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) + assert_frame_equal) import pandas.util.testing as tm @@ -91,11 +90,14 @@ def test_get_axis(self): assert f._get_axis(0) is f.index assert f._get_axis(1) is f.columns - assertRaisesRegexp(ValueError, 'No axis named', f._get_axis_number, 2) - assertRaisesRegexp(ValueError, 'No axis.*foo', f._get_axis_name, 'foo') - assertRaisesRegexp(ValueError, 'No axis.*None', f._get_axis_name, None) - assertRaisesRegexp(ValueError, 'No axis named', f._get_axis_number, - None) + tm.assert_raises_regex( + ValueError, 'No axis named', f._get_axis_number, 2) + tm.assert_raises_regex( + ValueError, 'No axis.*foo', f._get_axis_name, 'foo') + tm.assert_raises_regex( + ValueError, 'No axis.*None', f._get_axis_name, None) + tm.assert_raises_regex(ValueError, 'No axis named', + f._get_axis_number, None) def test_keys(self): getkeys = self.frame.keys diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index e8f34b977a707..b8be7c19203fa 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -699,23 +699,23 @@ def test_filter(self): tm.assert_frame_equal(filtered, expected) # pass in None - with tm.assertRaisesRegexp(TypeError, 'Must pass'): + with tm.assert_raises_regex(TypeError, 'Must pass'): self.frame.filter() - with tm.assertRaisesRegexp(TypeError, 'Must pass'): + with tm.assert_raises_regex(TypeError, 'Must pass'): self.frame.filter(items=None) - with tm.assertRaisesRegexp(TypeError, 'Must pass'): + with tm.assert_raises_regex(TypeError, 'Must pass'): self.frame.filter(axis=1) # test mutually exclusive arguments - with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$', like='bbi') - with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$', axis=1) - with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$') - with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], like='bbi', axis=0) - with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assert_raises_regex(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], like='bbi') # objects diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 63c1f0a50fbed..5e85b890be569 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -17,8 +17,7 @@ from pandas.util.testing import (assert_almost_equal, assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) + assert_frame_equal) import pandas.util.testing as tm @@ -481,7 +480,7 @@ def test_convert_objects(self): # via astype, but errors converted = self.mixed_frame.copy() - with assertRaisesRegexp(ValueError, 'invalid literal'): + with tm.assert_raises_regex(ValueError, 'invalid literal'): converted['H'].astype('int32') # mixed in a single column diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py index 6f06a55ad065e..0e4184b07f22e 100644 --- a/pandas/tests/frame/test_combine_concat.py +++ b/pandas/tests/frame/test_combine_concat.py @@ -15,9 +15,7 @@ from pandas.tests.frame.common import TestData import pandas.util.testing as tm -from pandas.util.testing import (assertRaisesRegexp, - assert_frame_equal, - assert_series_equal) +from pandas.util.testing import assert_frame_equal, assert_series_equal class TestDataFrameConcatCommon(tm.TestCase, TestData): @@ -78,11 +76,13 @@ def test_append_series_dict(self): columns=['foo', 'bar', 'baz', 'qux']) series = df.loc[4] - with assertRaisesRegexp(ValueError, 'Indexes have overlapping values'): + with tm.assert_raises_regex(ValueError, + 'Indexes have overlapping values'): df.append(series, verify_integrity=True) series.name = None - with assertRaisesRegexp(TypeError, 'Can only append a Series if ' - 'ignore_index=True'): + with tm.assert_raises_regex(TypeError, + 'Can only append a Series if ' + 'ignore_index=True'): df.append(series, verify_integrity=True) result = df.append(series[::-1], ignore_index=True) @@ -270,7 +270,7 @@ def test_update_raise(self): other = DataFrame([[2., nan], [nan, 7]], index=[1, 3], columns=[1, 2]) - with assertRaisesRegexp(ValueError, "Data overlaps"): + with tm.assert_raises_regex(ValueError, "Data overlaps"): df.update(other, raise_conflict=True) def test_update_from_non_df(self): @@ -419,7 +419,7 @@ def test_concat_axis_parameter(self): assert_frame_equal(concatted_1_series, expected_columns_series) # Testing ValueError - with assertRaisesRegexp(ValueError, 'No axis named'): + with tm.assert_raises_regex(ValueError, 'No axis named'): pd.concat([series1, series2], axis='something') def test_concat_numerical_names(self): diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index f6cdb37a2477a..db0293b71c3a3 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -290,37 +290,40 @@ def test_constructor_multi_index(self): def test_constructor_error_msgs(self): msg = "Empty data passed with indices specified." # passing an empty array with columns specified. - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): DataFrame(np.empty(0), columns=list('abc')) msg = "Mixing dicts with non-Series may lead to ambiguous ordering." # mix dict and array, wrong size - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): DataFrame({'A': {'a': 'a', 'b': 'b'}, 'B': ['a', 'b', 'c']}) # wrong size ndarray, GH 3105 msg = r"Shape of passed values is \(3, 4\), indices imply \(3, 3\)" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): DataFrame(np.arange(12).reshape((4, 3)), columns=['foo', 'bar', 'baz'], index=pd.date_range('2000-01-01', periods=3)) # higher dim raise exception - with tm.assertRaisesRegexp(ValueError, 'Must pass 2-d input'): + with tm.assert_raises_regex(ValueError, 'Must pass 2-d input'): DataFrame(np.zeros((3, 3, 3)), columns=['A', 'B', 'C'], index=[1]) # wrong size axis labels - with tm.assertRaisesRegexp(ValueError, "Shape of passed values is " - r"\(3, 2\), indices imply \(3, 1\)"): + with tm.assert_raises_regex(ValueError, "Shape of passed values " + "is \(3, 2\), indices " + "imply \(3, 1\)"): DataFrame(np.random.rand(2, 3), columns=['A', 'B', 'C'], index=[1]) - with tm.assertRaisesRegexp(ValueError, "Shape of passed values is " - r"\(3, 2\), indices imply \(2, 2\)"): + with tm.assert_raises_regex(ValueError, "Shape of passed values " + "is \(3, 2\), indices " + "imply \(2, 2\)"): DataFrame(np.random.rand(2, 3), columns=['A', 'B'], index=[1, 2]) - with tm.assertRaisesRegexp(ValueError, 'If using all scalar values, ' - 'you must pass an index'): + with tm.assert_raises_regex(ValueError, "If using all scalar " + "values, you must pass " + "an index"): DataFrame({'a': False, 'b': True}) def test_constructor_with_embedded_frames(self): @@ -542,14 +545,14 @@ def _check_basic_constructor(self, empty): # wrong size axis labels msg = r'Shape of passed values is \(3, 2\), indices imply \(3, 1\)' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): DataFrame(mat, columns=['A', 'B', 'C'], index=[1]) msg = r'Shape of passed values is \(3, 2\), indices imply \(2, 2\)' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): DataFrame(mat, columns=['A', 'B'], index=[1, 2]) # higher dim raise exception - with tm.assertRaisesRegexp(ValueError, 'Must pass 2-d input'): + with tm.assert_raises_regex(ValueError, 'Must pass 2-d input'): DataFrame(empty((3, 3, 3)), columns=['A', 'B', 'C'], index=[1]) @@ -739,7 +742,7 @@ def test_constructor_arrays_and_scalars(self): exp = DataFrame({'a': df['a'].values, 'b': [True] * 10}) tm.assert_frame_equal(df, exp) - with tm.assertRaisesRegexp(ValueError, 'must pass an index'): + with tm.assert_raises_regex(ValueError, 'must pass an index'): DataFrame({'a': False, 'b': True}) def test_constructor_DataFrame(self): @@ -772,13 +775,13 @@ def test_constructor_more(self): # corner, silly # TODO: Fix this Exception to be better... - with tm.assertRaisesRegexp(ValueError, 'constructor not ' - 'properly called'): + with tm.assert_raises_regex(ValueError, 'constructor not ' + 'properly called'): DataFrame((1, 2, 3)) # can't cast mat = np.array(['foo', 'bar'], dtype=object).reshape(2, 1) - with tm.assertRaisesRegexp(ValueError, 'cast'): + with tm.assert_raises_regex(ValueError, 'cast'): DataFrame(mat, index=[0, 1], columns=[0], dtype=float) dm = DataFrame(DataFrame(self.frame._series)) @@ -1004,8 +1007,8 @@ class CustomDict(dict): def test_constructor_ragged(self): data = {'A': randn(10), 'B': randn(8)} - with tm.assertRaisesRegexp(ValueError, - 'arrays must all be same length'): + with tm.assert_raises_regex(ValueError, + 'arrays must all be same length'): DataFrame(data) def test_constructor_scalar(self): @@ -1027,7 +1030,7 @@ def test_constructor_mixed_dict_and_Series(self): self.assertTrue(result.index.is_monotonic) # ordering ambiguous, raise exception - with tm.assertRaisesRegexp(ValueError, 'ambiguous ordering'): + with tm.assert_raises_regex(ValueError, 'ambiguous ordering'): DataFrame({'A': ['a', 'b'], 'B': {'a': 'a', 'b': 'b'}}) # this is OK though @@ -1155,8 +1158,9 @@ def test_constructor_from_items(self): tm.assert_frame_equal(recons, self.mixed_frame) self.assertEqual(recons['A'].dtype, np.float64) - with tm.assertRaisesRegexp(TypeError, - "Must pass columns with orient='index'"): + with tm.assert_raises_regex(TypeError, + "Must pass columns with " + "orient='index'"): DataFrame.from_items(row_items, orient='index') # orient='index', but thar be tuples @@ -1183,7 +1187,8 @@ def test_constructor_mix_series_nonseries(self): 'B': list(self.frame['B'])}, columns=['A', 'B']) tm.assert_frame_equal(df, self.frame.loc[:, ['A', 'B']]) - with tm.assertRaisesRegexp(ValueError, 'does not match index length'): + with tm.assert_raises_regex(ValueError, 'does not match ' + 'index length'): DataFrame({'A': self.frame['A'], 'B': list(self.frame['B'])[:-2]}) def test_constructor_miscast_na_int_dtype(self): @@ -1192,8 +1197,8 @@ def test_constructor_miscast_na_int_dtype(self): tm.assert_frame_equal(df, expected) def test_constructor_iterator_failure(self): - with tm.assertRaisesRegexp(TypeError, 'iterator'): - df = DataFrame(iter([1, 2, 3])) # noqa + with tm.assert_raises_regex(TypeError, 'iterator'): + DataFrame(iter([1, 2, 3])) def test_constructor_column_duplicates(self): # it works! #2079 @@ -1242,7 +1247,8 @@ def test_constructor_single_value(self): pytest.raises(ValueError, DataFrame, 'a', [1, 2]) pytest.raises(ValueError, DataFrame, 'a', columns=['a', 'c']) - with tm.assertRaisesRegexp(TypeError, 'incompatible data and dtype'): + with tm.assert_raises_regex(TypeError, 'incompatible data ' + 'and dtype'): DataFrame('a', [1, 2], ['a', 'c'], float) def test_constructor_with_datetimes(self): @@ -1526,7 +1532,7 @@ def test_from_records_to_records(self): # wrong length msg = r'Shape of passed values is \(3, 2\), indices imply \(3, 1\)' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): DataFrame.from_records(arr, index=index[:-1]) indexed_frame = DataFrame.from_records(arr, index='f1') diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 99141e3a8e1c4..ed6d72c08fdae 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -200,17 +200,21 @@ def test_select_dtypes_not_an_attr_but_still_valid_dtype(self): def test_select_dtypes_empty(self): df = DataFrame({'a': list('abc'), 'b': list(range(1, 4))}) - with tm.assertRaisesRegexp(ValueError, 'at least one of include or ' - 'exclude must be nonempty'): + with tm.assert_raises_regex(ValueError, 'at least one of ' + 'include or exclude ' + 'must be nonempty'): df.select_dtypes() def test_select_dtypes_raises_on_string(self): df = DataFrame({'a': list('abc'), 'b': list(range(1, 4))}) - with tm.assertRaisesRegexp(TypeError, 'include and exclude .+ non-'): + with tm.assert_raises_regex(TypeError, 'include and exclude ' + '.+ non-'): df.select_dtypes(include='object') - with tm.assertRaisesRegexp(TypeError, 'include and exclude .+ non-'): + with tm.assert_raises_regex(TypeError, 'include and exclude ' + '.+ non-'): df.select_dtypes(exclude='object') - with tm.assertRaisesRegexp(TypeError, 'include and exclude .+ non-'): + with tm.assert_raises_regex(TypeError, 'include and exclude ' + '.+ non-'): df.select_dtypes(include=int, exclude='object') def test_select_dtypes_bad_datetime64(self): @@ -220,10 +224,10 @@ def test_select_dtypes_bad_datetime64(self): 'd': np.arange(4.0, 7.0, dtype='float64'), 'e': [True, False, True], 'f': pd.date_range('now', periods=3).values}) - with tm.assertRaisesRegexp(ValueError, '.+ is too specific'): + with tm.assert_raises_regex(ValueError, '.+ is too specific'): df.select_dtypes(include=['datetime64[D]']) - with tm.assertRaisesRegexp(ValueError, '.+ is too specific'): + with tm.assert_raises_regex(ValueError, '.+ is too specific'): df.select_dtypes(exclude=['datetime64[as]']) def test_select_dtypes_datetime_with_tz(self): @@ -251,11 +255,11 @@ def test_select_dtypes_str_raises(self): except NameError: pass for dt in string_dtypes: - with tm.assertRaisesRegexp(TypeError, - 'string dtypes are not allowed'): + with tm.assert_raises_regex(TypeError, + 'string dtypes are not allowed'): df.select_dtypes(include=[dt]) - with tm.assertRaisesRegexp(TypeError, - 'string dtypes are not allowed'): + with tm.assert_raises_regex(TypeError, + 'string dtypes are not allowed'): df.select_dtypes(exclude=[dt]) def test_select_dtypes_bad_arg_raises(self): @@ -266,7 +270,8 @@ def test_select_dtypes_bad_arg_raises(self): 'd': np.arange(4.0, 7.0, dtype='float64'), 'e': [True, False, True], 'f': pd.date_range('now', periods=3).values}) - with tm.assertRaisesRegexp(TypeError, 'data type.*not understood'): + with tm.assert_raises_regex(TypeError, 'data type.' + '*not understood'): df.select_dtypes(['blargy, blarg, blarg']) def test_select_dtypes_typecodes(self): @@ -396,7 +401,7 @@ def test_astype_cast_nan_inf_int(self): for this_type in types: for this_val in values: df = DataFrame([this_val]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.astype(this_type) def test_astype_str(self): diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 5f8d04fdb16bd..be4e69fe99a4e 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -28,8 +28,7 @@ is_scalar) from pandas.util.testing import (assert_almost_equal, assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) + assert_frame_equal) from pandas.core.indexing import IndexingError import pandas.util.testing as tm @@ -53,7 +52,7 @@ def test_getitem(self): assert self.frame[key] is not None assert 'random' not in self.frame - with assertRaisesRegexp(KeyError, 'random'): + with tm.assert_raises_regex(KeyError, 'random'): self.frame['random'] df = self.frame.copy() @@ -116,9 +115,9 @@ def test_getitem_list(self): self.assertEqual(result.columns.name, 'foo') - with assertRaisesRegexp(KeyError, 'not in index'): + with tm.assert_raises_regex(KeyError, 'not in index'): self.frame[['B', 'A', 'food']] - with assertRaisesRegexp(KeyError, 'not in index'): + with tm.assert_raises_regex(KeyError, 'not in index'): self.frame[Index(['B', 'A', 'foo'])] # tuples @@ -152,12 +151,13 @@ def test_setitem_list(self): assert_series_equal(self.frame['B'], data['A'], check_names=False) assert_series_equal(self.frame['A'], data['B'], check_names=False) - with assertRaisesRegexp(ValueError, - 'Columns must be same length as key'): + with tm.assert_raises_regex(ValueError, + 'Columns must be same length as key'): data[['A']] = self.frame[['A', 'B']] - with assertRaisesRegexp(ValueError, 'Length of values does not match ' - 'length of index'): + with tm.assert_raises_regex(ValueError, 'Length of values ' + 'does not match ' + 'length of index'): data['A'] = range(len(data.index) - 1) df = DataFrame(0, lrange(3), ['tt1', 'tt2'], dtype=np.int_) @@ -239,13 +239,13 @@ def test_getitem_boolean(self): subframe = self.tsframe[indexer] tm.assert_index_equal(subindex, subframe.index) - with assertRaisesRegexp(ValueError, 'Item wrong length'): + with tm.assert_raises_regex(ValueError, 'Item wrong length'): self.tsframe[indexer[:-1]] subframe_obj = self.tsframe[indexer_obj] assert_frame_equal(subframe_obj, subframe) - with tm.assertRaisesRegexp(ValueError, 'boolean values only'): + with tm.assert_raises_regex(ValueError, 'boolean values only'): self.tsframe[self.tsframe] # test that Series work @@ -522,8 +522,9 @@ def test_setitem_boolean(self): values[values == 2] = 3 assert_almost_equal(df.values, values) - with assertRaisesRegexp(TypeError, 'Must pass DataFrame with boolean ' - 'values only'): + with tm.assert_raises_regex(TypeError, 'Must pass ' + 'DataFrame with ' + 'boolean values only'): df[df * 0] = 2 # index with DataFrame @@ -1350,7 +1351,7 @@ def test_getitem_fancy_ints(self): def test_getitem_setitem_fancy_exceptions(self): ix = self.frame.iloc - with assertRaisesRegexp(IndexingError, 'Too many indexers'): + with tm.assert_raises_regex(IndexingError, 'Too many indexers'): ix[:, :, :] with pytest.raises(IndexingError): @@ -1664,7 +1665,7 @@ def testit(df): with pytest.raises(KeyError): self.frame.lookup([self.frame.index[0]], ['xyz']) - with tm.assertRaisesRegexp(ValueError, 'same size'): + with tm.assert_raises_regex(ValueError, 'same size'): self.frame.lookup(['a', 'b', 'c'], ['a']) def test_set_value(self): @@ -2289,7 +2290,7 @@ def test_boolean_indexing(self): df1[df1 > 2.0 * df2] = -1 assert_frame_equal(df1, expected) - with assertRaisesRegexp(ValueError, 'Item wrong length'): + with tm.assert_raises_regex(ValueError, 'Item wrong length'): df1[df1.index[:-1] > 2] = -1 def test_boolean_indexing_mixed(self): @@ -2320,7 +2321,8 @@ def test_boolean_indexing_mixed(self): assert_frame_equal(df2, expected) df['foo'] = 'test' - with tm.assertRaisesRegexp(TypeError, 'boolean setting on mixed-type'): + with tm.assert_raises_regex(TypeError, 'boolean setting ' + 'on mixed-type'): df[df > 0.3] = 1 def test_where(self): @@ -2498,7 +2500,7 @@ def test_where_invalid_input(self): ] for cond in conds: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.where(cond) df['b'] = 2 @@ -2514,7 +2516,7 @@ def test_where_invalid_input(self): ] for cond in conds: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.where(cond) def test_where_dataframe_col_match(self): @@ -2527,7 +2529,7 @@ def test_where_dataframe_col_match(self): cond.columns = ["a", "b", "c"] # Columns no longer match. msg = "Boolean array expected for the condition" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.where(cond) def test_where_ndframe_align(self): @@ -2535,7 +2537,7 @@ def test_where_ndframe_align(self): df = DataFrame([[1, 2, 3], [4, 5, 6]]) cond = [True] - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.where(cond) expected = DataFrame([[1, 2, 3], [np.nan, np.nan, np.nan]]) @@ -2544,7 +2546,7 @@ def test_where_ndframe_align(self): tm.assert_frame_equal(out, expected) cond = np.array([False, True, False, True]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.where(cond) expected = DataFrame([[np.nan, np.nan, np.nan], [4, 5, 6]]) @@ -2632,7 +2634,8 @@ def test_where_none(self): df = DataFrame([{'A': 1, 'B': np.nan, 'C': 'Test'}, { 'A': np.nan, 'B': 'Test', 'C': np.nan}]) expected = df.where(~isnull(df), None) - with tm.assertRaisesRegexp(TypeError, 'boolean setting on mixed-type'): + with tm.assert_raises_regex(TypeError, 'boolean setting ' + 'on mixed-type'): df.where(~isnull(df), None, inplace=True) def test_where_align(self): @@ -2890,7 +2893,7 @@ def test_type_error_multiindex(self): dg = df.pivot_table(index='i', columns='c', values=['x', 'y']) - with assertRaisesRegexp(TypeError, "is an invalid key"): + with tm.assert_raises_regex(TypeError, "is an invalid key"): str(dg[:, 0]) index = Index(range(2), name='i') diff --git a/pandas/tests/frame/test_join.py b/pandas/tests/frame/test_join.py index f7a510023ca07..21807cb42aa6e 100644 --- a/pandas/tests/frame/test_join.py +++ b/pandas/tests/frame/test_join.py @@ -86,12 +86,13 @@ def test_join_index(frame): tm.assert_index_equal(joined.index, frame.index.sort_values()) tm.assert_index_equal(joined.columns, expected_columns) - tm.assertRaisesRegexp(ValueError, 'join method', f.join, f2, how='foo') + tm.assert_raises_regex( + ValueError, 'join method', f.join, f2, how='foo') # corner case - overlapping columns for how in ('outer', 'left', 'inner'): - with tm.assertRaisesRegexp(ValueError, 'columns overlap but ' - 'no suffix'): + with tm.assert_raises_regex(ValueError, 'columns overlap but ' + 'no suffix'): frame.join(frame, how=how) @@ -122,7 +123,7 @@ def test_join_index_series(frame): tm.assert_frame_equal(joined, frame, check_names=False) s.name = None - tm.assertRaisesRegexp(ValueError, 'must have a name', df.join, s) + tm.assert_raises_regex(ValueError, 'must have a name', df.join, s) def test_join_overlap(frame): diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 74f1d3292fa4e..721cee7f3141b 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -13,9 +13,7 @@ date_range) import pandas as pd -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_series_equal, assert_frame_equal import pandas.util.testing as tm from pandas.tests.frame.common import TestData, _check_mixed_float @@ -439,7 +437,8 @@ def test_fillna_dict_series(self): assert_frame_equal(result, expected) # disable this for now - with assertRaisesRegexp(NotImplementedError, 'column by column'): + with tm.assert_raises_regex(NotImplementedError, + 'column by column'): df.fillna(df.max(1), axis=1) def test_fillna_dataframe(self): @@ -479,7 +478,7 @@ def test_fillna_columns(self): assert_frame_equal(result, expected) def test_fillna_invalid_method(self): - with assertRaisesRegexp(ValueError, 'ffil'): + with tm.assert_raises_regex(ValueError, 'ffil'): self.frame.fillna(method='ffil') def test_fillna_invalid_value(self): diff --git a/pandas/tests/frame/test_mutate_columns.py b/pandas/tests/frame/test_mutate_columns.py index dfaeaea49cf75..b82a549bae3a0 100644 --- a/pandas/tests/frame/test_mutate_columns.py +++ b/pandas/tests/frame/test_mutate_columns.py @@ -7,7 +7,7 @@ from pandas import DataFrame, Series, Index, MultiIndex -from pandas.util.testing import assert_frame_equal, assertRaisesRegexp +from pandas.util.testing import assert_frame_equal import pandas.util.testing as tm @@ -91,7 +91,7 @@ def test_insert_error_msmgs(self): s = DataFrame({'foo': ['a', 'b', 'c', 'a'], 'fiz': [ 'g', 'h', 'i', 'j']}).set_index('foo') msg = 'cannot reindex from a duplicate axis' - with assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df['newcol'] = s # GH 4107, more descriptive error message @@ -99,7 +99,7 @@ def test_insert_error_msmgs(self): columns=['a', 'b', 'c', 'd']) msg = 'incompatible index of inserted column with frame index' - with assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): df['gr'] = df.groupby(['b', 'c']).count() def test_insert_benchmark(self): @@ -143,7 +143,7 @@ def test_insert(self): result = Series(dict(float64=4, float32=2, int32=1)) self.assertTrue((df.get_dtype_counts() == result).all()) - with assertRaisesRegexp(ValueError, 'already exists'): + with tm.assert_raises_regex(ValueError, 'already exists'): df.insert(1, 'a', df['b']) pytest.raises(ValueError, df.insert, 1, 'c', df['b']) diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 9d5a99eaf2e9d..5c141b6a46eec 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -9,9 +9,7 @@ from pandas import DataFrame, Series, MultiIndex, date_range import pandas as pd -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_series_equal, assert_frame_equal import pandas.util.testing as tm @@ -53,7 +51,7 @@ def check(result, expected=None): [2, 1, 3, 5, 'bah']], columns=['foo', 'bar', 'foo', 'hello', 'string']) check(df, expected) - with assertRaisesRegexp(ValueError, 'Length of value'): + with tm.assert_raises_regex(ValueError, 'Length of value'): df.insert(0, 'AnotherColumn', range(len(df.index) - 1)) # insert same dtype @@ -103,8 +101,8 @@ def check(result, expected=None): check(df, expected) # insert a dup - assertRaisesRegexp(ValueError, 'cannot insert', - df.insert, 2, 'new_col', 4.) + tm.assert_raises_regex(ValueError, 'cannot insert', + df.insert, 2, 'new_col', 4.) df.insert(2, 'new_col', 4., allow_duplicates=True) expected = DataFrame([[1, 1, 4., 5., 'bah', 3], [1, 2, 4., 5., 'bah', 3], diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index 3f77bc754a525..d90e859509454 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -20,8 +20,7 @@ from pandas.util.testing import (assert_numpy_array_equal, assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) + assert_frame_equal) import pandas.util.testing as tm @@ -423,10 +422,10 @@ def test_arith_flex_frame(self): # ndim >= 3 ndim_5 = np.ones(self.frame.shape + (3, 4, 5)) msg = "Unable to coerce to Series/DataFrame" - with assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): f(self.frame, ndim_5) - with assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): getattr(self.frame, op)(ndim_5) # res_add = self.frame.add(self.frame) @@ -448,9 +447,9 @@ def test_arith_flex_frame(self): result = self.frame[:0].add(self.frame) assert_frame_equal(result, self.frame * np.nan) - with assertRaisesRegexp(NotImplementedError, 'fill_value'): + with tm.assert_raises_regex(NotImplementedError, 'fill_value'): self.frame.add(self.frame.iloc[0], fill_value=3) - with assertRaisesRegexp(NotImplementedError, 'fill_value'): + with tm.assert_raises_regex(NotImplementedError, 'fill_value'): self.frame.add(self.frame.iloc[0], axis='index', fill_value=3) def test_binary_ops_align(self): @@ -589,7 +588,7 @@ def _check_unaligned_frame(meth, op, df, other): # NAs msg = "Unable to coerce to Series/DataFrame" assert_frame_equal(f(np.nan), o(df, np.nan)) - with assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): f(ndim_5) # Series @@ -921,8 +920,8 @@ def test_comp(func): result = func(df1, df2) tm.assert_numpy_array_equal(result.values, func(df1.values, df2.values)) - with tm.assertRaisesRegexp(ValueError, - 'Wrong number of dimensions'): + with tm.assert_raises_regex(ValueError, + 'Wrong number of dimensions'): func(df1, ndim_5) result2 = func(self.simple, row) @@ -933,9 +932,9 @@ def test_comp(func): tm.assert_numpy_array_equal(result3.values, func(self.frame.values, 0)) - with tm.assertRaisesRegexp(ValueError, - 'Can only compare identically' - '-labeled DataFrame'): + with tm.assert_raises_regex(ValueError, + 'Can only compare identically' + '-labeled DataFrame'): func(self.simple, self.simple[:2]) test_comp(operator.eq) @@ -1179,10 +1178,10 @@ def test_alignment_non_pandas(self): # length mismatch msg = 'Unable to coerce to Series, length must be 3: given 2' for val in [[1, 2], (1, 2), np.array([1, 2])]: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): align(df, val, 'index') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): align(df, val, 'columns') val = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) @@ -1196,10 +1195,10 @@ def test_alignment_non_pandas(self): # shape mismatch msg = 'Unable to coerce to DataFrame, shape must be' val = np.array([[1, 2, 3], [4, 5, 6]]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): align(df, val, 'index') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): align(df, val, 'columns') val = np.zeros((3, 3, 3)) diff --git a/pandas/tests/frame/test_period.py b/pandas/tests/frame/test_period.py index c1b5a92725868..194b6c0e251bc 100644 --- a/pandas/tests/frame/test_period.py +++ b/pandas/tests/frame/test_period.py @@ -106,7 +106,8 @@ def _get_with_delta(delta, freq='A-DEC'): tm.assert_index_equal(result.columns, exp_index) # invalid axis - tm.assertRaisesRegexp(ValueError, 'axis', df.to_timestamp, axis=2) + tm.assert_raises_regex( + ValueError, 'axis', df.to_timestamp, axis=2) result1 = df.to_timestamp('5t', axis=1) result2 = df.to_timestamp('t', axis=1) diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py index 1a5ba3ccad400..406f8107952ef 100644 --- a/pandas/tests/frame/test_quantile.py +++ b/pandas/tests/frame/test_quantile.py @@ -9,9 +9,7 @@ from pandas import (DataFrame, Series, Timestamp, _np_version_under1p11) import pandas as pd -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_series_equal, assert_frame_equal import pandas.util.testing as tm from pandas import _np_version_under1p9 @@ -189,21 +187,21 @@ def test_quantile_interpolation_np_lt_1p9(self): # interpolation method other than default linear expErrMsg = "Interpolation methods other than linear" df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3]) - with assertRaisesRegexp(ValueError, expErrMsg): + with tm.assert_raises_regex(ValueError, expErrMsg): df.quantile(.5, axis=1, interpolation='nearest') - with assertRaisesRegexp(ValueError, expErrMsg): + with tm.assert_raises_regex(ValueError, expErrMsg): df.quantile([.5, .75], axis=1, interpolation='lower') # test degenerate case df = DataFrame({'x': [], 'y': []}) - with assertRaisesRegexp(ValueError, expErrMsg): + with tm.assert_raises_regex(ValueError, expErrMsg): q = df.quantile(0.1, axis=0, interpolation='higher') # multi df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=['a', 'b', 'c']) - with assertRaisesRegexp(ValueError, expErrMsg): + with tm.assert_raises_regex(ValueError, expErrMsg): df.quantile([.25, .5], interpolation='midpoint') def test_quantile_multi(self): @@ -268,7 +266,7 @@ def test_quantile_datetime(self): def test_quantile_invalid(self): msg = 'percentiles should all be in the interval \\[0, 1\\]' for invalid in [-1, 2, [0.5, -1], [0.5, 2]]: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.tsframe.quantile(invalid) def test_quantile_box(self): diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index b787d63d3c754..2232205a57326 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -138,10 +138,10 @@ def test_query_non_str(self): df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'b']}) msg = "expr must be a string to be evaluated" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.query(lambda x: x.B == "b") - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.query(111) def test_query_empty_string(self): @@ -149,7 +149,7 @@ def test_query_empty_string(self): df = pd.DataFrame({'A': [1, 2, 3]}) msg = "expr cannot be an empty string" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df.query('') def test_eval_resolvers_as_list(self): @@ -552,8 +552,8 @@ def test_query_builtin(self): df = DataFrame(np.random.randint(m, size=(n, 3)), columns=list('abc')) df.index.name = 'sin' - with tm.assertRaisesRegexp(NumExprClobberingError, - 'Variables in expression.+'): + with tm.assert_raises_regex(NumExprClobberingError, + 'Variables in expression.+'): df.query('sin > 5', engine=engine, parser=parser) def test_query(self): @@ -686,8 +686,8 @@ def test_query_undefined_local(self): engine, parser = self.engine, self.parser skip_if_no_pandas_parser(parser) df = DataFrame(np.random.rand(10, 2), columns=list('ab')) - with tm.assertRaisesRegexp(UndefinedVariableError, - "local variable 'c' is not defined"): + with tm.assert_raises_regex(UndefinedVariableError, + "local variable 'c' is not defined"): df.query('a == @c', engine=engine, parser=parser) def test_index_resolvers_come_after_columns_with_the_same_name(self): @@ -1119,9 +1119,9 @@ def test_invalid_type_for_operator_raises(self): df = DataFrame({'a': [1, 2], 'b': ['c', 'd']}) ops = '+', '-', '*', '/' for op in ops: - with tm.assertRaisesRegexp(TypeError, - r"unsupported operand type\(s\) for " - r".+: '.+' and '.+'"): + with tm.assert_raises_regex(TypeError, + "unsupported operand type\(s\) " + "for .+: '.+' and '.+'"): df.eval('a {0} b'.format(op), engine=self.engine, parser=self.parser) diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index bb2baaf0e02e2..262734d093d4e 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -918,7 +918,7 @@ def test_replace_bool_with_bool(self): def test_replace_with_dict_with_bool_keys(self): df = DataFrame({0: [True, False], 1: [False, True]}) - with tm.assertRaisesRegexp(TypeError, 'Cannot compare types .+'): + with tm.assert_raises_regex(TypeError, 'Cannot compare types .+'): df.replace({'asdf': 'asdb', True: 'yes'}) def test_replace_truthy(self): @@ -929,7 +929,8 @@ def test_replace_truthy(self): def test_replace_int_to_int_chain(self): df = DataFrame({'a': lrange(1, 5)}) - with tm.assertRaisesRegexp(ValueError, "Replacement not allowed .+"): + with tm.assert_raises_regex(ValueError, + "Replacement not allowed .+"): df.replace({'a': dict(zip(range(1, 5), range(2, 6)))}) def test_replace_str_to_str_chain(self): @@ -937,7 +938,8 @@ def test_replace_str_to_str_chain(self): astr = a.astype(str) bstr = np.arange(2, 6).astype(str) df = DataFrame({'a': astr}) - with tm.assertRaisesRegexp(ValueError, "Replacement not allowed .+"): + with tm.assert_raises_regex(ValueError, + "Replacement not allowed .+"): df.replace({'a': dict(zip(astr, bstr))}) def test_replace_swapping_bug(self): diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 60f19b7e6c87b..c1905fa0476c4 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -17,9 +17,7 @@ Timedelta, Period) import pandas as pd -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_series_equal, assert_frame_equal import pandas.util.testing as tm @@ -67,7 +65,7 @@ def test_pivot_duplicates(self): data = DataFrame({'a': ['bar', 'bar', 'foo', 'foo', 'foo'], 'b': ['one', 'two', 'one', 'one', 'two'], 'c': [1., 2., 3., 3., 4.]}) - with assertRaisesRegexp(ValueError, 'duplicate entries'): + with tm.assert_raises_regex(ValueError, 'duplicate entries'): data.pivot('a', 'b', 'c') def test_pivot_empty(self): diff --git a/pandas/tests/frame/test_sorting.py b/pandas/tests/frame/test_sorting.py index f1bca0d6a99b8..bdb5fd0e8354c 100644 --- a/pandas/tests/frame/test_sorting.py +++ b/pandas/tests/frame/test_sorting.py @@ -11,9 +11,7 @@ from pandas import (DataFrame, Series, MultiIndex, Timestamp, date_range, NaT, IntervalIndex) -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_series_equal, assert_frame_equal import pandas.util.testing as tm @@ -88,7 +86,7 @@ def test_sort_values(self): assert_frame_equal(sorted_df, expected) msg = r'Length of ascending \(5\) != length of by \(2\)' - with assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): frame.sort_values(by=['A', 'B'], axis=0, ascending=[True] * 5) def test_sort_values_inplace(self): @@ -264,7 +262,7 @@ def test_sort_datetimes(self): def test_frame_column_inplace_sort_exception(self): s = self.frame['A'] - with assertRaisesRegexp(ValueError, "This Series is a view"): + with tm.assert_raises_regex(ValueError, "This Series is a view"): s.sort_values(inplace=True) cp = s.copy() @@ -420,26 +418,26 @@ def test_sort_index_duplicates(self): df = DataFrame([lrange(5, 9), lrange(4)], columns=['a', 'a', 'b', 'b']) - with assertRaisesRegexp(ValueError, 'duplicate'): + with tm.assert_raises_regex(ValueError, 'duplicate'): # use .sort_values #9816 with tm.assert_produces_warning(FutureWarning): df.sort_index(by='a') - with assertRaisesRegexp(ValueError, 'duplicate'): + with tm.assert_raises_regex(ValueError, 'duplicate'): df.sort_values(by='a') - with assertRaisesRegexp(ValueError, 'duplicate'): + with tm.assert_raises_regex(ValueError, 'duplicate'): # use .sort_values #9816 with tm.assert_produces_warning(FutureWarning): df.sort_index(by=['a']) - with assertRaisesRegexp(ValueError, 'duplicate'): + with tm.assert_raises_regex(ValueError, 'duplicate'): df.sort_values(by=['a']) - with assertRaisesRegexp(ValueError, 'duplicate'): + with tm.assert_raises_regex(ValueError, 'duplicate'): # use .sort_values #9816 with tm.assert_produces_warning(FutureWarning): # multi-column 'by' is separate codepath df.sort_index(by=['a', 'b']) - with assertRaisesRegexp(ValueError, 'duplicate'): + with tm.assert_raises_regex(ValueError, 'duplicate'): # multi-column 'by' is separate codepath df.sort_values(by=['a', 'b']) @@ -447,11 +445,11 @@ def test_sort_index_duplicates(self): # GH4370 df = DataFrame(np.random.randn(4, 2), columns=MultiIndex.from_tuples([('a', 0), ('a', 1)])) - with assertRaisesRegexp(ValueError, 'levels'): + with tm.assert_raises_regex(ValueError, 'levels'): # use .sort_values #9816 with tm.assert_produces_warning(FutureWarning): df.sort_index(by='a') - with assertRaisesRegexp(ValueError, 'levels'): + with tm.assert_raises_regex(ValueError, 'levels'): df.sort_values(by='a') # convert tuples to a list of tuples diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index 995abfb1ca01a..db4f4b909f7cb 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -156,7 +156,7 @@ class A(DataFrame): @property def bar(self): return self.i_dont_exist - with tm.assertRaisesRegexp(AttributeError, '.*i_dont_exist.*'): + with tm.assert_raises_regex(AttributeError, '.*i_dont_exist.*'): A().bar def test_subclass_align(self): diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 090f742a69b63..7a5afa178208a 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -16,9 +16,7 @@ import pandas as pd import pandas.tseries.offsets as offsets -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_series_equal, assert_frame_equal import pandas.util.testing as tm from pandas.compat import product @@ -220,8 +218,9 @@ def test_shift(self): assert_frame_equal(shifted2, shifted3) assert_frame_equal(ps, shifted2.shift(-1, 'B')) - assertRaisesRegexp(ValueError, 'does not match PeriodIndex freq', - ps.shift, freq='D') + tm.assert_raises_regex(ValueError, + 'does not match PeriodIndex freq', + ps.shift, freq='D') # shift other axis # GH 6371 @@ -281,7 +280,8 @@ def test_tshift(self): shifted3 = ps.tshift(freq=offsets.BDay()) assert_frame_equal(shifted, shifted3) - assertRaisesRegexp(ValueError, 'does not match', ps.tshift, freq='M') + tm.assert_raises_regex( + ValueError, 'does not match', ps.tshift, freq='M') # DatetimeIndex shifted = self.tsframe.tshift(1) diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index 0fd1df0b733f8..ffce525434ab5 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -17,9 +17,8 @@ from pandas.util.testing import (assert_almost_equal, assert_series_equal, assert_frame_equal, - ensure_clean, - makeCustomDataframe as mkdf, - assertRaisesRegexp, slow) + ensure_clean, slow, + makeCustomDataframe as mkdf) import pandas.util.testing as tm from pandas.tests.frame.common import TestData @@ -588,13 +587,13 @@ def _make_frame(names=None): for i in [6, 7]: msg = 'len of {i}, but only 5 lines in file'.format(i=i) - with assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): read_csv(path, tupleize_cols=False, header=lrange(i), index_col=0) # write with cols - with assertRaisesRegexp(TypeError, 'cannot specify cols with a ' - 'MultiIndex'): + with tm.assert_raises_regex(TypeError, 'cannot specify cols ' + 'with a MultiIndex'): df.to_csv(path, tupleize_cols=False, columns=['foo', 'bar']) with ensure_clean('__tmp_to_csv_multiindex__') as path: @@ -1106,11 +1105,11 @@ def test_to_csv_quoting(self): self.assertEqual(result, expected) msg = "need to escape, but no escapechar set" - tm.assertRaisesRegexp(csv.Error, msg, df.to_csv, - quoting=csv.QUOTE_NONE) - tm.assertRaisesRegexp(csv.Error, msg, df.to_csv, - quoting=csv.QUOTE_NONE, - escapechar=None) + tm.assert_raises_regex(csv.Error, msg, df.to_csv, + quoting=csv.QUOTE_NONE) + tm.assert_raises_regex(csv.Error, msg, df.to_csv, + quoting=csv.QUOTE_NONE, + escapechar=None) expected = """\ ,c_bool,c_float,c_int,c_string diff --git a/pandas/tests/groupby/test_aggregate.py b/pandas/tests/groupby/test_aggregate.py index e32dbb7846061..e3f166d2294e2 100644 --- a/pandas/tests/groupby/test_aggregate.py +++ b/pandas/tests/groupby/test_aggregate.py @@ -577,7 +577,8 @@ def test_cython_agg_nothing_to_agg_with_dates(self): 'b': ['foo', 'bar'] * 25, 'dates': pd.date_range('now', periods=50, freq='T')}) - with tm.assertRaisesRegexp(DataError, "No numeric types to aggregate"): + with tm.assert_raises_regex(DataError, + "No numeric types to aggregate"): frame.groupby('b').dates.mean() def test_cython_agg_frame_columns(self): diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py index 5f39f320b1ea1..2cfbe0ab68c8e 100644 --- a/pandas/tests/groupby/test_filters.py +++ b/pandas/tests/groupby/test_filters.py @@ -578,7 +578,8 @@ def test_filter_enforces_scalarness(self): ['worst', 'd', 'y'], ['best', 'd', 'z'], ], columns=['a', 'b', 'c']) - with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'): + with tm.assert_raises_regex(TypeError, + 'filter function returned a.*'): df.groupby('c').filter(lambda g: g['a'] == 'best') def test_filter_non_bool_raises(self): @@ -591,7 +592,8 @@ def test_filter_non_bool_raises(self): ['worst', 'd', 1], ['best', 'd', 1], ], columns=['a', 'b', 'c']) - with tm.assertRaisesRegexp(TypeError, 'filter function returned a.*'): + with tm.assert_raises_regex(TypeError, + 'filter function returned a.*'): df.groupby('a').filter(lambda g: g.c.mean()) def test_filter_dropna_with_empty_groups(self): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 8ca8ddded3073..177c2345ea143 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -14,7 +14,7 @@ from pandas.errors import UnsupportedFunctionCall, PerformanceWarning from pandas.util.testing import (assert_panel_equal, assert_frame_equal, assert_series_equal, assert_almost_equal, - assert_index_equal, assertRaisesRegexp) + assert_index_equal) from pandas.compat import (range, long, lrange, StringIO, lmap, lzip, map, zip, builtins, OrderedDict, product as cart_product) from pandas import compat @@ -82,7 +82,7 @@ def test_select_bad_cols(self): pytest.raises(KeyError, g.__getitem__, ['C']) # g[['C']] pytest.raises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']] - with assertRaisesRegexp(KeyError, '^[^A]+$'): + with tm.assert_raises_regex(KeyError, '^[^A]+$'): # A should not be referenced as a bad column... # will have to rethink regex if you change message! g[['A', 'C']] @@ -1874,16 +1874,14 @@ def test_groupby_args(self): def j(): frame.groupby() - tm.assertRaisesRegexp(TypeError, - "You have to supply one of 'by' and 'level'", - j) + tm.assert_raises_regex(TypeError, "You have to supply one of " + "'by' and 'level'", j) def k(): frame.groupby(by=None, level=None) - tm.assertRaisesRegexp(TypeError, - "You have to supply one of 'by' and 'level'", - k) + tm.assert_raises_regex(TypeError, "You have to supply one of " + "'by' and 'level'", k) def test_groupby_level_mapper(self): frame = self.mframe @@ -3753,10 +3751,10 @@ def test_numpy_compat(self): msg = "numpy operations are not valid with groupby" for func in ('mean', 'var', 'std', 'cumprod', 'cumsum'): - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(g, func), 1, 2, 3) - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(g, func), foo=1) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(g, func), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(g, func), foo=1) def test_grouping_string_repr(self): # GH 13394 diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 4624d43df6128..e0d81003e325f 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -556,7 +556,8 @@ def test_transform_with_non_scalar_group(self): df = pd.DataFrame(np.random.randint(1, 10, (4, 12)), columns=cols, index=['A', 'C', 'G', 'T']) - tm.assertRaisesRegexp(ValueError, 'transform must return a scalar ' - 'value for each group.*', df.groupby - (axis=1, level=1).transform, - lambda z: z.div(z.sum(axis=1), axis=0)) + tm.assert_raises_regex(ValueError, 'transform must return ' + 'a scalar value for each ' + 'group.*', + df.groupby(axis=1, level=1).transform, + lambda z: z.div(z.sum(axis=1), axis=0)) diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index 5a4f282789eeb..5d131717f8345 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -223,7 +223,7 @@ def test_groupby_blacklist(df_letters): for obj in (df, s): gb = obj.groupby(df.letters) msg = fmt.format(bl, type(gb).__name__) - with tm.assertRaisesRegexp(AttributeError, msg): + with tm.assert_raises_regex(AttributeError, msg): getattr(gb, bl) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index b62cab6cc8710..56a9af73e904a 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -13,7 +13,6 @@ notnull, isnull) from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin from pandas.core.dtypes.common import needs_i8_conversion -from pandas.util.testing import assertRaisesRegexp from pandas._libs.tslib import iNaT import pandas.util.testing as tm @@ -91,26 +90,26 @@ def test_create_index_existing_name(self): def test_numeric_compat(self): idx = self.create_index() - tm.assertRaisesRegexp(TypeError, "cannot perform __mul__", - lambda: idx * 1) - tm.assertRaisesRegexp(TypeError, "cannot perform __mul__", - lambda: 1 * idx) + tm.assert_raises_regex(TypeError, "cannot perform __mul__", + lambda: idx * 1) + tm.assert_raises_regex(TypeError, "cannot perform __mul__", + lambda: 1 * idx) div_err = "cannot perform __truediv__" if PY3 \ else "cannot perform __div__" - tm.assertRaisesRegexp(TypeError, div_err, lambda: idx / 1) - tm.assertRaisesRegexp(TypeError, div_err, lambda: 1 / idx) - tm.assertRaisesRegexp(TypeError, "cannot perform __floordiv__", - lambda: idx // 1) - tm.assertRaisesRegexp(TypeError, "cannot perform __floordiv__", - lambda: 1 // idx) + tm.assert_raises_regex(TypeError, div_err, lambda: idx / 1) + tm.assert_raises_regex(TypeError, div_err, lambda: 1 / idx) + tm.assert_raises_regex(TypeError, "cannot perform __floordiv__", + lambda: idx // 1) + tm.assert_raises_regex(TypeError, "cannot perform __floordiv__", + lambda: 1 // idx) def test_logical_compat(self): idx = self.create_index() - tm.assertRaisesRegexp(TypeError, 'cannot perform all', - lambda: idx.all()) - tm.assertRaisesRegexp(TypeError, 'cannot perform any', - lambda: idx.any()) + tm.assert_raises_regex(TypeError, 'cannot perform all', + lambda: idx.all()) + tm.assert_raises_regex(TypeError, 'cannot perform any', + lambda: idx.any()) def test_boolean_context_compat(self): @@ -121,7 +120,7 @@ def f(): if idx: pass - tm.assertRaisesRegexp(ValueError, 'The truth value of a', f) + tm.assert_raises_regex(ValueError, 'The truth value of a', f) def test_reindex_base(self): idx = self.create_index() @@ -130,7 +129,7 @@ def test_reindex_base(self): actual = idx.get_indexer(idx) tm.assert_numpy_array_equal(expected, actual) - with tm.assertRaisesRegexp(ValueError, 'Invalid fill method'): + with tm.assert_raises_regex(ValueError, 'Invalid fill method'): idx.get_indexer(idx, method='invalid') def test_ndarray_compat_properties(self): @@ -178,7 +177,7 @@ def testit(ind): ind.names = ["apple", "banana", "carrot"] for ind in self.indices.values(): - assertRaisesRegexp(ValueError, "^Length", testit, ind) + tm.assert_raises_regex(ValueError, "^Length", testit, ind) def test_set_name_methods(self): new_name = "This is the new name for this index" @@ -198,10 +197,10 @@ def test_set_name_methods(self): assert res is None self.assertEqual(ind.name, new_name) self.assertEqual(ind.names, [new_name]) - # with assertRaisesRegexp(TypeError, "list-like"): + # with tm.assert_raises_regex(TypeError, "list-like"): # # should still fail even if it would be the right length # ind.set_names("a") - with assertRaisesRegexp(ValueError, "Level must be None"): + with tm.assert_raises_regex(ValueError, "Level must be None"): ind.set_names("a", level=0) # rename in place just leaves tuples and other containers alone @@ -212,8 +211,8 @@ def test_set_name_methods(self): def test_hash_error(self): for ind in self.indices.values(): - with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % - type(ind).__name__): + with tm.assert_raises_regex(TypeError, "unhashable type: %r" % + type(ind).__name__): hash(ind) def test_copy_name(self): @@ -427,16 +426,16 @@ def test_numpy_argsort(self): # backwards compatibility concerns if isinstance(type(ind), (CategoricalIndex, RangeIndex)): msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, - np.argsort, ind, axis=1) + tm.assert_raises_regex(ValueError, msg, + np.argsort, ind, axis=1) msg = "the 'kind' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.argsort, - ind, kind='mergesort') + tm.assert_raises_regex(ValueError, msg, np.argsort, + ind, kind='mergesort') msg = "the 'order' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.argsort, - ind, order=('a', 'b')) + tm.assert_raises_regex(ValueError, msg, np.argsort, + ind, order=('a', 'b')) def test_pickle(self): for ind in self.indices.values(): @@ -467,16 +466,16 @@ def test_take_invalid_kwargs(self): indices = [1, 2] msg = r"take\(\) got an unexpected keyword argument 'foo'" - tm.assertRaisesRegexp(TypeError, msg, idx.take, - indices, foo=2) + tm.assert_raises_regex(TypeError, msg, idx.take, + indices, foo=2) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, out=indices) + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, out=indices) msg = "the 'mode' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, mode='clip') + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, mode='clip') def test_repeat(self): rep = 2 @@ -496,8 +495,8 @@ def test_numpy_repeat(self): tm.assert_index_equal(np.repeat(i, rep), expected) msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.repeat, - i, rep, axis=0) + tm.assert_raises_regex(ValueError, msg, np.repeat, + i, rep, axis=0) def test_where(self): i = self.create_index() @@ -533,9 +532,10 @@ def test_setops_errorcases(self): for method in methods: for case in cases: - assertRaisesRegexp(TypeError, - "Input must be Index or array-like", - method, case) + tm.assert_raises_regex(TypeError, + "Input must be Index " + "or array-like", + method, case) def test_intersection_base(self): for name, idx in compat.iteritems(self.indices): @@ -554,7 +554,7 @@ def test_intersection_base(self): for case in cases: if isinstance(idx, PeriodIndex): msg = "can only call with other PeriodIndex-ed objects" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): result = first.intersection(case) elif isinstance(idx, CategoricalIndex): pass @@ -564,7 +564,7 @@ def test_intersection_base(self): if isinstance(idx, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): result = first.intersection([1, 2, 3]) def test_union_base(self): @@ -581,7 +581,7 @@ def test_union_base(self): for case in cases: if isinstance(idx, PeriodIndex): msg = "can only call with other PeriodIndex-ed objects" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): result = first.union(case) elif isinstance(idx, CategoricalIndex): pass @@ -591,7 +591,7 @@ def test_union_base(self): if isinstance(idx, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): result = first.union([1, 2, 3]) def test_difference_base(self): @@ -612,7 +612,7 @@ def test_difference_base(self): for case in cases: if isinstance(idx, PeriodIndex): msg = "can only call with other PeriodIndex-ed objects" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): result = first.difference(case) elif isinstance(idx, CategoricalIndex): pass @@ -625,7 +625,7 @@ def test_difference_base(self): if isinstance(idx, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): result = first.difference([1, 2, 3]) def test_symmetric_difference(self): @@ -645,7 +645,7 @@ def test_symmetric_difference(self): for case in cases: if isinstance(idx, PeriodIndex): msg = "can only call with other PeriodIndex-ed objects" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): result = first.symmetric_difference(case) elif isinstance(idx, CategoricalIndex): pass @@ -655,7 +655,7 @@ def test_symmetric_difference(self): if isinstance(idx, MultiIndex): msg = "other must be a MultiIndex or a list of tuples" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): result = first.symmetric_difference([1, 2, 3]) # 12591 deprecated @@ -728,7 +728,7 @@ def test_equals_op(self): index_b = index_a[0:-1] index_c = index_a[0:-1].append(index_a[-2:-1]) index_d = index_a[0:1] - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): index_a == index_b expected1 = np.array([True] * n) expected2 = np.array([True] * (n - 1) + [False]) @@ -740,7 +740,7 @@ def test_equals_op(self): array_b = np.array(index_a[0:-1]) array_c = np.array(index_a[0:-1].append(index_a[-2:-1])) array_d = np.array(index_a[0:1]) - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): index_a == array_b tm.assert_numpy_array_equal(index_a == array_a, expected1) tm.assert_numpy_array_equal(index_a == array_c, expected2) @@ -750,22 +750,22 @@ def test_equals_op(self): series_b = Series(array_b) series_c = Series(array_c) series_d = Series(array_d) - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): index_a == series_b tm.assert_numpy_array_equal(index_a == series_a, expected1) tm.assert_numpy_array_equal(index_a == series_c, expected2) # cases where length is 1 for one of them - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): index_a == index_d - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): index_a == series_d - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): index_a == array_d msg = "Can only compare identically-labeled Series objects" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): series_a == series_d - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): series_a == array_d # comparing with a scalar should broadcast; note that we are excluding @@ -875,7 +875,7 @@ def test_fillna(self): elif isinstance(index, MultiIndex): idx = index.copy() msg = "isnull is not defined for MultiIndex" - with tm.assertRaisesRegexp(NotImplementedError, msg): + with tm.assert_raises_regex(NotImplementedError, msg): idx.fillna(idx[0]) else: idx = index.copy() @@ -884,7 +884,7 @@ def test_fillna(self): self.assertFalse(result is idx) msg = "'value' must be a scalar, passed: " - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): idx.fillna([idx[0]]) idx = index.copy() @@ -918,7 +918,7 @@ def test_nulls(self): elif isinstance(index, MultiIndex): idx = index.copy() msg = "isnull is not defined for MultiIndex" - with tm.assertRaisesRegexp(NotImplementedError, msg): + with tm.assert_raises_regex(NotImplementedError, msg): idx.isnull() else: diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index ca673e3059ea2..ea9f7c65fb49b 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -246,7 +246,8 @@ def test_construction_dti_with_mixed_timezones(self): Timestamp('2011-01-02 10:00', tz='US/Eastern')], name='idx') - with tm.assertRaisesRegexp(TypeError, 'data is already tz-aware'): + with tm.assert_raises_regex(TypeError, + 'data is already tz-aware'): DatetimeIndex([Timestamp('2011-01-01 10:00'), Timestamp('2011-01-02 10:00', tz='US/Eastern')], tz='Asia/Tokyo', name='idx') @@ -256,7 +257,8 @@ def test_construction_dti_with_mixed_timezones(self): Timestamp('2011-01-02 10:00', tz='US/Eastern')], tz='US/Eastern', name='idx') - with tm.assertRaisesRegexp(TypeError, 'data is already tz-aware'): + with tm.assert_raises_regex(TypeError, + 'data is already tz-aware'): # passing tz should results in DatetimeIndex, then mismatch raises # TypeError Index([pd.NaT, Timestamp('2011-01-01 10:00'), diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 6e49b1612b4c5..e570313b716cb 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -212,31 +212,31 @@ def test_naive_aware_conflicts(self): naive = bdate_range(START, END, freq=BDay(), tz=None) aware = bdate_range(START, END, freq=BDay(), tz="Asia/Hong_Kong") - tm.assertRaisesRegexp(TypeError, "tz-naive.*tz-aware", - naive.join, aware) - tm.assertRaisesRegexp(TypeError, "tz-naive.*tz-aware", - aware.join, naive) + tm.assert_raises_regex(TypeError, "tz-naive.*tz-aware", + naive.join, aware) + tm.assert_raises_regex(TypeError, "tz-naive.*tz-aware", + aware.join, naive) def test_cached_range(self): DatetimeIndex._cached_range(START, END, offset=BDay()) DatetimeIndex._cached_range(START, periods=20, offset=BDay()) DatetimeIndex._cached_range(end=START, periods=20, offset=BDay()) - tm.assertRaisesRegexp(TypeError, "offset", - DatetimeIndex._cached_range, - START, END) + tm.assert_raises_regex(TypeError, "offset", + DatetimeIndex._cached_range, + START, END) - tm.assertRaisesRegexp(TypeError, "specify period", - DatetimeIndex._cached_range, START, - offset=BDay()) + tm.assert_raises_regex(TypeError, "specify period", + DatetimeIndex._cached_range, START, + offset=BDay()) - tm.assertRaisesRegexp(TypeError, "specify period", - DatetimeIndex._cached_range, end=END, - offset=BDay()) + tm.assert_raises_regex(TypeError, "specify period", + DatetimeIndex._cached_range, end=END, + offset=BDay()) - tm.assertRaisesRegexp(TypeError, "start or end", - DatetimeIndex._cached_range, periods=20, - offset=BDay()) + tm.assert_raises_regex(TypeError, "start or end", + DatetimeIndex._cached_range, periods=20, + offset=BDay()) def test_cached_range_bug(self): rng = date_range('2010-09-01 05:00:00', periods=50, diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index abfc52728ef0f..8a4cff2974b0d 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -40,7 +40,7 @@ def test_get_loc(self): tolerance=np.timedelta64(1, 'D')), 1) self.assertEqual(idx.get_loc('2000-01-01T12', method='nearest', tolerance=timedelta(1)), 1) - with tm.assertRaisesRegexp(ValueError, 'must be convertible'): + with tm.assert_raises_regex(ValueError, 'must be convertible'): idx.get_loc('2000-01-01T12', method='nearest', tolerance='foo') with pytest.raises(KeyError): idx.get_loc('2000-01-01T03', method='nearest', tolerance='2 hours') @@ -212,8 +212,8 @@ def test_week_of_month_frequency(self): def test_hash_error(self): index = date_range('20010101', periods=10) - with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % - type(index).__name__): + with tm.assert_raises_regex(TypeError, "unhashable type: %r" % + type(index).__name__): hash(index) def test_stringified_slice_with_tz(self): @@ -508,9 +508,9 @@ def test_take_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -539,9 +539,9 @@ def test_take_fill_value_with_timezone(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -645,8 +645,9 @@ def test_join_with_period_index(self): joins = 'left', 'right', 'inner', 'outer' for join in joins: - with tm.assertRaisesRegexp(ValueError, 'can only call with other ' - 'PeriodIndex-ed objects'): + with tm.assert_raises_regex(ValueError, + 'can only call with other ' + 'PeriodIndex-ed objects'): df.columns.join(s.index, how=join) def test_factorize(self): @@ -755,12 +756,12 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): ts = Series(np.arange(20), date_range('2014-01-01', periods=20, freq='MS')) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts[::0]) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) def test_slice_bounds_empty(self): # GH 14354 diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index d531d0913df77..020bb0e27d9de 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -131,16 +131,18 @@ def test_numpy_minmax(self): Timestamp('2016-01-20 00:00:00', freq='D')) errmsg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, errmsg, np.min, dr, out=0) - tm.assertRaisesRegexp(ValueError, errmsg, np.max, dr, out=0) + tm.assert_raises_regex(ValueError, errmsg, np.min, dr, out=0) + tm.assert_raises_regex(ValueError, errmsg, np.max, dr, out=0) self.assertEqual(np.argmin(dr), 0) self.assertEqual(np.argmax(dr), 5) if not _np_version_under1p10: errmsg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, errmsg, np.argmin, dr, out=0) - tm.assertRaisesRegexp(ValueError, errmsg, np.argmax, dr, out=0) + tm.assert_raises_regex( + ValueError, errmsg, np.argmin, dr, out=0) + tm.assert_raises_regex( + ValueError, errmsg, np.argmax, dr, out=0) def test_round(self): for tz in self.tz: @@ -161,14 +163,14 @@ def test_round(self): self.assertEqual(elt.round(freq='H'), expected_elt) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): rng.round(freq='foo') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): elt.round(freq='foo') msg = "<MonthEnd> is a non-fixed frequency" - tm.assertRaisesRegexp(ValueError, msg, rng.round, freq='M') - tm.assertRaisesRegexp(ValueError, msg, elt.round, freq='M') + tm.assert_raises_regex(ValueError, msg, rng.round, freq='M') + tm.assert_raises_regex(ValueError, msg, elt.round, freq='M') # GH 14440 & 15578 index = pd.DatetimeIndex(['2016-10-17 12:00:00.0015'], tz=tz) @@ -245,8 +247,8 @@ def test_repeat(self): assert res.freq is None tm.assert_index_equal(np.repeat(rng, reps), expected_rng) - tm.assertRaisesRegexp(ValueError, msg, np.repeat, - rng, reps, axis=1) + tm.assert_raises_regex(ValueError, msg, np.repeat, + rng, reps, axis=1) def test_representation(self): @@ -433,10 +435,10 @@ def test_add_iadd(self): idx = DatetimeIndex(['2011-01-01', '2011-01-02']) msg = "cannot add a datelike to a DatetimeIndex" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): idx + Timestamp('2011-01-01') - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): Timestamp('2011-01-01') + idx def test_add_dti_dti(self): @@ -830,16 +832,16 @@ def test_take_invalid_kwargs(self): indices = [1, 6, 5, 9, 10, 13, 15, 3] msg = r"take\(\) got an unexpected keyword argument 'foo'" - tm.assertRaisesRegexp(TypeError, msg, idx.take, - indices, foo=2) + tm.assert_raises_regex(TypeError, msg, idx.take, + indices, foo=2) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, out=indices) + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, out=indices) msg = "the 'mode' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, mode='clip') + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, mode='clip') def test_infer_freq(self): # GH 11018 diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index 352e066c6c90c..c3eda8b378c96 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -122,8 +122,8 @@ def test_partial_slice_second_precision(self): tm.assert_series_equal(s['2005-1-1 00:01:00'], s.iloc[10:]) self.assertEqual(s[Timestamp('2005-1-1 00:00:59.999990')], s.iloc[0]) - tm.assertRaisesRegexp(KeyError, '2005-1-1 00:00:00', - lambda: s['2005-1-1 00:00:00']) + tm.assert_raises_regex(KeyError, '2005-1-1 00:00:00', + lambda: s['2005-1-1 00:00:00']) def test_partial_slicing_dataframe(self): # GH14856 @@ -249,14 +249,14 @@ def test_partial_slice_doesnt_require_monotonicity(self): timestamp = pd.Timestamp('2014-01-10') tm.assert_series_equal(nonmonotonic['2014-01-10':], expected) - tm.assertRaisesRegexp(KeyError, - r"Timestamp\('2014-01-10 00:00:00'\)", - lambda: nonmonotonic[timestamp:]) + tm.assert_raises_regex(KeyError, + r"Timestamp\('2014-01-10 00:00:00'\)", + lambda: nonmonotonic[timestamp:]) tm.assert_series_equal(nonmonotonic.loc['2014-01-10':], expected) - tm.assertRaisesRegexp(KeyError, - r"Timestamp\('2014-01-10 00:00:00'\)", - lambda: nonmonotonic.loc[timestamp:]) + tm.assert_raises_regex(KeyError, + r"Timestamp\('2014-01-10 00:00:00'\)", + lambda: nonmonotonic.loc[timestamp:]) def test_loc_datetime_length_one(self): # GH16071 diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index c637b36d1bbb5..715825417cd31 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -1308,13 +1308,13 @@ def test_parsers_monthfreq(self): def test_parsers_quarterly_with_freq(self): msg = ('Incorrect quarterly string is given, quarter ' 'must be between 1 and 4: 2013Q5') - with tm.assertRaisesRegexp(tslib.DateParseError, msg): + with tm.assert_raises_regex(tslib.DateParseError, msg): tools.parse_time_string('2013Q5') # GH 5418 msg = ('Unable to retrieve month information from given freq: ' 'INVLD-L-DEC-SAT') - with tm.assertRaisesRegexp(tslib.DateParseError, msg): + with tm.assert_raises_regex(tslib.DateParseError, msg): tools.parse_time_string('2013Q1', freq='INVLD-L-DEC-SAT') cases = {('2013Q2', None): datetime(2013, 4, 1), diff --git a/pandas/tests/indexes/period/test_construction.py b/pandas/tests/indexes/period/test_construction.py index 8f2b03829b128..434271cbe22ec 100644 --- a/pandas/tests/indexes/period/test_construction.py +++ b/pandas/tests/indexes/period/test_construction.py @@ -181,7 +181,7 @@ def test_constructor_dtype(self): self.assertEqual(res.dtype, 'period[M]') msg = 'specified freq and dtype are different' - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): PeriodIndex(['2011-01'], freq='M', dtype='period[D]') def test_constructor_empty(self): @@ -190,7 +190,7 @@ def test_constructor_empty(self): self.assertEqual(len(idx), 0) self.assertEqual(idx.freq, 'M') - with tm.assertRaisesRegexp(ValueError, 'freq not specified'): + with tm.assert_raises_regex(ValueError, 'freq not specified'): pd.PeriodIndex([]) def test_constructor_pi_nat(self): @@ -216,35 +216,35 @@ def test_constructor_pi_nat(self): idx = PeriodIndex([pd.NaT, pd.NaT, '2011-01', '2011-01'], freq='M') tm.assert_index_equal(idx, exp) - with tm.assertRaisesRegexp(ValueError, 'freq not specified'): + with tm.assert_raises_regex(ValueError, 'freq not specified'): PeriodIndex([pd.NaT, pd.NaT]) - with tm.assertRaisesRegexp(ValueError, 'freq not specified'): + with tm.assert_raises_regex(ValueError, 'freq not specified'): PeriodIndex(np.array([pd.NaT, pd.NaT])) - with tm.assertRaisesRegexp(ValueError, 'freq not specified'): + with tm.assert_raises_regex(ValueError, 'freq not specified'): PeriodIndex(['NaT', 'NaT']) - with tm.assertRaisesRegexp(ValueError, 'freq not specified'): + with tm.assert_raises_regex(ValueError, 'freq not specified'): PeriodIndex(np.array(['NaT', 'NaT'])) def test_constructor_incompat_freq(self): msg = "Input has different freq=D from PeriodIndex\\(freq=M\\)" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): PeriodIndex([Period('2011-01', freq='M'), pd.NaT, Period('2011-01', freq='D')]) - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): PeriodIndex(np.array([Period('2011-01', freq='M'), pd.NaT, Period('2011-01', freq='D')])) # first element is pd.NaT - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): PeriodIndex([pd.NaT, Period('2011-01', freq='M'), Period('2011-01', freq='D')]) - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): PeriodIndex(np.array([pd.NaT, Period('2011-01', freq='M'), Period('2011-01', freq='D')])) @@ -332,15 +332,15 @@ def test_constructor_freq_mult(self): msg = ('Frequency must be positive, because it' ' represents span: -1M') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): PeriodIndex(['2011-01'], freq='-1M') msg = ('Frequency must be positive, because it' ' represents span: 0M') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): PeriodIndex(['2011-01'], freq='0M') msg = ('Frequency must be positive, because it' ' represents span: 0M') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): period_range('2011-01', periods=3, freq='0M') def test_constructor_freq_mult_dti_compat(self): @@ -437,11 +437,11 @@ def test_constructor_error(self): end_intv = Period('2006-12-31', ('w', 1)) msg = 'Start and end must have same freq' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): PeriodIndex(start=start, end=end_intv) msg = 'Must specify 2 of start, end, periods' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): PeriodIndex(start=start) def test_recreate_from_data(self): diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 4d5fdd748219c..7af9e9ae3b14c 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -103,10 +103,10 @@ def test_getitem_partial(self): tm.assert_series_equal(exp, result) ts = ts[10:].append(ts[10:]) - tm.assertRaisesRegexp(KeyError, - "left slice bound for non-unique " - "label: '2008'", - ts.__getitem__, slice('2008', '2009')) + tm.assert_raises_regex(KeyError, + "left slice bound for non-unique " + "label: '2008'", + ts.__getitem__, slice('2008', '2009')) def test_getitem_datetime(self): rng = period_range(start='2012-01-01', periods=10, freq='W-MON') @@ -311,9 +311,9 @@ def test_take_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): diff --git a/pandas/tests/indexes/period/test_ops.py b/pandas/tests/indexes/period/test_ops.py index 4f54f44b7bdab..70c0879a0871a 100644 --- a/pandas/tests/indexes/period/test_ops.py +++ b/pandas/tests/indexes/period/test_ops.py @@ -105,16 +105,18 @@ def test_numpy_minmax(self): self.assertEqual(np.max(pr), Period('2016-01-20', freq='D')) errmsg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, errmsg, np.min, pr, out=0) - tm.assertRaisesRegexp(ValueError, errmsg, np.max, pr, out=0) + tm.assert_raises_regex(ValueError, errmsg, np.min, pr, out=0) + tm.assert_raises_regex(ValueError, errmsg, np.max, pr, out=0) self.assertEqual(np.argmin(pr), 0) self.assertEqual(np.argmax(pr), 5) if not _np_version_under1p10: errmsg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, errmsg, np.argmin, pr, out=0) - tm.assertRaisesRegexp(ValueError, errmsg, np.argmax, pr, out=0) + tm.assert_raises_regex( + ValueError, errmsg, np.argmin, pr, out=0) + tm.assert_raises_regex( + ValueError, errmsg, np.argmax, pr, out=0) def test_representation(self): # GH 7601 @@ -309,7 +311,8 @@ def test_add_iadd(self): timedelta(365), Timedelta(days=365)]: msg = ('Input has different freq(=.+)? ' 'from PeriodIndex\\(freq=A-DEC\\)') - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng + o rng = pd.period_range('2014-01', '2016-12', freq='M') @@ -324,7 +327,8 @@ def test_add_iadd(self): timedelta(365), Timedelta(days=365)]: rng = pd.period_range('2014-01', '2016-12', freq='M') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=M\\)' - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng + o # Tick @@ -345,7 +349,8 @@ def test_add_iadd(self): timedelta(hours=23), Timedelta('23:00:00')]: rng = pd.period_range('2014-05-01', '2014-05-15', freq='D') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=D\\)' - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng + o offsets = [pd.offsets.Hour(2), timedelta(hours=2), @@ -367,9 +372,11 @@ def test_add_iadd(self): rng = pd.period_range('2014-01-01 10:00', '2014-01-05 10:00', freq='H') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=H\\)' - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): - result = rng + delta - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): + rng + delta + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng += delta # int @@ -415,7 +422,8 @@ def test_sub_isub(self): rng = pd.period_range('2014', '2024', freq='A') msg = ('Input has different freq(=.+)? ' 'from PeriodIndex\\(freq=A-DEC\\)') - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng - o rng = pd.period_range('2014-01', '2016-12', freq='M') @@ -430,7 +438,8 @@ def test_sub_isub(self): timedelta(365)]: rng = pd.period_range('2014-01', '2016-12', freq='M') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=M\\)' - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng - o # Tick @@ -450,7 +459,8 @@ def test_sub_isub(self): timedelta(hours=23)]: rng = pd.period_range('2014-05-01', '2014-05-15', freq='D') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=D\\)' - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng - o offsets = [pd.offsets.Hour(2), timedelta(hours=2), @@ -471,9 +481,11 @@ def test_sub_isub(self): rng = pd.period_range('2014-01-01 10:00', '2014-01-05 10:00', freq='H') msg = 'Input has different freq(=.+)? from PeriodIndex\\(freq=H\\)' - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): - result = rng + delta - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): + rng + delta + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): rng += delta # int @@ -884,14 +896,14 @@ def test_pi_ops_errors(self): for obj in [idx, s]: for ng in ["str", 1.5]: - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj + ng with pytest.raises(TypeError): # error message differs between PY2 and 3 ng + obj - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj - ng with pytest.raises(TypeError): @@ -987,13 +999,16 @@ def test_pi_offset_errors(self): msg_idx = r"Input has different freq from PeriodIndex\(freq=D\)" msg_s = r"Input cannot be converted to Period\(freq=D\)" for obj, msg in [(idx, msg_idx), (s, msg_s)]: - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): obj + offsets.Hour(2) - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): offsets.Hour(2) + obj - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): obj - offsets.Hour(2) def test_pi_sub_period(self): @@ -1247,25 +1262,31 @@ def test_pi_pi_comp(self): # different base freq msg = "Input has different freq=A-DEC from PeriodIndex" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): base <= Period('2011', freq='A') - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): Period('2011', freq='A') >= base - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): idx = PeriodIndex(['2011', '2012', '2013', '2014'], freq='A') base <= idx - # different mult + # Different frequency msg = "Input has different freq=4M from PeriodIndex" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): base <= Period('2011', freq='4M') - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): Period('2011', freq='4M') >= base - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): idx = PeriodIndex(['2011', '2012', '2013', '2014'], freq='4M') base <= idx @@ -1317,8 +1338,10 @@ def test_pi_nat_comp(self): diff = PeriodIndex(['2011-02', '2011-01', '2011-04', 'NaT'], freq='4M') msg = "Input has different freq=4M from PeriodIndex" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): idx1 > diff - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): idx1 == diff diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py index b13e231db6c1c..7c1279a12450c 100644 --- a/pandas/tests/indexes/period/test_partial_slicing.py +++ b/pandas/tests/indexes/period/test_partial_slicing.py @@ -42,12 +42,12 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): ts = Series(np.arange(20), period_range('2014-01', periods=20, freq='M')) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts[::0]) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) def test_slice_keep_name(self): idx = period_range('20010101', periods=10, freq='D', name='bob') diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 6036d6c0fb19b..e563f683bf8ca 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -82,11 +82,11 @@ def test_get_loc(self): tolerance=np.timedelta64(1, 'D')), 1) self.assertEqual(idx.get_loc('2000-01-02T12', method='nearest', tolerance=timedelta(1)), 1) - with tm.assertRaisesRegexp(ValueError, 'must be convertible'): + with tm.assert_raises_regex(ValueError, 'must be convertible'): idx.get_loc('2000-01-10', method='nearest', tolerance='foo') msg = 'Input has different freq from PeriodIndex\\(freq=D\\)' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.get_loc('2000-01-10', method='nearest', tolerance='1 hour') with pytest.raises(KeyError): idx.get_loc('2000-01-10', method='nearest', tolerance='1 day') @@ -151,7 +151,7 @@ def test_get_indexer(self): np.array([0, -1, 1], dtype=np.intp)) msg = 'Input has different freq from PeriodIndex\\(freq=H\\)' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.get_indexer(target, 'nearest', tolerance='1 minute') tm.assert_numpy_array_equal(idx.get_indexer(target, 'nearest', @@ -223,8 +223,8 @@ def test_difference_freq(self): def test_hash_error(self): index = period_range('20010101', periods=10) - with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % - type(index).__name__): + with tm.assert_raises_regex(TypeError, "unhashable type: %r" % + type(index).__name__): hash(index) def test_make_time_series(self): @@ -679,7 +679,8 @@ def test_numpy_repeat(self): tm.assert_index_equal(np.repeat(index, 2), expected) msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.repeat, index, 2, axis=1) + tm.assert_raises_regex( + ValueError, msg, np.repeat, index, 2, axis=1) def test_pindex_multiples(self): pi = PeriodIndex(start='1/1/11', end='12/31/11', freq='2M') diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index 97f9cff2d193e..e1fdc85d670d4 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -112,7 +112,7 @@ def test_union_misc(self): index.union(index2) msg = 'can only call with other PeriodIndex-ed objects' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): index.join(index.to_timestamp()) index3 = period_range('1/1/2000', '1/20/2000', freq='2D') diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py index 3887463cae827..60ad8fed32399 100644 --- a/pandas/tests/indexes/period/test_tools.py +++ b/pandas/tests/indexes/period/test_tools.py @@ -271,7 +271,7 @@ def test_to_timestamp_pi_nat(self): msg = ('Frequency must be positive, because it' ' represents span: -2A') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): result.to_period(freq='-2A') def test_to_timestamp_pi_mult(self): @@ -386,7 +386,7 @@ def test_to_period_monthish(self): self.assertEqual(prng.freq, 'M') msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): date_range('01-Jan-2012', periods=8, freq='EOM') def test_period_dt64_round_trip(self): @@ -439,11 +439,13 @@ def test_searchsorted(self): self.assertEqual(pidx.searchsorted(p2), 3) msg = "Input has different freq=H from PeriodIndex" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): pidx.searchsorted(pd.Period('2014-01-01', freq='H')) msg = "Input has different freq=5D from PeriodIndex" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): pidx.searchsorted(pd.Period('2014-01-01', freq='5D')) with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 06f98527deefb..caf2dde249600 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -206,10 +206,10 @@ def test_constructor_int_dtype_nan(self): data = [np.nan] msg = "cannot convert" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Index(data, dtype='int64') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Index(data, dtype='uint64') # This, however, should not break @@ -1062,10 +1062,10 @@ def test_get_indexer_invalid(self): # GH10411 idx = Index(np.arange(10)) - with tm.assertRaisesRegexp(ValueError, 'tolerance argument'): + with tm.assert_raises_regex(ValueError, 'tolerance argument'): idx.get_indexer([1, 0], tolerance=1) - with tm.assertRaisesRegexp(ValueError, 'limit argument'): + with tm.assert_raises_regex(ValueError, 'limit argument'): idx.get_indexer([1, 0], limit=1) def test_get_indexer_nearest(self): @@ -1099,7 +1099,7 @@ def test_get_indexer_nearest(self): tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp)) - with tm.assertRaisesRegexp(ValueError, 'limit argument'): + with tm.assert_raises_regex(ValueError, 'limit argument'): idx.get_indexer([1, 0], method='nearest', limit=1) def test_get_indexer_nearest_decreasing(self): @@ -1154,9 +1154,9 @@ def test_get_loc(self): with pytest.raises(KeyError): idx.get_loc(1.1, method, tolerance=0.05) - with tm.assertRaisesRegexp(ValueError, 'must be numeric'): + with tm.assert_raises_regex(ValueError, 'must be numeric'): idx.get_loc(1.1, 'nearest', tolerance='invalid') - with tm.assertRaisesRegexp(ValueError, 'tolerance .* valid if'): + with tm.assert_raises_regex(ValueError, 'tolerance .* valid if'): idx.get_loc(1.1, tolerance=1) idx = pd.Index(['a', 'c']) @@ -1450,8 +1450,8 @@ def test_str_attribute(self): MultiIndex.from_tuples([('foo', '1'), ('bar', '3')]), PeriodIndex(start='2000', end='2010', freq='A')] for idx in indices: - with tm.assertRaisesRegexp(AttributeError, - 'only use .str accessor'): + with tm.assert_raises_regex(AttributeError, + 'only use .str accessor'): idx.str.repeat(2) idx = Index(['a b c', 'd e', 'f']) @@ -1526,9 +1526,9 @@ def test_take_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -1537,8 +1537,8 @@ def test_take_fill_value(self): def test_reshape_raise(self): msg = "reshaping is not supported" idx = pd.Index([0, 1, 2]) - tm.assertRaisesRegexp(NotImplementedError, msg, - idx.reshape, idx.shape) + tm.assert_raises_regex(NotImplementedError, msg, + idx.reshape, idx.shape) def test_reindex_preserves_name_if_target_is_list_or_ndarray(self): # GH6552 @@ -1617,11 +1617,11 @@ def test_equals_op_multiindex(self): mi2 = MultiIndex.from_tuples([(1, 2), (4, 6)]) tm.assert_numpy_array_equal(df.index == mi2, np.array([True, False])) mi3 = MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)]) - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): df.index == mi3 index_a = Index(['foo', 'bar', 'baz']) - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): df.index == index_a tm.assert_numpy_array_equal(index_a == mi3, np.array([False, False, False])) @@ -1821,10 +1821,10 @@ def create_index(self): def test_argsort(self): idx = self.create_index() if PY36: - with tm.assertRaisesRegexp(TypeError, "'>' not supported"): + with tm.assert_raises_regex(TypeError, "'>' not supported"): result = idx.argsort() elif PY3: - with tm.assertRaisesRegexp(TypeError, "unorderable types"): + with tm.assert_raises_regex(TypeError, "unorderable types"): result = idx.argsort() else: result = idx.argsort() @@ -1834,10 +1834,10 @@ def test_argsort(self): def test_numpy_argsort(self): idx = self.create_index() if PY36: - with tm.assertRaisesRegexp(TypeError, "'>' not supported"): + with tm.assert_raises_regex(TypeError, "'>' not supported"): result = np.argsort(idx) elif PY3: - with tm.assertRaisesRegexp(TypeError, "unorderable types"): + with tm.assert_raises_regex(TypeError, "unorderable types"): result = np.argsort(idx) else: result = np.argsort(idx) @@ -2002,7 +2002,7 @@ def test_dropna(self): tm.assert_index_equal(nanidx.dropna(), idx) msg = "invalid how option: xxx" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): pd.Index([1, 2, 3]).dropna(how='xxx') def test_get_combined_index(self): diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index 057ea1a416275..5dcd45e8c85b0 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -373,7 +373,7 @@ def test_reindex_base(self): actual = idx.get_indexer(idx) tm.assert_numpy_array_equal(expected, actual) - with tm.assertRaisesRegexp(ValueError, 'Invalid fill method'): + with tm.assert_raises_regex(ValueError, 'Invalid fill method'): idx.get_indexer(idx, method='invalid') def test_reindexing(self): @@ -579,7 +579,7 @@ def test_equals_categorical(self): self.assertTrue((ci1 == ci1.values).all()) # invalid comparisons - with tm.assertRaisesRegexp(ValueError, "Lengths must match"): + with tm.assert_raises_regex(ValueError, "Lengths must match"): ci1 == Index(['a', 'b', 'c']) pytest.raises(TypeError, lambda: ci1 == ci2) pytest.raises( @@ -806,8 +806,8 @@ def test_fillna_categorical(self): tm.assert_index_equal(idx.fillna(1.0), exp) # fill by value not in categories raises ValueError - with tm.assertRaisesRegexp(ValueError, - 'fill value must be in categories'): + with tm.assert_raises_regex(ValueError, + 'fill value must be in categories'): idx.fillna(2.0) def test_take_fill_value(self): @@ -861,9 +861,9 @@ def test_take_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -899,9 +899,9 @@ def test_take_fill_value_datetime(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -912,13 +912,13 @@ def test_take_invalid_kwargs(self): indices = [1, 0, -1] msg = r"take\(\) got an unexpected keyword argument 'foo'" - tm.assertRaisesRegexp(TypeError, msg, idx.take, - indices, foo=2) + tm.assert_raises_regex(TypeError, msg, idx.take, + indices, foo=2) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, out=indices) + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, out=indices) msg = "the 'mode' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, mode='clip') + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, mode='clip') diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index 8e020846f5c50..ec56791a6ec67 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -602,9 +602,9 @@ def test_comparison(self): actual = self.index == self.index.left tm.assert_numpy_array_equal(actual, np.array([False, False])) - with tm.assertRaisesRegexp(TypeError, 'unorderable types'): + with tm.assert_raises_regex(TypeError, 'unorderable types'): self.index > 0 - with tm.assertRaisesRegexp(TypeError, 'unorderable types'): + with tm.assert_raises_regex(TypeError, 'unorderable types'): self.index <= 0 with pytest.raises(TypeError): self.index > np.arange(2) diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 34051a9749af8..ab403cf56e033 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -22,9 +22,7 @@ import pandas.util.testing as tm -from pandas.util.testing import (assertRaisesRegexp, - assert_almost_equal, assert_copy) - +from pandas.util.testing import assert_almost_equal, assert_copy from .common import Base @@ -61,7 +59,7 @@ def f(): if common: pass - tm.assertRaisesRegexp(ValueError, 'The truth value of a', f) + tm.assert_raises_regex(ValueError, 'The truth value of a', f) def test_labels_dtypes(self): @@ -125,7 +123,8 @@ def test_numpy_repeat(self): tm.assert_index_equal(np.repeat(m, reps), expected) msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.repeat, m, reps, axis=1) + tm.assert_raises_regex( + ValueError, msg, np.repeat, m, reps, axis=1) def test_set_name_methods(self): # so long as these are synonyms, we don't need to test set_names @@ -134,7 +133,7 @@ def test_set_name_methods(self): ind = self.index.set_names(new_names) self.assertEqual(self.index.names, self.index_names) self.assertEqual(ind.names, new_names) - with assertRaisesRegexp(ValueError, "^Length"): + with tm.assert_raises_regex(ValueError, "^Length"): ind.set_names(new_names + new_names) new_names2 = [name + "SUFFIX2" for name in new_names] res = ind.set_names(new_names2, inplace=True) @@ -224,23 +223,23 @@ def assert_matching(actual, expected, check_dtype=False): # GH 13754 original_index = self.index.copy() for inplace in [True, False]: - with assertRaisesRegexp(ValueError, "^On"): + with tm.assert_raises_regex(ValueError, "^On"): self.index.set_levels(['c'], level=0, inplace=inplace) assert_matching(self.index.levels, original_index.levels, check_dtype=True) - with assertRaisesRegexp(ValueError, "^On"): + with tm.assert_raises_regex(ValueError, "^On"): self.index.set_labels([0, 1, 2, 3, 4, 5], level=0, inplace=inplace) assert_matching(self.index.labels, original_index.labels, check_dtype=True) - with assertRaisesRegexp(TypeError, "^Levels"): + with tm.assert_raises_regex(TypeError, "^Levels"): self.index.set_levels('c', level=0, inplace=inplace) assert_matching(self.index.levels, original_index.levels, check_dtype=True) - with assertRaisesRegexp(TypeError, "^Labels"): + with tm.assert_raises_regex(TypeError, "^Labels"): self.index.set_labels(1, level=0, inplace=inplace) assert_matching(self.index.labels, original_index.labels, check_dtype=True) @@ -313,46 +312,46 @@ def test_set_levels_labels_names_bad_input(self): levels, labels = self.index.levels, self.index.labels names = self.index.names - with tm.assertRaisesRegexp(ValueError, 'Length of levels'): + with tm.assert_raises_regex(ValueError, 'Length of levels'): self.index.set_levels([levels[0]]) - with tm.assertRaisesRegexp(ValueError, 'Length of labels'): + with tm.assert_raises_regex(ValueError, 'Length of labels'): self.index.set_labels([labels[0]]) - with tm.assertRaisesRegexp(ValueError, 'Length of names'): + with tm.assert_raises_regex(ValueError, 'Length of names'): self.index.set_names([names[0]]) # shouldn't scalar data error, instead should demand list-like - with tm.assertRaisesRegexp(TypeError, 'list of lists-like'): + with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_levels(levels[0]) # shouldn't scalar data error, instead should demand list-like - with tm.assertRaisesRegexp(TypeError, 'list of lists-like'): + with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_labels(labels[0]) # shouldn't scalar data error, instead should demand list-like - with tm.assertRaisesRegexp(TypeError, 'list-like'): + with tm.assert_raises_regex(TypeError, 'list-like'): self.index.set_names(names[0]) # should have equal lengths - with tm.assertRaisesRegexp(TypeError, 'list of lists-like'): + with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_levels(levels[0], level=[0, 1]) - with tm.assertRaisesRegexp(TypeError, 'list-like'): + with tm.assert_raises_regex(TypeError, 'list-like'): self.index.set_levels(levels, level=0) # should have equal lengths - with tm.assertRaisesRegexp(TypeError, 'list of lists-like'): + with tm.assert_raises_regex(TypeError, 'list of lists-like'): self.index.set_labels(labels[0], level=[0, 1]) - with tm.assertRaisesRegexp(TypeError, 'list-like'): + with tm.assert_raises_regex(TypeError, 'list-like'): self.index.set_labels(labels, level=0) # should have equal lengths - with tm.assertRaisesRegexp(ValueError, 'Length of names'): + with tm.assert_raises_regex(ValueError, 'Length of names'): self.index.set_names(names[0], level=[0, 1]) - with tm.assertRaisesRegexp(TypeError, 'string'): + with tm.assert_raises_regex(TypeError, 'string'): self.index.set_names(names, level=0) def test_set_levels_categorical(self): @@ -375,18 +374,18 @@ def test_metadata_immutable(self): levels, labels = self.index.levels, self.index.labels # shouldn't be able to set at either the top level or base level mutable_regex = re.compile('does not support mutable operations') - with assertRaisesRegexp(TypeError, mutable_regex): + with tm.assert_raises_regex(TypeError, mutable_regex): levels[0] = levels[0] - with assertRaisesRegexp(TypeError, mutable_regex): + with tm.assert_raises_regex(TypeError, mutable_regex): levels[0][0] = levels[0][0] # ditto for labels - with assertRaisesRegexp(TypeError, mutable_regex): + with tm.assert_raises_regex(TypeError, mutable_regex): labels[0] = labels[0] - with assertRaisesRegexp(TypeError, mutable_regex): + with tm.assert_raises_regex(TypeError, mutable_regex): labels[0][0] = labels[0][0] # and for names names = self.index.names - with assertRaisesRegexp(TypeError, mutable_regex): + with tm.assert_raises_regex(TypeError, mutable_regex): names[0] = names[0] def test_inplace_mutation_resets_values(self): @@ -494,22 +493,23 @@ def test_names(self): # setting bad names on existing index = self.index - assertRaisesRegexp(ValueError, "^Length of names", setattr, index, - "names", list(index.names) + ["third"]) - assertRaisesRegexp(ValueError, "^Length of names", setattr, index, - "names", []) + tm.assert_raises_regex(ValueError, "^Length of names", + setattr, index, "names", + list(index.names) + ["third"]) + tm.assert_raises_regex(ValueError, "^Length of names", + setattr, index, "names", []) # initializing with bad names (should always be equivalent) major_axis, minor_axis = self.index.levels major_labels, minor_labels = self.index.labels - assertRaisesRegexp(ValueError, "^Length of names", MultiIndex, - levels=[major_axis, minor_axis], - labels=[major_labels, minor_labels], - names=['first']) - assertRaisesRegexp(ValueError, "^Length of names", MultiIndex, - levels=[major_axis, minor_axis], - labels=[major_labels, minor_labels], - names=['first', 'second', 'third']) + tm.assert_raises_regex(ValueError, "^Length of names", MultiIndex, + levels=[major_axis, minor_axis], + labels=[major_labels, minor_labels], + names=['first']) + tm.assert_raises_regex(ValueError, "^Length of names", MultiIndex, + levels=[major_axis, minor_axis], + labels=[major_labels, minor_labels], + names=['first', 'second', 'third']) # names are assigned index.names = ["a", "b"] @@ -533,7 +533,7 @@ def test_astype(self): assert_copy(actual.labels, expected.labels) self.check_level_names(actual, expected.names) - with assertRaisesRegexp(TypeError, "^Setting.*dtype.*object"): + with tm.assert_raises_regex(TypeError, "^Setting.*dtype.*object"): self.index.astype(np.dtype(int)) def test_constructor_single_level(self): @@ -548,46 +548,47 @@ def test_constructor_single_level(self): assert single_level.name is None def test_constructor_no_levels(self): - tm.assertRaisesRegexp(ValueError, "non-zero number of levels/labels", - MultiIndex, levels=[], labels=[]) + tm.assert_raises_regex(ValueError, "non-zero number " + "of levels/labels", + MultiIndex, levels=[], labels=[]) both_re = re.compile('Must pass both levels and labels') - with tm.assertRaisesRegexp(TypeError, both_re): + with tm.assert_raises_regex(TypeError, both_re): MultiIndex(levels=[]) - with tm.assertRaisesRegexp(TypeError, both_re): + with tm.assert_raises_regex(TypeError, both_re): MultiIndex(labels=[]) def test_constructor_mismatched_label_levels(self): labels = [np.array([1]), np.array([2]), np.array([3])] levels = ["a"] - assertRaisesRegexp(ValueError, "Length of levels and labels must be" - " the same", MultiIndex, levels=levels, - labels=labels) + tm.assert_raises_regex(ValueError, "Length of levels and labels " + "must be the same", MultiIndex, + levels=levels, labels=labels) length_error = re.compile('>= length of level') label_error = re.compile(r'Unequal label lengths: \[4, 2\]') # important to check that it's looking at the right thing. - with tm.assertRaisesRegexp(ValueError, length_error): + with tm.assert_raises_regex(ValueError, length_error): MultiIndex(levels=[['a'], ['b']], labels=[[0, 1, 2, 3], [0, 3, 4, 1]]) - with tm.assertRaisesRegexp(ValueError, label_error): + with tm.assert_raises_regex(ValueError, label_error): MultiIndex(levels=[['a'], ['b']], labels=[[0, 0, 0, 0], [0, 0]]) # external API - with tm.assertRaisesRegexp(ValueError, length_error): + with tm.assert_raises_regex(ValueError, length_error): self.index.copy().set_levels([['a'], ['b']]) - with tm.assertRaisesRegexp(ValueError, label_error): + with tm.assert_raises_regex(ValueError, label_error): self.index.copy().set_labels([[0, 0, 0, 0], [0, 0]]) # deprecated properties with warnings.catch_warnings(): warnings.simplefilter('ignore') - with tm.assertRaisesRegexp(ValueError, length_error): + with tm.assert_raises_regex(ValueError, length_error): self.index.copy().levels = [['a'], ['b']] - with tm.assertRaisesRegexp(ValueError, label_error): + with tm.assert_raises_regex(ValueError, label_error): self.index.copy().labels = [[0, 0, 0, 0], [0, 0]] def assert_multiindex_copied(self, copy, original): @@ -650,16 +651,16 @@ def test_changing_names(self): def test_duplicate_names(self): self.index.names = ['foo', 'foo'] - assertRaisesRegexp(KeyError, 'Level foo not found', - self.index._get_level_number, 'foo') + tm.assert_raises_regex(KeyError, 'Level foo not found', + self.index._get_level_number, 'foo') def test_get_level_number_integer(self): self.index.names = [1, 0] self.assertEqual(self.index._get_level_number(1), 0) self.assertEqual(self.index._get_level_number(0), 1) pytest.raises(IndexError, self.index._get_level_number, 2) - assertRaisesRegexp(KeyError, 'Level fourth not found', - self.index._get_level_number, 'fourth') + tm.assert_raises_regex(KeyError, 'Level fourth not found', + self.index._get_level_number, 'fourth') def test_from_arrays(self): arrays = [] @@ -762,7 +763,7 @@ def test_from_arrays_index_series_categorical(self): def test_from_arrays_empty(self): # 0 levels - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( ValueError, "Must pass non-zero number of levels/labels"): MultiIndex.from_arrays(arrays=[]) @@ -787,21 +788,24 @@ def test_from_arrays_invalid_input(self): pytest.raises(TypeError, MultiIndex.from_arrays, arrays=i) def test_from_arrays_different_lengths(self): - # GH13599 + # see gh-13599 idx1 = [1, 2, 3] idx2 = ['a', 'b'] - assertRaisesRegexp(ValueError, '^all arrays must be same length$', - MultiIndex.from_arrays, [idx1, idx2]) + tm.assert_raises_regex(ValueError, '^all arrays must ' + 'be same length$', + MultiIndex.from_arrays, [idx1, idx2]) idx1 = [] idx2 = ['a', 'b'] - assertRaisesRegexp(ValueError, '^all arrays must be same length$', - MultiIndex.from_arrays, [idx1, idx2]) + tm.assert_raises_regex(ValueError, '^all arrays must ' + 'be same length$', + MultiIndex.from_arrays, [idx1, idx2]) idx1 = [1, 2, 3] idx2 = [] - assertRaisesRegexp(ValueError, '^all arrays must be same length$', - MultiIndex.from_arrays, [idx1, idx2]) + tm.assert_raises_regex(ValueError, '^all arrays must ' + 'be same length$', + MultiIndex.from_arrays, [idx1, idx2]) def test_from_product(self): @@ -820,7 +824,7 @@ def test_from_product(self): def test_from_product_empty(self): # 0 levels - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( ValueError, "Must pass non-zero number of levels/labels"): MultiIndex.from_product([]) @@ -990,8 +994,8 @@ def test_get_level_values_na(self): def test_reorder_levels(self): # this blows up - assertRaisesRegexp(IndexError, '^Too many levels', - self.index.reorder_levels, [2, 1, 0]) + tm.assert_raises_regex(IndexError, '^Too many levels', + self.index.reorder_levels, [2, 1, 0]) def test_nlevels(self): self.assertEqual(self.index.nlevels, 2) @@ -1189,17 +1193,19 @@ def test_slice_locs_with_type_mismatch(self): df = tm.makeTimeDataFrame() stacked = df.stack() idx = stacked.index - assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs, - (1, 3)) - assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs, - df.index[5] + timedelta(seconds=30), (5, 2)) + tm.assert_raises_regex(TypeError, '^Level type mismatch', + idx.slice_locs, (1, 3)) + tm.assert_raises_regex(TypeError, '^Level type mismatch', + idx.slice_locs, + df.index[5] + timedelta( + seconds=30), (5, 2)) df = tm.makeCustomDataframe(5, 5) stacked = df.stack() idx = stacked.index - with assertRaisesRegexp(TypeError, '^Level type mismatch'): + with tm.assert_raises_regex(TypeError, '^Level type mismatch'): idx.slice_locs(timedelta(seconds=30)) # TODO: Try creating a UnicodeDecodeError in exception message - with assertRaisesRegexp(TypeError, '^Level type mismatch'): + with tm.assert_raises_regex(TypeError, '^Level type mismatch'): idx.slice_locs(df.index[1], (16, "a")) def test_slice_locs_not_sorted(self): @@ -1207,9 +1213,9 @@ def test_slice_locs_not_sorted(self): lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array( [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])]) - assertRaisesRegexp(KeyError, "[Kk]ey length.*greater than MultiIndex" - " lexsort depth", index.slice_locs, (1, 0, 1), - (2, 1, 0)) + tm.assert_raises_regex(KeyError, "[Kk]ey length.*greater than " + "MultiIndex lexsort depth", + index.slice_locs, (1, 0, 1), (2, 1, 0)) # works sorted_index, _ = index.sortlevel(0) @@ -1348,7 +1354,7 @@ def test_get_indexer(self): idx2 = Index(lrange(20)) msg = "Reindexing only valid with uniquely valued Index objects" - with assertRaisesRegexp(InvalidIndexError, msg): + with tm.assert_raises_regex(InvalidIndexError, msg): idx1.get_indexer(idx2) def test_get_indexer_nearest(self): @@ -1695,12 +1701,14 @@ def test_difference(self): 'foo', 'two'), ('qux', 'one'), ('qux', 'two')]) expected.names = first.names self.assertEqual(first.names, result.names) - assertRaisesRegexp(TypeError, "other must be a MultiIndex or a list" - " of tuples", first.difference, [1, 2, 3, 4, 5]) + tm.assert_raises_regex(TypeError, "other must be a MultiIndex " + "or a list of tuples", + first.difference, [1, 2, 3, 4, 5]) def test_from_tuples(self): - assertRaisesRegexp(TypeError, 'Cannot infer number of levels from' - ' empty list', MultiIndex.from_tuples, []) + tm.assert_raises_regex(TypeError, 'Cannot infer number of levels ' + 'from empty list', + MultiIndex.from_tuples, []) idx = MultiIndex.from_tuples(((1, 2), (3, 4)), names=['a', 'b']) self.assertEqual(len(idx), 2) @@ -1880,7 +1888,7 @@ def test_insert(self): # key wrong length msg = "Item must have length equal to number of levels" - with assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.index.insert(0, ('foo2', )) left = pd.DataFrame([['a', 'b', 0], ['b', 'd', 1]], @@ -1964,9 +1972,9 @@ def test_take_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -1979,16 +1987,16 @@ def take_invalid_kwargs(self): indices = [1, 2] msg = r"take\(\) got an unexpected keyword argument 'foo'" - tm.assertRaisesRegexp(TypeError, msg, idx.take, - indices, foo=2) + tm.assert_raises_regex(TypeError, msg, idx.take, + indices, foo=2) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, out=indices) + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, out=indices) msg = "the 'mode' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, mode='clip') + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, mode='clip') def test_join_level(self): def _check_how(other, how): @@ -2031,8 +2039,8 @@ def _check_all(other): result = idx.join(self.index, level='second') assert isinstance(result, MultiIndex) - assertRaisesRegexp(TypeError, "Join.*MultiIndex.*ambiguous", - self.index.join, self.index, level=1) + tm.assert_raises_regex(TypeError, "Join.*MultiIndex.*ambiguous", + self.index.join, self.index, level=1) def test_join_self(self): kinds = 'outer', 'inner', 'left', 'right' @@ -2102,12 +2110,13 @@ def test_reindex_level(self): exp_indexer2 = np.array([0, -1, 0, -1, 0, -1]) tm.assert_numpy_array_equal(indexer2, exp_indexer2, check_dtype=False) - assertRaisesRegexp(TypeError, "Fill method not supported", - self.index.reindex, self.index, method='pad', - level='second') + tm.assert_raises_regex(TypeError, "Fill method not supported", + self.index.reindex, self.index, + method='pad', level='second') - assertRaisesRegexp(TypeError, "Fill method not supported", idx.reindex, - idx, method='bfill', level='first') + tm.assert_raises_regex(TypeError, "Fill method not supported", + idx.reindex, idx, method='bfill', + level='first') def test_duplicates(self): self.assertFalse(self.index.has_duplicates) @@ -2760,7 +2769,7 @@ def test_dropna(self): tm.assert_index_equal(idx.dropna(how='all'), exp) msg = "invalid how option: xxx" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.dropna(how='xxx') def test_unsortedindex(self): diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index f0c42a3dae239..8a46da37572ff 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -349,7 +349,7 @@ def test_get_loc(self): pytest.raises(KeyError, idx.get_loc, 1.5, method='pad', tolerance=0.1) - with tm.assertRaisesRegexp(ValueError, 'must be numeric'): + with tm.assert_raises_regex(ValueError, 'must be numeric'): idx.get_loc(1.4, method='nearest', tolerance='foo') def test_get_loc_na(self): @@ -438,9 +438,9 @@ def test_take_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -566,7 +566,7 @@ def test_take_fill_value(self): "{name} cannot contain NA").format(name=name) # fill_value=True - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -1]), fill_value=True) # allow_fill=False @@ -575,9 +575,9 @@ def test_take_fill_value(self): expected = self._holder([2, 1, 3], name='xxx') tm.assert_index_equal(result, expected) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -672,11 +672,11 @@ def test_constructor_corner(self): # preventing casting arr = np.array([1, '2', 3, '4'], dtype=object) - with tm.assertRaisesRegexp(TypeError, 'casting'): + with tm.assert_raises_regex(TypeError, 'casting'): Int64Index(arr) arr_with_floats = [0, 2, 3, 4, 5, 1.25, 3, -1] - with tm.assertRaisesRegexp(TypeError, 'casting'): + with tm.assert_raises_regex(TypeError, 'casting'): Int64Index(arr_with_floats) def test_coerce_list(self): diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index 6f87687f822e9..c3ffb32c36e3b 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -12,7 +12,6 @@ from pandas import (notnull, Series, Index, Float64Index, Int64Index, RangeIndex) -from pandas.util.testing import assertRaisesRegexp import pandas.util.testing as tm @@ -65,7 +64,7 @@ def test_too_many_names(self): def testit(): self.index.names = ["roger", "harold"] - assertRaisesRegexp(ValueError, "^Length", testit) + tm.assert_raises_regex(ValueError, "^Length", testit) def test_constructor(self): index = RangeIndex(5) @@ -90,7 +89,7 @@ def test_constructor(self): tm.assert_index_equal(Index(expected), index) msg = "RangeIndex\\(\\.\\.\\.\\) must be called with integers" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): RangeIndex() for index in [RangeIndex(0), RangeIndex(start=0), RangeIndex(stop=0), @@ -102,7 +101,7 @@ def test_constructor(self): self.assertEqual(index._step, 1) tm.assert_index_equal(Index(expected), index) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): RangeIndex(name='Foo') for index in [RangeIndex(0, name='Foo'), @@ -724,7 +723,7 @@ def test_take_fill_value(self): # fill_value msg = "Unable to fill values because RangeIndex cannot contain NA" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -1]), fill_value=True) # allow_fill=False @@ -734,9 +733,9 @@ def test_take_fill_value(self): tm.assert_index_equal(result, expected) msg = "Unable to fill values because RangeIndex cannot contain NA" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index da23f8698f4dc..c3cc05271e978 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -87,16 +87,18 @@ def test_numpy_minmax(self): self.assertEqual(np.max(td), Timedelta('16820 days')) errmsg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, errmsg, np.min, td, out=0) - tm.assertRaisesRegexp(ValueError, errmsg, np.max, td, out=0) + tm.assert_raises_regex(ValueError, errmsg, np.min, td, out=0) + tm.assert_raises_regex(ValueError, errmsg, np.max, td, out=0) self.assertEqual(np.argmin(td), 0) self.assertEqual(np.argmax(td), 5) if not _np_version_under1p10: errmsg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, errmsg, np.argmin, td, out=0) - tm.assertRaisesRegexp(ValueError, errmsg, np.argmax, td, out=0) + tm.assert_raises_regex( + ValueError, errmsg, np.argmin, td, out=0) + tm.assert_raises_regex( + ValueError, errmsg, np.argmax, td, out=0) def test_round(self): td = pd.timedelta_range(start='16801 days', periods=5, freq='30Min') @@ -115,14 +117,14 @@ def test_round(self): self.assertEqual(elt.round(freq='H'), expected_elt) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): td.round(freq='foo') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): elt.round(freq='foo') msg = "<MonthEnd> is a non-fixed frequency" - tm.assertRaisesRegexp(ValueError, msg, td.round, freq='M') - tm.assertRaisesRegexp(ValueError, msg, elt.round, freq='M') + tm.assert_raises_regex(ValueError, msg, td.round, freq='M') + tm.assert_raises_regex(ValueError, msg, elt.round, freq='M') def test_representation(self): idx1 = TimedeltaIndex([], freq='D') @@ -262,7 +264,7 @@ def test_sub_isub(self): idx = TimedeltaIndex(['1 day', '2 day']) msg = "cannot subtract a datelike from a TimedeltaIndex" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): idx - Timestamp('2011-01-01') result = Timestamp('2011-01-01') + idx @@ -497,7 +499,7 @@ def test_addition_ops(self): def test_comp_nat(self): left = pd.TimedeltaIndex([pd.Timedelta('1 days'), pd.NaT, - pd.Timedelta('3 days')]) + pd.Timedelta('3 days')]) right = pd.TimedeltaIndex([pd.NaT, pd.NaT, pd.Timedelta('3 days')]) for l, r in [(left, right), (left.asobject, right.asobject)]: @@ -751,16 +753,16 @@ def test_take_invalid_kwargs(self): indices = [1, 6, 5, 9, 10, 13, 15, 3] msg = r"take\(\) got an unexpected keyword argument 'foo'" - tm.assertRaisesRegexp(TypeError, msg, idx.take, - indices, foo=2) + tm.assert_raises_regex(TypeError, msg, idx.take, + indices, foo=2) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, out=indices) + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, out=indices) msg = "the 'mode' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, idx.take, - indices, mode='clip') + tm.assert_raises_regex(ValueError, msg, idx.take, + indices, mode='clip') def test_infer_freq(self): # GH 11018 @@ -1248,22 +1250,22 @@ def test_tdi_ops_attributes(self): def test_add_overflow(self): # see gh-14068 msg = "too (big|large) to convert" - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): to_timedelta(106580, 'D') + Timestamp('2000') - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): Timestamp('2000') + to_timedelta(106580, 'D') _NaT = int(pd.NaT) + 1 msg = "Overflow in int64 addition" - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): to_timedelta([106580], 'D') + Timestamp('2000') - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): Timestamp('2000') + to_timedelta([106580], 'D') - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): to_timedelta([_NaT]) - Timedelta('1 days') - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): to_timedelta(['5 days', _NaT]) - Timedelta('1 days') - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): (to_timedelta([_NaT, '5 days', '1 hours']) - to_timedelta(['7 seconds', _NaT, '4 hours'])) diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py index ccb9a7f1803e7..230dbe91b4e34 100644 --- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py +++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py @@ -75,9 +75,9 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): ts = Series(np.arange(20), timedelta_range('0', periods=20, freq='H')) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts[::0]) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index b93f76c14dcfe..b5bdf031180ec 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -59,7 +59,7 @@ def test_get_loc(self): idx.get_loc(idx[1], 'pad', tolerance=np.timedelta64(0, 's')), 1) self.assertEqual(idx.get_loc(idx[1], 'pad', tolerance=timedelta(0)), 1) - with tm.assertRaisesRegexp(ValueError, 'must be convertible'): + with tm.assert_raises_regex(ValueError, 'must be convertible'): idx.get_loc(idx[1], method='nearest', tolerance='foo') for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]: @@ -235,9 +235,9 @@ def test_take_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -461,8 +461,8 @@ def test_pickle(self): def test_hash_error(self): index = timedelta_range('1 days', periods=10) - with tm.assertRaisesRegexp(TypeError, "unhashable type: %r" % - type(index).__name__): + with tm.assert_raises_regex(TypeError, "unhashable type: %r" % + type(index).__name__): hash(index) def test_append_join_nondatetimeindex(self): diff --git a/pandas/tests/indexes/timedeltas/test_timedelta_range.py b/pandas/tests/indexes/timedeltas/test_timedelta_range.py index 8bd56b5885bba..55f16c10e9945 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta_range.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta_range.py @@ -37,10 +37,10 @@ def test_timedelta_range(self): arr = np.arange(10).reshape(2, 5) df = pd.DataFrame(np.arange(10).reshape(2, 5)) for arg in (arr, df): - with tm.assertRaisesRegexp(TypeError, "1-d array"): + with tm.assert_raises_regex(TypeError, "1-d array"): to_timedelta(arg) for errors in ['ignore', 'raise', 'coerce']: - with tm.assertRaisesRegexp(TypeError, "1-d array"): + with tm.assert_raises_regex(TypeError, "1-d array"): to_timedelta(arg, errors=errors) # issue10583 diff --git a/pandas/tests/indexes/timedeltas/test_tools.py b/pandas/tests/indexes/timedeltas/test_tools.py index b4f6f33a6e06a..12ed8a2e38f92 100644 --- a/pandas/tests/indexes/timedeltas/test_tools.py +++ b/pandas/tests/indexes/timedeltas/test_tools.py @@ -113,8 +113,8 @@ def test_to_timedelta_invalid(self): # bad value for errors parameter msg = "errors must be one of" - tm.assertRaisesRegexp(ValueError, msg, to_timedelta, - ['foo'], errors='never') + tm.assert_raises_regex(ValueError, msg, to_timedelta, + ['foo'], errors='never') # these will error pytest.raises(ValueError, lambda: to_timedelta([1, 2], unit='foo')) diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index e0f95a1fd5c0d..f9fcef16c12d4 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -135,7 +135,7 @@ def test_loc_listlike_dtypes(self): exp = DataFrame({'A': [1, 1, 2], 'B': [4, 4, 5]}, index=exp_index) tm.assert_frame_equal(res, exp, check_index_type=True) - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( KeyError, 'a list-indexer must only include values that are ' 'in the categories'): @@ -160,7 +160,7 @@ def test_loc_listlike_dtypes(self): ]}, index=CategoricalIndex(['a', 'a', 'a', 'a', 'b'])) tm.assert_frame_equal(res, exp, check_index_type=True) - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( KeyError, 'a list-indexer must only include values ' 'that are in the categories'): @@ -190,7 +190,7 @@ def test_loc_listlike_dtypes(self): categories=list('abcde'))) tm.assert_frame_equal(res, exp, check_index_type=True) - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( KeyError, 'a list-indexer must only include values ' 'that are in the categories'): diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 15a56d97eeaec..b8030d84e7929 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -423,12 +423,12 @@ def test_insert_index_datetime64(self): # ToDo: must coerce to object msg = "Passed item and index have different timezone" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): obj.insert(1, pd.Timestamp('2012-01-01', tz='US/Eastern')) # ToDo: must coerce to object msg = "cannot insert DatetimeIndex with incompatible label" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj.insert(1, 1) def test_insert_index_datetime64tz(self): @@ -445,17 +445,17 @@ def test_insert_index_datetime64tz(self): # ToDo: must coerce to object msg = "Passed item and index have different timezone" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): obj.insert(1, pd.Timestamp('2012-01-01')) # ToDo: must coerce to object msg = "Passed item and index have different timezone" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): obj.insert(1, pd.Timestamp('2012-01-01', tz='Asia/Tokyo')) # ToDo: must coerce to object msg = "cannot insert DatetimeIndex with incompatible label" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj.insert(1, 1) def test_insert_index_timedelta64(self): @@ -469,12 +469,12 @@ def test_insert_index_timedelta64(self): # ToDo: must coerce to object msg = "cannot insert TimedeltaIndex with incompatible label" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj.insert(1, pd.Timestamp('2012-01-01')) # ToDo: must coerce to object msg = "cannot insert TimedeltaIndex with incompatible label" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj.insert(1, 1) def test_insert_index_period(self): @@ -778,7 +778,7 @@ def test_where_series_datetime64(self): # ToDo: coerce to object msg = "cannot coerce a Timestamp with a tz on a naive Block" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj.where(cond, pd.Timestamp('2012-01-01', tz='US/Eastern')) # ToDo: do not coerce to UTC, must be object @@ -819,7 +819,7 @@ def test_where_index_datetime64(self): # ToDo: coerce to object msg = ("Index\\(\\.\\.\\.\\) must be called with a collection " "of some kind") - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): obj.where(cond, pd.Timestamp('2012-01-01', tz='US/Eastern')) # ToDo: do not ignore timezone, must be object diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 02df4de010fbe..bdee41acbc8fd 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -48,9 +48,9 @@ def test_scalar_error(self): def f(): s.iloc[3.0] - tm.assertRaisesRegexp(TypeError, - 'cannot do positional indexing', - f) + tm.assert_raises_regex(TypeError, + 'cannot do positional indexing', + f) def f(): s.iloc[3.0] = 0 diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 174026a00fcdd..18b169559b2d4 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -22,8 +22,9 @@ def test_iloc_exceeds_bounds(self): expected = df # lists of positions should raise IndexErrror! - with tm.assertRaisesRegexp(IndexError, - 'positional indexers are out-of-bounds'): + with tm.assert_raises_regex(IndexError, + 'positional indexers ' + 'are out-of-bounds'): df.iloc[:, [0, 1, 2, 3, 4, 5]] pytest.raises(IndexError, lambda: df.iloc[[1, 30]]) pytest.raises(IndexError, lambda: df.iloc[[1, -30]]) @@ -35,14 +36,14 @@ def test_iloc_exceeds_bounds(self): # still raise on a single indexer msg = 'single positional indexer is out-of-bounds' - with tm.assertRaisesRegexp(IndexError, msg): + with tm.assert_raises_regex(IndexError, msg): df.iloc[30] pytest.raises(IndexError, lambda: df.iloc[-30]) # GH10779 # single positive/negative indexer exceeding Series bounds should raise # an IndexError - with tm.assertRaisesRegexp(IndexError, msg): + with tm.assert_raises_regex(IndexError, msg): s.iloc[30] pytest.raises(IndexError, lambda: s.iloc[-30]) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index f7a9c9fe59594..f8a7c57ad5061 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -716,13 +716,14 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): s = Series(np.arange(20), index=_mklbl('A', 20)) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: s[::0]) - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: s.loc[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: s[::0]) + tm.assert_raises_regex(ValueError, 'slice step cannot be zero', + lambda: s.loc[::0]) with catch_warnings(record=True): - tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: s.ix[::0]) + tm.assert_raises_regex(ValueError, + 'slice step cannot be zero', + lambda: s.ix[::0]) def test_indexing_assignment_dict_already_exists(self): df = pd.DataFrame({'x': [1, 2, 6], diff --git a/pandas/tests/indexing/test_multiindex.py b/pandas/tests/indexing/test_multiindex.py index 18cb9a3a063b9..a85c6bb446140 100644 --- a/pandas/tests/indexing/test_multiindex.py +++ b/pandas/tests/indexing/test_multiindex.py @@ -294,9 +294,9 @@ def test_getitem_partial_int(self): tm.assert_frame_equal(result, expected) # missing item: - with tm.assertRaisesRegexp(KeyError, '1'): + with tm.assert_raises_regex(KeyError, '1'): df[1] - with tm.assertRaisesRegexp(KeyError, "'\[1\] not in index'"): + with tm.assert_raises_regex(KeyError, "'\[1\] not in index'"): df[[1]] def test_loc_multiindex_indexer_none(self): @@ -801,7 +801,7 @@ def f(): self.assertEqual(df.index.lexsort_depth, 2) df = df.sort_index(level=1, axis=0) self.assertEqual(df.index.lexsort_depth, 0) - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( UnsortedIndexError, 'MultiIndex Slicing requires the index to be fully ' r'lexsorted tuple len \(2\), lexsort depth \(0\)'): diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index a583bf1c5ef16..70c7eaf7446db 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -154,8 +154,8 @@ def test_at_to_fail(self): df.columns = ['x', 'x', 'z'] # Check that we get the correct value in the KeyError - tm.assertRaisesRegexp(KeyError, r"\['y'\] not in index", - lambda: df[['x', 'y', 'z']]) + tm.assert_raises_regex(KeyError, r"\['y'\] not in index", + lambda: df[['x', 'y', 'z']]) def test_at_with_tz(self): # gh-15822 diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 51295fd750602..02c73019b0f65 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -31,7 +31,7 @@ def test_to_csv_quotechar(self): self.assertEqual(f.read(), expected) with tm.ensure_clean('test.csv') as path: - with tm.assertRaisesRegexp(TypeError, 'quotechar'): + with tm.assert_raises_regex(TypeError, 'quotechar'): df.to_csv(path, quoting=1, quotechar=None) def test_to_csv_doublequote(self): @@ -49,7 +49,7 @@ def test_to_csv_doublequote(self): from _csv import Error with tm.ensure_clean('test.csv') as path: - with tm.assertRaisesRegexp(Error, 'escapechar'): + with tm.assert_raises_regex(Error, 'escapechar'): df.to_csv(path, doublequote=False) # no escapechar set def test_to_csv_escapechar(self): diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index a8ea76ff9459c..0dfae0fb88bf6 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -342,7 +342,8 @@ def test_frame_from_json_bad_data(self): json = StringIO('{"badkey":["A","B"],' '"index":["2","3"],' '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}') - with tm.assertRaisesRegexp(ValueError, r"unexpected key\(s\): badkey"): + with tm.assert_raises_regex(ValueError, + r"unexpected key\(s\): badkey"): read_json(json, orient="split") def test_frame_from_json_nones(self): @@ -783,7 +784,7 @@ def test_misc_example(self): DataFrame\\.index values are different \\(100\\.0 %\\) \\[left\\]: Index\\(\\[u?'a', u?'b'\\], dtype='object'\\) \\[right\\]: RangeIndex\\(start=0, stop=2, step=1\\)""" - with tm.assertRaisesRegexp(AssertionError, error_msg): + with tm.assert_raises_regex(AssertionError, error_msg): assert_frame_equal(result, expected, check_index_type=False) result = read_json('[{"a": 1, "b": 2}, {"b":2, "a" :1}]') @@ -1036,7 +1037,7 @@ def test_to_jsonl(self): def test_latin_encoding(self): if compat.PY2: - tm.assertRaisesRegexp( + tm.assert_raises_regex( TypeError, r'\[unicode\] is not implemented as a table column') return diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index f0ccce5830a65..037e47bfc2a46 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -923,7 +923,7 @@ def my_handler(obj): def my_handler_raises(obj): raise TypeError("I raise for anything") - with tm.assertRaisesRegexp(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): diff --git a/pandas/tests/io/parser/c_parser_only.py b/pandas/tests/io/parser/c_parser_only.py index f4ca632e09f39..7ce8c61777bc7 100644 --- a/pandas/tests/io/parser/c_parser_only.py +++ b/pandas/tests/io/parser/c_parser_only.py @@ -96,7 +96,7 @@ def test_dtype_and_names_error(self): 3.0 3 """ # fallback casting, but not castable - with tm.assertRaisesRegexp(ValueError, 'cannot safely convert'): + with tm.assert_raises_regex(ValueError, 'cannot safely convert'): self.read_csv(StringIO(data), sep=r'\s+', header=None, names=['a', 'b'], dtype={'a': np.int32}) diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index deeeaef63da39..9abd3c5bfe993 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -44,7 +44,7 @@ def test_empty_decimal_marker(self): """ # Parsers support only length-1 decimals msg = 'Only length-1 decimal markers supported' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(data), decimal='') def test_bad_stream_exception(self): @@ -64,7 +64,7 @@ def test_bad_stream_exception(self): msg = "'utf-8' codec can't decode byte" else: msg = "'utf8' codec can't decode byte" - with tm.assertRaisesRegexp(UnicodeDecodeError, msg): + with tm.assert_raises_regex(UnicodeDecodeError, msg): self.read_csv(stream) stream.close() @@ -126,7 +126,7 @@ def test_malformed(self): 2,3,4 """ msg = 'Expected 3 fields in line 4, saw 5' - with tm.assertRaisesRegexp(Exception, msg): + with tm.assert_raises_regex(Exception, msg): self.read_table(StringIO(data), sep=',', header=1, comment='#') @@ -140,7 +140,7 @@ def test_malformed(self): 2,3,4 """ msg = 'Expected 3 fields in line 6, saw 5' - with tm.assertRaisesRegexp(Exception, msg): + with tm.assert_raises_regex(Exception, msg): it = self.read_table(StringIO(data), sep=',', header=1, comment='#', iterator=True, chunksize=1, @@ -157,7 +157,7 @@ def test_malformed(self): 2,3,4 """ msg = 'Expected 3 fields in line 6, saw 5' - with tm.assertRaisesRegexp(Exception, msg): + with tm.assert_raises_regex(Exception, msg): it = self.read_table(StringIO(data), sep=',', header=1, comment='#', iterator=True, chunksize=1, skiprows=[2]) @@ -173,7 +173,7 @@ def test_malformed(self): 2,3,4 """ msg = 'Expected 3 fields in line 6, saw 5' - with tm.assertRaisesRegexp(Exception, msg): + with tm.assert_raises_regex(Exception, msg): it = self.read_table(StringIO(data), sep=',', header=1, comment='#', iterator=True, chunksize=1, skiprows=[2]) @@ -190,7 +190,7 @@ def test_malformed(self): footer """ msg = 'Expected 3 fields in line 4, saw 5' - with tm.assertRaisesRegexp(Exception, msg): + with tm.assert_raises_regex(Exception, msg): self.read_table(StringIO(data), sep=',', header=1, comment='#', skipfooter=1) @@ -385,13 +385,13 @@ def test_read_nrows(self): msg = r"'nrows' must be an integer >=0" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(self.data1), nrows=1.2) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(self.data1), nrows='foo') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(self.data1), nrows=-1) def test_read_chunksize(self): @@ -407,13 +407,13 @@ def test_read_chunksize(self): # with invalid chunksize value: msg = r"'chunksize' must be an integer >=1" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(self.data1), chunksize=1.3) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(self.data1), chunksize='foo') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(self.data1), chunksize=0) def test_read_chunksize_and_nrows(self): @@ -1104,7 +1104,7 @@ def test_uneven_lines_with_usecols(self): # make sure that an error is still thrown # when the 'usecols' parameter is not provided msg = r"Expected \d+ fields in line \d+, saw \d+" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): df = self.read_csv(StringIO(csv)) expected = DataFrame({ @@ -1130,10 +1130,10 @@ def test_read_empty_with_usecols(self): # throws the correct error, with or without usecols errmsg = "No columns to parse from file" - with tm.assertRaisesRegexp(EmptyDataError, errmsg): + with tm.assert_raises_regex(EmptyDataError, errmsg): self.read_csv(StringIO('')) - with tm.assertRaisesRegexp(EmptyDataError, errmsg): + with tm.assert_raises_regex(EmptyDataError, errmsg): self.read_csv(StringIO(''), usecols=usecols) expected = DataFrame(columns=usecols, index=[0], dtype=np.float64) @@ -1172,7 +1172,8 @@ def test_trailing_spaces(self): def test_raise_on_sep_with_delim_whitespace(self): # see gh-6607 data = 'a b c\n1 2 3' - with tm.assertRaisesRegexp(ValueError, 'you can only specify one'): + with tm.assert_raises_regex(ValueError, + 'you can only specify one'): self.read_table(StringIO(data), sep=r'\s', delim_whitespace=True) def test_single_char_leading_whitespace(self): @@ -1563,7 +1564,7 @@ def test_null_byte_char(self): tm.assert_frame_equal(out, expected) else: msg = "NULL byte detected" - with tm.assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): self.read_csv(StringIO(data), names=cols) def test_utf8_bom(self): @@ -1681,13 +1682,13 @@ class InvalidBuffer(object): msg = "Invalid file path or buffer object type" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(InvalidBuffer()) if PY3: from unittest import mock - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(mock.Mock()) @tm.capture_stderr diff --git a/pandas/tests/io/parser/compression.py b/pandas/tests/io/parser/compression.py index 26e216cfbcffa..55c0506acb132 100644 --- a/pandas/tests/io/parser/compression.py +++ b/pandas/tests/io/parser/compression.py @@ -45,18 +45,19 @@ def test_zip(self): tmp.writestr(file_name, data) tmp.close() - tm.assertRaisesRegexp(ValueError, 'Multiple files', - self.read_csv, path, compression='zip') + tm.assert_raises_regex(ValueError, 'Multiple files', + self.read_csv, path, compression='zip') - tm.assertRaisesRegexp(ValueError, 'Multiple files', - self.read_csv, path, compression='infer') + tm.assert_raises_regex(ValueError, 'Multiple files', + self.read_csv, path, + compression='infer') with tm.ensure_clean() as path: tmp = zipfile.ZipFile(path, mode='w') tmp.close() - tm.assertRaisesRegexp(ValueError, 'Zero files', - self.read_csv, path, compression='zip') + tm.assert_raises_regex(ValueError, 'Zero files', + self.read_csv, path, compression='zip') with tm.ensure_clean() as path: with open(path, 'wb') as f: @@ -167,5 +168,5 @@ def test_read_csv_infer_compression(self): def test_invalid_compression(self): msg = 'Unrecognized compression type: sfark' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv('test_file.zip', compression='sfark') diff --git a/pandas/tests/io/parser/converters.py b/pandas/tests/io/parser/converters.py index f2b3ce532b59e..6cea0f3e7b36c 100644 --- a/pandas/tests/io/parser/converters.py +++ b/pandas/tests/io/parser/converters.py @@ -24,7 +24,7 @@ def test_converters_type_must_be_dict(self): data = """index,A,B,C,D foo,2,3,4,5 """ - with tm.assertRaisesRegexp(TypeError, 'Type converters.+'): + with tm.assert_raises_regex(TypeError, 'Type converters.+'): self.read_csv(StringIO(data), converters=0) def test_converters(self): diff --git a/pandas/tests/io/parser/dialect.py b/pandas/tests/io/parser/dialect.py index 82871628e54d6..f756fe71bf684 100644 --- a/pandas/tests/io/parser/dialect.py +++ b/pandas/tests/io/parser/dialect.py @@ -61,7 +61,7 @@ class InvalidDialect(object): data = 'a\n1' msg = 'Invalid dialect' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(data), dialect=InvalidDialect) def test_dialect_conflict(self): diff --git a/pandas/tests/io/parser/header.py b/pandas/tests/io/parser/header.py index 2f0ca5b311aef..f7967f4fe9765 100644 --- a/pandas/tests/io/parser/header.py +++ b/pandas/tests/io/parser/header.py @@ -19,7 +19,7 @@ class HeaderTests(object): def test_read_with_bad_header(self): errmsg = r"but only \d+ lines in file" - with tm.assertRaisesRegexp(ValueError, errmsg): + with tm.assert_raises_regex(ValueError, errmsg): s = StringIO(',,') self.read_csv(s, header=[10]) diff --git a/pandas/tests/io/parser/parse_dates.py b/pandas/tests/io/parser/parse_dates.py index f0a1f58be4026..3833fa3d7ff4e 100644 --- a/pandas/tests/io/parser/parse_dates.py +++ b/pandas/tests/io/parser/parse_dates.py @@ -435,11 +435,11 @@ def test_read_with_parse_dates_scalar_non_bool(self): data = """A,B,C 1,2,2003-11-1""" - tm.assertRaisesRegexp(TypeError, errmsg, self.read_csv, - StringIO(data), parse_dates="C") - tm.assertRaisesRegexp(TypeError, errmsg, self.read_csv, - StringIO(data), parse_dates="C", - index_col="C") + tm.assert_raises_regex(TypeError, errmsg, self.read_csv, + StringIO(data), parse_dates="C") + tm.assert_raises_regex(TypeError, errmsg, self.read_csv, + StringIO(data), parse_dates="C", + index_col="C") def test_read_with_parse_dates_invalid_type(self): errmsg = ("Only booleans, lists, and " @@ -448,12 +448,13 @@ def test_read_with_parse_dates_invalid_type(self): data = """A,B,C 1,2,2003-11-1""" - tm.assertRaisesRegexp(TypeError, errmsg, self.read_csv, - StringIO(data), parse_dates=(1,)) - tm.assertRaisesRegexp(TypeError, errmsg, self.read_csv, - StringIO(data), parse_dates=np.array([4, 5])) - tm.assertRaisesRegexp(TypeError, errmsg, self.read_csv, - StringIO(data), parse_dates=set([1, 3, 3])) + tm.assert_raises_regex(TypeError, errmsg, self.read_csv, + StringIO(data), parse_dates=(1,)) + tm.assert_raises_regex(TypeError, errmsg, + self.read_csv, StringIO(data), + parse_dates=np.array([4, 5])) + tm.assert_raises_regex(TypeError, errmsg, self.read_csv, + StringIO(data), parse_dates=set([1, 3, 3])) def test_parse_dates_empty_string(self): # see gh-2263 diff --git a/pandas/tests/io/parser/python_parser_only.py b/pandas/tests/io/parser/python_parser_only.py index c5fa64d067ee6..1356ace4bb38a 100644 --- a/pandas/tests/io/parser/python_parser_only.py +++ b/pandas/tests/io/parser/python_parser_only.py @@ -24,17 +24,17 @@ def test_invalid_skipfooter(self): # see gh-15925 (comment) msg = "skipfooter must be an integer" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(text), skipfooter="foo") - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(text), skipfooter=1.5) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(text), skipfooter=True) msg = "skipfooter cannot be negative" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(text), skipfooter=-1) def test_sniff_delimiter(self): @@ -208,13 +208,13 @@ def test_multi_char_sep_quotes(self): data = 'a,,b\n1,,a\n2,,"2,,b"' msg = 'ignored when a multi-char delimiter is used' - with tm.assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): self.read_csv(StringIO(data), sep=',,') # We expect no match, so there should be an assertion # error out of the inner context manager. with pytest.raises(AssertionError): - with tm.assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): self.read_csv(StringIO(data), sep=',,', quoting=csv.QUOTE_NONE) @@ -226,11 +226,11 @@ def test_skipfooter_bad_row(self): for data in ('a\n1\n"b"a', 'a,b,c\ncat,foo,bar\ndog,foo,"baz'): - with tm.assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): self.read_csv(StringIO(data), skipfooter=1) # We expect no match, so there should be an assertion # error out of the inner context manager. with pytest.raises(AssertionError): - with tm.assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): self.read_csv(StringIO(data)) diff --git a/pandas/tests/io/parser/quoting.py b/pandas/tests/io/parser/quoting.py index a692e03e868c7..15427aaf9825c 100644 --- a/pandas/tests/io/parser/quoting.py +++ b/pandas/tests/io/parser/quoting.py @@ -20,29 +20,29 @@ def test_bad_quote_char(self): # Python 2.x: "...must be an 1-character..." # Python 3.x: "...must be a 1-character..." msg = '"quotechar" must be a(n)? 1-character string' - tm.assertRaisesRegexp(TypeError, msg, self.read_csv, - StringIO(data), quotechar='foo') + tm.assert_raises_regex(TypeError, msg, self.read_csv, + StringIO(data), quotechar='foo') msg = 'quotechar must be set if quoting enabled' - tm.assertRaisesRegexp(TypeError, msg, self.read_csv, - StringIO(data), quotechar=None, - quoting=csv.QUOTE_MINIMAL) + tm.assert_raises_regex(TypeError, msg, self.read_csv, + StringIO(data), quotechar=None, + quoting=csv.QUOTE_MINIMAL) msg = '"quotechar" must be string, not int' - tm.assertRaisesRegexp(TypeError, msg, self.read_csv, - StringIO(data), quotechar=2) + tm.assert_raises_regex(TypeError, msg, self.read_csv, + StringIO(data), quotechar=2) def test_bad_quoting(self): data = '1,2,3' msg = '"quoting" must be an integer' - tm.assertRaisesRegexp(TypeError, msg, self.read_csv, - StringIO(data), quoting='foo') + tm.assert_raises_regex(TypeError, msg, self.read_csv, + StringIO(data), quoting='foo') # quoting must in the range [0, 3] msg = 'bad "quoting" value' - tm.assertRaisesRegexp(TypeError, msg, self.read_csv, - StringIO(data), quoting=5) + tm.assert_raises_regex(TypeError, msg, self.read_csv, + StringIO(data), quoting=5) def test_quote_char_basic(self): data = 'a,b,c\n1,2,"cat"' @@ -68,13 +68,13 @@ def test_null_quote_char(self): # sanity checks msg = 'quotechar must be set if quoting enabled' - tm.assertRaisesRegexp(TypeError, msg, self.read_csv, - StringIO(data), quotechar=None, - quoting=csv.QUOTE_MINIMAL) + tm.assert_raises_regex(TypeError, msg, self.read_csv, + StringIO(data), quotechar=None, + quoting=csv.QUOTE_MINIMAL) - tm.assertRaisesRegexp(TypeError, msg, self.read_csv, - StringIO(data), quotechar='', - quoting=csv.QUOTE_MINIMAL) + tm.assert_raises_regex(TypeError, msg, self.read_csv, + StringIO(data), quotechar='', + quoting=csv.QUOTE_MINIMAL) # no errors should be raised if quoting is None expected = DataFrame([[1, 2, 3]], diff --git a/pandas/tests/io/parser/skiprows.py b/pandas/tests/io/parser/skiprows.py index cb1b656e42be2..fb08ec0447267 100644 --- a/pandas/tests/io/parser/skiprows.py +++ b/pandas/tests/io/parser/skiprows.py @@ -215,11 +215,11 @@ def test_skiprows_callable(self): skiprows = lambda x: True msg = "No columns to parse from file" - with tm.assertRaisesRegexp(EmptyDataError, msg): + with tm.assert_raises_regex(EmptyDataError, msg): self.read_csv(StringIO(data), skiprows=skiprows) # This is a bad callable and should raise. msg = "by zero" skiprows = lambda x: 1 / 0 - with tm.assertRaisesRegexp(ZeroDivisionError, msg): + with tm.assert_raises_regex(ZeroDivisionError, msg): self.read_csv(StringIO(data), skiprows=skiprows) diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index 9498a7d83e0de..ffb04c52e8d93 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -67,10 +67,11 @@ def test_fwf(self): StringIO(data3), colspecs=colspecs, delimiter='~', header=None) tm.assert_frame_equal(df, expected) - with tm.assertRaisesRegexp(ValueError, "must specify only one of"): + with tm.assert_raises_regex(ValueError, + "must specify only one of"): read_fwf(StringIO(data3), colspecs=colspecs, widths=[6, 10, 10, 7]) - with tm.assertRaisesRegexp(ValueError, "Must specify either"): + with tm.assert_raises_regex(ValueError, "Must specify either"): read_fwf(StringIO(data3), colspecs=None, widths=None) def test_BytesIO_input(self): @@ -93,9 +94,9 @@ def test_fwf_colspecs_is_list_or_tuple(self): bar2,12,13,14,15 """ - with tm.assertRaisesRegexp(TypeError, - 'column specifications must be a list or ' - 'tuple.+'): + with tm.assert_raises_regex(TypeError, + 'column specifications must ' + 'be a list or tuple.+'): pd.io.parsers.FixedWidthReader(StringIO(data), {'a': 1}, ',', '#') @@ -109,8 +110,9 @@ def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples(self): bar2,12,13,14,15 """ - with tm.assertRaisesRegexp(TypeError, - 'Each column specification must be.+'): + with tm.assert_raises_regex(TypeError, + 'Each column specification ' + 'must be.+'): read_fwf(StringIO(data), [('a', 1)]) def test_fwf_colspecs_None(self): diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py index 9637b449de6da..6c2d883aeb16b 100644 --- a/pandas/tests/io/parser/test_unsupported.py +++ b/pandas/tests/io/parser/test_unsupported.py @@ -25,7 +25,7 @@ def test_mangle_dupe_cols_false(self): msg = 'is not supported' for engine in ('c', 'python'): - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_csv(StringIO(data), engine=engine, mangle_dupe_cols=False) @@ -35,14 +35,14 @@ def test_c_engine(self): msg = 'does not support' # specify C engine with unsupported options (raise) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_table(StringIO(data), engine='c', sep=None, delim_whitespace=False) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_table(StringIO(data), engine='c', sep=r'\s') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_table(StringIO(data), engine='c', quotechar=chr(128)) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_table(StringIO(data), engine='c', skipfooter=1) # specify C-unsupported options without python-unsupported options @@ -62,9 +62,9 @@ def test_c_engine(self): x q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838""" msg = 'Error tokenizing data' - with tm.assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): read_table(StringIO(text), sep='\\s+') - with tm.assertRaisesRegexp(ParserError, msg): + with tm.assert_raises_regex(ParserError, msg): read_table(StringIO(text), engine='c', sep='\\s+') msg = "Only length-1 thousands markers supported" @@ -72,14 +72,14 @@ def test_c_engine(self): 1|2,334|5 10|13|10. """ - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_csv(StringIO(data), thousands=',,') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_csv(StringIO(data), thousands='') msg = "Only length-1 line terminators supported" data = 'a,b,c~~1,2,3~~4,5,6' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_csv(StringIO(data), lineterminator='~~') def test_python_engine(self): @@ -98,7 +98,7 @@ def test_python_engine(self): 'with the %r engine' % (default, engine)) kwargs = {default: object()} - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): read_csv(StringIO(data), engine=engine, **kwargs) diff --git a/pandas/tests/io/parser/usecols.py b/pandas/tests/io/parser/usecols.py index 1ea7353427c30..db8e5b7653a51 100644 --- a/pandas/tests/io/parser/usecols.py +++ b/pandas/tests/io/parser/usecols.py @@ -28,7 +28,7 @@ def test_raise_on_mixed_dtype_usecols(self): "all integers or a callable") usecols = [0, 'b', 2] - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(data), usecols=usecols) def test_usecols(self): @@ -351,10 +351,10 @@ def test_usecols_with_mixed_encoding_strings(self): msg = ("'usecols' must either be all strings, all unicode, " "all integers or a callable") - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(s), usecols=[u'AAA', b'BBB']) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.read_csv(StringIO(s), usecols=[b'AAA', u'BBB']) def test_usecols_with_multibyte_characters(self): diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index fd29caefb8cb5..82819b94413b4 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -108,13 +108,14 @@ def test_constructor_bad_file(self): msg = "[Errno 22]" err = mmap.error - tm.assertRaisesRegexp(err, msg, common.MMapWrapper, non_file) + tm.assert_raises_regex(err, msg, common.MMapWrapper, non_file) target = open(self.mmap_file, 'r') target.close() msg = "I/O operation on closed file" - tm.assertRaisesRegexp(ValueError, msg, common.MMapWrapper, target) + tm.assert_raises_regex( + ValueError, msg, common.MMapWrapper, target) def test_get_attr(self): with open(self.mmap_file, 'r') as target: diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 02652be2153f1..2a3a4992ead71 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -1870,7 +1870,7 @@ def wrapped(self, *args, **kwargs): else: msg = (r'Installed openpyxl is not supported at this ' r'time\. Use.+') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): orig_method(self, *args, **kwargs) return wrapped return versioned_raise_wrapper @@ -2292,7 +2292,7 @@ class XlsxWriterTests_NoMerge(ExcelWriterBase, tm.TestCase): class ExcelWriterEngineTests(tm.TestCase): def test_ExcelWriter_dispatch(self): - with tm.assertRaisesRegexp(ValueError, 'No engine'): + with tm.assert_raises_regex(ValueError, 'No engine'): ExcelWriter('nothing') try: diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index e7eaab098fe4d..5a30ff2afe7e5 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -219,8 +219,8 @@ def test_skiprows_ndarray(self): assert_framelist_equal(df1, df2) def test_skiprows_invalid(self): - with tm.assertRaisesRegexp(TypeError, - 'is not a valid type for skipping rows'): + with tm.assert_raises_regex(TypeError, 'is not a valid type ' + 'for skipping rows'): self.read_html(self.spam_data, '.*Water.*', skiprows='asdf') def test_index(self): @@ -302,7 +302,7 @@ def test_file_url(self): @tm.slow def test_invalid_table_attrs(self): url = self.banklist_data - with tm.assertRaisesRegexp(ValueError, 'No tables found'): + with tm.assert_raises_regex(ValueError, 'No tables found'): self.read_html(url, 'First Federal Bank of Florida', attrs={'id': 'tasdfable'}) @@ -353,8 +353,8 @@ def test_regex_idempotency(self): assert isinstance(df, DataFrame) def test_negative_skiprows(self): - with tm.assertRaisesRegexp(ValueError, - r'\(you passed a negative value\)'): + with tm.assert_raises_regex(ValueError, + r'\(you passed a negative value\)'): self.read_html(self.spam_data, 'Water', skiprows=-1) @network @@ -652,9 +652,10 @@ def test_parse_dates_combine(self): def test_computer_sales_page(self): data = os.path.join(DATA_PATH, 'computer_sales_page.html') - with tm.assertRaisesRegexp(ParserError, r"Passed header=\[0,1\] are " - "too many rows for this multi_index " - "of columns"): + 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]) def test_wikipedia_states_table(self): diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 94e4fec07e775..875b5bd3055b9 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -403,8 +403,8 @@ def test_write_explicit(self, compression, get_random_path): @pytest.mark.parametrize('compression', ['', 'None', 'bad', '7z']) def test_write_explicit_bad(self, compression, get_random_path): - with tm.assertRaisesRegexp(ValueError, - "Unrecognized compression type"): + with tm.assert_raises_regex(ValueError, + "Unrecognized compression type"): with tm.ensure_clean(get_random_path) as path: df = tm.makeDataFrame() df.to_pickle(path, compression=compression) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 7d2c7a97fce0a..1b656e7b1b004 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -971,7 +971,7 @@ def test_encoding(self): def test_latin_encoding(self): if compat.PY2: - tm.assertRaisesRegexp( + tm.assert_raises_regex( TypeError, r'\[unicode\] is not implemented as a table column') return @@ -2563,7 +2563,7 @@ def test_terms(self): for t in terms: store.select('p4d', t) - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( TypeError, 'Only named functions are supported'): store.select( 'wp', @@ -2575,8 +2575,9 @@ def test_terms(self): expected = Panel({-1: wpneg[-1]}) tm.assert_panel_equal(res, expected) - with tm.assertRaisesRegexp(NotImplementedError, - 'Unary addition not supported'): + with tm.assert_raises_regex(NotImplementedError, + 'Unary addition ' + 'not supported'): store.select('wpneg', 'items == +1') def test_term_compat(self): @@ -4388,7 +4389,7 @@ def f(): def f(): store.select('df') - tm.assertRaisesRegexp(ClosedFileError, 'file is not open', f) + tm.assert_raises_regex(ClosedFileError, 'file is not open', f) def test_pytables_native_read(self): diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 63fcfb0d2f5ac..36ff3bdbb24b5 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -984,7 +984,7 @@ def test_database_uri_string(self): # using driver that will not be installed on Travis to trigger error # in sqlalchemy.create_engine -> test passing of this error to user db_uri = "postgresql+pg8000://user:pass@host/dbname" - with tm.assertRaisesRegexp(ImportError, "pg8000"): + with tm.assert_raises_regex(ImportError, "pg8000"): sql.read_sql("select * from table", db_uri) def _make_iris_table_metadata(self): @@ -2380,8 +2380,8 @@ def test_unsupported_flavor(self): msg = 'is not supported' for func in self.funcs: - tm.assertRaisesRegexp(ValueError, msg, getattr(sql, func), - self.con, flavor='mysql') + tm.assert_raises_regex(ValueError, msg, getattr(sql, func), + self.con, flavor='mysql') def test_deprecated_flavor(self): for func in self.funcs: diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index cc71cf6b1a4dc..2bde4349f6000 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -124,10 +124,12 @@ def test_concatlike_same_dtypes(self): tm.assert_index_equal(res, exp) # cannot append non-index - with tm.assertRaisesRegexp(TypeError, 'all inputs must be Index'): + with tm.assert_raises_regex(TypeError, + 'all inputs must be Index'): pd.Index(vals1).append(vals2) - with tm.assertRaisesRegexp(TypeError, 'all inputs must be Index'): + with tm.assert_raises_regex(TypeError, + 'all inputs must be Index'): pd.Index(vals1).append([pd.Index(vals2), vals3]) # ----- Series ----- # @@ -175,16 +177,16 @@ def test_concatlike_same_dtypes(self): # cannot append non-index msg = "cannot concatenate a non-NDFrame object" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): pd.Series(vals1).append(vals2) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): pd.Series(vals1).append([pd.Series(vals2), vals3]) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): pd.concat([pd.Series(vals1), vals2]) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): pd.concat([pd.Series(vals1), pd.Series(vals2), vals3]) def test_concatlike_dtypes_coercion(self): diff --git a/pandas/tests/reshape/test_join.py b/pandas/tests/reshape/test_join.py index 7e39806b42cbf..475b17d9fe792 100644 --- a/pandas/tests/reshape/test_join.py +++ b/pandas/tests/reshape/test_join.py @@ -234,9 +234,9 @@ def test_join_on_fails_with_wrong_object_type(self): df = DataFrame({'a': [1, 1]}) for obj in wrongly_typed: - with tm.assertRaisesRegexp(ValueError, str(type(obj))): + with tm.assert_raises_regex(ValueError, str(type(obj))): merge(obj, df, left_on='a', right_on='a') - with tm.assertRaisesRegexp(ValueError, str(type(obj))): + with tm.assert_raises_regex(ValueError, str(type(obj))): merge(df, obj, left_on='a', right_on='a') def test_join_on_pass_vector(self): diff --git a/pandas/tests/reshape/test_merge_ordered.py b/pandas/tests/reshape/test_merge_ordered.py index e445ad9323b51..77f47ff0a76e9 100644 --- a/pandas/tests/reshape/test_merge_ordered.py +++ b/pandas/tests/reshape/test_merge_ordered.py @@ -83,7 +83,7 @@ def test_empty_sequence_concat(self): ([None, None], none_pat) ] for df_seq, pattern in test_cases: - tm.assertRaisesRegexp(ValueError, pattern, pd.concat, df_seq) + tm.assert_raises_regex(ValueError, pattern, pd.concat, df_seq) pd.concat([pd.DataFrame()]) pd.concat([None, pd.DataFrame()]) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 242011d6f23da..f15616a16678f 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -1321,22 +1321,22 @@ def test_crosstab_errors(self): 'c': [1, 1, np.nan, 1, 1]}) error = 'values cannot be used without an aggfunc.' - with tm.assertRaisesRegexp(ValueError, error): + with tm.assert_raises_regex(ValueError, error): pd.crosstab(df.a, df.b, values=df.c) error = 'aggfunc cannot be used without values' - with tm.assertRaisesRegexp(ValueError, error): + with tm.assert_raises_regex(ValueError, error): pd.crosstab(df.a, df.b, aggfunc=np.mean) error = 'Not a valid normalize argument' - with tm.assertRaisesRegexp(ValueError, error): + with tm.assert_raises_regex(ValueError, error): pd.crosstab(df.a, df.b, normalize='42') - with tm.assertRaisesRegexp(ValueError, error): + with tm.assert_raises_regex(ValueError, error): pd.crosstab(df.a, df.b, normalize=42) error = 'Not a valid margins argument' - with tm.assertRaisesRegexp(ValueError, error): + with tm.assert_raises_regex(ValueError, error): pd.crosstab(df.a, df.b, normalize='all', margins=42) def test_crosstab_with_categorial_columns(self): diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index f41c977cc03e1..87f16cfaf31ec 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -117,7 +117,7 @@ def test_tuple_vars_fail_with_multiindex(self): for id_vars, value_vars in ((tuple_a, list_b), (list_a, tuple_b), (tuple_a, tuple_b)): - with tm.assertRaisesRegexp(ValueError, r'MultiIndex'): + with tm.assert_raises_regex(ValueError, r'MultiIndex'): self.df1.melt(id_vars=id_vars, value_vars=value_vars) def test_custom_var_name(self): diff --git a/pandas/tests/reshape/test_tile.py b/pandas/tests/reshape/test_tile.py index 8aaa8a51d7020..1cc5c5f229bce 100644 --- a/pandas/tests/reshape/test_tile.py +++ b/pandas/tests/reshape/test_tile.py @@ -192,8 +192,8 @@ def test_qcut_specify_quantiles(self): tm.assert_categorical_equal(factor, expected) def test_qcut_all_bins_same(self): - tm.assertRaisesRegexp(ValueError, "edges.*unique", qcut, - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3) + tm.assert_raises_regex(ValueError, "edges.*unique", qcut, + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3) def test_cut_out_of_bounds(self): arr = np.random.randn(100) diff --git a/pandas/tests/reshape/test_union_categoricals.py b/pandas/tests/reshape/test_union_categoricals.py index 1c67b13a9c1c9..5cc476718add2 100644 --- a/pandas/tests/reshape/test_union_categoricals.py +++ b/pandas/tests/reshape/test_union_categoricals.py @@ -58,11 +58,11 @@ def test_union_categorical(self): s = Categorical([0, 1.2, 2]) s2 = Categorical([2, 3, 4]) msg = 'dtype of categories must be the same' - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): union_categoricals([s, s2]) msg = 'No Categoricals to union' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): union_categoricals([]) def test_union_categoricals_nan(self): @@ -139,7 +139,7 @@ def test_union_categoricals_ordered(self): c2 = Categorical([1, 2, 3], ordered=False) msg = 'Categorical.ordered must be the same' - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): union_categoricals([c1, c2]) res = union_categoricals([c1, c1]) @@ -157,7 +157,7 @@ def test_union_categoricals_ordered(self): c2 = Categorical([1, 2, 3], categories=[3, 2, 1], ordered=True) msg = "to union ordered Categoricals, all categories must be the same" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): union_categoricals([c1, c2]) def test_union_categoricals_ignore_order(self): @@ -170,7 +170,7 @@ def test_union_categoricals_ignore_order(self): tm.assert_categorical_equal(res, exp) msg = 'Categorical.ordered must be the same' - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): union_categoricals([c1, c2], ignore_order=False) res = union_categoricals([c1, c1], ignore_order=True) @@ -208,10 +208,10 @@ def test_union_categoricals_ignore_order(self): tm.assert_categorical_equal(result, expected) msg = "to union ordered Categoricals, all categories must be the same" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): union_categoricals([c1, c2], ignore_order=False) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): union_categoricals([c1, c2]) def test_union_categoricals_sort(self): diff --git a/pandas/tests/reshape/test_util.py b/pandas/tests/reshape/test_util.py index fd3a683e80397..a7fbe8d305011 100644 --- a/pandas/tests/reshape/test_util.py +++ b/pandas/tests/reshape/test_util.py @@ -46,4 +46,4 @@ def test_invalid_input(self): 'a', ['a'], ['a', 'b'], [['a'], 'b']] msg = "Input must be a list-like of list-likes" for X in invalid_inputs: - tm.assertRaisesRegexp(TypeError, msg, cartesian_product, X=X) + tm.assert_raises_regex(TypeError, msg, cartesian_product, X=X) diff --git a/pandas/tests/scalar/test_interval.py b/pandas/tests/scalar/test_interval.py index ea267fabd13ed..526a2916e2924 100644 --- a/pandas/tests/scalar/test_interval.py +++ b/pandas/tests/scalar/test_interval.py @@ -46,7 +46,7 @@ def test_equal(self): self.assertNotEqual(Interval(0, 1), 0) def test_comparison(self): - with tm.assertRaisesRegexp(TypeError, 'unorderable types'): + with tm.assert_raises_regex(TypeError, 'unorderable types'): Interval(0, 1) < 2 self.assertTrue(Interval(0, 1) < Interval(1, 2)) diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py index f8b103836e9a1..b5c2439524e34 100644 --- a/pandas/tests/scalar/test_period.py +++ b/pandas/tests/scalar/test_period.py @@ -135,11 +135,11 @@ def test_period_cons_mult(self): msg = ('Frequency must be positive, because it' ' represents span: -3M') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2011-01', freq='-3M') msg = ('Frequency must be positive, because it' ' represents span: 0M') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2011-01', freq='0M') def test_period_cons_combined(self): @@ -185,28 +185,28 @@ def test_period_cons_combined(self): msg = ('Frequency must be positive, because it' ' represents span: -25H') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2011-01', freq='-1D1H') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2011-01', freq='-1H1D') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(ordinal=1, freq='-1D1H') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(ordinal=1, freq='-1H1D') msg = ('Frequency must be positive, because it' ' represents span: 0D') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2011-01', freq='0D0H') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(ordinal=1, freq='0D0H') # You can only combine together day and intraday offsets msg = ('Invalid frequency: 1W1D') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2011-01', freq='1W1D') msg = ('Invalid frequency: 1D1W') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2011-01', freq='1D1W') def test_timestamp_tz_arg(self): @@ -518,9 +518,9 @@ def test_period_deprecated_freq(self): msg = pd.tseries.frequencies._INVALID_FREQ_ERROR for exp, freqs in iteritems(cases): for freq in freqs: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period('2016-03-01 09:00', freq=freq) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(ordinal=1, freq=freq) # check supported freq-aliases still works @@ -762,7 +762,7 @@ def test_properties_weekly_legacy(self): self.assertEqual(exp.days_in_month, 29) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK', year=2007, month=1, day=7) def test_properties_daily(self): @@ -1032,14 +1032,14 @@ def test_add_raises(self): dt1 = Period(freq='D', year=2008, month=1, day=1) dt2 = Period(freq='D', year=2008, month=1, day=2) msg = r"unsupported operand type\(s\)" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): dt1 + "str" msg = r"unsupported operand type\(s\)" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): "str" + dt1 - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): dt1 + dt2 def test_sub(self): @@ -1050,7 +1050,7 @@ def test_sub(self): self.assertEqual(dt2 - dt1, 14) msg = r"Input has different freq=M from Period\(freq=D\)" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): dt1 - pd.Period('2011-02', freq='M') def test_add_offset(self): @@ -1414,8 +1414,8 @@ def test_period_ops_offset(self): self.assertEqual(result, exp) msg = r"Input cannot be converted to Period\(freq=D\)" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): p + offsets.Hour(2) - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): p - offsets.Hour(2) diff --git a/pandas/tests/scalar/test_period_asfreq.py b/pandas/tests/scalar/test_period_asfreq.py index 611a1cc97e9c6..84793658a6537 100644 --- a/pandas/tests/scalar/test_period_asfreq.py +++ b/pandas/tests/scalar/test_period_asfreq.py @@ -295,26 +295,26 @@ def test_conv_weekly(self): self.assertEqual(ival_W.asfreq('W'), ival_W) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, 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.tseries.frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK', year=2007, month=1, day=1) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK-SAT', year=2007, month=1, day=6) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK-FRI', year=2007, month=1, day=5) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK-THU', year=2007, month=1, day=4) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK-WED', year=2007, month=1, day=3) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK-TUE', year=2007, month=1, day=2) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): Period(freq='WK-MON', year=2007, month=1, day=1) def test_conv_business(self): @@ -712,10 +712,10 @@ def test_asfreq_MS(self): Period('2013-01', 'M')) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): initial.asfreq(freq="MS", how="S") - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): pd.Period('2013-01', 'MS') self.assertTrue(_period_code_map.get("MS") is None) diff --git a/pandas/tests/scalar/test_timedelta.py b/pandas/tests/scalar/test_timedelta.py index 4cced3e480c78..86b02d20b6996 100644 --- a/pandas/tests/scalar/test_timedelta.py +++ b/pandas/tests/scalar/test_timedelta.py @@ -125,16 +125,17 @@ def test_construction(self): pytest.raises(ValueError, lambda: Timedelta('3.1415')) # invalid construction - tm.assertRaisesRegexp(ValueError, "cannot construct a Timedelta", - lambda: Timedelta()) - tm.assertRaisesRegexp(ValueError, "unit abbreviation w/o a number", - lambda: Timedelta('foo')) - tm.assertRaisesRegexp(ValueError, - "cannot construct a Timedelta from the passed " - "arguments, allowed keywords are ", - lambda: Timedelta(day=10)) - - # roundtripping both for string and value + tm.assert_raises_regex(ValueError, "cannot construct a Timedelta", + lambda: Timedelta()) + tm.assert_raises_regex(ValueError, + "unit abbreviation w/o a number", + lambda: Timedelta('foo')) + tm.assert_raises_regex(ValueError, + "cannot construct a Timedelta from the " + "passed arguments, allowed keywords are ", + lambda: Timedelta(day=10)) + + # round-trip both for string and value for v in ['1s', '-1s', '1us', '-1us', '1 day', '-1 day', '-23:59:59.999999', '-1 days +23:59:59.999999', '-1ns', '1ns', '-23:59:59.999999999']: diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index b7b1b4c198701..bad0b697eef6c 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -172,9 +172,9 @@ def test_constructor_with_stringoffset(self): self.assertEqual(result, eval(repr(result))) def test_constructor_invalid(self): - with tm.assertRaisesRegexp(TypeError, 'Cannot convert input'): + with tm.assert_raises_regex(TypeError, 'Cannot convert input'): Timestamp(slice(2)) - with tm.assertRaisesRegexp(ValueError, 'Cannot convert Period'): + with tm.assert_raises_regex(ValueError, 'Cannot convert Period'): Timestamp(Period('1000-01-01')) def test_constructor_positional(self): @@ -245,7 +245,7 @@ def test_constructor_offset_depr(self): self.assertEqual(ts.offset, 'D') msg = "Can only specify freq or offset, not both" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): Timestamp('2011-01-01', offset='D', freq='D') def test_constructor_offset_depr_fromordinal(self): @@ -260,7 +260,7 @@ def test_constructor_offset_depr_fromordinal(self): self.assertEqual(base.toordinal(), ts.toordinal()) msg = "Can only specify freq or offset, not both" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): Timestamp.fromordinal(base.toordinal(), offset='D', freq='D') def test_conversion(self): @@ -393,14 +393,14 @@ def test_tz_localize_ambiguous(self): ambiguous='infer') # GH 8025 - with tm.assertRaisesRegexp(TypeError, - 'Cannot localize tz-aware Timestamp, use ' - 'tz_convert for conversions'): + with tm.assert_raises_regex(TypeError, + 'Cannot localize tz-aware Timestamp, ' + 'use tz_convert for conversions'): Timestamp('2011-01-01', tz='US/Eastern').tz_localize('Asia/Tokyo') - with tm.assertRaisesRegexp(TypeError, - 'Cannot convert tz-naive Timestamp, use ' - 'tz_localize to localize'): + with tm.assert_raises_regex(TypeError, + 'Cannot convert tz-naive Timestamp, ' + 'use tz_localize to localize'): Timestamp('2011-01-01').tz_convert('Asia/Tokyo') def test_tz_localize_nonexistent(self): @@ -710,7 +710,7 @@ def _check_round(freq, expected): _check_round(freq, expected) msg = frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): stamp.round('foo') def test_class_ops_pytz(self): diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 02748aee4628d..eb8a83bb85847 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -550,8 +550,8 @@ def testit(): # Unimplemented numeric_only parameter. if 'numeric_only' in compat.signature(f).args: - tm.assertRaisesRegexp(NotImplementedError, name, f, - self.series, numeric_only=True) + tm.assert_raises_regex(NotImplementedError, name, f, + self.series, numeric_only=True) testit() @@ -596,12 +596,12 @@ def test_numpy_compress(self): tm.assert_series_equal(np.compress(cond, s), expected) msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.compress, - cond, s, axis=1) + tm.assert_raises_regex(ValueError, msg, np.compress, + cond, s, axis=1) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.compress, - cond, s, out=s) + tm.assert_raises_regex(ValueError, msg, np.compress, + cond, s, out=s) def test_round(self): self.ts.index.name = "index_name" @@ -619,7 +619,7 @@ def test_numpy_round(self): assert_series_equal(out, expected) msg = "the 'out' parameter is not supported" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): np.round(s, decimals=0, out=s) def test_built_in_round(self): @@ -1184,8 +1184,8 @@ def test_numpy_argmin(self): if not _np_version_under1p10: msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.argmin, - Series(data), out=data) + tm.assert_raises_regex(ValueError, msg, np.argmin, + Series(data), out=data) def test_idxmax(self): # test idxmax @@ -1240,8 +1240,8 @@ def test_numpy_argmax(self): if not _np_version_under1p10: msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.argmax, - Series(data), out=data) + tm.assert_raises_regex(ValueError, msg, np.argmax, + Series(data), out=data) def test_ptp(self): N = 1000 @@ -1307,7 +1307,7 @@ def test_numpy_repeat(self): assert_series_equal(np.repeat(s, 2), expected) msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.repeat, s, 2, axis=0) + tm.assert_raises_regex(ValueError, msg, np.repeat, s, 2, axis=0) def test_searchsorted(self): s = Series([1, 2, 3]) @@ -1483,11 +1483,13 @@ def test_reshape_bad_kwarg(self): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): msg = "'foo' is an invalid keyword argument for this function" - tm.assertRaisesRegexp(TypeError, msg, a.reshape, (2, 2), foo=2) + tm.assert_raises_regex( + TypeError, msg, a.reshape, (2, 2), foo=2) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): msg = r"reshape\(\) got an unexpected keyword argument 'foo'" - tm.assertRaisesRegexp(TypeError, msg, a.reshape, a.shape, foo=2) + tm.assert_raises_regex( + TypeError, msg, a.reshape, a.shape, foo=2) def test_numpy_reshape(self): a = Series([1, 2, 3, 4]) @@ -1697,7 +1699,7 @@ def test_error(self, r): args = 2, len(r), 0, -1 methods = r.nlargest, r.nsmallest for method, arg in product(methods, args): - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): method(arg) @pytest.mark.parametrize( @@ -1729,9 +1731,9 @@ def test_misc(self): assert_series_equal(s.nsmallest(), s.iloc[[2, 3, 0, 4]]) msg = 'keep must be either "first", "last"' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.nsmallest(keep='invalid') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.nlargest(keep='invalid') # GH 15297 diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index f1a904498b727..397058c4bb8ce 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -341,7 +341,8 @@ def test_str_attribute(self): # str accessor only valid with string values s = Series(range(5)) - with tm.assertRaisesRegexp(AttributeError, 'only use .str accessor'): + with tm.assert_raises_regex(AttributeError, + 'only use .str accessor'): s.str.repeat(2) def test_empty_method(self): diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py index 51a2a5ed6c574..b4615e5420a81 100644 --- a/pandas/tests/series/test_combine_concat.py +++ b/pandas/tests/series/test_combine_concat.py @@ -55,9 +55,9 @@ def test_append_duplicates(self): exp, check_index_type=True) msg = 'Indexes have overlapping values:' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s1.append(s2, verify_integrity=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): pd.concat([s1, s2], verify_integrity=True) def test_combine_first(self): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 74c2544d900ea..c461556644275 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -851,10 +851,10 @@ def test_auto_conversion(self): def test_constructor_cant_cast_datetime64(self): msg = "Cannot cast datetime64 to " - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): Series(date_range('1/1/2000', periods=10), dtype=float) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): Series(date_range('1/1/2000', periods=10), dtype=int) def test_constructor_cast_object(self): @@ -882,9 +882,9 @@ def test_constructor_generic_timestamp_deprecated(self): # These timestamps have the wrong frequencies, # so an Exception should be raised now. msg = "cannot convert timedeltalike" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): Series([], dtype='m8[ps]') msg = "cannot convert datetimelike" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): Series([], dtype='M8[ps]') diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index ecb457b4ff1b0..74a4e37f0923a 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -251,7 +251,7 @@ def get_dir(s): # no setting allowed s = Series(date_range('20130101', periods=5, freq='D'), name='xxx') - with tm.assertRaisesRegexp(ValueError, "modifications"): + with tm.assert_raises_regex(ValueError, "modifications"): s.dt.hour = 5 # trying to set a copy @@ -265,8 +265,8 @@ def f(): def test_dt_accessor_no_new_attributes(self): # https://github.com/pandas-dev/pandas/issues/10673 s = Series(date_range('20130101', periods=5, freq='D')) - with tm.assertRaisesRegexp(AttributeError, - "You cannot add any new attribute"): + with tm.assert_raises_regex(AttributeError, + "You cannot add any new attribute"): s.dt.xlabel = "a" def test_strftime(self): @@ -375,8 +375,8 @@ def test_dt_accessor_api(self): for s in [Series(np.arange(5)), Series(list('abcde')), Series(np.random.randn(5))]: - with tm.assertRaisesRegexp(AttributeError, - "only use .dt accessor"): + with tm.assert_raises_regex(AttributeError, + "only use .dt accessor"): s.dt self.assertFalse(hasattr(s, 'dt')) diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index 6bbf00d6cab22..e084fa58d6c51 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -50,7 +50,7 @@ def test_astype_cast_nan_inf_int(self, dtype, value): msg = 'Cannot convert non-finite values \\(NA or inf\\) to integer' s = Series([value]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.astype(dtype) @pytest.mark.parametrize("dtype", [int, np.int8, np.int64]) diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 135e208877f2d..6907cc194f0f0 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -808,9 +808,9 @@ def test_setslice(self): def test_basic_getitem_setitem_corner(self): # invalid tuples, e.g. self.ts[:, None] vs. self.ts[:, 2] - with tm.assertRaisesRegexp(ValueError, 'tuple-index'): + with tm.assert_raises_regex(ValueError, 'tuple-index'): self.ts[:, 2] - with tm.assertRaisesRegexp(ValueError, 'tuple-index'): + with tm.assert_raises_regex(ValueError, 'tuple-index'): self.ts[:, 2] = 2 # weird lists. [slice(0, 5)] will work but not two slices @@ -1206,11 +1206,11 @@ def test_where_invalid_input(self): ] for cond in conds: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.where(cond) msg = "Array conditional must be same shape as self" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.where([True]) def test_where_ndframe_align(self): @@ -1218,7 +1218,7 @@ def test_where_ndframe_align(self): s = Series([1, 2, 3]) cond = [True] - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.where(cond) expected = Series([1, np.nan, np.nan]) @@ -1227,7 +1227,7 @@ def test_where_ndframe_align(self): tm.assert_series_equal(out, expected) cond = np.array([False, True, False, True]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.where(cond) expected = Series([np.nan, 2, np.nan]) diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index 159b29aca1e7c..89ed7975e8017 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -612,7 +612,7 @@ def run_ops(ops, get_ser, test_ser): # defined for op_str in ops: op = getattr(get_ser, op_str, None) - with tm.assertRaisesRegexp(TypeError, 'operate'): + with tm.assert_raises_regex(TypeError, 'operate'): op(test_ser) # ## timedelta64 ### @@ -1260,7 +1260,7 @@ def test_comparison_flex_basic(self): # msg = 'No axis named 1 for object type' for op in ['eq', 'ne', 'le', 'le', 'gt', 'ge']: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): getattr(left, op)(right, axis=1) def test_comparison_flex_alignment(self): @@ -1539,23 +1539,23 @@ def test_comp_ops_df_compat(self): for l, r in [(s1, s2), (s2, s1), (s3, s4), (s4, s3)]: msg = "Can only compare identically-labeled Series objects" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): l == r - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): l != r - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): l < r msg = "Can only compare identically-labeled DataFrame objects" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): l.to_frame() == r.to_frame() - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): l.to_frame() != r.to_frame() - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): l.to_frame() < r.to_frame() def test_bool_ops_df_compat(self): diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index a67d097f341db..fdc12459f8c59 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -161,10 +161,12 @@ def test_comp_series_period_scalar(self): # different base freq msg = "Input has different freq=A-DEC from Period" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): base <= Period('2011', freq='A') - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): Period('2011', freq='A') >= base def test_comp_series_period_series(self): @@ -199,7 +201,8 @@ def test_comp_series_period_series(self): # different base freq msg = "Input has different freq=A-DEC from Period" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex( + period.IncompatibleFrequency, msg): base <= s2 def test_comp_series_period_object(self): @@ -244,5 +247,5 @@ def test_align_series(self): for kind in ['inner', 'outer', 'left', 'right']: ts.align(ts[::2], join=kind) msg = "Input has different freq=D from PeriodIndex\\(freq=A-DEC\\)" - with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assert_raises_regex(period.IncompatibleFrequency, msg): ts + ts.asfreq('D', how="end") diff --git a/pandas/tests/series/test_quantile.py b/pandas/tests/series/test_quantile.py index e61297bdcce3e..6f9c65e37533d 100644 --- a/pandas/tests/series/test_quantile.py +++ b/pandas/tests/series/test_quantile.py @@ -43,7 +43,7 @@ def test_quantile(self): msg = 'percentiles should all be in the interval \\[0, 1\\]' for invalid in [-1, 2, [0.5, -1], [0.5, 2]]: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.ts.quantile(invalid) def test_quantile_multi(self): @@ -109,11 +109,11 @@ def test_quantile_interpolation_np_lt_1p9(self): # interpolation other than linear expErrMsg = "Interpolation methods other than " - with tm.assertRaisesRegexp(ValueError, expErrMsg): + with tm.assert_raises_regex(ValueError, expErrMsg): self.ts.quantile(0.9, interpolation='nearest') # object dtype - with tm.assertRaisesRegexp(ValueError, expErrMsg): + with tm.assert_raises_regex(ValueError, expErrMsg): q = Series(self.ts, dtype=object).quantile(0.7, interpolation='higher') diff --git a/pandas/tests/series/test_replace.py b/pandas/tests/series/test_replace.py index a9a9204cf7f67..ee7b264bde8bc 100644 --- a/pandas/tests/series/test_replace.py +++ b/pandas/tests/series/test_replace.py @@ -78,7 +78,7 @@ def test_replace(self): # make sure that we aren't just masking a TypeError because bools don't # implement indexing - with tm.assertRaisesRegexp(TypeError, 'Cannot compare types .+'): + with tm.assert_raises_regex(TypeError, 'Cannot compare types .+'): ser.replace([1, 2], [np.nan, 0]) ser = pd.Series([0, 1, 2, 3, 4]) @@ -186,7 +186,7 @@ def test_replace_bool_with_bool(self): def test_replace_with_dict_with_bool_keys(self): s = pd.Series([True, False, True]) - with tm.assertRaisesRegexp(TypeError, 'Cannot compare types .+'): + with tm.assert_raises_regex(TypeError, 'Cannot compare types .+'): s.replace({'asdf': 'asdb', True: 'yes'}) def test_replace2(self): diff --git a/pandas/tests/sparse/test_array.py b/pandas/tests/sparse/test_array.py index df14a3139edab..bb6ff7a0c728f 100644 --- a/pandas/tests/sparse/test_array.py +++ b/pandas/tests/sparse/test_array.py @@ -11,7 +11,7 @@ from pandas import _np_version_under1p8 from pandas.core.sparse.api import SparseArray, SparseSeries from pandas.core.sparse.libsparse import IntIndex -from pandas.util.testing import assert_almost_equal, assertRaisesRegexp +from pandas.util.testing import assert_almost_equal import pandas.util.testing as tm @@ -142,8 +142,8 @@ def test_get_item(self): self.assertEqual(self.zarr[7], 5) errmsg = re.compile("bounds") - assertRaisesRegexp(IndexError, errmsg, lambda: self.arr[11]) - assertRaisesRegexp(IndexError, errmsg, lambda: self.arr[-11]) + tm.assert_raises_regex(IndexError, errmsg, lambda: self.arr[11]) + tm.assert_raises_regex(IndexError, errmsg, lambda: self.arr[-11]) self.assertEqual(self.arr[-1], self.arr[len(self.arr) - 1]) def test_take(self): @@ -179,21 +179,22 @@ def test_take_negative(self): tm.assert_sp_array_equal(self.arr.take([-4, -3, -2]), exp) def test_bad_take(self): - assertRaisesRegexp(IndexError, "bounds", lambda: self.arr.take(11)) + tm.assert_raises_regex( + IndexError, "bounds", lambda: self.arr.take(11)) pytest.raises(IndexError, lambda: self.arr.take(-11)) def test_take_invalid_kwargs(self): msg = r"take\(\) got an unexpected keyword argument 'foo'" - tm.assertRaisesRegexp(TypeError, msg, self.arr.take, - [2, 3], foo=2) + tm.assert_raises_regex(TypeError, msg, self.arr.take, + [2, 3], foo=2) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, self.arr.take, - [2, 3], out=self.arr) + tm.assert_raises_regex(ValueError, msg, self.arr.take, + [2, 3], out=self.arr) msg = "the 'mode' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, self.arr.take, - [2, 3], mode='clip') + tm.assert_raises_regex(ValueError, msg, self.arr.take, + [2, 3], mode='clip') def test_take_filling(self): # similar tests as GH 12631 @@ -215,9 +216,9 @@ def test_take_filling(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): sparse.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): sparse.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -247,9 +248,9 @@ def test_take_filling_fill_value(self): msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): sparse.take(np.array([1, 0, -2]), fill_value=True) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): sparse.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): @@ -283,12 +284,12 @@ def setitem(): def setslice(): self.arr[1:5] = 2 - assertRaisesRegexp(TypeError, "item assignment", setitem) - assertRaisesRegexp(TypeError, "item assignment", setslice) + tm.assert_raises_regex(TypeError, "item assignment", setitem) + tm.assert_raises_regex(TypeError, "item assignment", setslice) def test_constructor_from_too_large_array(self): - assertRaisesRegexp(TypeError, "expected dimension <= 1 data", - SparseArray, np.arange(10).reshape((2, 5))) + tm.assert_raises_regex(TypeError, "expected dimension <= 1 data", + SparseArray, np.arange(10).reshape((2, 5))) def test_constructor_from_sparse(self): res = SparseArray(self.zarr) @@ -354,16 +355,16 @@ def test_astype(self): self.assertFalse((self.arr.sp_values[:3] == 27).any()) msg = "unable to coerce current fill_value nan to int64 dtype" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.arr.astype('i8') arr = SparseArray([0, np.nan, 0, 1]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): arr.astype('i8') arr = SparseArray([0, np.nan, 0, 1], fill_value=0) msg = 'Cannot convert non-finite values \\(NA or inf\\) to integer' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): arr.astype('i8') def test_astype_all(self): @@ -390,11 +391,11 @@ def test_set_fill_value(self): # coerces to int msg = "unable to set fill_value 3\\.1 to int64 dtype" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): arr.fill_value = 3.1 msg = "unable to set fill_value nan to int64 dtype" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): arr.fill_value = np.nan arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool) @@ -403,17 +404,17 @@ def test_set_fill_value(self): # coerces to bool msg = "unable to set fill_value 0 to bool dtype" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): arr.fill_value = 0 msg = "unable to set fill_value nan to bool dtype" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): arr.fill_value = np.nan # invalid msg = "fill_value must be a scalar" for val in [[1, 2, 3], np.array([1, 2]), (1, 2, 3)]: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): arr.fill_value = val def test_copy_shallow(self): @@ -682,12 +683,12 @@ def test_numpy_sum(self): self.assertEqual(out, 40.0) msg = "the 'dtype' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.sum, - SparseArray(data), dtype=np.int64) + tm.assert_raises_regex(ValueError, msg, np.sum, + SparseArray(data), dtype=np.int64) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.sum, - SparseArray(data), out=out) + tm.assert_raises_regex(ValueError, msg, np.sum, + SparseArray(data), out=out) def test_cumsum(self): non_null_data = np.array([1, 2, 3, 4, 5], dtype=float) @@ -711,7 +712,7 @@ def test_cumsum(self): axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid. msg = "axis\\(={axis}\\) out of bounds".format(axis=axis) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): SparseArray(data).cumsum(axis=axis) def test_numpy_cumsum(self): @@ -735,12 +736,12 @@ def test_numpy_cumsum(self): tm.assert_sp_array_equal(out, expected) msg = "the 'dtype' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.cumsum, - SparseArray(data), dtype=np.int64) + tm.assert_raises_regex(ValueError, msg, np.cumsum, + SparseArray(data), dtype=np.int64) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.cumsum, - SparseArray(data), out=out) + tm.assert_raises_regex(ValueError, msg, np.cumsum, + SparseArray(data), out=out) def test_mean(self): data = np.arange(10).astype(float) @@ -761,12 +762,12 @@ def test_numpy_mean(self): self.assertEqual(out, 40.0 / 9) msg = "the 'dtype' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.mean, - SparseArray(data), dtype=np.int64) + tm.assert_raises_regex(ValueError, msg, np.mean, + SparseArray(data), dtype=np.int64) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.mean, - SparseArray(data), out=out) + tm.assert_raises_regex(ValueError, msg, np.mean, + SparseArray(data), out=out) def test_ufunc(self): # GH 13853 make sure ufunc is applied to fill_value diff --git a/pandas/tests/sparse/test_frame.py b/pandas/tests/sparse/test_frame.py index cf6d80e9c0133..a5080bbd81005 100644 --- a/pandas/tests/sparse/test_frame.py +++ b/pandas/tests/sparse/test_frame.py @@ -151,10 +151,10 @@ def test_constructor_ndarray(self): level=1) # wrong length index / columns - with tm.assertRaisesRegexp(ValueError, "^Index length"): + with tm.assert_raises_regex(ValueError, "^Index length"): SparseDataFrame(self.frame.values, index=self.frame.index[:-1]) - with tm.assertRaisesRegexp(ValueError, "^Column length"): + with tm.assert_raises_regex(ValueError, "^Column length"): SparseDataFrame(self.frame.values, columns=self.frame.columns[:-1]) # GH 9272 @@ -798,8 +798,8 @@ def test_join(self): right = self.frame.loc[:, ['B', 'D']] pytest.raises(Exception, left.join, right) - with tm.assertRaisesRegexp(ValueError, - 'Other Series must have a name'): + with tm.assert_raises_regex(ValueError, + 'Other Series must have a name'): self.frame.join(Series( np.random.randn(len(self.frame)), index=self.frame.index)) @@ -1042,7 +1042,7 @@ def test_numpy_transpose(self): tm.assert_sp_frame_equal(result, sdf) msg = "the 'axes' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.transpose, sdf, axes=1) + tm.assert_raises_regex(ValueError, msg, np.transpose, sdf, axes=1) def test_combine_first(self): df = self.frame @@ -1303,12 +1303,12 @@ def test_numpy_cumsum(self): tm.assert_sp_frame_equal(result, expected) msg = "the 'dtype' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.cumsum, - self.frame, dtype=np.int64) + tm.assert_raises_regex(ValueError, msg, np.cumsum, + self.frame, dtype=np.int64) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.cumsum, - self.frame, out=result) + tm.assert_raises_regex(ValueError, msg, np.cumsum, + self.frame, out=result) def test_numpy_func_call(self): # no exception should be raised even though diff --git a/pandas/tests/sparse/test_indexing.py b/pandas/tests/sparse/test_indexing.py index cf91e41624276..bfa0a0440761f 100644 --- a/pandas/tests/sparse/test_indexing.py +++ b/pandas/tests/sparse/test_indexing.py @@ -440,7 +440,7 @@ def tests_indexing_with_sparse(self): msg = ("iLocation based boolean indexing cannot use an " "indexable as a mask") - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s.iloc[indexer] diff --git a/pandas/tests/sparse/test_libsparse.py b/pandas/tests/sparse/test_libsparse.py index 14038777fdd02..63ed11845a896 100644 --- a/pandas/tests/sparse/test_libsparse.py +++ b/pandas/tests/sparse/test_libsparse.py @@ -479,37 +479,37 @@ def test_check_integrity(self): # Too many indices than specified in self.length msg = "Too many indices" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): IntIndex(length=1, indices=[1, 2, 3]) # No index can be negative. msg = "No index can be less than zero" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): IntIndex(length=5, indices=[1, -2, 3]) # No index can be negative. msg = "No index can be less than zero" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): IntIndex(length=5, indices=[1, -2, 3]) # All indices must be less than the length. msg = "All indices must be less than the length" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): IntIndex(length=5, indices=[1, 2, 5]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): IntIndex(length=5, indices=[1, 2, 6]) # Indices must be strictly ascending. msg = "Indices must be strictly increasing" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): IntIndex(length=5, indices=[1, 3, 2]) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): IntIndex(length=5, indices=[1, 3, 3]) def test_int_internal(self): diff --git a/pandas/tests/sparse/test_series.py b/pandas/tests/sparse/test_series.py index 1502aaa7e0b9e..e0b0809c756b1 100644 --- a/pandas/tests/sparse/test_series.py +++ b/pandas/tests/sparse/test_series.py @@ -506,12 +506,12 @@ def test_numpy_take(self): np.take(sp.to_dense(), indices, axis=0)) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.take, - sp, indices, out=np.empty(sp.shape)) + tm.assert_raises_regex(ValueError, msg, np.take, + sp, indices, out=np.empty(sp.shape)) msg = "the 'mode' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.take, - sp, indices, mode='clip') + tm.assert_raises_regex(ValueError, msg, np.take, + sp, indices, mode='clip') def test_setitem(self): self.bseries[5] = 7. @@ -703,8 +703,8 @@ def _check_all(values, first, second): first_series = SparseSeries(values1, sparse_index=IntIndex(length, index1), fill_value=nan) - with tm.assertRaisesRegexp(TypeError, - 'new index must be a SparseIndex'): + with tm.assert_raises_regex(TypeError, + 'new index must be a SparseIndex'): reindexed = first_series.sparse_reindex(0) # noqa def test_repr(self): @@ -797,7 +797,7 @@ def _check_matches(indices, expected): # must have NaN fill value data = {'a': SparseSeries(np.arange(7), sparse_index=expected2, fill_value=0)} - with tm.assertRaisesRegexp(TypeError, "NaN fill value"): + with tm.assert_raises_regex(TypeError, "NaN fill value"): spf.homogenize(data) def test_fill_value_corner(self): @@ -1332,7 +1332,7 @@ def test_cumsum(self): axis = 1 # Series is 1-D, so only axis = 0 is valid. msg = "No axis named {axis}".format(axis=axis) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): self.bseries.cumsum(axis=axis) def test_numpy_cumsum(self): @@ -1345,12 +1345,12 @@ def test_numpy_cumsum(self): tm.assert_series_equal(result, expected) msg = "the 'dtype' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.cumsum, - self.bseries, dtype=np.int64) + tm.assert_raises_regex(ValueError, msg, np.cumsum, + self.bseries, dtype=np.int64) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.cumsum, - self.zbseries, out=result) + tm.assert_raises_regex(ValueError, msg, np.cumsum, + self.zbseries, out=result) def test_numpy_func_call(self): # no exception should be raised even though diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 01c18dc64f578..96628322e4ee2 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -133,15 +133,16 @@ def test_unsortable(self): pytest.raises(TypeError, algos.safe_sort, arr) def test_exceptions(self): - with tm.assertRaisesRegexp(TypeError, - "Only list-like objects are allowed"): + with tm.assert_raises_regex(TypeError, + "Only list-like objects are allowed"): algos.safe_sort(values=1) - with tm.assertRaisesRegexp(TypeError, - "Only list-like objects or None"): + with tm.assert_raises_regex(TypeError, + "Only list-like objects or None"): algos.safe_sort(values=[0, 1, 2], labels=1) - with tm.assertRaisesRegexp(ValueError, "values should be unique"): + with tm.assert_raises_regex(ValueError, + "values should be unique"): algos.safe_sort(values=[0, 1, 2, 1], labels=[0, 1]) @@ -1152,7 +1153,7 @@ def test_too_many_ndims(self): arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) msg = "Array with ndim > 2 are not supported" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): algos.rank(arr) @@ -1335,27 +1336,27 @@ def test_int64_add_overflow(): m = np.iinfo(np.int64).max n = np.iinfo(np.int64).min - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), m) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m])) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([n, n]), n) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([n, n]), np.array([n, n])) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, n]), np.array([n, n])) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), arr_mask=np.array([False, True])) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), b_mask=np.array([False, True])) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), arr_mask=np.array([False, True]), b_mask=np.array([False, True])) - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): with tm.assert_produces_warning(RuntimeWarning): algos.checked_add_with_arr(np.array([m, m]), np.array([np.nan, m])) @@ -1364,15 +1365,15 @@ def test_int64_add_overflow(): # the addition overflows. We don't check the result but just # the fact that an OverflowError is not raised. with pytest.raises(AssertionError): - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), arr_mask=np.array([True, True])) with pytest.raises(AssertionError): - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), b_mask=np.array([True, True])) with pytest.raises(AssertionError): - with tm.assertRaisesRegexp(OverflowError, msg): + with tm.assert_raises_regex(OverflowError, msg): algos.checked_add_with_arr(np.array([m, m]), np.array([m, m]), arr_mask=np.array([True, False]), b_mask=np.array([False, True])) diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index bec743fac18e1..86343e441f49a 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -47,7 +47,8 @@ class CheckImmutable(object): def check_mutable_error(self, *args, **kwargs): # Pass whatever function you normally would to assertRaisesRegexp # (after the Exception kind). - tm.assertRaisesRegexp(TypeError, self.mutable_regex, *args, **kwargs) + tm.assert_raises_regex( + TypeError, self.mutable_regex, *args, **kwargs) def test_no_mutable_funcs(self): def setitem(): @@ -831,7 +832,7 @@ def test_duplicated_drop_duplicates_index(self): result = idx.drop_duplicates(keep=False) tm.assert_index_equal(result, idx[~expected]) - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( TypeError, r"drop_duplicates\(\) got an unexpected " "keyword argument"): idx.drop_duplicates(inplace=True) @@ -995,10 +996,10 @@ def test_transpose(self): def test_transpose_non_default_axes(self): for obj in self.objs: - tm.assertRaisesRegexp(ValueError, self.errmsg, - obj.transpose, 1) - tm.assertRaisesRegexp(ValueError, self.errmsg, - obj.transpose, axes=1) + tm.assert_raises_regex(ValueError, self.errmsg, + obj.transpose, 1) + tm.assert_raises_regex(ValueError, self.errmsg, + obj.transpose, axes=1) def test_numpy_transpose(self): for obj in self.objs: @@ -1007,8 +1008,8 @@ def test_numpy_transpose(self): else: tm.assert_series_equal(np.transpose(obj), obj) - tm.assertRaisesRegexp(ValueError, self.errmsg, - np.transpose, obj, axes=1) + tm.assert_raises_regex(ValueError, self.errmsg, + np.transpose, obj, axes=1) class TestNoNewAttributesMixin(tm.TestCase): diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index d516448acd876..bbcd42b147654 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -452,10 +452,10 @@ def test_validate_ordered(self): # This should be a boolean. ordered = np.array([0, 1, 2]) - with tm.assertRaisesRegexp(exp_err, exp_msg): + with tm.assert_raises_regex(exp_err, exp_msg): Categorical([1, 2, 3], ordered=ordered) - with tm.assertRaisesRegexp(exp_err, exp_msg): + with tm.assert_raises_regex(exp_err, exp_msg): Categorical.from_codes([0, 0, 1], categories=['a', 'b', 'c'], ordered=ordered) @@ -587,16 +587,16 @@ def test_numpy_argsort(self): check_dtype=False) msg = "the 'kind' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.argsort, - c, kind='mergesort') + tm.assert_raises_regex(ValueError, msg, np.argsort, + c, kind='mergesort') msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.argsort, - c, axis=0) + tm.assert_raises_regex(ValueError, msg, np.argsort, + c, axis=0) msg = "the 'order' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.argsort, - c, order='C') + tm.assert_raises_regex(ValueError, msg, np.argsort, + c, order='C') def test_na_flags_int_categories(self): # #1457 @@ -835,9 +835,9 @@ def test_set_ordered(self): # removed in 0.19.0 msg = "can\'t set attribute" - with tm.assertRaisesRegexp(AttributeError, msg): + with tm.assert_raises_regex(AttributeError, msg): cat.ordered = True - with tm.assertRaisesRegexp(AttributeError, msg): + with tm.assert_raises_regex(AttributeError, msg): cat.ordered = False def test_set_categories(self): @@ -1955,7 +1955,7 @@ def test_series_delegations(self): # invalid accessor pytest.raises(AttributeError, lambda: Series([1, 2, 3]).cat) - tm.assertRaisesRegexp( + tm.assert_raises_regex( AttributeError, r"Can only use .cat accessor with a 'category' dtype", lambda: Series([1, 2, 3]).cat) @@ -3987,7 +3987,7 @@ def test_numpy_repeat(self): tm.assert_categorical_equal(np.repeat(cat, 2), exp) msg = "the 'axis' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.repeat, cat, 2, axis=1) + tm.assert_raises_regex(ValueError, msg, np.repeat, cat, 2, axis=1) def test_reshape(self): cat = pd.Categorical([], categories=["a", "b"]) @@ -4012,7 +4012,7 @@ def test_reshape(self): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): msg = "can only specify one unknown dimension" cat = pd.Categorical(["a", "b"], categories=["a", "b"]) - tm.assertRaisesRegexp(ValueError, msg, cat.reshape, (-2, -1)) + tm.assert_raises_regex(ValueError, msg, cat.reshape, (-2, -1)) def test_numpy_reshape(self): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): @@ -4021,8 +4021,8 @@ def test_numpy_reshape(self): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): msg = "the 'order' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.reshape, - cat, cat.shape, order='F') + tm.assert_raises_regex(ValueError, msg, np.reshape, + cat, cat.shape, order='F') def test_na_actions(self): @@ -4223,15 +4223,16 @@ def test_cat_accessor_api(self): assert isinstance(s.cat, CategoricalAccessor) invalid = Series([1]) - with tm.assertRaisesRegexp(AttributeError, "only use .cat accessor"): + with tm.assert_raises_regex(AttributeError, + "only use .cat accessor"): invalid.cat self.assertFalse(hasattr(invalid, 'cat')) def test_cat_accessor_no_new_attributes(self): # https://github.com/pandas-dev/pandas/issues/10673 c = Series(list('aabbcde')).astype('category') - with tm.assertRaisesRegexp(AttributeError, - "You cannot add any new attribute"): + with tm.assert_raises_regex(AttributeError, + "You cannot add any new attribute"): c.cat.xlabel = "a" def test_str_accessor_api_for_categorical(self): @@ -4304,8 +4305,9 @@ def test_str_accessor_api_for_categorical(self): tm.assert_series_equal(res, exp) invalid = Series([1, 2, 3]).astype('category') - with tm.assertRaisesRegexp(AttributeError, - "Can only use .str accessor with string"): + with tm.assert_raises_regex(AttributeError, + "Can only use .str " + "accessor with string"): invalid.str self.assertFalse(hasattr(invalid, 'str')) @@ -4385,7 +4387,7 @@ def test_dt_accessor_api_for_categorical(self): tm.assert_almost_equal(res, exp) invalid = Series([1, 2, 3]).astype('category') - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( AttributeError, "Can only use .dt accessor with datetimelike"): invalid.dt self.assertFalse(hasattr(invalid, 'str')) diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 435fca14d164f..d7dbaccb87ee8 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -12,7 +12,7 @@ def test_mut_exclusive(): msg = "mutually exclusive arguments: '[ab]' and '[ab]'" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): com._mut_exclusive(a=1, b=2) assert com._mut_exclusive(a=1, b=None) == 1 assert com._mut_exclusive(major=None, major_axis=None) is None diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index ddbaedc3ef919..14e08411fa106 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -390,22 +390,22 @@ def test_bool_ops_raise_on_arithmetic(self): f = getattr(operator, name) err_msg = re.escape(msg % op) - with tm.assertRaisesRegexp(NotImplementedError, err_msg): + with tm.assert_raises_regex(NotImplementedError, err_msg): f(df, df) - with tm.assertRaisesRegexp(NotImplementedError, err_msg): + with tm.assert_raises_regex(NotImplementedError, err_msg): f(df.a, df.b) - with tm.assertRaisesRegexp(NotImplementedError, err_msg): + with tm.assert_raises_regex(NotImplementedError, err_msg): f(df.a, True) - with tm.assertRaisesRegexp(NotImplementedError, err_msg): + with tm.assert_raises_regex(NotImplementedError, err_msg): f(False, df.a) - with tm.assertRaisesRegexp(TypeError, err_msg): + with tm.assert_raises_regex(TypeError, err_msg): f(False, df) - with tm.assertRaisesRegexp(TypeError, err_msg): + with tm.assert_raises_regex(TypeError, err_msg): f(df, True) def test_bool_ops_warn_on_arithmetic(self): diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index f58a6d4b146bd..61b4369d21ab4 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -1090,8 +1090,8 @@ def test_zero_step_raises(self): def test_unbounded_slice_raises(self): def assert_unbounded_slice_error(slc): - tm.assertRaisesRegexp(ValueError, "unbounded slice", - lambda: BlockPlacement(slc)) + tm.assert_raises_regex(ValueError, "unbounded slice", + lambda: BlockPlacement(slc)) assert_unbounded_slice_error(slice(None, None)) assert_unbounded_slice_error(slice(10, None)) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index e81e6e2d987c6..f350ef4351585 100755 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -320,7 +320,7 @@ def test_frame_getitem_setitem_boolean(self): np.putmask(values[:-1], values[:-1] < 0, 2) tm.assert_almost_equal(df.values, values) - with tm.assertRaisesRegexp(TypeError, 'boolean values only'): + with tm.assert_raises_regex(TypeError, 'boolean values only'): df[df * 0] = 2 def test_frame_getitem_setitem_slice(self): @@ -755,7 +755,8 @@ def _check_counts(frame, axis=0): # can't call with level on regular DataFrame df = tm.makeTimeDataFrame() - tm.assertRaisesRegexp(TypeError, 'hierarchical', df.count, level=0) + tm.assert_raises_regex( + TypeError, 'hierarchical', df.count, level=0) self.frame['D'] = 'foo' result = self.frame.count(level=0, numeric_only=True) @@ -792,9 +793,10 @@ def test_count_level_corner(self): tm.assert_frame_equal(result, expected) def test_get_level_number_out_of_bounds(self): - with tm.assertRaisesRegexp(IndexError, "Too many levels"): + with tm.assert_raises_regex(IndexError, "Too many levels"): self.frame.index._get_level_number(2) - with tm.assertRaisesRegexp(IndexError, "not a valid level number"): + with tm.assert_raises_regex(IndexError, + "not a valid level number"): self.frame.index._get_level_number(-3) def test_unstack(self): @@ -1011,16 +1013,17 @@ def test_stack_names_and_numbers(self): unstacked = self.ymd.unstack(['year', 'month']) # Can't use mixture of names and numbers to stack - with tm.assertRaisesRegexp(ValueError, "level should contain"): + with tm.assert_raises_regex(ValueError, "level should contain"): unstacked.stack([0, 'month']) def test_stack_multiple_out_of_bounds(self): # nlevels == 3 unstacked = self.ymd.unstack(['year', 'month']) - with tm.assertRaisesRegexp(IndexError, "Too many levels"): + with tm.assert_raises_regex(IndexError, "Too many levels"): unstacked.stack([2, 3]) - with tm.assertRaisesRegexp(IndexError, "not a valid level number"): + with tm.assert_raises_regex(IndexError, + "not a valid level number"): unstacked.stack([-4, -3]) def test_unstack_period_series(self): @@ -1275,10 +1278,10 @@ def test_reorder_levels(self): expected = self.ymd.T.swaplevel(0, 1, axis=1).swaplevel(1, 2, axis=1) tm.assert_frame_equal(result, expected) - with tm.assertRaisesRegexp(TypeError, 'hierarchical axis'): + with tm.assert_raises_regex(TypeError, 'hierarchical axis'): self.ymd.reorder_levels([1, 2], axis=1) - with tm.assertRaisesRegexp(IndexError, 'Too many levels'): + with tm.assert_raises_regex(IndexError, 'Too many levels'): self.ymd.index.reorder_levels([1, 2, 3]) def test_insert_index(self): @@ -2244,11 +2247,10 @@ def test_reset_index_multiindex_columns(self): result = df[['B']].reset_index() tm.assert_frame_equal(result, expected) - # GH 16120 - # already existing column - with tm.assertRaisesRegexp(ValueError, - ("cannot insert \('A', ''\), " - "already exists")): + # gh-16120: already existing column + with tm.assert_raises_regex(ValueError, + ("cannot insert \('A', ''\), " + "already exists")): df.reset_index() def test_set_index_period(self): diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 17bc06b5ee9c7..322ea32a93562 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -23,9 +23,8 @@ from pandas.tseries.offsets import BDay, MonthEnd from pandas.util.testing import (assert_panel_equal, assert_frame_equal, assert_series_equal, assert_almost_equal, - ensure_clean, assertRaisesRegexp, - makeCustomDataframe as mkdf, - makeMixedDataFrame) + ensure_clean, makeMixedDataFrame, + makeCustomDataframe as mkdf) import pandas.core.panel as panelm import pandas.util.testing as tm @@ -180,8 +179,8 @@ def wrapper(x): # Unimplemented numeric_only parameter. if 'numeric_only' in signature(f).args: - tm.assertRaisesRegexp(NotImplementedError, name, f, - numeric_only=True) + tm.assert_raises_regex(NotImplementedError, name, f, + numeric_only=True) class SafeForSparse(object): @@ -227,10 +226,10 @@ def test_get_axis_number(self): self.assertEqual(self.panel._get_axis_number('major'), 1) self.assertEqual(self.panel._get_axis_number('minor'), 2) - with tm.assertRaisesRegexp(ValueError, "No axis named foo"): + with tm.assert_raises_regex(ValueError, "No axis named foo"): self.panel._get_axis_number('foo') - with tm.assertRaisesRegexp(ValueError, "No axis named foo"): + with tm.assert_raises_regex(ValueError, "No axis named foo"): self.panel.__ge__(self.panel, axis='foo') def test_get_axis_name(self): @@ -514,9 +513,10 @@ def test_setitem(self): # bad shape p = Panel(np.random.randn(4, 3, 2)) - with tm.assertRaisesRegexp(ValueError, - r"shape of value must be \(3, 2\), " - r"shape of given object was \(4, 2\)"): + with tm.assert_raises_regex(ValueError, + r"shape of value must be " + r"\(3, 2\), shape of given " + r"object was \(4, 2\)"): p[0] = np.random.randn(4, 2) def test_setitem_ndarray(self): @@ -874,8 +874,9 @@ def test_get_value(self): result = self.panel.get_value(item, mjr, mnr) expected = self.panel[item][mnr][mjr] assert_almost_equal(result, expected) - with tm.assertRaisesRegexp(TypeError, - "There must be an argument for each axis"): + with tm.assert_raises_regex(TypeError, + "There must be an argument " + "for each axis"): self.panel.get_value('a') def test_set_value(self): @@ -897,7 +898,7 @@ def test_set_value(self): msg = ("There must be an argument for each " "axis plus the value provided") - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): self.panel.set_value('a') @@ -1041,7 +1042,7 @@ def _check_dtype(panel, dtype): def test_constructor_fails_with_not_3d_input(self): with catch_warnings(record=True): - with tm.assertRaisesRegexp(ValueError, "The number of dimensions required is 3"): # noqa + with tm.assert_raises_regex(ValueError, "The number of dimensions required is 3"): # noqa Panel(np.random.randn(10, 2)) def test_consolidate(self): @@ -1181,28 +1182,31 @@ def testit(): Panel(np.random.randn(3, 4, 5), lrange(4), lrange(5), lrange(5)) - assertRaisesRegexp(ValueError, - r"Shape of passed values is \(3, 4, 5\), " - r"indices imply \(4, 5, 5\)", - testit) + tm.assert_raises_regex(ValueError, + r"Shape of passed values is " + r"\(3, 4, 5\), indices imply " + r"\(4, 5, 5\)", + testit) def testit(): Panel(np.random.randn(3, 4, 5), lrange(5), lrange(4), lrange(5)) - assertRaisesRegexp(ValueError, - r"Shape of passed values is \(3, 4, 5\), " - r"indices imply \(5, 4, 5\)", - testit) + tm.assert_raises_regex(ValueError, + r"Shape of passed values is " + r"\(3, 4, 5\), indices imply " + r"\(5, 4, 5\)", + testit) def testit(): Panel(np.random.randn(3, 4, 5), lrange(5), lrange(5), lrange(4)) - assertRaisesRegexp(ValueError, - r"Shape of passed values is \(3, 4, 5\), " - r"indices imply \(5, 5, 4\)", - testit) + tm.assert_raises_regex(ValueError, + r"Shape of passed values is " + r"\(3, 4, 5\), indices imply " + r"\(5, 5, 4\)", + testit) def test_conform(self): with catch_warnings(record=True): @@ -1660,12 +1664,12 @@ def test_transpose(self): assert_panel_equal(result, expected) # duplicate axes - with tm.assertRaisesRegexp(TypeError, - 'not enough/duplicate arguments'): + with tm.assert_raises_regex(TypeError, + 'not enough/duplicate arguments'): self.panel.transpose('minor', maj='major', minor='items') - with tm.assertRaisesRegexp(ValueError, - 'repeated axis in transpose'): + with tm.assert_raises_regex(ValueError, + 'repeated axis in transpose'): self.panel.transpose('minor', 'major', major='minor', minor='items') @@ -1867,7 +1871,7 @@ def test_to_panel_duplicates(self): with catch_warnings(record=True): df = DataFrame({'a': [0, 0, 1], 'b': [1, 1, 1], 'c': [1, 2, 3]}) idf = df.set_index(['a', 'b']) - assertRaisesRegexp( + tm.assert_raises_regex( ValueError, 'non-uniquely indexed', idf.to_panel) def test_panel_dups(self): @@ -1992,8 +1996,8 @@ def test_tshift(self): shifted3 = ps.tshift(freq=BDay()) assert_panel_equal(shifted, shifted3) - assertRaisesRegexp(ValueError, 'does not match', - ps.tshift, freq='M') + tm.assert_raises_regex(ValueError, 'does not match', + ps.tshift, freq='M') # DatetimeIndex panel = make_test_panel() @@ -2108,7 +2112,7 @@ def test_numpy_round(self): assert_panel_equal(expected, result) msg = "the 'out' parameter is not supported" - tm.assertRaisesRegexp(ValueError, msg, np.round, p, out=p) + tm.assert_raises_regex(ValueError, msg, np.round, p, out=p) def test_multiindex_get(self): with catch_warnings(record=True): @@ -2540,8 +2544,8 @@ def test_to_string(self): def test_to_sparse(self): if isinstance(self.panel, Panel): msg = 'sparsifying is not supported' - tm.assertRaisesRegexp(NotImplementedError, msg, - self.panel.to_sparse) + tm.assert_raises_regex(NotImplementedError, msg, + self.panel.to_sparse) def test_truncate(self): with catch_warnings(record=True): diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index e5795eea12135..f5309a985a499 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -272,7 +272,7 @@ def test_select_bad_cols(self): pytest.raises(KeyError, g.__getitem__, ['D']) pytest.raises(KeyError, g.__getitem__, ['A', 'D']) - with tm.assertRaisesRegexp(KeyError, '^[^A]+$'): + with tm.assert_raises_regex(KeyError, '^[^A]+$'): # A should not be referenced as a bad column... # will have to rethink regex if you change message! g[['A', 'D']] @@ -983,11 +983,11 @@ def test_numpy_compat(self): for func in ('min', 'max', 'sum', 'prod', 'mean', 'var', 'std'): - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(r, func), - func, 1, 2, 3) - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(r, func), axis=1) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(r, func), + func, 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(r, func), axis=1) def test_resample_how_callables(self): # GH 7929 @@ -3081,17 +3081,18 @@ def test_fails_on_no_datetime_index(self): for name, func in zip(index_names, index_funcs): index = func(n) df = DataFrame({'a': np.random.randn(n)}, index=index) - with tm.assertRaisesRegexp(TypeError, - "Only valid with DatetimeIndex, " - "TimedeltaIndex or PeriodIndex, " - "but got an instance of %r" % name): + with tm.assert_raises_regex(TypeError, + "Only valid with " + "DatetimeIndex, TimedeltaIndex " + "or PeriodIndex, but got an " + "instance of %r" % name): df.groupby(TimeGrouper('D')) # PeriodIndex gives a specific error message df = DataFrame({'a': np.random.randn(n)}, index=tm.makePeriodIndex(n)) - with tm.assertRaisesRegexp(TypeError, - "axis must be a DatetimeIndex, but " - "got an instance of 'PeriodIndex'"): + with tm.assert_raises_regex(TypeError, + "axis must be a DatetimeIndex, but " + "got an instance of 'PeriodIndex'"): df.groupby(TimeGrouper('D')) def test_aaa_group_order(self): diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 6733fbdc3b9c6..db0c2fdc80fd2 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -29,7 +29,8 @@ def test_api(self): # GH 9184 invalid = Series([1]) - with tm.assertRaisesRegexp(AttributeError, "only use .str accessor"): + with tm.assert_raises_regex(AttributeError, + "only use .str accessor"): invalid.str self.assertFalse(hasattr(invalid, 'str')) @@ -451,15 +452,15 @@ def test_replace_callable(self): r'(?(3)required )positional arguments?') repl = lambda: None - with tm.assertRaisesRegexp(TypeError, p_err): + with tm.assert_raises_regex(TypeError, p_err): values.str.replace('a', repl) repl = lambda m, x: None - with tm.assertRaisesRegexp(TypeError, p_err): + with tm.assert_raises_regex(TypeError, p_err): values.str.replace('a', repl) repl = lambda m, x, y=None: None - with tm.assertRaisesRegexp(TypeError, p_err): + with tm.assert_raises_regex(TypeError, p_err): values.str.replace('a', repl) # test regex named groups @@ -512,13 +513,16 @@ def test_replace_compiled_regex(self): values = Series(['fooBAD__barBAD__bad', NA]) pat = re.compile(r'BAD[_]*') - with tm.assertRaisesRegexp(ValueError, "case and flags cannot be"): + with tm.assert_raises_regex(ValueError, + "case and flags cannot be"): result = values.str.replace(pat, '', flags=re.IGNORECASE) - with tm.assertRaisesRegexp(ValueError, "case and flags cannot be"): + with tm.assert_raises_regex(ValueError, + "case and flags cannot be"): result = values.str.replace(pat, '', case=False) - with tm.assertRaisesRegexp(ValueError, "case and flags cannot be"): + with tm.assert_raises_regex(ValueError, + "case and flags cannot be"): result = values.str.replace(pat, '', case=True) # test with callable @@ -648,7 +652,7 @@ def test_extract_expand_False(self): # Index only works with one regex group since # multi-group would expand to a frame idx = Index(['A1', 'A2', 'A3', 'A4', 'B5']) - with tm.assertRaisesRegexp(ValueError, "supported"): + with tm.assert_raises_regex(ValueError, "supported"): idx.str.extract('([AB])([123])', expand=False) # these should work for both Series and Index @@ -1124,7 +1128,7 @@ def test_extractall_errors(self): # no capture groups. (it returns DataFrame with one column for # each capture group) s = Series(['a3', 'b3', 'd4c2'], name='series_name') - with tm.assertRaisesRegexp(ValueError, "no capture groups"): + with tm.assert_raises_regex(ValueError, "no capture groups"): s.str.extractall(r'[a-z]') def test_extract_index_one_two_groups(self): @@ -1504,12 +1508,12 @@ def test_find(self): dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) - with tm.assertRaisesRegexp(TypeError, - "expected a string object, not int"): + with tm.assert_raises_regex(TypeError, + "expected a string object, not int"): result = values.str.find(0) - with tm.assertRaisesRegexp(TypeError, - "expected a string object, not int"): + with tm.assert_raises_regex(TypeError, + "expected a string object, not int"): result = values.str.rfind(0) def test_find_nan(self): @@ -1579,11 +1583,13 @@ def _check(result, expected): dtype=np.int64) tm.assert_numpy_array_equal(result.values, expected) - with tm.assertRaisesRegexp(ValueError, "substring not found"): + with tm.assert_raises_regex(ValueError, + "substring not found"): result = s.str.index('DE') - with tm.assertRaisesRegexp(TypeError, - "expected a string object, not int"): + with tm.assert_raises_regex(TypeError, + "expected a string " + "object, not int"): result = s.str.index(0) # test with nan @@ -1667,12 +1673,14 @@ def test_pad_fillchar(self): exp = Series(['XXaXX', 'XXbXX', NA, 'XXcXX', NA, 'eeeeee']) tm.assert_almost_equal(result, exp) - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not str"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not str"): result = values.str.pad(5, fillchar='XY') - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not int"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not int"): result = values.str.pad(5, fillchar=5) def test_pad_width(self): @@ -1680,8 +1688,9 @@ def test_pad_width(self): s = Series(['1', '22', 'a', 'bb']) for f in ['center', 'ljust', 'rjust', 'zfill', 'pad']: - with tm.assertRaisesRegexp(TypeError, - "width must be of integer type, not*"): + with tm.assert_raises_regex(TypeError, + "width must be of " + "integer type, not*"): getattr(s.str, f)('f') def test_translate(self): @@ -1713,7 +1722,7 @@ def _check(result, expected): expected = klass(['abcde', 'abcc', 'cddd', 'cde']) _check(result, expected) else: - with tm.assertRaisesRegexp( + with tm.assert_raises_regex( ValueError, "deletechars is not a valid argument"): result = s.str.translate(table, deletechars='fg') @@ -1802,28 +1811,34 @@ def test_center_ljust_rjust_fillchar(self): # If fillchar is not a charatter, normal str raises TypeError # 'aaa'.ljust(5, 'XY') # TypeError: must be char, not str - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not str"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not str"): result = values.str.center(5, fillchar='XY') - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not str"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not str"): result = values.str.ljust(5, fillchar='XY') - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not str"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not str"): result = values.str.rjust(5, fillchar='XY') - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not int"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not int"): result = values.str.center(5, fillchar=1) - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not int"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not int"): result = values.str.ljust(5, fillchar=1) - with tm.assertRaisesRegexp(TypeError, - "fillchar must be a character, not int"): + with tm.assert_raises_regex(TypeError, + "fillchar must be a " + "character, not int"): result = values.str.rjust(5, fillchar=1) def test_zfill(self): @@ -2005,7 +2020,7 @@ def test_split_to_dataframe(self): index=['preserve', 'me']) tm.assert_frame_equal(result, exp) - with tm.assertRaisesRegexp(ValueError, "expand must be"): + with tm.assert_raises_regex(ValueError, "expand must be"): s.str.split('_', expand="not_a_boolean") def test_split_to_multiindex_expand(self): @@ -2030,7 +2045,7 @@ def test_split_to_multiindex_expand(self): tm.assert_index_equal(result, exp) self.assertEqual(result.nlevels, 6) - with tm.assertRaisesRegexp(ValueError, "expand must be"): + with tm.assert_raises_regex(ValueError, "expand must be"): idx.str.split('_', expand="not_a_boolean") def test_rsplit_to_dataframe_expand(self): @@ -2651,7 +2666,8 @@ def test_normalize(self): result = s.str.normalize('NFC') tm.assert_series_equal(result, expected) - with tm.assertRaisesRegexp(ValueError, "invalid normalization form"): + with tm.assert_raises_regex(ValueError, + "invalid normalization form"): s.str.normalize('xxx') s = Index([u'ABC', u'123', u'アイエ']) @@ -2680,9 +2696,9 @@ def test_str_cat_raises_intuitive_error(self): # https://github.com/pandas-dev/pandas/issues/11334 s = Series(['a', 'b', 'c', 'd']) message = "Did you mean to supply a `sep` keyword?" - with tm.assertRaisesRegexp(ValueError, message): + with tm.assert_raises_regex(ValueError, message): s.str.cat('|') - with tm.assertRaisesRegexp(ValueError, message): + with tm.assert_raises_regex(ValueError, message): s.str.cat(' ') def test_index_str_accessor_visibility(self): @@ -2720,9 +2736,9 @@ def test_index_str_accessor_visibility(self): for values, tp in cases: idx = Index(values) message = 'Can only use .str accessor with string values' - with tm.assertRaisesRegexp(AttributeError, message): + with tm.assert_raises_regex(AttributeError, message): Series(values).str - with tm.assertRaisesRegexp(AttributeError, message): + with tm.assert_raises_regex(AttributeError, message): idx.str self.assertEqual(idx.inferred_type, tp) @@ -2730,14 +2746,14 @@ def test_index_str_accessor_visibility(self): idx = MultiIndex.from_tuples([('a', 'b'), ('a', 'b')]) self.assertEqual(idx.inferred_type, 'mixed') message = 'Can only use .str accessor with Index, not MultiIndex' - with tm.assertRaisesRegexp(AttributeError, message): + with tm.assert_raises_regex(AttributeError, message): idx.str def test_str_accessor_no_new_attributes(self): # https://github.com/pandas-dev/pandas/issues/10673 s = Series(list('aabbcde')) - with tm.assertRaisesRegexp(AttributeError, - "You cannot add any new attribute"): + with tm.assert_raises_regex(AttributeError, + "You cannot add any new attribute"): s.str.xlabel = "a" def test_method_on_bytes(self): diff --git a/pandas/tests/test_take.py b/pandas/tests/test_take.py index 4d60750fb4a20..9fb61998f6c54 100644 --- a/pandas/tests/test_take.py +++ b/pandas/tests/test_take.py @@ -32,7 +32,7 @@ def _test_dtype(dtype, can_hold_na, writeable=True): expected[3] = np.nan tm.assert_almost_equal(out, expected) else: - with tm.assertRaisesRegexp(TypeError, self.fill_error): + with tm.assert_raises_regex(TypeError, self.fill_error): algos.take_1d(data, indexer, out=out) # no exception o/w data.take(indexer, out=out) @@ -123,7 +123,8 @@ def _test_dtype(dtype, can_hold_na, writeable=True): tm.assert_almost_equal(out1, expected1) else: for i, out in enumerate([out0, out1]): - with tm.assertRaisesRegexp(TypeError, self.fill_error): + with tm.assert_raises_regex(TypeError, + self.fill_error): algos.take_nd(data, indexer, out=out, axis=i) # no exception o/w data.take(indexer, out=out, axis=i) @@ -235,7 +236,8 @@ def _test_dtype(dtype, can_hold_na): tm.assert_almost_equal(out2, expected2) else: for i, out in enumerate([out0, out1, out2]): - with tm.assertRaisesRegexp(TypeError, self.fill_error): + with tm.assert_raises_regex(TypeError, + self.fill_error): algos.take_nd(data, indexer, out=out, axis=i) # no exception o/w data.take(indexer, out=out, axis=i) diff --git a/pandas/tests/test_testing.py b/pandas/tests/test_testing.py index 4a9e4f4fbd37a..45994fd400912 100644 --- a/pandas/tests/test_testing.py +++ b/pandas/tests/test_testing.py @@ -6,10 +6,9 @@ import sys from pandas import Series, DataFrame import pandas.util.testing as tm -from pandas.util.testing import (assert_almost_equal, assertRaisesRegexp, - raise_with_traceback, assert_index_equal, - assert_series_equal, assert_frame_equal, - assert_numpy_array_equal, +from pandas.util.testing import (assert_almost_equal, raise_with_traceback, + assert_index_equal, assert_series_equal, + assert_frame_equal, assert_numpy_array_equal, RNGContext) from pandas.compat import is_platform_windows @@ -144,13 +143,13 @@ def test_assert_almost_equal_object(self): class TestUtilTesting(tm.TestCase): def test_raise_with_traceback(self): - with assertRaisesRegexp(LookupError, "error_text"): + with tm.assert_raises_regex(LookupError, "error_text"): try: raise ValueError("THIS IS AN ERROR") except ValueError as e: e = LookupError("error_text") raise_with_traceback(e) - with assertRaisesRegexp(LookupError, "error_text"): + with tm.assert_raises_regex(LookupError, "error_text"): try: raise ValueError("This is another error") except ValueError: @@ -173,18 +172,18 @@ def test_numpy_array_equal_message(self): \\[left\\]: \\(2,\\) \\[right\\]: \\(3,\\)""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5])) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(np.array([1, 2]), np.array([3, 4, 5])) # scalar comparison expected = """Expected type """ - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(1, 2) expected = """expected 2\\.00000 but got 1\\.00000, with decimal 5""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(1, 2) # array / scalar array comparison @@ -194,10 +193,10 @@ def test_numpy_array_equal_message(self): \\[left\\]: ndarray \\[right\\]: int""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): # numpy_array_equal only accepts np.ndarray assert_numpy_array_equal(np.array([1]), 1) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(np.array([1]), 1) # scalar / array comparison @@ -207,9 +206,9 @@ def test_numpy_array_equal_message(self): \\[left\\]: int \\[right\\]: ndarray""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(1, np.array([1])) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(1, np.array([1])) expected = """numpy array are different @@ -218,10 +217,10 @@ def test_numpy_array_equal_message(self): \\[left\\]: \\[nan, 2\\.0, 3\\.0\\] \\[right\\]: \\[1\\.0, nan, 3\\.0\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(np.array([np.nan, 2, 3]), np.array([1, np.nan, 3])) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(np.array([np.nan, 2, 3]), np.array([1, np.nan, 3])) @@ -231,9 +230,9 @@ def test_numpy_array_equal_message(self): \\[left\\]: \\[1, 2\\] \\[right\\]: \\[1, 3\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(np.array([1, 2]), np.array([1, 3])) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(np.array([1, 2]), np.array([1, 3])) expected = """numpy array are different @@ -242,7 +241,7 @@ def test_numpy_array_equal_message(self): \\[left\\]: \\[1\\.1, 2\\.000001\\] \\[right\\]: \\[1\\.1, 2.0\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal( np.array([1.1, 2.000001]), np.array([1.1, 2.0])) @@ -255,10 +254,10 @@ def test_numpy_array_equal_message(self): \\[left\\]: \\[\\[1, 2\\], \\[3, 4\\], \\[5, 6\\]\\] \\[right\\]: \\[\\[1, 3\\], \\[3, 4\\], \\[5, 6\\]\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(np.array([[1, 2], [3, 4], [5, 6]]), np.array([[1, 3], [3, 4], [5, 6]])) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(np.array([[1, 2], [3, 4], [5, 6]]), np.array([[1, 3], [3, 4], [5, 6]])) @@ -268,10 +267,10 @@ def test_numpy_array_equal_message(self): \\[left\\]: \\[\\[1, 2\\], \\[3, 4\\]\\] \\[right\\]: \\[\\[1, 3\\], \\[3, 4\\]\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(np.array([[1, 2], [3, 4]]), np.array([[1, 3], [3, 4]])) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(np.array([[1, 2], [3, 4]]), np.array([[1, 3], [3, 4]])) @@ -282,10 +281,10 @@ def test_numpy_array_equal_message(self): \\[left\\]: \\(2,\\) \\[right\\]: \\(3,\\)""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5]), obj='Index') - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(np.array([1, 2]), np.array([3, 4, 5]), obj='Index') @@ -304,9 +303,9 @@ def test_numpy_array_equal_object_message(self): \\[left\\]: \\[2011-01-01 00:00:00, 2011-01-01 00:00:00\\] \\[right\\]: \\[2011-01-01 00:00:00, 2011-01-02 00:00:00\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(a, b) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal(a, b) def test_numpy_array_equal_copy_flag(self): @@ -314,10 +313,10 @@ def test_numpy_array_equal_copy_flag(self): b = a.copy() c = a.view() expected = r'array\(\[1, 2, 3\]\) is not array\(\[1, 2, 3\]\)' - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(a, b, check_same='same') expected = r'array\(\[1, 2, 3\]\) is array\(\[1, 2, 3\]\)' - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_numpy_array_equal(a, c, check_same='copy') def test_assert_almost_equal_iterable_message(self): @@ -328,7 +327,7 @@ def test_assert_almost_equal_iterable_message(self): \\[left\\]: 2 \\[right\\]: 3""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal([1, 2], [3, 4, 5]) expected = """Iterable are different @@ -337,7 +336,7 @@ def test_assert_almost_equal_iterable_message(self): \\[left\\]: \\[1, 2\\] \\[right\\]: \\[1, 3\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_almost_equal([1, 2], [1, 3]) @@ -355,7 +354,7 @@ def test_index_equal_message(self): idx1 = pd.Index([1, 2, 3]) idx2 = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 3), ('B', 4)]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, exact=False) expected = """MultiIndex level \\[1\\] are different @@ -368,9 +367,9 @@ def test_index_equal_message(self): ('B', 3), ('B', 4)]) idx2 = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 3), ('B', 4)]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, check_exact=False) expected = """Index are different @@ -381,9 +380,9 @@ def test_index_equal_message(self): idx1 = pd.Index([1, 2, 3]) idx2 = pd.Index([1, 2, 3, 4]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, check_exact=False) expected = """Index are different @@ -394,9 +393,9 @@ def test_index_equal_message(self): idx1 = pd.Index([1, 2, 3]) idx2 = pd.Index([1, 2, 3.0]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, exact=True) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, exact=True, check_exact=False) expected = """Index are different @@ -407,7 +406,7 @@ def test_index_equal_message(self): idx1 = pd.Index([1, 2, 3.]) idx2 = pd.Index([1, 2, 3.0000000001]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) # must success @@ -421,9 +420,9 @@ def test_index_equal_message(self): idx1 = pd.Index([1, 2, 3.]) idx2 = pd.Index([1, 2, 3.0001]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, check_exact=False) # must success assert_index_equal(idx1, idx2, check_exact=False, @@ -437,9 +436,9 @@ def test_index_equal_message(self): idx1 = pd.Index([1, 2, 3]) idx2 = pd.Index([1, 2, 4]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, check_less_precise=True) expected = """MultiIndex level \\[1\\] are different @@ -452,9 +451,9 @@ def test_index_equal_message(self): ('B', 3), ('B', 4)]) idx2 = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 3), ('B', 4)]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2, check_exact=False) def test_index_equal_metadata_message(self): @@ -467,7 +466,7 @@ def test_index_equal_metadata_message(self): idx1 = pd.Index([1, 2, 3]) idx2 = pd.Index([1, 2, 3], name='x') - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) # same name, should pass @@ -484,7 +483,7 @@ def test_index_equal_metadata_message(self): idx1 = pd.Index([1, 2, 3], name=np.nan) idx2 = pd.Index([1, 2, 3], name=pd.NaT) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) @@ -566,7 +565,7 @@ def test_series_equal_message(self): \\[left\\]: 3, RangeIndex\\(start=0, stop=3, step=1\\) \\[right\\]: 4, RangeIndex\\(start=0, stop=4, step=1\\)""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_series_equal(pd.Series([1, 2, 3]), pd.Series([1, 2, 3, 4])) expected = """Series are different @@ -575,9 +574,9 @@ def test_series_equal_message(self): \\[left\\]: \\[1, 2, 3\\] \\[right\\]: \\[1, 2, 4\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_series_equal(pd.Series([1, 2, 3]), pd.Series([1, 2, 4])) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_series_equal(pd.Series([1, 2, 3]), pd.Series([1, 2, 4]), check_less_precise=True) @@ -637,7 +636,7 @@ def test_frame_equal_message(self): \\[left\\]: \\(3, 2\\) \\[right\\]: \\(3, 1\\)""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}), pd.DataFrame({'A': [1, 2, 3]})) @@ -647,7 +646,7 @@ def test_frame_equal_message(self): \\[left\\]: Index\\(\\[u?'a', u?'b', u?'c'\\], dtype='object'\\) \\[right\\]: Index\\(\\[u?'a', u?'b', u?'d'\\], dtype='object'\\)""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']), pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, @@ -659,7 +658,7 @@ def test_frame_equal_message(self): \\[left\\]: Index\\(\\[u?'A', u?'B'\\], dtype='object'\\) \\[right\\]: Index\\(\\[u?'A', u?'b'\\], dtype='object'\\)""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']), pd.DataFrame({'A': [1, 2, 3], 'b': [4, 5, 6]}, @@ -671,11 +670,11 @@ def test_frame_equal_message(self): \\[left\\]: \\[4, 5, 6\\] \\[right\\]: \\[4, 5, 7\\]""" - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}), pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 7]})) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): assert_frame_equal(pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}), pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 7]}), by_blocks=True) @@ -693,7 +692,7 @@ def test_categorical_equal_message(self): a = pd.Categorical([1, 2, 3, 4]) b = pd.Categorical([1, 2, 3, 5]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): tm.assert_categorical_equal(a, b) expected = """Categorical\\.codes are different @@ -704,7 +703,7 @@ def test_categorical_equal_message(self): a = pd.Categorical([1, 2, 4, 3], categories=[1, 2, 3, 4]) b = pd.Categorical([1, 2, 3, 4], categories=[1, 2, 3, 4]) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): tm.assert_categorical_equal(a, b) expected = """Categorical are different @@ -715,7 +714,7 @@ def test_categorical_equal_message(self): a = pd.Categorical([1, 2, 3, 4], ordered=False) b = pd.Categorical([1, 2, 3, 4], ordered=True) - with assertRaisesRegexp(AssertionError, expected): + with tm.assert_raises_regex(AssertionError, expected): tm.assert_categorical_equal(a, b) diff --git a/pandas/tests/test_util.py b/pandas/tests/test_util.py index 375463ec25c36..6581e7688a32f 100644 --- a/pandas/tests/test_util.py +++ b/pandas/tests/test_util.py @@ -93,7 +93,7 @@ class TestValidateArgs(tm.TestCase): def test_bad_min_fname_arg_count(self): msg = "'max_fname_arg_count' must be non-negative" - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): validate_args(self.fname, (None,), -1, 'foo') def test_bad_arg_length_max_value_single(self): @@ -108,7 +108,7 @@ def test_bad_arg_length_max_value_single(self): .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): validate_args(self.fname, args, min_fname_arg_count, compat_args) @@ -125,7 +125,7 @@ def test_bad_arg_length_max_value_multiple(self): .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): validate_args(self.fname, args, min_fname_arg_count, compat_args) @@ -144,7 +144,7 @@ def test_not_all_defaults(self): arg_vals = (1, -1, 3) for i in range(1, 3): - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): validate_args(self.fname, arg_vals[:i], 2, compat_args) def test_validation(self): @@ -173,7 +173,7 @@ def test_bad_kwarg(self): r"keyword argument '{arg}'".format( fname=self.fname, arg=badarg)) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): validate_kwargs(self.fname, kwargs, compat_args) def test_not_all_none(self): @@ -194,7 +194,7 @@ def test_not_all_none(self): kwargs = dict(zip(kwarg_keys[:i], kwarg_vals[:i])) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): validate_kwargs(self.fname, kwargs, compat_args) def test_validation(self): @@ -213,10 +213,11 @@ def test_validate_bool_kwarg(self): for name in arg_names: for value in invalid_values: - with tm.assertRaisesRegexp(ValueError, - ("For argument \"%s\" expected " - "type bool, received type %s") % - (name, type(value).__name__)): + with tm.assert_raises_regex(ValueError, + "For argument \"%s\" " + "expected type bool, " + "received type %s" % + (name, type(value).__name__)): validate_bool_kwarg(value, name) for value in valid_values: @@ -239,7 +240,7 @@ def test_invalid_total_length_max_length_one(self): .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): validate_args_and_kwargs(self.fname, args, kwargs, min_fname_arg_count, compat_args) @@ -257,7 +258,7 @@ def test_invalid_total_length_max_length_multiple(self): .format(fname=self.fname, max_length=max_length, actual_length=actual_length)) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): validate_args_and_kwargs(self.fname, args, kwargs, min_fname_arg_count, compat_args) @@ -276,17 +277,17 @@ def test_no_args_with_kwargs(self): args = () kwargs = {'foo': -5, bad_arg: 2} - tm.assertRaisesRegexp(ValueError, msg, - validate_args_and_kwargs, - self.fname, args, kwargs, - min_fname_arg_count, compat_args) + tm.assert_raises_regex(ValueError, msg, + validate_args_and_kwargs, + self.fname, args, kwargs, + min_fname_arg_count, compat_args) args = (-5, 2) kwargs = {} - tm.assertRaisesRegexp(ValueError, msg, - validate_args_and_kwargs, - self.fname, args, kwargs, - min_fname_arg_count, compat_args) + tm.assert_raises_regex(ValueError, msg, + validate_args_and_kwargs, + self.fname, args, kwargs, + min_fname_arg_count, compat_args) def test_duplicate_argument(self): min_fname_arg_count = 2 @@ -300,7 +301,7 @@ def test_duplicate_argument(self): msg = (r"{fname}\(\) got multiple values for keyword " r"argument '{arg}'".format(fname=self.fname, arg='foo')) - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): validate_args_and_kwargs(self.fname, args, kwargs, min_fname_arg_count, compat_args) @@ -327,7 +328,7 @@ def test_cannot_create_instance_of_stolenbuffer(self): ``move_into_mutable_buffer`` which has a bunch of checks in it. """ msg = "cannot create 'pandas.util._move.stolenbuf' instances" - with tm.assertRaisesRegexp(TypeError, msg): + with tm.assert_raises_regex(TypeError, msg): stolenbuf() def test_more_than_one_ref(self): diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index aea2525a3a1f9..adfecc90129e9 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -74,7 +74,7 @@ def test_select_bad_cols(self): pytest.raises(KeyError, g.__getitem__, ['C']) # g[['C']] pytest.raises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']] - with tm.assertRaisesRegexp(KeyError, '^[^A]+$'): + with tm.assert_raises_regex(KeyError, '^[^A]+$'): # A should not be referenced as a bad column... # will have to rethink regex if you change message! g[['A', 'C']] @@ -352,10 +352,10 @@ def test_numpy_compat(self): msg = "numpy operations are not valid with window objects" for func in ('sum', 'mean'): - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(w, func), 1, 2, 3) - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(w, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(w, func), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(w, func), dtype=np.float64) class TestRolling(Base): @@ -430,10 +430,10 @@ def test_numpy_compat(self): msg = "numpy operations are not valid with window objects" for func in ('std', 'mean', 'sum', 'max', 'min', 'var'): - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(r, func), 1, 2, 3) - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(r, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(r, func), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(r, func), dtype=np.float64) def test_closed(self): df = DataFrame({'A': [0, 1, 2, 3, 4]}) @@ -478,10 +478,10 @@ def test_numpy_compat(self): msg = "numpy operations are not valid with window objects" for func in ('std', 'mean', 'sum', 'max', 'min', 'var'): - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(e, func), 1, 2, 3) - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(e, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, func), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, func), dtype=np.float64) class TestEWM(Base): @@ -540,10 +540,10 @@ def test_numpy_compat(self): msg = "numpy operations are not valid with window objects" for func in ('std', 'mean', 'var'): - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(e, func), 1, 2, 3) - tm.assertRaisesRegexp(UnsupportedFunctionCall, msg, - getattr(e, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, func), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, func), dtype=np.float64) class TestDeprecations(Base): @@ -1825,10 +1825,10 @@ def test_no_pairwise_with_other(self, f): tm.assert_index_equal(result.index, expected_index) tm.assert_index_equal(result.columns, expected_columns) else: - tm.assertRaisesRegexp( + tm.assert_raises_regex( ValueError, "'arg1' columns are not unique", f, df, self.df2) - tm.assertRaisesRegexp( + tm.assert_raises_regex( ValueError, "'arg2' columns are not unique", f, self.df2, df) diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py index 1376101412112..290c03af3be4b 100644 --- a/pandas/tests/tools/test_numeric.py +++ b/pandas/tests/tools/test_numeric.py @@ -39,7 +39,7 @@ def test_series_numeric(self): def test_error(self): s = pd.Series([1, -3.14, 'apple']) msg = 'Unable to parse string "apple" at position 2' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): to_numeric(s, errors='raise') res = to_numeric(s, errors='ignore') @@ -52,13 +52,13 @@ def test_error(self): s = pd.Series(['orange', 1, -3.14, 'apple']) msg = 'Unable to parse string "orange" at position 0' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): to_numeric(s, errors='raise') def test_error_seen_bool(self): s = pd.Series([True, False, 'apple']) msg = 'Unable to parse string "apple" at position 2' - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): to_numeric(s, errors='raise') res = to_numeric(s, errors='ignore') @@ -149,10 +149,10 @@ def test_all_nan(self): def test_type_check(self): # GH 11776 df = pd.DataFrame({'a': [1, -3.14, 7], 'b': ['4', '5', '6']}) - with tm.assertRaisesRegexp(TypeError, "1-d array"): + with tm.assert_raises_regex(TypeError, "1-d array"): to_numeric(df) for errors in ['ignore', 'raise', 'coerce']: - with tm.assertRaisesRegexp(TypeError, "1-d array"): + with tm.assert_raises_regex(TypeError, "1-d array"): to_numeric(df, errors=errors) def test_scalar(self): @@ -253,7 +253,7 @@ def test_non_hashable(self): res = pd.to_numeric(s, errors='ignore') tm.assert_series_equal(res, pd.Series([[10.0, 2], 1.0, 'apple'])) - with tm.assertRaisesRegexp(TypeError, "Invalid object type"): + with tm.assert_raises_regex(TypeError, "Invalid object type"): pd.to_numeric(s) def test_downcast(self): @@ -274,7 +274,7 @@ def test_downcast(self): smallest_float_dtype = float_32_char for data in (mixed_data, int_data, date_data): - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): pd.to_numeric(data, downcast=invalid_downcast) expected = np.array([1, 2, 3], dtype=np.int64) diff --git a/pandas/tests/tseries/test_frequencies.py b/pandas/tests/tseries/test_frequencies.py index c9de997cdf067..af544d10a737c 100644 --- a/pandas/tests/tseries/test_frequencies.py +++ b/pandas/tests/tseries/test_frequencies.py @@ -101,7 +101,8 @@ def test_to_offset_multiple(self): assert (result == expected) # malformed - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: 2h20m'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: 2h20m'): frequencies.to_offset('2h20m') def test_to_offset_negative(self): @@ -123,17 +124,23 @@ def test_to_offset_negative(self): def test_to_offset_invalid(self): # GH 13930 - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: U1'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: U1'): frequencies.to_offset('U1') - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: -U'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: -U'): frequencies.to_offset('-U') - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: 3U1'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: 3U1'): frequencies.to_offset('3U1') - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: -2-3U'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: -2-3U'): frequencies.to_offset('-2-3U') - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: -2D:3H'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: -2D:3H'): frequencies.to_offset('-2D:3H') - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: 1.5.0S'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: 1.5.0S'): frequencies.to_offset('1.5.0S') # split offsets with spaces are valid @@ -146,10 +153,11 @@ def test_to_offset_invalid(self): # special cases assert frequencies.to_offset('2SMS-15') == offsets.SemiMonthBegin(2) - with tm.assertRaisesRegexp(ValueError, - 'Invalid frequency: 2SMS-15-15'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: 2SMS-15-15'): frequencies.to_offset('2SMS-15-15') - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: 2SMS-15D'): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: 2SMS-15D'): frequencies.to_offset('2SMS-15D') def test_to_offset_leading_zero(self): @@ -244,7 +252,8 @@ def test_anchored_shortcuts(self): 'SMS-1', 'SMS-28', 'SMS-30', 'SMS-BAR', 'BSMS', 'SMS--2'] for invalid_anchor in invalid_anchors: - with tm.assertRaisesRegexp(ValueError, 'Invalid frequency: '): + with tm.assert_raises_regex(ValueError, + 'Invalid frequency: '): frequencies.to_offset(invalid_anchor) @@ -306,7 +315,7 @@ def _assert_depr(freq, expected, aliases): msg = frequencies._INVALID_FREQ_ERROR for alias in aliases: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): frequencies._period_str_to_code(alias) _assert_depr("M", 3000, ["MTH", "MONTH", "MONTHLY"]) @@ -780,7 +789,7 @@ def test_series(self): for freq in ['Y']: msg = frequencies._INVALID_FREQ_ERROR - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): s = Series(period_range('2013', periods=10, freq=freq)) pytest.raises(TypeError, lambda: frequencies.infer_freq(s)) @@ -807,10 +816,10 @@ def test_legacy_offset_warnings(self): msg = frequencies._INVALID_FREQ_ERROR for freq in freqs: - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): frequencies.get_offset(freq) - with tm.assertRaisesRegexp(ValueError, msg): + with tm.assert_raises_regex(ValueError, msg): date_range('2011-01-01', periods=5, freq=freq) diff --git a/pandas/tests/tseries/test_offsets.py b/pandas/tests/tseries/test_offsets.py index ff38d5ec46a44..cb3fc3b60226f 100644 --- a/pandas/tests/tseries/test_offsets.py +++ b/pandas/tests/tseries/test_offsets.py @@ -35,7 +35,6 @@ from pandas.io.pickle import read_pickle from pandas._libs.tslib import normalize_date, NaT, Timestamp, Timedelta import pandas._libs.tslib as tslib -from pandas.util.testing import assertRaisesRegexp import pandas.util.testing as tm from pandas.tseries.holiday import USFederalHolidayCalendar @@ -2226,7 +2225,8 @@ def test_repr(self): def test_corner(self): pytest.raises(ValueError, Week, weekday=7) - assertRaisesRegexp(ValueError, "Day must be", Week, weekday=-1) + tm.assert_raises_regex( + ValueError, "Day must be", Week, weekday=-1) def test_isAnchored(self): self.assertTrue(Week(weekday=0).isAnchored()) @@ -2291,16 +2291,16 @@ class TestWeekOfMonth(Base): _offset = WeekOfMonth def test_constructor(self): - assertRaisesRegexp(ValueError, "^N cannot be 0", WeekOfMonth, n=0, - week=1, weekday=1) - assertRaisesRegexp(ValueError, "^Week", WeekOfMonth, n=1, week=4, - weekday=0) - assertRaisesRegexp(ValueError, "^Week", WeekOfMonth, n=1, week=-1, - weekday=0) - assertRaisesRegexp(ValueError, "^Day", WeekOfMonth, n=1, week=0, - weekday=-1) - assertRaisesRegexp(ValueError, "^Day", WeekOfMonth, n=1, week=0, - weekday=7) + tm.assert_raises_regex(ValueError, "^N cannot be 0", + WeekOfMonth, n=0, week=1, weekday=1) + tm.assert_raises_regex(ValueError, "^Week", WeekOfMonth, + n=1, week=4, weekday=0) + tm.assert_raises_regex(ValueError, "^Week", WeekOfMonth, + n=1, week=-1, weekday=0) + tm.assert_raises_regex(ValueError, "^Day", WeekOfMonth, + n=1, week=0, weekday=-1) + tm.assert_raises_regex(ValueError, "^Day", WeekOfMonth, + n=1, week=0, weekday=7) def test_repr(self): self.assertEqual(repr(WeekOfMonth(weekday=1, week=2)), @@ -2377,12 +2377,13 @@ class TestLastWeekOfMonth(Base): _offset = LastWeekOfMonth def test_constructor(self): - assertRaisesRegexp(ValueError, "^N cannot be 0", LastWeekOfMonth, n=0, - weekday=1) + tm.assert_raises_regex(ValueError, "^N cannot be 0", + LastWeekOfMonth, n=0, weekday=1) - assertRaisesRegexp(ValueError, "^Day", LastWeekOfMonth, n=1, - weekday=-1) - assertRaisesRegexp(ValueError, "^Day", LastWeekOfMonth, n=1, weekday=7) + tm.assert_raises_regex(ValueError, "^Day", LastWeekOfMonth, n=1, + weekday=-1) + tm.assert_raises_regex( + ValueError, "^Day", LastWeekOfMonth, n=1, weekday=7) def test_offset(self): # Saturday @@ -4567,9 +4568,9 @@ def test_get_offset_name(self): def test_get_offset(): - with tm.assertRaisesRegexp(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): get_offset('gibberish') - with tm.assertRaisesRegexp(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): get_offset('QS-JAN-B') pairs = [ @@ -4597,7 +4598,7 @@ def test_get_offset(): def test_get_offset_legacy(): pairs = [('w@Sat', Week(weekday=5))] for name, expected in pairs: - with tm.assertRaisesRegexp(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): get_offset(name) @@ -4637,7 +4638,7 @@ def test_get_standard_freq(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): assert fstr == get_standard_freq(('W', 1)) - with tm.assertRaisesRegexp(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): get_standard_freq('WeEk') @@ -4646,7 +4647,7 @@ def test_get_standard_freq(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): assert fstr == get_standard_freq('5q') - with tm.assertRaisesRegexp(ValueError, _INVALID_FREQ_ERROR): + with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): get_standard_freq('5QuarTer') diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py index e3f2c242e3294..807d6866cbf74 100644 --- a/pandas/tests/tseries/test_timezones.py +++ b/pandas/tests/tseries/test_timezones.py @@ -1335,8 +1335,8 @@ def test_series_frame_tz_localize(self): # Can't localize if already tz-aware rng = date_range('1/1/2011', periods=100, freq='H', tz='utc') ts = Series(1, index=rng) - tm.assertRaisesRegexp(TypeError, 'Already tz-aware', ts.tz_localize, - 'US/Eastern') + tm.assert_raises_regex(TypeError, 'Already tz-aware', + ts.tz_localize, 'US/Eastern') def test_series_frame_tz_convert(self): rng = date_range('1/1/2011', periods=200, freq='D', tz='US/Eastern') @@ -1359,8 +1359,8 @@ def test_series_frame_tz_convert(self): # can't convert tz-naive rng = date_range('1/1/2011', periods=200, freq='D') ts = Series(1, index=rng) - tm.assertRaisesRegexp(TypeError, "Cannot convert tz-naive", - ts.tz_convert, 'US/Eastern') + tm.assert_raises_regex(TypeError, "Cannot convert tz-naive", + ts.tz_convert, 'US/Eastern') def test_tz_convert_roundtrip(self): for tz in self.timezones: diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 75d24938ed309..3f07937a6e552 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2423,7 +2423,8 @@ def stdin_encoding(encoding=None): sys.stdin = _stdin -def assertRaisesRegexp(_exception, _regexp, _callable=None, *args, **kwargs): +def assert_raises_regex(_exception, _regexp, _callable=None, + *args, **kwargs): """ Check that the specified Exception is raised and that the error message matches a given regular expression pattern. This may be a regular @@ -2440,27 +2441,26 @@ def assertRaisesRegexp(_exception, _regexp, _callable=None, *args, **kwargs): Examples -------- - >>> assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ', - ... int, 'XYZ') + >>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ') >>> import re - >>> assertRaisesRegexp(ValueError, re.compile('literal'), int, 'XYZ') + >>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ') If an exception of a different type is raised, it bubbles up. - >>> assertRaisesRegexp(TypeError, 'literal', int, 'XYZ') + >>> assert_raises_regex(TypeError, 'literal', int, 'XYZ') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'XYZ' >>> dct = dict() - >>> assertRaisesRegexp(KeyError, 'pear', dct.__getitem__, 'apple') + >>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple') Traceback (most recent call last): ... AssertionError: "pear" does not match "'apple'" You can also use this in a with statement. - >>> with assertRaisesRegexp(TypeError, 'unsupported operand type\(s\)'): + >>> with assert_raises_regex(TypeError, 'unsupported operand type\(s\)'): ... 1 + {} - >>> with assertRaisesRegexp(TypeError, 'banana'): + >>> with assert_raises_regex(TypeError, 'banana'): ... 'apple'[0] = 'b' Traceback (most recent call last): ... @@ -2477,7 +2477,7 @@ def assertRaisesRegexp(_exception, _regexp, _callable=None, *args, **kwargs): class _AssertRaisesContextmanager(object): """ - Context manager behind assertRaisesRegexp. + Context manager behind `assert_raises_regex`. """ def __init__(self, exception, regexp=None):
Title is self-explanatory. xref <a href="https://github.com/pandas-dev/pandas/pull/16089#issuecomment-296327919">#16089 (comment)</a>
https://api.github.com/repos/pandas-dev/pandas/pulls/16119
2017-04-24T22:32:43Z
2017-04-26T15:42:18Z
2017-04-26T15:42:18Z
2017-04-26T16:25:58Z
MAINT: Remove self.assertRaisesRegexp from testing
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 2d673b2dac259..8ca8ddded3073 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1874,16 +1874,16 @@ def test_groupby_args(self): def j(): frame.groupby() - self.assertRaisesRegexp(TypeError, - "You have to supply one of 'by' and 'level'", - j) + tm.assertRaisesRegexp(TypeError, + "You have to supply one of 'by' and 'level'", + j) def k(): frame.groupby(by=None, level=None) - self.assertRaisesRegexp(TypeError, - "You have to supply one of 'by' and 'level'", - k) + tm.assertRaisesRegexp(TypeError, + "You have to supply one of 'by' and 'level'", + k) def test_groupby_level_mapper(self): frame = self.mframe diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 57ea8eb067a2b..4624d43df6128 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -556,7 +556,7 @@ def test_transform_with_non_scalar_group(self): df = pd.DataFrame(np.random.randint(1, 10, (4, 12)), columns=cols, index=['A', 'C', 'G', 'T']) - self.assertRaisesRegexp(ValueError, 'transform must return a scalar ' - 'value for each group.*', df.groupby - (axis=1, level=1).transform, - lambda z: z.div(z.sum(axis=1), axis=0)) + tm.assertRaisesRegexp(ValueError, 'transform must return a scalar ' + 'value for each group.*', df.groupby + (axis=1, level=1).transform, + lambda z: z.div(z.sum(axis=1), axis=0)) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index fa1f31ded5f1c..746932b7c2975 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -875,7 +875,7 @@ def test_fillna(self): elif isinstance(index, MultiIndex): idx = index.copy() msg = "isnull is not defined for MultiIndex" - with self.assertRaisesRegexp(NotImplementedError, msg): + with tm.assertRaisesRegexp(NotImplementedError, msg): idx.fillna(idx[0]) else: idx = index.copy() @@ -884,7 +884,7 @@ def test_fillna(self): self.assertFalse(result is idx) msg = "'value' must be a scalar, passed: " - with self.assertRaisesRegexp(TypeError, msg): + with tm.assertRaisesRegexp(TypeError, msg): idx.fillna([idx[0]]) idx = index.copy() @@ -918,7 +918,7 @@ def test_nulls(self): elif isinstance(index, MultiIndex): idx = index.copy() msg = "isnull is not defined for MultiIndex" - with self.assertRaisesRegexp(NotImplementedError, msg): + with tm.assertRaisesRegexp(NotImplementedError, msg): idx.isnull() else: diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 665dcc45050f3..6e49b1612b4c5 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -212,31 +212,31 @@ def test_naive_aware_conflicts(self): naive = bdate_range(START, END, freq=BDay(), tz=None) aware = bdate_range(START, END, freq=BDay(), tz="Asia/Hong_Kong") - self.assertRaisesRegexp(TypeError, "tz-naive.*tz-aware", - naive.join, aware) - self.assertRaisesRegexp(TypeError, "tz-naive.*tz-aware", - aware.join, naive) + tm.assertRaisesRegexp(TypeError, "tz-naive.*tz-aware", + naive.join, aware) + tm.assertRaisesRegexp(TypeError, "tz-naive.*tz-aware", + aware.join, naive) def test_cached_range(self): DatetimeIndex._cached_range(START, END, offset=BDay()) DatetimeIndex._cached_range(START, periods=20, offset=BDay()) DatetimeIndex._cached_range(end=START, periods=20, offset=BDay()) - self.assertRaisesRegexp(TypeError, "offset", - DatetimeIndex._cached_range, - START, END) + tm.assertRaisesRegexp(TypeError, "offset", + DatetimeIndex._cached_range, + START, END) - self.assertRaisesRegexp(TypeError, "specify period", - DatetimeIndex._cached_range, START, - offset=BDay()) + tm.assertRaisesRegexp(TypeError, "specify period", + DatetimeIndex._cached_range, START, + offset=BDay()) - self.assertRaisesRegexp(TypeError, "specify period", - DatetimeIndex._cached_range, end=END, - offset=BDay()) + tm.assertRaisesRegexp(TypeError, "specify period", + DatetimeIndex._cached_range, end=END, + offset=BDay()) - self.assertRaisesRegexp(TypeError, "start or end", - DatetimeIndex._cached_range, periods=20, - offset=BDay()) + tm.assertRaisesRegexp(TypeError, "start or end", + DatetimeIndex._cached_range, periods=20, + offset=BDay()) def test_cached_range_bug(self): rng = date_range('2010-09-01 05:00:00', periods=50, diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 66dcb195611e1..abfc52728ef0f 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -755,12 +755,12 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): ts = Series(np.arange(20), date_range('2014-01-01', periods=20, freq='MS')) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts[::0]) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) def test_slice_bounds_empty(self): # GH 14354 diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index 9c41e2d823238..352e066c6c90c 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -122,8 +122,8 @@ def test_partial_slice_second_precision(self): tm.assert_series_equal(s['2005-1-1 00:01:00'], s.iloc[10:]) self.assertEqual(s[Timestamp('2005-1-1 00:00:59.999990')], s.iloc[0]) - self.assertRaisesRegexp(KeyError, '2005-1-1 00:00:00', - lambda: s['2005-1-1 00:00:00']) + tm.assertRaisesRegexp(KeyError, '2005-1-1 00:00:00', + lambda: s['2005-1-1 00:00:00']) def test_partial_slicing_dataframe(self): # GH14856 @@ -249,14 +249,14 @@ def test_partial_slice_doesnt_require_monotonicity(self): timestamp = pd.Timestamp('2014-01-10') tm.assert_series_equal(nonmonotonic['2014-01-10':], expected) - self.assertRaisesRegexp(KeyError, - r"Timestamp\('2014-01-10 00:00:00'\)", - lambda: nonmonotonic[timestamp:]) + tm.assertRaisesRegexp(KeyError, + r"Timestamp\('2014-01-10 00:00:00'\)", + lambda: nonmonotonic[timestamp:]) tm.assert_series_equal(nonmonotonic.loc['2014-01-10':], expected) - self.assertRaisesRegexp(KeyError, - r"Timestamp\('2014-01-10 00:00:00'\)", - lambda: nonmonotonic.loc[timestamp:]) + tm.assertRaisesRegexp(KeyError, + r"Timestamp\('2014-01-10 00:00:00'\)", + lambda: nonmonotonic.loc[timestamp:]) def test_loc_datetime_length_one(self): # GH16071 diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 79998d5a6ad7f..4d5fdd748219c 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -103,10 +103,10 @@ def test_getitem_partial(self): tm.assert_series_equal(exp, result) ts = ts[10:].append(ts[10:]) - self.assertRaisesRegexp(KeyError, - "left slice bound for non-unique " - "label: '2008'", - ts.__getitem__, slice('2008', '2009')) + tm.assertRaisesRegexp(KeyError, + "left slice bound for non-unique " + "label: '2008'", + ts.__getitem__, slice('2008', '2009')) def test_getitem_datetime(self): rng = period_range(start='2012-01-01', periods=10, freq='W-MON') diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py index a8ac6a3e55fe5..b13e231db6c1c 100644 --- a/pandas/tests/indexes/period/test_partial_slicing.py +++ b/pandas/tests/indexes/period/test_partial_slicing.py @@ -42,12 +42,12 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): ts = Series(np.arange(20), period_range('2014-01', periods=20, freq='M')) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts[::0]) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) def test_slice_keep_name(self): idx = period_range('20010101', periods=10, freq='D', name='bob') diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 9f72c10316c90..6036d6c0fb19b 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -151,7 +151,7 @@ def test_get_indexer(self): np.array([0, -1, 1], dtype=np.intp)) msg = 'Input has different freq from PeriodIndex\\(freq=H\\)' - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): idx.get_indexer(target, 'nearest', tolerance='1 minute') tm.assert_numpy_array_equal(idx.get_indexer(target, 'nearest', diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py index 49bc4a4cabe59..3887463cae827 100644 --- a/pandas/tests/indexes/period/test_tools.py +++ b/pandas/tests/indexes/period/test_tools.py @@ -386,7 +386,7 @@ def test_to_period_monthish(self): self.assertEqual(prng.freq, 'M') msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): date_range('01-Jan-2012', periods=8, freq='EOM') def test_period_dt64_round_trip(self): @@ -439,11 +439,11 @@ def test_searchsorted(self): self.assertEqual(pidx.searchsorted(p2), 3) msg = "Input has different freq=H from PeriodIndex" - with self.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): pidx.searchsorted(pd.Period('2014-01-01', freq='H')) msg = "Input has different freq=5D from PeriodIndex" - with self.assertRaisesRegexp(period.IncompatibleFrequency, msg): + with tm.assertRaisesRegexp(period.IncompatibleFrequency, msg): pidx.searchsorted(pd.Period('2014-01-01', freq='5D')) with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 2b6d69a90a55f..06f98527deefb 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1450,8 +1450,8 @@ def test_str_attribute(self): MultiIndex.from_tuples([('foo', '1'), ('bar', '3')]), PeriodIndex(start='2000', end='2010', freq='A')] for idx in indices: - with self.assertRaisesRegexp(AttributeError, - 'only use .str accessor'): + with tm.assertRaisesRegexp(AttributeError, + 'only use .str accessor'): idx.str.repeat(2) idx = Index(['a b c', 'd e', 'f']) diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index c34d93cb21b0f..8e020846f5c50 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -602,9 +602,9 @@ def test_comparison(self): actual = self.index == self.index.left tm.assert_numpy_array_equal(actual, np.array([False, False])) - with self.assertRaisesRegexp(TypeError, 'unorderable types'): + with tm.assertRaisesRegexp(TypeError, 'unorderable types'): self.index > 0 - with self.assertRaisesRegexp(TypeError, 'unorderable types'): + with tm.assertRaisesRegexp(TypeError, 'unorderable types'): self.index <= 0 with pytest.raises(TypeError): self.index > np.arange(2) diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index 6da6653b752c9..da23f8698f4dc 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -115,7 +115,7 @@ def test_round(self): self.assertEqual(elt.round(freq='H'), expected_elt) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): td.round(freq='foo') with tm.assertRaisesRegexp(ValueError, msg): elt.round(freq='foo') diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py index f7560c37e814b..ccb9a7f1803e7 100644 --- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py +++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py @@ -75,9 +75,9 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): ts = Series(np.arange(20), timedelta_range('0', periods=20, freq='H')) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts[::0]) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: ts.loc[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: ts.loc[::0]) diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index ef64c6e0475e9..02df4de010fbe 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -48,9 +48,9 @@ def test_scalar_error(self): def f(): s.iloc[3.0] - self.assertRaisesRegexp(TypeError, - 'cannot do positional indexing', - f) + tm.assertRaisesRegexp(TypeError, + 'cannot do positional indexing', + f) def f(): s.iloc[3.0] = 0 diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index fe934e7b2a7e0..f7a9c9fe59594 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -716,13 +716,13 @@ def assert_slices_equivalent(l_slc, i_slc): def test_slice_with_zero_step_raises(self): s = Series(np.arange(20), index=_mklbl('A', 20)) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: s[::0]) - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: s.loc[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: s[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: s.loc[::0]) with catch_warnings(record=True): - self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', - lambda: s.ix[::0]) + tm.assertRaisesRegexp(ValueError, 'slice step cannot be zero', + lambda: s.ix[::0]) def test_indexing_assignment_dict_already_exists(self): df = pd.DataFrame({'x': [1, 2, 6], diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index 3522974c18061..a583bf1c5ef16 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -154,8 +154,8 @@ def test_at_to_fail(self): df.columns = ['x', 'x', 'z'] # Check that we get the correct value in the KeyError - self.assertRaisesRegexp(KeyError, r"\['y'\] not in index", - lambda: df[['x', 'y', 'z']]) + tm.assertRaisesRegexp(KeyError, r"\['y'\] not in index", + lambda: df[['x', 'y', 'z']]) def test_at_with_tz(self): # gh-15822 diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index b152f7bb089de..a8ea76ff9459c 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1036,7 +1036,7 @@ def test_to_jsonl(self): def test_latin_encoding(self): if compat.PY2: - self.assertRaisesRegexp( + tm.assertRaisesRegexp( TypeError, r'\[unicode\] is not implemented as a table column') return diff --git a/pandas/tests/io/parser/compression.py b/pandas/tests/io/parser/compression.py index c7e9401665cdf..26e216cfbcffa 100644 --- a/pandas/tests/io/parser/compression.py +++ b/pandas/tests/io/parser/compression.py @@ -45,18 +45,18 @@ def test_zip(self): tmp.writestr(file_name, data) tmp.close() - self.assertRaisesRegexp(ValueError, 'Multiple files', - self.read_csv, path, compression='zip') + tm.assertRaisesRegexp(ValueError, 'Multiple files', + self.read_csv, path, compression='zip') - self.assertRaisesRegexp(ValueError, 'Multiple files', - self.read_csv, path, compression='infer') + tm.assertRaisesRegexp(ValueError, 'Multiple files', + self.read_csv, path, compression='infer') with tm.ensure_clean() as path: tmp = zipfile.ZipFile(path, mode='w') tmp.close() - self.assertRaisesRegexp(ValueError, 'Zero files', - self.read_csv, path, compression='zip') + tm.assertRaisesRegexp(ValueError, 'Zero files', + self.read_csv, path, compression='zip') with tm.ensure_clean() as path: with open(path, 'wb') as f: diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index ea9911d8ee66c..7d2c7a97fce0a 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -971,7 +971,7 @@ def test_encoding(self): def test_latin_encoding(self): if compat.PY2: - self.assertRaisesRegexp( + tm.assertRaisesRegexp( TypeError, r'\[unicode\] is not implemented as a table column') return diff --git a/pandas/tests/scalar/test_interval.py b/pandas/tests/scalar/test_interval.py index bd73a7d173962..ea267fabd13ed 100644 --- a/pandas/tests/scalar/test_interval.py +++ b/pandas/tests/scalar/test_interval.py @@ -46,7 +46,7 @@ def test_equal(self): self.assertNotEqual(Interval(0, 1), 0) def test_comparison(self): - with self.assertRaisesRegexp(TypeError, 'unorderable types'): + with tm.assertRaisesRegexp(TypeError, 'unorderable types'): Interval(0, 1) < 2 self.assertTrue(Interval(0, 1) < Interval(1, 2)) diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py index dff954b25f839..f8b103836e9a1 100644 --- a/pandas/tests/scalar/test_period.py +++ b/pandas/tests/scalar/test_period.py @@ -518,9 +518,9 @@ def test_period_deprecated_freq(self): msg = pd.tseries.frequencies._INVALID_FREQ_ERROR for exp, freqs in iteritems(cases): for freq in freqs: - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period('2016-03-01 09:00', freq=freq) - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(ordinal=1, freq=freq) # check supported freq-aliases still works @@ -762,7 +762,7 @@ def test_properties_weekly_legacy(self): self.assertEqual(exp.days_in_month, 29) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK', year=2007, month=1, day=7) def test_properties_daily(self): diff --git a/pandas/tests/scalar/test_period_asfreq.py b/pandas/tests/scalar/test_period_asfreq.py index d311fef8a826d..611a1cc97e9c6 100644 --- a/pandas/tests/scalar/test_period_asfreq.py +++ b/pandas/tests/scalar/test_period_asfreq.py @@ -295,26 +295,26 @@ def test_conv_weekly(self): self.assertEqual(ival_W.asfreq('W'), ival_W) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): ival_W.asfreq('WK') def test_conv_weekly_legacy(self): # frequency conversion tests: from Weekly Frequency msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK', year=2007, month=1, day=1) - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK-SAT', year=2007, month=1, day=6) - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK-FRI', year=2007, month=1, day=5) - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK-THU', year=2007, month=1, day=4) - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK-WED', year=2007, month=1, day=3) - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK-TUE', year=2007, month=1, day=2) - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): Period(freq='WK-MON', year=2007, month=1, day=1) def test_conv_business(self): @@ -712,7 +712,7 @@ def test_asfreq_MS(self): Period('2013-01', 'M')) msg = pd.tseries.frequencies._INVALID_FREQ_ERROR - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): initial.asfreq(freq="MS", how="S") with tm.assertRaisesRegexp(ValueError, msg): diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index 2b00ac68ee555..b7b1b4c198701 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -710,7 +710,7 @@ def _check_round(freq, expected): _check_round(freq, expected) msg = frequencies._INVALID_FREQ_ERROR - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): stamp.round('foo') def test_class_ops_pytz(self): diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 63e291836b472..02748aee4628d 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -550,8 +550,8 @@ def testit(): # Unimplemented numeric_only parameter. if 'numeric_only' in compat.signature(f).args: - self.assertRaisesRegexp(NotImplementedError, name, f, - self.series, numeric_only=True) + tm.assertRaisesRegexp(NotImplementedError, name, f, + self.series, numeric_only=True) testit() diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 341d4006c5fcc..f1a904498b727 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -341,7 +341,7 @@ def test_str_attribute(self): # str accessor only valid with string values s = Series(range(5)) - with self.assertRaisesRegexp(AttributeError, 'only use .str accessor'): + with tm.assertRaisesRegexp(AttributeError, 'only use .str accessor'): s.str.repeat(2) def test_empty_method(self): diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 1d0788ae160dd..17bc06b5ee9c7 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -180,8 +180,8 @@ def wrapper(x): # Unimplemented numeric_only parameter. if 'numeric_only' in signature(f).args: - self.assertRaisesRegexp(NotImplementedError, name, f, - numeric_only=True) + tm.assertRaisesRegexp(NotImplementedError, name, f, + numeric_only=True) class SafeForSparse(object): diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 761bfa6bfe29a..a818bf84b8e9b 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -2722,9 +2722,9 @@ def test_index_str_accessor_visibility(self): for values, tp in cases: idx = Index(values) message = 'Can only use .str accessor with string values' - with self.assertRaisesRegexp(AttributeError, message): + with tm.assertRaisesRegexp(AttributeError, message): Series(values).str - with self.assertRaisesRegexp(AttributeError, message): + with tm.assertRaisesRegexp(AttributeError, message): idx.str self.assertEqual(idx.inferred_type, tp) @@ -2732,7 +2732,7 @@ def test_index_str_accessor_visibility(self): idx = MultiIndex.from_tuples([('a', 'b'), ('a', 'b')]) self.assertEqual(idx.inferred_type, 'mixed') message = 'Can only use .str accessor with Index, not MultiIndex' - with self.assertRaisesRegexp(AttributeError, message): + with tm.assertRaisesRegexp(AttributeError, message): idx.str def test_str_accessor_no_new_attributes(self): diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py index 5fa3f38f31ae1..1376101412112 100644 --- a/pandas/tests/tools/test_numeric.py +++ b/pandas/tests/tools/test_numeric.py @@ -253,7 +253,7 @@ def test_non_hashable(self): res = pd.to_numeric(s, errors='ignore') tm.assert_series_equal(res, pd.Series([[10.0, 2], 1.0, 'apple'])) - with self.assertRaisesRegexp(TypeError, "Invalid object type"): + with tm.assertRaisesRegexp(TypeError, "Invalid object type"): pd.to_numeric(s) def test_downcast(self): @@ -274,7 +274,7 @@ def test_downcast(self): smallest_float_dtype = float_32_char for data in (mixed_data, int_data, date_data): - with self.assertRaisesRegexp(ValueError, msg): + with tm.assertRaisesRegexp(ValueError, msg): pd.to_numeric(data, downcast=invalid_downcast) expected = np.array([1, 2, 3], dtype=np.int64) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 08b298fabdd57..75d24938ed309 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2665,12 +2665,6 @@ def use_numexpr(use, min_elements=expr._MIN_ELEMENTS): expr.set_use_numexpr(olduse) -# Also provide all assert_* functions in the TestCase class -for name, obj in inspect.getmembers(sys.modules[__name__]): - if inspect.isfunction(obj) and name.startswith('assert'): - setattr(TestCase, name, staticmethod(obj)) - - def test_parallel(num_threads=2, kwargs_list=None): """Decorator to run the same function multiple times in parallel.
Title is self-explanatory. Partially addresses #15990.
https://api.github.com/repos/pandas-dev/pandas/pulls/16113
2017-04-24T17:33:14Z
2017-04-24T19:59:43Z
2017-04-24T19:59:43Z
2017-04-24T20:05:05Z
REGR: assure .unique of mixed strings does not stringize
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 8437861bea19e..3df82b6c13259 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -161,7 +161,11 @@ def _ensure_arraylike(values): """ if not isinstance(values, (np.ndarray, ABCCategorical, ABCIndexClass, ABCSeries)): - values = np.array(values) + inferred = lib.infer_dtype(values) + if inferred in ['mixed', 'string', 'unicode']: + values = np.asarray(values, dtype=object) + else: + values = np.asarray(values) return values diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 746932b7c2975..b62cab6cc8710 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -323,6 +323,7 @@ def test_get_unique_index(self): idx = ind[[0] * 5] idx_unique = ind[[0]] + # We test against `idx_unique`, so first we make sure it's unique # and doesn't contain nans. self.assertTrue(idx_unique.is_unique) @@ -336,7 +337,6 @@ def test_get_unique_index(self): tm.assert_index_equal(result, idx_unique) # nans: - if not ind._can_hold_na: continue diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index df267f2374051..01c18dc64f578 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -387,6 +387,12 @@ def test_uint64_overflow(self): exp = np.array([1, 2, 2**63], dtype=np.uint64) tm.assert_numpy_array_equal(algos.unique(s), exp) + def test_nan_in_object_array(self): + l = ['a', np.nan, 'c', 'c'] + result = pd.unique(l) + expected = np.array(['a', np.nan, 'c'], dtype=object) + tm.assert_numpy_array_equal(result, expected) + def test_categorical(self): # we are expecting to return in the order @@ -1378,8 +1384,8 @@ def test_no_mode(self): exp = Series([], dtype=np.float64) tm.assert_series_equal(algos.mode([]), exp) - # GH 15714 def test_mode_single(self): + # GH 15714 exp_single = [1] data_single = [1]
closes #16107 this *might* slow things down (because of the inferring), so will have to make a fix for that.
https://api.github.com/repos/pandas-dev/pandas/pulls/16108
2017-04-24T12:32:17Z
2017-04-25T01:53:13Z
2017-04-25T01:53:13Z
2017-04-25T01:54:37Z
MAINT: Remove assertIs from testing
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index 1017f93b8241c..86233c5d2b192 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -26,7 +26,7 @@ def test_datetimetz_dtype(self): for dtype in ['datetime64[ns, US/Eastern]', 'datetime64[ns, Asia/Tokyo]', 'datetime64[ns, UTC]']: - self.assertIs(pandas_dtype(dtype), DatetimeTZDtype(dtype)) + assert pandas_dtype(dtype) is DatetimeTZDtype(dtype) self.assertEqual(pandas_dtype(dtype), DatetimeTZDtype(dtype)) self.assertEqual(pandas_dtype(dtype), dtype) @@ -36,7 +36,7 @@ def test_categorical_dtype(self): def test_period_dtype(self): for dtype in ['period[D]', 'period[3M]', 'period[U]', 'Period[D]', 'Period[3M]', 'Period[U]']: - self.assertIs(pandas_dtype(dtype), PeriodDtype(dtype)) + assert pandas_dtype(dtype) is PeriodDtype(dtype) self.assertEqual(pandas_dtype(dtype), PeriodDtype(dtype)) self.assertEqual(pandas_dtype(dtype), dtype) diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index 32ec1194639ae..e3bae3675a9e4 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -249,20 +249,14 @@ def test_subclass(self): self.assertTrue(issubclass(type(a), type(b))) def test_identity(self): - self.assertEqual(PeriodDtype('period[D]'), - PeriodDtype('period[D]')) - self.assertIs(PeriodDtype('period[D]'), - PeriodDtype('period[D]')) + assert PeriodDtype('period[D]') == PeriodDtype('period[D]') + assert PeriodDtype('period[D]') is PeriodDtype('period[D]') - self.assertEqual(PeriodDtype('period[3D]'), - PeriodDtype('period[3D]')) - self.assertIs(PeriodDtype('period[3D]'), - PeriodDtype('period[3D]')) + assert PeriodDtype('period[3D]') == PeriodDtype('period[3D]') + assert PeriodDtype('period[3D]') is PeriodDtype('period[3D]') - self.assertEqual(PeriodDtype('period[1S1U]'), - PeriodDtype('period[1000001U]')) - self.assertIs(PeriodDtype('period[1S1U]'), - PeriodDtype('period[1000001U]')) + assert PeriodDtype('period[1S1U]') == PeriodDtype('period[1000001U]') + assert PeriodDtype('period[1S1U]') is PeriodDtype('period[1000001U]') def test_coerce_to_dtype(self): self.assertEqual(_coerce_to_dtype('period[D]'), @@ -371,12 +365,12 @@ def test_construction(self): def test_construction_generic(self): # generic i = IntervalDtype('interval') - self.assertIs(i.subtype, None) + assert i.subtype is None self.assertTrue(is_interval_dtype(i)) self.assertTrue(str(i) == 'interval') i = IntervalDtype() - self.assertIs(i.subtype, None) + assert i.subtype is None self.assertTrue(is_interval_dtype(i)) self.assertTrue(str(i) == 'interval') diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 1a3de7b463a19..b4b86d8ea1907 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -35,7 +35,7 @@ def test_set_index(self): # cache it _ = self.mixed_frame['foo'] # noqa self.mixed_frame.index = idx - self.assertIs(self.mixed_frame['foo'].index, idx) + assert self.mixed_frame['foo'].index is idx with assertRaisesRegexp(ValueError, 'Length mismatch'): self.mixed_frame.index = idx[::2] diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index e060e863c0431..9e16698bab39c 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -88,8 +88,8 @@ def test_get_axis(self): self.assertEqual(f._get_axis_name('rows'), 'index') self.assertEqual(f._get_axis_name('columns'), 'columns') - self.assertIs(f._get_axis(0), f.index) - self.assertIs(f._get_axis(1), f.columns) + assert f._get_axis(0) is f.index + assert f._get_axis(1) is f.columns assertRaisesRegexp(ValueError, 'No axis named', f._get_axis_number, 2) assertRaisesRegexp(ValueError, 'No axis.*foo', f._get_axis_name, 'foo') @@ -99,7 +99,7 @@ def test_get_axis(self): def test_keys(self): getkeys = self.frame.keys - self.assertIs(getkeys(), self.frame.columns) + assert getkeys() is self.frame.columns def test_column_contains_typeerror(self): try: @@ -122,17 +122,17 @@ def test_array_interface(self): with np.errstate(all='ignore'): result = np.sqrt(self.frame) assert isinstance(result, type(self.frame)) - self.assertIs(result.index, self.frame.index) - self.assertIs(result.columns, self.frame.columns) + assert result.index is self.frame.index + assert result.columns is self.frame.columns assert_frame_equal(result, self.frame.apply(np.sqrt)) def test_get_agg_axis(self): cols = self.frame._get_agg_axis(0) - self.assertIs(cols, self.frame.columns) + assert cols is self.frame.columns idx = self.frame._get_agg_axis(1) - self.assertIs(idx, self.frame.index) + assert idx is self.frame.index pytest.raises(ValueError, self.frame._get_agg_axis, 2) diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index d31fb4218adeb..9d0f00c6eeffe 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -25,29 +25,30 @@ def test_apply(self): with np.errstate(all='ignore'): # ufunc applied = self.frame.apply(np.sqrt) - assert_series_equal(np.sqrt(self.frame['A']), applied['A']) + tm.assert_series_equal(np.sqrt(self.frame['A']), applied['A']) # aggregator applied = self.frame.apply(np.mean) - self.assertEqual(applied['A'], np.mean(self.frame['A'])) + assert applied['A'] == np.mean(self.frame['A']) d = self.frame.index[0] applied = self.frame.apply(np.mean, axis=1) - self.assertEqual(applied[d], np.mean(self.frame.xs(d))) - self.assertIs(applied.index, self.frame.index) # want this + assert applied[d] == np.mean(self.frame.xs(d)) + assert applied.index is self.frame.index # want this # invalid axis df = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=['a', 'a', 'c']) pytest.raises(ValueError, df.apply, lambda x: x, 2) - # GH9573 + # see gh-9573 df = DataFrame({'c0': ['A', 'A', 'B', 'B'], 'c1': ['C', 'C', 'D', 'D']}) df = df.apply(lambda ts: ts.astype('category')) - self.assertEqual(df.shape, (4, 2)) - self.assertTrue(isinstance(df['c0'].dtype, CategoricalDtype)) - self.assertTrue(isinstance(df['c1'].dtype, CategoricalDtype)) + + assert df.shape == (4, 2) + assert isinstance(df['c0'].dtype, CategoricalDtype) + assert isinstance(df['c1'].dtype, CategoricalDtype) def test_apply_mixed_datetimelike(self): # mixed datetimelike @@ -190,7 +191,7 @@ def _checkit(axis=0, raw=False): if is_reduction: agg_axis = df._get_agg_axis(axis) assert isinstance(res, Series) - self.assertIs(res.index, agg_axis) + assert res.index is agg_axis else: assert isinstance(res, DataFrame) diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 636194d32ad46..e8f34b977a707 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -204,7 +204,7 @@ def test_reindex(self): # Same index, copies values but not index if copy=False newFrame = self.frame.reindex(self.frame.index, copy=False) - self.assertIs(newFrame.index, self.frame.index) + assert newFrame.index is self.frame.index # length zero newFrame = self.frame.reindex([]) diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 088f863e5358b..5f8d04fdb16bd 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -1171,29 +1171,29 @@ def test_getitem_fancy_1d(self): # return self if no slicing...for now with catch_warnings(record=True): - self.assertIs(f.ix[:, :], f) + assert f.ix[:, :] is f # low dimensional slice with catch_warnings(record=True): xs1 = f.ix[2, ['C', 'B', 'A']] xs2 = f.xs(f.index[2]).reindex(['C', 'B', 'A']) - assert_series_equal(xs1, xs2) + tm.assert_series_equal(xs1, xs2) with catch_warnings(record=True): ts1 = f.ix[5:10, 2] ts2 = f[f.columns[2]][5:10] - assert_series_equal(ts1, ts2) + tm.assert_series_equal(ts1, ts2) # positional xs with catch_warnings(record=True): xs1 = f.ix[0] xs2 = f.xs(f.index[0]) - assert_series_equal(xs1, xs2) + tm.assert_series_equal(xs1, xs2) with catch_warnings(record=True): xs1 = f.ix[f.index[5]] xs2 = f.xs(f.index[5]) - assert_series_equal(xs1, xs2) + tm.assert_series_equal(xs1, xs2) # single column with catch_warnings(record=True): @@ -1204,18 +1204,18 @@ def test_getitem_fancy_1d(self): exp = f.copy() exp.values[5] = 4 f.ix[5][:] = 4 - assert_frame_equal(exp, f) + tm.assert_frame_equal(exp, f) with catch_warnings(record=True): exp.values[:, 1] = 6 f.ix[:, 1][:] = 6 - assert_frame_equal(exp, f) + tm.assert_frame_equal(exp, f) # slice of mixed-frame with catch_warnings(record=True): xs = self.mixed_frame.ix[5] exp = self.mixed_frame.xs(self.mixed_frame.index[5]) - assert_series_equal(xs, exp) + tm.assert_series_equal(xs, exp) def test_setitem_fancy_1d(self): @@ -1676,7 +1676,7 @@ def test_set_value(self): def test_set_value_resize(self): res = self.frame.set_value('foobar', 'B', 0) - self.assertIs(res, self.frame) + assert res is self.frame self.assertEqual(res.index[-1], 'foobar') self.assertEqual(res.get_value('foobar', 'B'), 0) diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index 18639990662b0..3f77bc754a525 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -907,7 +907,7 @@ def test_combineFunc(self): _check_mixed_float(result, dtype=dict(C=None)) result = self.empty * 2 - self.assertIs(result.index, self.empty.index) + assert result.index is self.empty.index self.assertEqual(len(result.columns), 0) def test_comparisons(self): @@ -1117,16 +1117,16 @@ def test_inplace_ops_identity(self): s += 1 assert_series_equal(s, s2) assert_series_equal(s_orig + 1, s) - self.assertIs(s, s2) - self.assertIs(s._data, s2._data) + assert s is s2 + assert s._data is s2._data df = df_orig.copy() df2 = df df += 1 assert_frame_equal(df, df2) assert_frame_equal(df_orig + 1, df) - self.assertIs(df, df2) - self.assertIs(df._data, df2._data) + assert df is df2 + assert df._data is df2._data # dtype change s = s_orig.copy() @@ -1140,8 +1140,8 @@ def test_inplace_ops_identity(self): df += 1.5 assert_frame_equal(df, df2) assert_frame_equal(df_orig + 1.5, df) - self.assertIs(df, df2) - self.assertIs(df._data, df2._data) + assert df is df2 + assert df._data is df2._data # mixed dtype arr = np.random.randint(0, 10, size=5) @@ -1152,7 +1152,7 @@ def test_inplace_ops_identity(self): expected = DataFrame({'A': arr.copy() + 1, 'B': 'foo'}) assert_frame_equal(df, expected) assert_frame_equal(df2, expected) - self.assertIs(df._data, df2._data) + assert df._data is df2._data df = df_orig.copy() df2 = df @@ -1160,7 +1160,7 @@ def test_inplace_ops_identity(self): expected = DataFrame({'A': arr.copy() + 1.5, 'B': 'foo'}) assert_frame_equal(df, expected) assert_frame_equal(df2, expected) - self.assertIs(df._data, df2._data) + assert df._data is df2._data def test_alignment_non_pandas(self): index = ['A', 'B', 'C'] diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 02ef9e614150c..2d673b2dac259 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -759,17 +759,18 @@ def test_len(self): def test_groups(self): grouped = self.df.groupby(['A']) groups = grouped.groups - self.assertIs(groups, grouped.groups) # caching works + assert groups is grouped.groups # caching works for k, v in compat.iteritems(grouped.groups): - self.assertTrue((self.df.loc[v]['A'] == k).all()) + assert (self.df.loc[v]['A'] == k).all() grouped = self.df.groupby(['A', 'B']) groups = grouped.groups - self.assertIs(groups, grouped.groups) # caching works + assert groups is grouped.groups # caching works + for k, v in compat.iteritems(grouped.groups): - self.assertTrue((self.df.loc[v]['A'] == k[0]).all()) - self.assertTrue((self.df.loc[v]['B'] == k[1]).all()) + assert (self.df.loc[v]['A'] == k[0]).all() + assert (self.df.loc[v]['B'] == k[1]).all() def test_basic_regression(self): # regression diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 31e795a80f2e6..66dcb195611e1 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -156,7 +156,7 @@ def test_time_overflow_for_32bit_machines(self): self.assertEqual(len(idx2), periods) def test_nat(self): - self.assertIs(DatetimeIndex([np.nan])[0], pd.NaT) + assert DatetimeIndex([np.nan])[0] is pd.NaT def test_ufunc_coercions(self): idx = date_range('2011-01-01', periods=3, freq='2D', name='x') @@ -617,7 +617,7 @@ def test_join_self(self): kinds = 'outer', 'inner', 'left', 'right' for kind in kinds: joined = index.join(index, how=kind) - self.assertIs(index, joined) + assert index is joined def assert_index_parameters(self, index): assert index.freq == '40960N' diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index de41f321b245b..d531d0913df77 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -879,8 +879,8 @@ def test_shift(self): tm.assert_index_equal(idx.shift(-3, freq='H'), exp) def test_nat(self): - self.assertIs(pd.DatetimeIndex._na_value, pd.NaT) - self.assertIs(pd.DatetimeIndex([])._na_value, pd.NaT) + assert pd.DatetimeIndex._na_value is pd.NaT + assert pd.DatetimeIndex([])._na_value is pd.NaT for tz in [None, 'US/Eastern', 'UTC']: idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02'], tz=tz) diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 3e6ed7756b9bd..84a1adce2c0aa 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -185,7 +185,7 @@ def test_datetimeindex_union_join_empty(self): result = dti.union(empty) assert isinstance(result, DatetimeIndex) - self.assertIs(result, result) + assert result is result result = dti.join(empty) assert isinstance(result, DatetimeIndex) diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index b7427f1935a8c..c637b36d1bbb5 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -179,14 +179,14 @@ def test_to_datetime_dt64s(self): ] for dt in in_bound_dts: - self.assertEqual(pd.to_datetime(dt), Timestamp(dt)) + assert pd.to_datetime(dt) == Timestamp(dt) oob_dts = [np.datetime64('1000-01-01'), np.datetime64('5000-01-02'), ] for dt in oob_dts: pytest.raises(ValueError, pd.to_datetime, dt, errors='raise') pytest.raises(ValueError, Timestamp, dt) - self.assertIs(pd.to_datetime(dt, errors='coerce'), NaT) + assert pd.to_datetime(dt, errors='coerce') is NaT def test_to_datetime_array_of_dt64s(self): dts = [np.datetime64('2000-01-01'), np.datetime64('2000-01-02'), ] @@ -681,7 +681,7 @@ def test_to_datetime_types(self): # empty string result = to_datetime('') - self.assertIs(result, NaT) + assert result is NaT result = to_datetime(['', '']) self.assertTrue(isnull(result).all()) diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 982ac7d96a9cc..79998d5a6ad7f 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -121,7 +121,7 @@ def test_getitem_datetime(self): def test_getitem_nat(self): idx = pd.PeriodIndex(['2011-01', 'NaT', '2011-02'], freq='M') self.assertEqual(idx[0], pd.Period('2011-01', freq='M')) - self.assertIs(idx[1], tslib.NaT) + assert idx[1] is tslib.NaT s = pd.Series([0, 1, 2], index=idx) self.assertEqual(s[pd.NaT], 1) @@ -129,7 +129,7 @@ def test_getitem_nat(self): s = pd.Series(idx, index=idx) self.assertEqual(s[pd.Period('2011-01', freq='M')], pd.Period('2011-01', freq='M')) - self.assertIs(s[pd.NaT], tslib.NaT) + assert s[pd.NaT] is tslib.NaT def test_getitem_list_periods(self): # GH 7710 diff --git a/pandas/tests/indexes/period/test_ops.py b/pandas/tests/indexes/period/test_ops.py index 70a27eada7774..4f54f44b7bdab 100644 --- a/pandas/tests/indexes/period/test_ops.py +++ b/pandas/tests/indexes/period/test_ops.py @@ -56,13 +56,13 @@ def test_asobject_tolist(self): tm.assert_index_equal(result, expected) for i in [0, 1, 3]: self.assertEqual(result[i], expected[i]) - self.assertIs(result[2], pd.NaT) + assert result[2] is pd.NaT self.assertEqual(result.name, expected.name) result_list = idx.tolist() for i in [0, 1, 3]: self.assertEqual(result_list[i], expected_list[i]) - self.assertIs(result_list[2], pd.NaT) + assert result_list[2] is pd.NaT def test_minmax(self): @@ -88,15 +88,15 @@ def test_minmax(self): # Return NaT obj = PeriodIndex([], freq='M') result = getattr(obj, op)() - self.assertIs(result, tslib.NaT) + assert result is tslib.NaT obj = PeriodIndex([pd.NaT], freq='M') result = getattr(obj, op)() - self.assertIs(result, tslib.NaT) + assert result is tslib.NaT obj = PeriodIndex([pd.NaT, pd.NaT, pd.NaT], freq='M') result = getattr(obj, op)() - self.assertIs(result, tslib.NaT) + assert result is tslib.NaT def test_numpy_minmax(self): pr = pd.period_range(start='2016-01-15', end='2016-01-20') @@ -787,8 +787,8 @@ def test_repeat(self): tm.assert_index_equal(res, exp) def test_nat(self): - self.assertIs(pd.PeriodIndex._na_value, pd.NaT) - self.assertIs(pd.PeriodIndex([], freq='M')._na_value, pd.NaT) + assert pd.PeriodIndex._na_value is pd.NaT + assert pd.PeriodIndex([], freq='M')._na_value is pd.NaT idx = pd.PeriodIndex(['2011-01-01', '2011-01-02'], freq='D') self.assertTrue(idx._can_hold_na) @@ -898,7 +898,7 @@ def test_pi_ops_errors(self): np.add(obj, ng) if _np_version_under1p10: - self.assertIs(np.add(ng, obj), NotImplemented) + assert np.add(ng, obj) is NotImplemented else: with pytest.raises(TypeError): np.add(ng, obj) @@ -907,7 +907,7 @@ def test_pi_ops_errors(self): np.subtract(obj, ng) if _np_version_under1p10: - self.assertIs(np.subtract(ng, obj), NotImplemented) + assert np.subtract(ng, obj) is NotImplemented else: with pytest.raises(TypeError): np.subtract(ng, obj) @@ -1014,7 +1014,7 @@ def test_pi_sub_period(self): result = np.subtract(pd.Period('2012-01', freq='M'), idx) if _np_version_under1p10: - self.assertIs(result, NotImplemented) + assert result is NotImplemented else: tm.assert_index_equal(result, exp) diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index 54dafd832fd23..97f9cff2d193e 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -31,7 +31,7 @@ def test_join_self(self): for kind in ['inner', 'outer', 'left', 'right']: res = index.join(index, how=kind) - self.assertIs(index, res) + assert index is res def test_join_does_not_recur(self): df = tm.makeCustomDataframe( diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 91d5068ee9f19..2b6d69a90a55f 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -608,7 +608,7 @@ def test_intersection(self): # Corner cases inter = first.intersection(first) - self.assertIs(inter, first) + assert inter is first idx1 = Index([1, 2, 3, 4, 5], name='idx') # if target has the same name, it is preserved @@ -681,13 +681,13 @@ def test_union(self): # Corner cases union = first.union(first) - self.assertIs(union, first) + assert union is first union = first.union([]) - self.assertIs(union, first) + assert union is first union = Index([]).union(first) - self.assertIs(union, first) + assert union is first # preserve names first = Index(list('ab'), name='A') @@ -1434,7 +1434,7 @@ def test_join_self(self): for kind in kinds: joined = res.join(res, how=kind) - self.assertIs(res, joined) + assert res is joined def test_str_attribute(self): # GH9068 diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 7a9b3c1c4b5d6..34051a9749af8 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -1582,10 +1582,10 @@ def test_union(self): # corner case, pass self or empty thing: the_union = self.index.union(self.index) - self.assertIs(the_union, self.index) + assert the_union is self.index the_union = self.index.union(self.index[:0]) - self.assertIs(the_union, self.index) + assert the_union is self.index # won't work in python 3 # tuples = self.index.values @@ -1614,7 +1614,7 @@ def test_intersection(self): # corner case, pass self the_int = self.index.intersection(self.index) - self.assertIs(the_int, self.index) + assert the_int is self.index # empty intersection: disjoint empty = self.index[:2] & self.index[2:] @@ -2039,7 +2039,7 @@ def test_join_self(self): for kind in kinds: res = self.index joined = res.join(res, how=kind) - self.assertIs(res, joined) + assert res is joined def test_join_multi(self): # GH 10665 diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 56e0d858f1f0f..f0c42a3dae239 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -518,7 +518,7 @@ def test_join_self(self): kinds = 'outer', 'inner', 'left', 'right' for kind in kinds: joined = self.index.join(self.index, how=kind) - self.assertIs(self.index, joined) + assert self.index is joined def test_union_noncomparable(self): from datetime import datetime, timedelta diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index 4b622ad3fce49..6f87687f822e9 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -573,7 +573,7 @@ def test_join_self(self): kinds = 'outer', 'inner', 'left', 'right' for kind in kinds: joined = self.index.join(self.index, how=kind) - self.assertIs(self.index, joined) + assert self.index is joined def test_intersection(self): # intersect with Int64Index diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index a847467518b92..6da6653b752c9 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -819,8 +819,8 @@ def test_repeat(self): assert res.freq is None def test_nat(self): - self.assertIs(pd.TimedeltaIndex._na_value, pd.NaT) - self.assertIs(pd.TimedeltaIndex([])._na_value, pd.NaT) + assert pd.TimedeltaIndex._na_value is pd.NaT + assert pd.TimedeltaIndex([])._na_value is pd.NaT idx = pd.TimedeltaIndex(['1 days', '2 days']) self.assertTrue(idx._can_hold_na) diff --git a/pandas/tests/io/parser/parse_dates.py b/pandas/tests/io/parser/parse_dates.py index b7147cd77f4f6..f0a1f58be4026 100644 --- a/pandas/tests/io/parser/parse_dates.py +++ b/pandas/tests/io/parser/parse_dates.py @@ -363,7 +363,7 @@ def test_parse_tz_aware(self): stamp = result.index[0] self.assertEqual(stamp.minute, 39) try: - self.assertIs(result.index.tz, pytz.utc) + assert result.index.tz is pytz.utc except AssertionError: # hello Yaroslav arr = result.index.to_pydatetime() result = tools.to_datetime(arr, utc=True)[0] diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index ca6d0605c193b..f8923035b3a63 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -272,7 +272,7 @@ def test_timestamp(self): def test_nat(self): nat_rec = self.encode_decode(NaT) - self.assertIs(NaT, nat_rec) + assert NaT is nat_rec def test_datetimes(self): diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index ce341a1e02e0d..018cbbe170313 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -71,19 +71,19 @@ def test_boxplot_legacy(self): fig, ax = self.plt.subplots() axes = df.boxplot('Col1', by='X', ax=ax) ax_axes = ax.axes if self.mpl_ge_1_5_0 else ax.get_axes() - self.assertIs(ax_axes, axes) + assert ax_axes is axes fig, ax = self.plt.subplots() axes = df.groupby('Y').boxplot(ax=ax, return_type='axes') ax_axes = ax.axes if self.mpl_ge_1_5_0 else ax.get_axes() - self.assertIs(ax_axes, axes['A']) + assert ax_axes is axes['A'] # Multiple columns with an ax argument should use same figure fig, ax = self.plt.subplots() with tm.assert_produces_warning(UserWarning): axes = df.boxplot(column=['Col1', 'Col2'], by='X', ax=ax, return_type='axes') - self.assertIs(axes['Col1'].get_figure(), fig) + assert axes['Col1'].get_figure() is fig # When by is None, check that all relevant lines are present in the # dict @@ -357,7 +357,7 @@ def test_grouped_box_multiple_axes(self): returned = np.array(list(returned.values)) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[0]) - self.assertIs(returned[0].figure, fig) + assert returned[0].figure is fig # draw on second row with tm.assert_produces_warning(UserWarning): @@ -367,7 +367,7 @@ def test_grouped_box_multiple_axes(self): returned = np.array(list(returned.values)) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[1]) - self.assertIs(returned[0].figure, fig) + assert returned[0].figure is fig with pytest.raises(ValueError): fig, axes = self.plt.subplots(2, 3) diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 0e9aa3355a658..c72bce28b5862 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -139,7 +139,7 @@ def test_plot(self): result = ax.axes else: result = ax.get_axes() # deprecated - self.assertIs(result, axes[0]) + assert result is axes[0] # GH 15516 def test_mpl2_color_cycle_str(self): @@ -443,13 +443,13 @@ def test_subplots_multiple_axes(self): sharey=False) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) self.assertEqual(returned.shape, (3, )) - self.assertIs(returned[0].figure, fig) + assert returned[0].figure is fig # draw on second row returned = df.plot(subplots=True, ax=axes[1], sharex=False, sharey=False) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) self.assertEqual(returned.shape, (3, )) - self.assertIs(returned[0].figure, fig) + assert returned[0].figure is fig self._check_axes_shape(axes, axes_num=6, layout=(2, 3)) tm.close() @@ -933,11 +933,11 @@ def test_plot_scatter_with_c(self): # verify turning off colorbar works ax = df.plot.scatter(x='x', y='y', c='z', colorbar=False) - self.assertIs(ax.collections[0].colorbar, None) + assert ax.collections[0].colorbar is None # verify that we can still plot a solid color ax = df.plot.scatter(x=0, y=1, c='red') - self.assertIs(ax.collections[0].colorbar, None) + assert ax.collections[0].colorbar is None self._check_colors(ax.collections, facecolors=['r']) # Ensure that we can pass an np.array straight through to matplotlib, @@ -2065,7 +2065,7 @@ def test_no_color_bar(self): df = self.hexbin_df ax = df.plot.hexbin(x='A', y='B', colorbar=None) - self.assertIs(ax.collections[0].colorbar, None) + assert ax.collections[0].colorbar is None @slow def test_allow_cmap(self): diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index 6dd97a1181f22..79d5f74e6ea06 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -376,11 +376,11 @@ def test_grouped_hist_multiple_axes(self): returned = df.hist(column=['height', 'weight', 'category'], ax=axes[0]) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[0]) - self.assertIs(returned[0].figure, fig) + assert returned[0].figure is fig returned = df.hist(by='classroom', ax=axes[1]) self._check_axes_shape(returned, axes_num=3, layout=(1, 3)) tm.assert_numpy_array_equal(returned, axes[1]) - self.assertIs(returned[0].figure, fig) + assert returned[0].figure is fig with pytest.raises(ValueError): fig, axes = self.plt.subplots(2, 3) diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py index 1635d90189b50..dff954b25f839 100644 --- a/pandas/tests/scalar/test_period.py +++ b/pandas/tests/scalar/test_period.py @@ -92,25 +92,25 @@ def test_period_from_ordinal(self): def test_period_cons_nat(self): p = Period('NaT', freq='M') - self.assertIs(p, pd.NaT) + assert p is pd.NaT p = Period('nat', freq='W-SUN') - self.assertIs(p, pd.NaT) + assert p is pd.NaT p = Period(tslib.iNaT, freq='D') - self.assertIs(p, pd.NaT) + assert p is pd.NaT p = Period(tslib.iNaT, freq='3D') - self.assertIs(p, pd.NaT) + assert p is pd.NaT p = Period(tslib.iNaT, freq='1D1H') - self.assertIs(p, pd.NaT) + assert p is pd.NaT p = Period('NaT') - self.assertIs(p, pd.NaT) + assert p is pd.NaT p = Period(tslib.iNaT) - self.assertIs(p, pd.NaT) + assert p is pd.NaT def test_period_cons_mult(self): p1 = Period('2011-01', freq='3M') @@ -858,7 +858,7 @@ def test_constructor_corner(self): pytest.raises(ValueError, Period, 1.6, freq='D') pytest.raises(ValueError, Period, ordinal=1.6, freq='D') pytest.raises(ValueError, Period, ordinal=2, value=1, freq='D') - self.assertIs(Period(None), pd.NaT) + assert Period(None) is pd.NaT pytest.raises(ValueError, Period, month=1) p = Period('2007-01-01', freq='D') @@ -1020,12 +1020,12 @@ def test_add(self): def test_add_pdnat(self): p = pd.Period('2011-01', freq='M') - self.assertIs(p + pd.NaT, pd.NaT) - self.assertIs(pd.NaT + p, pd.NaT) + assert p + pd.NaT is pd.NaT + assert pd.NaT + p is pd.NaT p = pd.Period('NaT', freq='M') - self.assertIs(p + pd.NaT, pd.NaT) - self.assertIs(pd.NaT + p, pd.NaT) + assert p + pd.NaT is pd.NaT + assert pd.NaT + p is pd.NaT def test_add_raises(self): # GH 4731 @@ -1187,41 +1187,41 @@ def test_add_offset_nat(self): for freq in ['A', '2A', '3A']: p = Period('NaT', freq=freq) for o in [offsets.YearEnd(2)]: - self.assertIs(p + o, tslib.NaT) - self.assertIs(o + p, tslib.NaT) + assert p + o is tslib.NaT + assert o + p is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - self.assertIs(p + o, tslib.NaT) + assert p + o is tslib.NaT if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - self.assertIs(o + p, tslib.NaT) + assert o + p is tslib.NaT for freq in ['M', '2M', '3M']: p = Period('NaT', freq=freq) for o in [offsets.MonthEnd(2), offsets.MonthEnd(12)]: - self.assertIs(p + o, tslib.NaT) + assert p + o is tslib.NaT if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - self.assertIs(o + p, tslib.NaT) + assert o + p is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - self.assertIs(p + o, tslib.NaT) + assert p + o is tslib.NaT if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - self.assertIs(o + p, tslib.NaT) + assert o + p is tslib.NaT # freq is Tick for freq in ['D', '2D', '3D']: @@ -1229,55 +1229,55 @@ def test_add_offset_nat(self): for o in [offsets.Day(5), offsets.Hour(24), np.timedelta64(2, 'D'), np.timedelta64(3600 * 24, 's'), timedelta(-2), timedelta(hours=48)]: - self.assertIs(p + o, tslib.NaT) + assert p + o is tslib.NaT if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - self.assertIs(o + p, tslib.NaT) + assert o + p is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(4, 'h'), timedelta(hours=23)]: - self.assertIs(p + o, tslib.NaT) + assert p + o is tslib.NaT if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - self.assertIs(o + p, tslib.NaT) + assert o + p is tslib.NaT for freq in ['H', '2H', '3H']: p = Period('NaT', freq=freq) for o in [offsets.Day(2), offsets.Hour(3), np.timedelta64(3, 'h'), np.timedelta64(3600, 's'), timedelta(minutes=120), timedelta(days=4, minutes=180)]: - self.assertIs(p + o, tslib.NaT) + assert p + o is tslib.NaT if not isinstance(o, np.timedelta64): - self.assertIs(o + p, tslib.NaT) + assert o + p is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(3200, 's'), timedelta(hours=23, minutes=30)]: - self.assertIs(p + o, tslib.NaT) + assert p + o is tslib.NaT if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - self.assertIs(o + p, tslib.NaT) + assert o + p is tslib.NaT def test_sub_pdnat(self): # GH 13071 p = pd.Period('2011-01', freq='M') - self.assertIs(p - pd.NaT, pd.NaT) - self.assertIs(pd.NaT - p, pd.NaT) + assert p - pd.NaT is pd.NaT + assert pd.NaT - p is pd.NaT p = pd.Period('NaT', freq='M') - self.assertIs(p - pd.NaT, pd.NaT) - self.assertIs(pd.NaT - p, pd.NaT) + assert p - pd.NaT is pd.NaT + assert pd.NaT - p is pd.NaT def test_sub_offset(self): # freq is DateOffset @@ -1352,22 +1352,22 @@ def test_sub_offset_nat(self): for freq in ['A', '2A', '3A']: p = Period('NaT', freq=freq) for o in [offsets.YearEnd(2)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT for freq in ['M', '2M', '3M']: p = Period('NaT', freq=freq) for o in [offsets.MonthEnd(2), offsets.MonthEnd(12)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(365, 'D'), timedelta(365)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT # freq is Tick for freq in ['D', '2D', '3D']: @@ -1375,33 +1375,33 @@ def test_sub_offset_nat(self): for o in [offsets.Day(5), offsets.Hour(24), np.timedelta64(2, 'D'), np.timedelta64(3600 * 24, 's'), timedelta(-2), timedelta(hours=48)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(4, 'h'), timedelta(hours=23)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT for freq in ['H', '2H', '3H']: p = Period('NaT', freq=freq) for o in [offsets.Day(2), offsets.Hour(3), np.timedelta64(3, 'h'), np.timedelta64(3600, 's'), timedelta(minutes=120), timedelta(days=4, minutes=180)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT for o in [offsets.YearBegin(2), offsets.MonthBegin(1), offsets.Minute(), np.timedelta64(3200, 's'), timedelta(hours=23, minutes=30)]: - self.assertIs(p - o, tslib.NaT) + assert p - o is tslib.NaT def test_nat_ops(self): for freq in ['M', '2M', '3M']: p = Period('NaT', freq=freq) - self.assertIs(p + 1, tslib.NaT) - self.assertIs(1 + p, tslib.NaT) - self.assertIs(p - 1, tslib.NaT) - self.assertIs(p - Period('2011-01', freq=freq), tslib.NaT) - self.assertIs(Period('2011-01', freq=freq) - p, tslib.NaT) + assert p + 1 is tslib.NaT + assert 1 + p is tslib.NaT + assert p - 1 is tslib.NaT + assert p - Period('2011-01', freq=freq) is tslib.NaT + assert Period('2011-01', freq=freq) - p is tslib.NaT def test_period_ops_offset(self): p = Period('2011-04-01', freq='D') diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index 2cf40335f3ded..2b00ac68ee555 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -416,8 +416,7 @@ def test_tz_localize_nonexistent(self): tz) pytest.raises(NonExistentTimeError, ts.tz_localize, tz, errors='raise') - self.assertIs(ts.tz_localize(tz, errors='coerce'), - NaT) + assert ts.tz_localize(tz, errors='coerce') is NaT def test_tz_localize_errors_ambiguous(self): # See issue 13057 diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index eaa88da94ccd2..63e291836b472 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -1276,8 +1276,8 @@ def test_ptp(self): def test_empty_timeseries_redections_return_nat(self): # covers #11245 for dtype in ('m8[ns]', 'm8[ns]', 'M8[ns]', 'M8[ns, UTC]'): - self.assertIs(Series([], dtype=dtype).min(), pd.NaT) - self.assertIs(Series([], dtype=dtype).max(), pd.NaT) + assert Series([], dtype=dtype).min() is pd.NaT + assert Series([], dtype=dtype).max() is pd.NaT def test_unique_data_ownership(self): # it works! #1807 diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index a477bb325061f..341d4006c5fcc 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -35,7 +35,7 @@ def test_copy_index_name_checking(self): self.ts.index.name = None assert self.ts.index.name is None - self.assertIs(self.ts, self.ts) + assert self.ts is self.ts cp = self.ts.copy() cp.index.name = 'foo' @@ -203,7 +203,7 @@ def test_keys(self): # HACK: By doing this in two stages, we avoid 2to3 wrapping the call # to .keys() in a list() getkeys = self.ts.keys - self.assertIs(getkeys(), self.ts.index) + assert getkeys() is self.ts.index def test_values(self): tm.assert_almost_equal(self.ts.values, self.ts, check_dtype=False) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index e02698f96ca49..57cce1d1cf199 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -55,7 +55,7 @@ def test_constructor(self): # Mixed type Series mixed = Series(['hello', np.NaN], index=[0, 1]) self.assertEqual(mixed.dtype, np.object_) - self.assertIs(mixed[1], np.NaN) + assert mixed[1] is np.NaN self.assertFalse(self.empty.index.is_all_dates) self.assertFalse(Series({}).index.is_all_dates) @@ -226,7 +226,7 @@ def test_series_ctor_plus_datetimeindex(self): data = dict((k, 1) for k in rng) result = Series(data, index=rng) - self.assertIs(result.index, rng) + assert result.index is rng def test_constructor_default_index(self): s = Series([0, 1, 2]) diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index ac3e3a2abbd69..ecb457b4ff1b0 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -368,7 +368,7 @@ def test_dt_accessor_api(self): # GH 9322 from pandas.core.indexes.accessors import ( CombinedDatetimelikeProperties, DatetimeProperties) - self.assertIs(Series.dt, CombinedDatetimelikeProperties) + assert Series.dt is CombinedDatetimelikeProperties s = Series(date_range('2000-01-01', periods=3)) assert isinstance(s.dt, DatetimeProperties) diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 9872a1982a770..135e208877f2d 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -786,13 +786,13 @@ def test_setitem_dtypes(self): def test_set_value(self): idx = self.ts.index[10] res = self.ts.set_value(idx, 0) - self.assertIs(res, self.ts) + assert res is self.ts self.assertEqual(self.ts[idx], 0) # equiv s = self.series.copy() res = s.set_value('foobar', 0) - self.assertIs(res, s) + assert res is s self.assertEqual(res.index[-1], 'foobar') self.assertEqual(res['foobar'], 0) @@ -2659,16 +2659,16 @@ def setUp(self): def test_set_none_nan(self): self.series[3] = None - self.assertIs(self.series[3], NaT) + assert self.series[3] is NaT self.series[3:5] = None - self.assertIs(self.series[4], NaT) + assert self.series[4] is NaT self.series[5] = np.nan - self.assertIs(self.series[5], NaT) + assert self.series[5] is NaT self.series[5:7] = np.nan - self.assertIs(self.series[6], NaT) + assert self.series[6] is NaT def test_nat_operations(self): # GH 8617 diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index e0f1c8e060378..a67d097f341db 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -103,10 +103,10 @@ def test_NaT_cast(self): def test_set_none_nan(self): # currently Period is stored as object dtype, not as NaT self.series[3] = None - self.assertIs(self.series[3], None) + assert self.series[3] is None self.series[3:5] = None - self.assertIs(self.series[4], None) + assert self.series[4] is None self.series[5] = np.nan self.assertTrue(np.isnan(self.series[5])) diff --git a/pandas/tests/series/test_sorting.py b/pandas/tests/series/test_sorting.py index 7ab2ec245f611..6fe18e712a29d 100644 --- a/pandas/tests/series/test_sorting.py +++ b/pandas/tests/series/test_sorting.py @@ -129,16 +129,17 @@ def test_sort_index_inplace(self): # descending random_order = self.ts.reindex(rindex) result = random_order.sort_index(ascending=False, inplace=True) - self.assertIs(result, None, - msg='sort_index() inplace should return None') - assert_series_equal(random_order, self.ts.reindex(self.ts.index[::-1])) + + assert result is None + tm.assert_series_equal(random_order, self.ts.reindex( + self.ts.index[::-1])) # ascending random_order = self.ts.reindex(rindex) result = random_order.sort_index(ascending=True, inplace=True) - self.assertIs(result, None, - msg='sort_index() inplace should return None') - assert_series_equal(random_order, self.ts) + + assert result is None + tm.assert_series_equal(random_order, self.ts) def test_sort_index_multiindex(self): diff --git a/pandas/tests/sparse/test_frame.py b/pandas/tests/sparse/test_frame.py index ccb72d1f0d788..cf6d80e9c0133 100644 --- a/pandas/tests/sparse/test_frame.py +++ b/pandas/tests/sparse/test_frame.py @@ -593,7 +593,7 @@ def test_apply(self): exp = self.frame.to_dense().apply(np.sum, broadcast=True) tm.assert_frame_equal(broadcasted.to_dense(), exp) - self.assertIs(self.empty.apply(np.sqrt), self.empty) + assert self.empty.apply(np.sqrt) is self.empty from pandas.core import nanops applied = self.frame.apply(np.sum) diff --git a/pandas/tests/sparse/test_libsparse.py b/pandas/tests/sparse/test_libsparse.py index 00e01b8ba14bc..14038777fdd02 100644 --- a/pandas/tests/sparse/test_libsparse.py +++ b/pandas/tests/sparse/test_libsparse.py @@ -469,7 +469,7 @@ def test_to_int_index(self): def test_to_block_index(self): index = BlockIndex(10, [0, 5], [4, 5]) - self.assertIs(index.to_block_index(), index) + assert index.to_block_index() is index class TestIntIndex(tm.TestCase): @@ -554,7 +554,7 @@ def _check_case(xloc, xlen, yloc, ylen, eloc, elen): def test_to_int_index(self): index = IntIndex(10, [2, 3, 4, 5, 6]) - self.assertIs(index.to_int_index(), index) + assert index.to_int_index() is index class TestSparseOperators(tm.TestCase): diff --git a/pandas/tests/sparse/test_series.py b/pandas/tests/sparse/test_series.py index 2fd7ac3d13b98..1502aaa7e0b9e 100644 --- a/pandas/tests/sparse/test_series.py +++ b/pandas/tests/sparse/test_series.py @@ -664,7 +664,7 @@ def _check(values, index1, index2, fill_value): first_series = SparseSeries(values, sparse_index=index1, fill_value=fill_value) reindexed = first_series.sparse_reindex(index2) - self.assertIs(reindexed.sp_index, index2) + assert reindexed.sp_index is index2 int_indices1 = index1.to_int_index().indices int_indices2 = index2.to_int_index().indices diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 5814ae3494b44..bec743fac18e1 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -525,7 +525,7 @@ def test_value_counts_unique_nunique_null(self): # unable to compare NaT / nan tm.assert_numpy_array_equal(result[1:], values[2:].asobject.values) - self.assertIs(result[0], pd.NaT) + assert result[0] is pd.NaT else: tm.assert_numpy_array_equal(result[1:], values[2:]) @@ -1018,15 +1018,17 @@ class T(NoNewAttributesMixin): pass t = T() - self.assertFalse(hasattr(t, "__frozen")) + assert not hasattr(t, "__frozen") + t.a = "test" - self.assertEqual(t.a, "test") + assert t.a == "test" + t._freeze() - # self.assertTrue("__frozen" not in dir(t)) - self.assertIs(getattr(t, "__frozen"), True) + assert "__frozen" in dir(t) + assert getattr(t, "__frozen") def f(): t.b = "test" pytest.raises(AttributeError, f) - self.assertFalse(hasattr(t, "b")) + assert not hasattr(t, "b") diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 2b9afb8e1dd6b..d516448acd876 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -4218,7 +4218,7 @@ def get_dir(s): def test_cat_accessor_api(self): # GH 9322 from pandas.core.categorical import CategoricalAccessor - self.assertIs(Series.cat, CategoricalAccessor) + assert Series.cat is CategoricalAccessor s = Series(list('aabbcde')).astype('category') assert isinstance(s.cat, CategoricalAccessor) diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index adca47488413d..f58a6d4b146bd 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -382,7 +382,7 @@ def test_pickle(self, mgr): assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) # share ref_items - # self.assertIs(mgr2.blocks[0].ref_items, mgr2.blocks[1].ref_items) + # assert mgr2.blocks[0].ref_items is mgr2.blocks[1].ref_items # GH2431 assert hasattr(mgr2, "_is_consolidated") diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index a7a80c635a364..173ac97691b3b 100755 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -198,21 +198,21 @@ def test_reindex(self): def test_reindex_preserve_levels(self): new_index = self.ymd.index[::10] chunk = self.ymd.reindex(new_index) - self.assertIs(chunk.index, new_index) + assert chunk.index is new_index chunk = self.ymd.loc[new_index] - self.assertIs(chunk.index, new_index) + assert chunk.index is new_index with catch_warnings(record=True): chunk = self.ymd.ix[new_index] - self.assertIs(chunk.index, new_index) + assert chunk.index is new_index ymdT = self.ymd.T chunk = ymdT.reindex(columns=new_index) - self.assertIs(chunk.columns, new_index) + assert chunk.columns is new_index chunk = ymdT.loc[:, new_index] - self.assertIs(chunk.columns, new_index) + assert chunk.columns is new_index def test_repr_to_string(self): repr(self.frame) @@ -939,7 +939,7 @@ def test_stack_mixed_dtype(self): stacked = df.stack() result = df['foo'].stack().sort_index() tm.assert_series_equal(stacked['foo'], result, check_names=False) - self.assertIs(result.name, None) + assert result.name is None self.assertEqual(stacked['bar'].dtype, np.float_) def test_unstack_bug(self): diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 24248d735adb0..1d0788ae160dd 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -1447,9 +1447,9 @@ def test_reindex_multi(self): major=self.panel.major_axis, minor=self.panel.minor_axis, copy=False) - self.assertIs(result.items, self.panel.items) - self.assertIs(result.major_axis, self.panel.major_axis) - self.assertIs(result.minor_axis, self.panel.minor_axis) + assert result.items is self.panel.items + assert result.major_axis is self.panel.major_axis + assert result.minor_axis is self.panel.minor_axis result = self.panel.reindex( items=self.panel.items, @@ -1612,13 +1612,13 @@ def test_truncate_fillna_bug(self): def test_swapaxes(self): with catch_warnings(record=True): result = self.panel.swapaxes('items', 'minor') - self.assertIs(result.items, self.panel.minor_axis) + assert result.items is self.panel.minor_axis result = self.panel.swapaxes('items', 'major') - self.assertIs(result.items, self.panel.major_axis) + assert result.items is self.panel.major_axis result = self.panel.swapaxes('major', 'minor') - self.assertIs(result.major_axis, self.panel.minor_axis) + assert result.major_axis is self.panel.minor_axis panel = self.panel.copy() result = panel.swapaxes('major', 'minor') @@ -1628,7 +1628,7 @@ def test_swapaxes(self): # this should also work result = self.panel.swapaxes(0, 1) - self.assertIs(result.items, self.panel.major_axis) + assert result.items is self.panel.major_axis # this works, but return a copy result = self.panel.swapaxes('items', 'items') diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index 33b17bc04cd79..05b42cdf00e94 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -867,23 +867,23 @@ def test_fillna(self): def test_swapaxes(self): with catch_warnings(record=True): result = self.panel4d.swapaxes('labels', 'items') - self.assertIs(result.items, self.panel4d.labels) + assert result.items is self.panel4d.labels result = self.panel4d.swapaxes('labels', 'minor') - self.assertIs(result.labels, self.panel4d.minor_axis) + assert result.labels is self.panel4d.minor_axis result = self.panel4d.swapaxes('items', 'minor') - self.assertIs(result.items, self.panel4d.minor_axis) + assert result.items is self.panel4d.minor_axis result = self.panel4d.swapaxes('items', 'major') - self.assertIs(result.items, self.panel4d.major_axis) + assert result.items is self.panel4d.major_axis result = self.panel4d.swapaxes('major', 'minor') - self.assertIs(result.major_axis, self.panel4d.minor_axis) + assert result.major_axis is self.panel4d.minor_axis # this should also work result = self.panel4d.swapaxes(0, 1) - self.assertIs(result.labels, self.panel4d.items) + assert result.labels is self.panel4d.items # this works, but return a copy result = self.panel4d.swapaxes('items', 'items') diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index 107720d90e489..761bfa6bfe29a 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -24,7 +24,7 @@ class TestStringMethods(tm.TestCase): def test_api(self): # GH 6106, GH 9322 - self.assertIs(Series.str, strings.StringMethods) + assert Series.str is strings.StringMethods assert isinstance(Series(['']).str, strings.StringMethods) # GH 9184 diff --git a/pandas/tests/test_util.py b/pandas/tests/test_util.py index c9b2e1c9c1c75..375463ec25c36 100644 --- a/pandas/tests/test_util.py +++ b/pandas/tests/test_util.py @@ -42,7 +42,7 @@ def test_deprecate_kwarg(self): x = 78 with tm.assert_produces_warning(FutureWarning): result = self.f1(old=x) - self.assertIs(result, x) + assert result is x with tm.assert_produces_warning(None): self.f1(new=x) @@ -338,7 +338,7 @@ def test_more_than_one_ref(self): with pytest.raises(BadMove) as e: def handle_success(type_, value, tb): - self.assertIs(value.args[0], b) + assert value.args[0] is b return type(e).handle_success(e, type_, value, tb) # super e.handle_success = handle_success diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py index 40ff2421a9f63..e3f2c242e3294 100644 --- a/pandas/tests/tseries/test_timezones.py +++ b/pandas/tests/tseries/test_timezones.py @@ -291,7 +291,7 @@ def test_create_with_tz(self): self.assertEqual(stamp, rng[1]) utc_stamp = Timestamp('3/11/2012 05:00', tz='utc') - self.assertIs(utc_stamp.tzinfo, pytz.utc) + assert utc_stamp.tzinfo is pytz.utc self.assertEqual(utc_stamp.hour, 5) stamp = Timestamp('3/11/2012 05:00').tz_localize('utc') @@ -414,7 +414,7 @@ def test_with_tz(self): # just want it to work start = datetime(2011, 3, 12, tzinfo=pytz.utc) dr = bdate_range(start, periods=50, freq=offsets.Hour()) - self.assertIs(dr.tz, pytz.utc) + assert dr.tz is pytz.utc # DateRange with naive datetimes dr = bdate_range('1/1/2005', '1/1/2009', tz=pytz.utc) @@ -422,15 +422,15 @@ def test_with_tz(self): # normalized central = dr.tz_convert(tz) - self.assertIs(central.tz, tz) + assert central.tz is tz comp = self.localize(tz, central[0].to_pydatetime().replace( tzinfo=None)).tzinfo - self.assertIs(central[0].tz, comp) + assert central[0].tz is comp # compare vs a localized tz comp = self.localize(tz, dr[0].to_pydatetime().replace(tzinfo=None)).tzinfo - self.assertIs(central[0].tz, comp) + assert central[0].tz is comp # datetimes with tzinfo set dr = bdate_range(datetime(2005, 1, 1, tzinfo=pytz.utc), @@ -762,14 +762,14 @@ def test_convert_tz_aware_datetime_datetime(self): converted = to_datetime(dates_aware, utc=True) ex_vals = np.array([Timestamp(x).value for x in dates_aware]) tm.assert_numpy_array_equal(converted.asi8, ex_vals) - self.assertIs(converted.tz, pytz.utc) + assert converted.tz is pytz.utc def test_to_datetime_utc(self): from dateutil.parser import parse arr = np.array([parse('2012-06-13T01:39:00Z')], dtype=object) result = to_datetime(arr, utc=True) - self.assertIs(result.tz, pytz.utc) + assert result.tz is pytz.utc def test_to_datetime_tzlocal(self): from dateutil.parser import parse @@ -780,12 +780,12 @@ def test_to_datetime_tzlocal(self): arr = np.array([dt], dtype=object) result = to_datetime(arr, utc=True) - self.assertIs(result.tz, pytz.utc) + assert result.tz is pytz.utc rng = date_range('2012-11-03 03:00', '2012-11-05 03:00', tz=tzlocal()) arr = rng.to_pydatetime() result = to_datetime(arr, utc=True) - self.assertIs(result.tz, pytz.utc) + assert result.tz is pytz.utc def test_frame_no_datetime64_dtype(self): @@ -1554,18 +1554,18 @@ def test_equal_join_ensure_utc(self): ts_moscow = ts.tz_convert('Europe/Moscow') result = ts + ts_moscow - self.assertIs(result.index.tz, pytz.utc) + assert result.index.tz is pytz.utc result = ts_moscow + ts - self.assertIs(result.index.tz, pytz.utc) + assert result.index.tz is pytz.utc df = DataFrame({'a': ts}) df_moscow = df.tz_convert('Europe/Moscow') result = df + df_moscow - self.assertIs(result.index.tz, pytz.utc) + assert result.index.tz is pytz.utc result = df_moscow + df - self.assertIs(result.index.tz, pytz.utc) + assert result.index.tz is pytz.utc def test_arith_utc_convert(self): rng = date_range('1/1/2011', periods=100, freq='H', tz='utc') diff --git a/pandas/util/testing.py b/pandas/util/testing.py index b28bd6a696bda..08b298fabdd57 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1060,12 +1060,6 @@ def is_sorted(seq): return assert_numpy_array_equal(seq, np.sort(np.array(seq))) -def assertIs(first, second, msg=''): - """Checks that 'first' is 'second'""" - a, b = first, second - assert a is b, "%s: %r is not %r" % (msg.format(a, b), a, b) - - def assert_categorical_equal(left, right, check_dtype=True, obj='Categorical', check_category_order=True): """Test that Categoricals are equivalent.
Title is self-explanatory. Partially addresses #15990.
https://api.github.com/repos/pandas-dev/pandas/pulls/16105
2017-04-24T02:39:24Z
2017-04-24T10:04:41Z
2017-04-24T10:04:41Z
2017-04-24T15:48:26Z
PERF: maybe_convert_numeric speedup
diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx index f7dbae4ab736e..d87a0641291b1 100644 --- a/pandas/_libs/src/inference.pyx +++ b/pandas/_libs/src/inference.pyx @@ -96,7 +96,7 @@ cdef class Seen(object): encountered when trying to perform type conversions. """ - cdef public: + cdef: bint int_ # seen_int bint bool_ # seen_bool bint null_ # seen_null @@ -185,7 +185,7 @@ cdef class Seen(object): self.null_ = 1 self.float_ = 1 - def saw_int(self, val): + cdef saw_int(self, object val): """ Set flags indicating that an integer value was encountered. @@ -196,7 +196,7 @@ cdef class Seen(object): """ self.int_ = 1 self.sint_ = self.sint_ or (val < 0) - self.uint_ = self.uint_ or (val > iINT64_MAX) + self.uint_ = self.uint_ or (val > oINT64_MAX) @property def numeric_(self): @@ -908,11 +908,15 @@ cpdef bint is_interval_array(ndarray[object] values): cdef extern from "parse_helper.h": inline int floatify(object, double *result, int *maybe_int) except -1 -cdef int64_t iINT64_MAX = <int64_t> INT64_MAX -cdef int64_t iINT64_MIN = <int64_t> INT64_MIN -cdef uint64_t iUINT64_MAX = <uint64_t> UINT64_MAX +# constants that will be compared to potentially arbitrarily large +# python int +cdef object oINT64_MAX = <int64_t> INT64_MAX +cdef object oINT64_MIN = <int64_t> INT64_MIN +cdef object oUINT64_MAX = <uint64_t> UINT64_MAX +@cython.boundscheck(False) +@cython.wraparound(False) def maybe_convert_numeric(ndarray[object] values, set na_values, bint convert_empty=True, bint coerce_numeric=False): """ @@ -943,6 +947,17 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, ------- numeric_array : array of converted object values to numerical ones """ + # fastpath for ints - try to convert all based on first value + cdef object val = values[0] + if util.is_integer_object(val): + try: + maybe_ints = values.astype('i8') + if (maybe_ints == values).all(): + return maybe_ints + except (ValueError, OverflowError, TypeError): + pass + + # otherwise, iterate and do full infererence cdef: int status, maybe_int Py_ssize_t i, n = values.size @@ -952,7 +967,6 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, ndarray[int64_t] ints = np.empty(n, dtype='i8') ndarray[uint64_t] uints = np.empty(n, dtype='u8') ndarray[uint8_t] bools = np.empty(n, dtype='u1') - object val float64_t fval for i in range(n): @@ -962,21 +976,23 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, seen.saw_null() floats[i] = complexes[i] = nan elif util.is_float_object(val): - if val != val: + fval = val + if fval != fval: seen.null_ = True - floats[i] = complexes[i] = val + floats[i] = complexes[i] = fval seen.float_ = True elif util.is_integer_object(val): floats[i] = complexes[i] = val - as_int = int(val) - seen.saw_int(as_int) + val = int(val) + seen.saw_int(val) + + if val >= 0: + uints[i] = val - if as_int >= 0: - uints[i] = as_int - if as_int <= iINT64_MAX: - ints[i] = as_int + if val <= oINT64_MAX: + ints[i] = val elif util.is_bool_object(val): floats[i] = uints[i] = ints[i] = bools[i] = val seen.bool_ = True @@ -1017,12 +1033,12 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, seen.saw_int(as_int) if not (seen.float_ or as_int in na_values): - if as_int < iINT64_MIN or as_int > iUINT64_MAX: + if as_int < oINT64_MIN or as_int > oUINT64_MAX: raise ValueError('Integer out of range.') if as_int >= 0: uints[i] = as_int - if as_int <= iINT64_MAX: + if as_int <= oINT64_MAX: ints[i] = as_int else: seen.float_ = True @@ -1053,6 +1069,8 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, return ints +@cython.boundscheck(False) +@cython.wraparound(False) def maybe_convert_objects(ndarray[object] objects, bint try_float=0, bint safe=0, bint convert_datetime=0, bint convert_timedelta=0):
xref #16043 Probably more to be done, but picks up some easy performance on the int path. For some reason I'm having trouble running asv, here are some timings. ### setup ``` ints = np.array(list(range(1000000)), dtype=object) floats = np.array([float(x) for x in range(1000000)], dtype=object) ints_with_float = ints.copy() ints_with_float[-1] = 1.2 ``` ### Master ``` In [2]: %timeit pd.to_numeric(floats) 10 loops, best of 3: 132 ms per loop In [3]: %timeit pd.to_numeric(ints) 1 loop, best of 3: 437 ms per loop In [4]: %timeit pd.to_numeric(ints_with_float) 1 loop, best of 3: 444 ms per loop ``` ### PR ``` In [5]: %timeit pd.to_numeric(floats) 10 loops, best of 3: 88.9 ms per loop In [6]: %timeit pd.to_numeric(ints) 10 loops, best of 3: 57.6 ms per loop In [7]: %timeit pd.to_numeric(ints_with_float) 1 loop, best of 3: 392 ms per loop ```
https://api.github.com/repos/pandas-dev/pandas/pulls/16104
2017-04-23T22:54:10Z
2017-04-25T01:55:29Z
2017-04-25T01:55:29Z
2017-04-25T08:30:41Z
MAINT: Remove assertIsNone from testing
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index eacbd2b390154..6ec06f75de06d 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -1336,7 +1336,7 @@ def test_multi_line_expression(self): c = a + b d = c + b""", inplace=True) assert_frame_equal(expected, df) - self.assertIsNone(ans) + assert ans is None expected['a'] = expected['a'] - 1 expected['e'] = expected['a'] + 2 @@ -1344,7 +1344,7 @@ def test_multi_line_expression(self): a = a - 1 e = a + 2""", inplace=True) assert_frame_equal(expected, df) - self.assertIsNone(ans) + assert ans is None # multi-line not valid if not all assignments with pytest.raises(ValueError): @@ -1384,7 +1384,7 @@ def test_multi_line_expression_local_variable(self): d = c + @local_var """, inplace=True) assert_frame_equal(expected, df) - self.assertIsNone(ans) + assert ans is None def test_assignment_in_query(self): # GH 8664 diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 879458a38770d..e060e863c0431 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -38,7 +38,7 @@ def test_copy_index_name_checking(self): ind.name = None cp = self.frame.copy() getattr(cp, attr).name = 'foo' - self.assertIsNone(getattr(self.frame, attr).name) + assert getattr(self.frame, attr).name is None def test_getitem_pop_assign_name(self): s = self.frame['A'] @@ -116,7 +116,7 @@ def test_new_empty_index(self): df1 = DataFrame(randn(0, 3)) df2 = DataFrame(randn(0, 3)) df1.index.name = 'foo' - self.assertIsNone(df2.index.name) + assert df2.index.name is None def test_array_interface(self): with np.errstate(all='ignore'): diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 3bcc058316f77..737d9f8e50477 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -91,7 +91,7 @@ def test_constructor_dtype_nocast_view(self): def test_constructor_dtype_list_data(self): df = DataFrame([[1, '2'], [None, 'a']], dtype=object) - self.assertIsNone(df.loc[1, 0]) + assert df.loc[1, 0] is None self.assertEqual(df.loc[0, 1], '2') def test_constructor_list_frames(self): diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 12c5b33fcbce9..088f863e5358b 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -81,7 +81,7 @@ def test_get(self): b = self.frame.get('B') assert_series_equal(b, self.frame['B']) - self.assertIsNone(self.frame.get('foo')) + assert self.frame.get('foo') is None assert_series_equal(self.frame.get('foo', self.frame['B']), self.frame['B']) # None @@ -89,7 +89,7 @@ def test_get(self): for df in [DataFrame(), DataFrame(columns=list('AB')), DataFrame(columns=list('AB'), index=range(3))]: result = df.get(None) - self.assertIsNone(result) + assert result is None def test_getitem_iterator(self): idx = iter(['A', 'B', 'C']) diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index efbdc05ba23c8..630fa5ad57fad 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -189,7 +189,7 @@ def test_latex_repr(self): self.assertEqual(result, df._repr_latex_()) # GH 12182 - self.assertIsNone(df._repr_latex_()) + assert df._repr_latex_() is None @tm.capture_stdout def test_info(self): diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index cf42f751f390a..090f742a69b63 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -415,8 +415,8 @@ def test_first_last_valid(self): # GH12800 empty = DataFrame() - self.assertIsNone(empty.last_valid_index()) - self.assertIsNone(empty.first_valid_index()) + assert empty.last_valid_index() is None + assert empty.first_valid_index() is None def test_at_time_frame(self): rng = date_range('1/1/2000', '1/5/2000', freq='5min') diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 05fe1c6f58e9a..02ef9e614150c 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1972,11 +1972,11 @@ def test_apply_frame_yield_constant(self): # GH13568 result = self.df.groupby(['A', 'B']).apply(len) self.assertTrue(isinstance(result, Series)) - self.assertIsNone(result.name) + assert result.name is None result = self.df.groupby(['A', 'B'])[['C', 'D']].apply(len) self.assertTrue(isinstance(result, Series)) - self.assertIsNone(result.name) + assert result.name is None def test_apply_frame_to_series(self): grouped = self.df.groupby(['A', 'B']) @@ -2954,7 +2954,7 @@ def test_no_nonsense_name(self): s.name = None result = s.groupby(self.frame['A']).agg(np.sum) - self.assertIsNone(result.name) + assert result.name is None def test_multifunc_sum_bug(self): # GH #1065 @@ -3060,7 +3060,7 @@ def test_no_dummy_key_names(self): # GH #1291 result = self.df.groupby(self.df['A'].values).sum() - self.assertIsNone(result.index.name) + assert result.index.name is None result = self.df.groupby([self.df['A'].values, self.df['B'].values ]).sum() diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index ff90c924933f3..fa1f31ded5f1c 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -195,7 +195,7 @@ def test_set_name_methods(self): res = ind.rename(new_name, inplace=True) # should return None - self.assertIsNone(res) + assert res is None self.assertEqual(ind.name, new_name) self.assertEqual(ind.names, [new_name]) # with assertRaisesRegexp(TypeError, "list-like"): diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 93fc855178800..31e795a80f2e6 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -480,7 +480,7 @@ def test_take(self): for taken in [taken1, taken2]: tm.assert_index_equal(taken, expected) assert isinstance(taken, DatetimeIndex) - self.assertIsNone(taken.freq) + assert taken.freq is None self.assertEqual(taken.tz, expected.tz) self.assertEqual(taken.name, expected.name) diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 235c8f1de1fae..de41f321b245b 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -197,7 +197,7 @@ def test_repeat_range(self): rng = date_range('1/1/2000', '1/1/2001') result = rng.repeat(5) - self.assertIsNone(result.freq) + assert result.freq is None self.assertEqual(len(result), 5 * len(rng)) for tz in self.tz: @@ -206,14 +206,14 @@ def test_repeat_range(self): '2001-01-02', '2001-01-02'], tz=tz) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) - self.assertIsNone(res.freq) + assert res.freq is None index = pd.date_range('2001-01-01', periods=2, freq='2D', tz=tz) exp = pd.DatetimeIndex(['2001-01-01', '2001-01-01', '2001-01-03', '2001-01-03'], tz=tz) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) - self.assertIsNone(res.freq) + assert res.freq is None index = pd.DatetimeIndex(['2001-01-01', 'NaT', '2003-01-01'], tz=tz) @@ -223,7 +223,7 @@ def test_repeat_range(self): tz=tz) for res in [index.repeat(3), np.repeat(index, 3)]: tm.assert_index_equal(res, exp) - self.assertIsNone(res.freq) + assert res.freq is None def test_repeat(self): reps = 2 @@ -242,7 +242,7 @@ def test_repeat(self): res = rng.repeat(reps) tm.assert_index_equal(res, expected_rng) - self.assertIsNone(res.freq) + assert res.freq is None tm.assert_index_equal(np.repeat(rng, reps), expected_rng) tm.assertRaisesRegexp(ValueError, msg, np.repeat, @@ -694,18 +694,18 @@ def test_order(self): for idx, expected in [(idx1, exp1), (idx2, exp2), (idx3, exp3)]: ordered = idx.sort_values() tm.assert_index_equal(ordered, expected) - self.assertIsNone(ordered.freq) + assert ordered.freq is None ordered = idx.sort_values(ascending=False) tm.assert_index_equal(ordered, expected[::-1]) - self.assertIsNone(ordered.freq) + assert ordered.freq is None ordered, indexer = idx.sort_values(return_indexer=True) tm.assert_index_equal(ordered, expected) exp = np.array([0, 4, 3, 1, 2]) tm.assert_numpy_array_equal(indexer, exp, check_dtype=False) - self.assertIsNone(ordered.freq) + assert ordered.freq is None ordered, indexer = idx.sort_values(return_indexer=True, ascending=False) @@ -713,7 +713,7 @@ def test_order(self): exp = np.array([2, 1, 3, 4, 0]) tm.assert_numpy_array_equal(indexer, exp, check_dtype=False) - self.assertIsNone(ordered.freq) + assert ordered.freq is None def test_getitem(self): idx1 = pd.date_range('2011-01-01', '2011-01-31', freq='D', name='idx') @@ -757,10 +757,10 @@ def test_drop_duplicates_metadata(self): self.assertEqual(idx.freq, result.freq) idx_dup = idx.append(idx) - self.assertIsNone(idx_dup.freq) # freq is reset + assert idx_dup.freq is None # freq is reset result = idx_dup.drop_duplicates() tm.assert_index_equal(idx, result) - self.assertIsNone(result.freq) + assert result.freq is None def test_drop_duplicates(self): # to check Index/Series compat @@ -816,14 +816,14 @@ def test_take(self): '2011-01-06'], freq=None, tz=idx.tz, name='idx') tm.assert_index_equal(result, expected) - self.assertIsNone(result.freq) + assert result.freq is None result = idx.take([-3, 2, 5]) expected = DatetimeIndex(['2011-01-29', '2011-01-03', '2011-01-06'], freq=None, tz=idx.tz, name='idx') tm.assert_index_equal(result, expected) - self.assertIsNone(result.freq) + assert result.freq is None def test_take_invalid_kwargs(self): idx = pd.date_range('2011-01-01', '2011-01-31', freq='D', name='idx') @@ -1145,7 +1145,7 @@ def test_getitem(self): fancy_indexed = self.rng[[4, 3, 2, 1, 0]] self.assertEqual(len(fancy_indexed), 5) assert isinstance(fancy_indexed, DatetimeIndex) - self.assertIsNone(fancy_indexed.freq) + assert fancy_indexed.freq is None # 32-bit vs. 64-bit platforms self.assertEqual(self.rng[4], self.rng[np.int_(4)]) @@ -1240,7 +1240,7 @@ def test_getitem(self): fancy_indexed = self.rng[[4, 3, 2, 1, 0]] self.assertEqual(len(fancy_indexed), 5) assert isinstance(fancy_indexed, DatetimeIndex) - self.assertIsNone(fancy_indexed.freq) + assert fancy_indexed.freq is None # 32-bit vs. 64-bit platforms self.assertEqual(self.rng[4], self.rng[np.int_(4)]) diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 3191b0e2c586d..3e6ed7756b9bd 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -65,7 +65,7 @@ def test_union_freq_both_none(self): result = expected.union(expected) tm.assert_index_equal(result, expected) - self.assertIsNone(result.freq) + assert result.freq is None def test_union_dataframe_index(self): rng1 = date_range('1/1/1999', '1/1/2012', freq='MS') @@ -137,7 +137,7 @@ def test_intersection(self): result = base.intersection(rng) tm.assert_index_equal(result, expected) self.assertEqual(result.name, expected.name) - self.assertIsNone(result.freq) + assert result.freq is None self.assertEqual(result.tz, expected.tz) # empty same freq GH2129 @@ -251,7 +251,7 @@ def test_outer_join(self): the_join = left.join(right, how='outer') assert isinstance(the_join, DatetimeIndex) - self.assertIsNone(the_join.freq) + assert the_join.freq is None # non-overlapping, no gap left = self.rng[:5] @@ -265,7 +265,7 @@ def test_outer_join(self): the_join = self.rng.join(rng, how='outer') assert isinstance(the_join, DatetimeIndex) - self.assertIsNone(the_join.freq) + assert the_join.freq is None def test_union_not_cacheable(self): rng = date_range('1/1/2000', periods=50, freq=Minute()) @@ -395,7 +395,7 @@ def test_outer_join(self): the_join = left.join(right, how='outer') assert isinstance(the_join, DatetimeIndex) - self.assertIsNone(the_join.freq) + assert the_join.freq is None # non-overlapping, no gap left = self.rng[:5] @@ -409,7 +409,7 @@ def test_outer_join(self): the_join = self.rng.join(rng, how='outer') assert isinstance(the_join, DatetimeIndex) - self.assertIsNone(the_join.freq) + assert the_join.freq is None def test_intersection_bug(self): # GH #771 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 7db7410d79349..91d5068ee9f19 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -659,12 +659,12 @@ def test_intersection(self): second.name = 'B' intersect = first.intersection(second) - self.assertIsNone(intersect.name) + assert intersect.name is None first.name = None second.name = 'B' intersect = first.intersection(second) - self.assertIsNone(intersect.name) + assert intersect.name is None def test_union(self): first = self.strIndex[5:20] @@ -844,7 +844,7 @@ def test_append_empty_preserve_name(self): right = Index([1, 2, 3], name='bar') result = left.append(right) - self.assertIsNone(result.name) + assert result.name is None def test_add_string(self): # from bug report @@ -896,12 +896,12 @@ def test_symmetric_difference(self): result = idx1.symmetric_difference(idx2) expected = Index([1, 5]) self.assertTrue(tm.equalContents(result, expected)) - self.assertIsNone(result.name) + assert result.name is None # __xor__ syntax expected = idx1 ^ idx2 self.assertTrue(tm.equalContents(result, expected)) - self.assertIsNone(result.name) + assert result.name is None # multiIndex idx1 = MultiIndex.from_tuples(self.tuples) @@ -1015,7 +1015,7 @@ def test_format_none(self): idx = Index(values) idx.format() - self.assertIsNone(idx[3]) + assert idx[3] is None def test_logical_compat(self): idx = self.create_index() diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 98fce437d26c8..7a9b3c1c4b5d6 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -138,7 +138,7 @@ def test_set_name_methods(self): ind.set_names(new_names + new_names) new_names2 = [name + "SUFFIX2" for name in new_names] res = ind.set_names(new_names2, inplace=True) - self.assertIsNone(res) + assert res is None self.assertEqual(ind.names, new_names2) # set names for specific level (# GH7792) @@ -147,7 +147,7 @@ def test_set_name_methods(self): self.assertEqual(ind.names, [new_names[0], self.index_names[1]]) res = ind.set_names(new_names2[0], level=0, inplace=True) - self.assertIsNone(res) + assert res is None self.assertEqual(ind.names, [new_names2[0], self.index_names[1]]) # set names for multiple levels @@ -156,7 +156,7 @@ def test_set_name_methods(self): self.assertEqual(ind.names, new_names) res = ind.set_names(new_names2, level=[0, 1], inplace=True) - self.assertIsNone(res) + assert res is None self.assertEqual(ind.names, new_names2) def test_set_levels(self): @@ -182,7 +182,7 @@ def assert_matching(actual, expected, check_dtype=False): # level changing [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels, inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.levels, new_levels) # level changing specific level [w/o mutation] @@ -202,13 +202,13 @@ def assert_matching(actual, expected, check_dtype=False): # level changing specific level [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels[0], level=0, inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.levels, [new_levels[0], levels[1]]) assert_matching(self.index.levels, levels) ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels[1], level=1, inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.levels, [levels[0], new_levels[1]]) assert_matching(self.index.levels, levels) @@ -216,7 +216,7 @@ def assert_matching(actual, expected, check_dtype=False): ind2 = self.index.copy() inplace_return = ind2.set_levels(new_levels, level=[0, 1], inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.levels, new_levels) assert_matching(self.index.levels, levels) @@ -271,7 +271,7 @@ def assert_matching(actual, expected): # label changing [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels, inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.labels, new_labels) # label changing specific level [w/o mutation] @@ -291,13 +291,13 @@ def assert_matching(actual, expected): # label changing specific level [w/ mutation] ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels[0], level=0, inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.labels, [new_labels[0], labels[1]]) assert_matching(self.index.labels, labels) ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels[1], level=1, inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.labels, [labels[0], new_labels[1]]) assert_matching(self.index.labels, labels) @@ -305,7 +305,7 @@ def assert_matching(actual, expected): ind2 = self.index.copy() inplace_return = ind2.set_labels(new_labels, level=[0, 1], inplace=True) - self.assertIsNone(inplace_return) + assert inplace_return is None assert_matching(ind2.labels, new_labels) assert_matching(self.index.labels, labels) @@ -457,10 +457,10 @@ def test_set_value_keeps_names(self): columns=['one', 'two', 'three', 'four'], index=idx) df = df.sort_index() - self.assertIsNone(df.is_copy) + assert df.is_copy is None self.assertEqual(df.index.names, ('Name', 'Number')) df = df.set_value(('grethe', '4'), 'one', 99.34) - self.assertIsNone(df.is_copy) + assert df.is_copy is None self.assertEqual(df.index.names, ('Name', 'Number')) def test_copy_names(self): @@ -1158,7 +1158,7 @@ def test_get_loc_level(self): loc, new_index = index.get_loc_level((0, 1, 0)) expected = 1 self.assertEqual(loc, expected) - self.assertIsNone(new_index) + assert new_index is None pytest.raises(KeyError, index.get_loc_level, (2, 2)) @@ -2067,12 +2067,12 @@ def test_join_multi(self): exp_ridx = np.array([-1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1], dtype=np.intp) tm.assert_index_equal(jidx, midx) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, exp_ridx) # flip jidx, ridx, lidx = idx.join(midx, how='right', return_indexers=True) tm.assert_index_equal(jidx, midx) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, exp_ridx) def test_reindex(self): @@ -2082,7 +2082,7 @@ def test_reindex(self): result, indexer = self.index.reindex(list(self.index)) assert isinstance(result, MultiIndex) - self.assertIsNone(indexer) + assert indexer is None self.check_level_names(result, self.index.names) def test_reindex_level(self): diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 62aabaaef100c..56e0d858f1f0f 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -791,7 +791,7 @@ def test_join_left(self): assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, eridx) # monotonic @@ -801,7 +801,7 @@ def test_join_left(self): dtype=np.intp) assert isinstance(res, Int64Index) tm.assert_index_equal(res, eres) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, eridx) # non-unique @@ -828,7 +828,7 @@ def test_join_right(self): assert isinstance(other, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) - self.assertIsNone(ridx) + assert ridx is None # monotonic res, lidx, ridx = self.index.join(other_mono, how='right', @@ -838,7 +838,7 @@ def test_join_right(self): assert isinstance(other, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) - self.assertIsNone(ridx) + assert ridx is None # non-unique idx = Index([1, 1, 2, 5]) @@ -1031,7 +1031,7 @@ def test_join_left(self): assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, eridx) # monotonic @@ -1041,7 +1041,7 @@ def test_join_left(self): assert isinstance(res, UInt64Index) tm.assert_index_equal(res, eres) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, eridx) # non-unique @@ -1074,7 +1074,7 @@ def test_join_right(self): tm.assert_numpy_array_equal(lidx, elidx) assert isinstance(other, UInt64Index) tm.assert_index_equal(res, eres) - self.assertIsNone(ridx) + assert ridx is None # monotonic res, lidx, ridx = self.index.join(other_mono, how='right', @@ -1085,7 +1085,7 @@ def test_join_right(self): assert isinstance(other, UInt64Index) tm.assert_numpy_array_equal(lidx, elidx) tm.assert_index_equal(res, eres) - self.assertIsNone(ridx) + assert ridx is None # non-unique idx = UInt64Index(2**63 + np.array([1, 1, 2, 5], dtype='uint64')) diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py index 0b27eb0c34111..4b622ad3fce49 100644 --- a/pandas/tests/indexes/test_range.py +++ b/pandas/tests/indexes/test_range.py @@ -487,7 +487,7 @@ def test_join_left(self): assert isinstance(res, RangeIndex) tm.assert_index_equal(res, eres) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, eridx) # Join withRangeIndex @@ -498,7 +498,7 @@ def test_join_left(self): assert isinstance(res, RangeIndex) tm.assert_index_equal(res, eres) - self.assertIsNone(lidx) + assert lidx is None tm.assert_numpy_array_equal(ridx, eridx) def test_join_right(self): @@ -514,7 +514,7 @@ def test_join_right(self): assert isinstance(other, Int64Index) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) - self.assertIsNone(ridx) + assert ridx is None # Join withRangeIndex other = RangeIndex(25, 14, -1) @@ -526,7 +526,7 @@ def test_join_right(self): assert isinstance(other, RangeIndex) tm.assert_index_equal(res, eres) tm.assert_numpy_array_equal(lidx, elidx) - self.assertIsNone(ridx) + assert ridx is None def test_join_non_int_index(self): other = Index([3, 6, 7, 8, 10], dtype=object) diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index adf164977205f..a847467518b92 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -620,18 +620,18 @@ def test_order(self): for idx, expected in [(idx1, exp1), (idx1, exp1), (idx1, exp1)]: ordered = idx.sort_values() tm.assert_index_equal(ordered, expected) - self.assertIsNone(ordered.freq) + assert ordered.freq is None ordered = idx.sort_values(ascending=False) tm.assert_index_equal(ordered, expected[::-1]) - self.assertIsNone(ordered.freq) + assert ordered.freq is None ordered, indexer = idx.sort_values(return_indexer=True) tm.assert_index_equal(ordered, expected) exp = np.array([0, 4, 3, 1, 2]) tm.assert_numpy_array_equal(indexer, exp, check_dtype=False) - self.assertIsNone(ordered.freq) + assert ordered.freq is None ordered, indexer = idx.sort_values(return_indexer=True, ascending=False) @@ -639,7 +639,7 @@ def test_order(self): exp = np.array([2, 1, 3, 4, 0]) tm.assert_numpy_array_equal(indexer, exp, check_dtype=False) - self.assertIsNone(ordered.freq) + assert ordered.freq is None def test_getitem(self): idx1 = pd.timedelta_range('1 day', '31 day', freq='D', name='idx') @@ -681,10 +681,10 @@ def test_drop_duplicates_metadata(self): self.assertEqual(idx.freq, result.freq) idx_dup = idx.append(idx) - self.assertIsNone(idx_dup.freq) # freq is reset + assert idx_dup.freq is None # freq is reset result = idx_dup.drop_duplicates() tm.assert_index_equal(idx, result) - self.assertIsNone(result.freq) + assert result.freq is None def test_drop_duplicates(self): # to check Index/Series compat @@ -739,12 +739,12 @@ def test_take(self): result = idx.take([3, 2, 5]) expected = TimedeltaIndex(['4 day', '3 day', '6 day'], name='idx') tm.assert_index_equal(result, expected) - self.assertIsNone(result.freq) + assert result.freq is None result = idx.take([-3, 2, 5]) expected = TimedeltaIndex(['29 day', '3 day', '6 day'], name='idx') tm.assert_index_equal(result, expected) - self.assertIsNone(result.freq) + assert result.freq is None def test_take_invalid_kwargs(self): idx = pd.timedelta_range('1 day', '31 day', freq='D', name='idx') @@ -808,7 +808,7 @@ def test_repeat(self): exp = pd.TimedeltaIndex(['1 days', '1 days', '2 days', '2 days']) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) - self.assertIsNone(res.freq) + assert res.freq is None index = TimedeltaIndex(['1 days', 'NaT', '3 days']) exp = TimedeltaIndex(['1 days', '1 days', '1 days', @@ -816,7 +816,7 @@ def test_repeat(self): '3 days', '3 days', '3 days']) for res in [index.repeat(3), np.repeat(index, 3)]: tm.assert_index_equal(res, exp) - self.assertIsNone(res.freq) + assert res.freq is None def test_nat(self): self.assertIs(pd.TimedeltaIndex._na_value, pd.NaT) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 9ca207876520f..b93f76c14dcfe 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -208,7 +208,7 @@ def test_take(self): for taken in [taken1, taken2]: tm.assert_index_equal(taken, expected) assert isinstance(taken, TimedeltaIndex) - self.assertIsNone(taken.freq) + assert taken.freq is None self.assertEqual(taken.name, expected.name) def test_take_fill_value(self): diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index ba59add4305d8..35a71efbbf5ba 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1126,7 +1126,7 @@ def test_to_string(self): buf = StringIO() retval = biggie.to_string(buf=buf) - self.assertIsNone(retval) + assert retval is None self.assertEqual(buf.getvalue(), s) assert isinstance(s, compat.string_types) @@ -1631,7 +1631,7 @@ def test_to_string(self): s = self.ts.to_string() retval = self.ts.to_string(buf=buf) - self.assertIsNone(retval) + assert retval is None self.assertEqual(buf.getvalue().strip(), s) # pass float_format diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index 882c9b9bd42f6..f9d911f523699 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -151,7 +151,7 @@ def test_publishes(self): with opt, make_patch as mock_display: handle = obj._ipython_display_() self.assertEqual(mock_display.call_count, 1) - self.assertIsNone(handle) + assert handle is None args, kwargs = mock_display.call_args arg, = args # just one argument diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index 90c6db1dcc7fb..28c6a0e95e0f1 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -1423,7 +1423,7 @@ def test_to_html(self): buf = StringIO() retval = biggie.to_html(buf=buf) - self.assertIsNone(retval) + assert retval is None self.assertEqual(buf.getvalue(), s) assert isinstance(s, compat.string_types) diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index a0c50bb3a573d..deeeaef63da39 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -641,7 +641,7 @@ def test_no_unnamed_index(self): 2 2 2 e f """ df = self.read_table(StringIO(data), sep=' ') - self.assertIsNone(df.index.name) + assert df.index.name is None def test_read_csv_parse_simple_list(self): text = """foo @@ -1243,7 +1243,7 @@ def test_regex_separator(self): df = self.read_table(StringIO(data), sep=r'\s+') expected = self.read_csv(StringIO(re.sub('[ ]+', ',', data)), index_col=0) - self.assertIsNone(expected.index.name) + assert expected.index.name is None tm.assert_frame_equal(df, expected) data = ' a b c\n1 2 3 \n4 5 6\n 7 8 9' diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index d077dd879d44a..ea9911d8ee66c 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -878,12 +878,12 @@ def test_append_series(self): store.append('ss', ss) result = store['ss'] tm.assert_series_equal(result, ss) - self.assertIsNone(result.name) + assert result.name is None store.append('ts', ts) result = store['ts'] tm.assert_series_equal(result, ts) - self.assertIsNone(result.name) + assert result.name is None ns.name = 'foo' store.append('ns', ns) @@ -3573,7 +3573,7 @@ def test_retain_index_attributes(self): periods=3, freq='D')))) store.append('data', df2) - self.assertIsNone(store.get_storer('data').info['index']['freq']) + assert store.get_storer('data').info['index']['freq'] is None # this is ok _maybe_remove(store, 'df2') @@ -3618,7 +3618,7 @@ def test_retain_index_attributes2(self): df2 = DataFrame(dict(A=Series(lrange(3), index=idx2))) df2.to_hdf(path, 'data', append=True) - self.assertIsNone(read_hdf(path, 'data').index.name) + assert read_hdf(path, 'data').index.name is None def test_panel_select(self): diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 64d0fec2b5646..ce341a1e02e0d 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -150,7 +150,7 @@ def _check_ax_limits(col, ax): _check_ax_limits(df['age'], age_ax) self.assertEqual(weight_ax._sharey, height_ax) self.assertEqual(age_ax._sharey, height_ax) - self.assertIsNone(dummy_ax._sharey) + assert dummy_ax._sharey is None @slow def test_boxplot_empty_column(self): diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 364a561669ed2..f0a56592158d3 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -145,7 +145,7 @@ def test_high_freq(self): def test_get_datevalue(self): from pandas.plotting._converter import get_datevalue - self.assertIsNone(get_datevalue(None, 'D')) + assert get_datevalue(None, 'D') is None self.assertEqual(get_datevalue(1987, 'A'), 1987) self.assertEqual(get_datevalue(Period(1987, 'A'), 'M'), Period('1987-12', 'M').ordinal) @@ -1069,7 +1069,7 @@ def test_secondary_legend(self): self.assertEqual(leg.get_texts()[1].get_text(), 'B (right)') self.assertEqual(leg.get_texts()[2].get_text(), 'C') self.assertEqual(leg.get_texts()[3].get_text(), 'D') - self.assertIsNone(ax.right_ax.get_legend()) + assert ax.right_ax.get_legend() is None colors = set() for line in leg.get_lines(): colors.add(line.get_color()) @@ -1105,7 +1105,7 @@ def test_secondary_legend(self): ax = df.plot(secondary_y=['C', 'D']) leg = ax.get_legend() self.assertEqual(len(leg.get_lines()), 4) - self.assertIsNone(ax.right_ax.get_legend()) + assert ax.right_ax.get_legend() is None colors = set() for line in leg.get_lines(): colors.add(line.get_color()) @@ -1120,7 +1120,7 @@ def test_secondary_legend(self): ax = df.plot(secondary_y=['A', 'B']) leg = ax.get_legend() self.assertEqual(len(leg.get_lines()), 4) - self.assertIsNone(ax.right_ax.get_legend()) + assert ax.right_ax.get_legend() is None colors = set() for line in leg.get_lines(): colors.add(line.get_color()) @@ -1133,7 +1133,7 @@ def test_secondary_legend(self): ax = df.plot(secondary_y=['C', 'D']) leg = ax.get_legend() self.assertEqual(len(leg.get_lines()), 4) - self.assertIsNone(ax.right_ax.get_legend()) + assert ax.right_ax.get_legend() is None colors = set() for line in leg.get_lines(): colors.add(line.get_color()) diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index c1d5a069c248b..2cf40335f3ded 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -1467,7 +1467,7 @@ def test_dti_slicing(self): self.assertEqual(v3, Timestamp('6/30/2005')) # don't carry freq through irregular slicing - self.assertIsNone(dti2.freq) + assert dti2.freq is None def test_woy_boundary(self): # make sure weeks at year boundaries are correct diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 68d8e382ef046..a477bb325061f 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -34,13 +34,13 @@ def test_copy_index_name_checking(self): # making a copy self.ts.index.name = None - self.assertIsNone(self.ts.index.name) + assert self.ts.index.name is None self.assertIs(self.ts, self.ts) cp = self.ts.copy() cp.index.name = 'foo' printing.pprint_thing(self.ts.index.name) - self.assertIsNone(self.ts.index.name) + assert self.ts.index.name is None def test_append_preserve_name(self): result = self.ts[:5].append(self.ts[5:]) @@ -60,9 +60,9 @@ def test_binop_maybe_preserve_name(self): cp = self.ts.copy() cp.name = 'something else' result = self.ts + cp - self.assertIsNone(result.name) + assert result.name is None result = self.ts.add(cp) - self.assertIsNone(result.name) + assert result.name is None ops = ['add', 'sub', 'mul', 'div', 'truediv', 'floordiv', 'mod', 'pow'] ops = ops + ['r' + op for op in ops] @@ -76,7 +76,7 @@ def test_binop_maybe_preserve_name(self): cp = self.ts.copy() cp.name = 'changed' result = getattr(s, op)(cp) - self.assertIsNone(result.name) + assert result.name is None def test_combine_first_name(self): result = self.ts.combine_first(self.ts[:5]) @@ -170,7 +170,7 @@ def test_iter_box(self): for res, exp in zip(s, vals): assert isinstance(res, pd.Timestamp) self.assertEqual(res, exp) - self.assertIsNone(res.tz) + assert res.tz is None vals = [pd.Timestamp('2011-01-01', tz='US/Eastern'), pd.Timestamp('2011-01-02', tz='US/Eastern')] diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py index cc29c45d74c9d..51a2a5ed6c574 100644 --- a/pandas/tests/series/test_combine_concat.py +++ b/pandas/tests/series/test_combine_concat.py @@ -246,7 +246,7 @@ def test_append_concat(self): rng1.name = 'foo' rng2.name = 'bar' self.assertEqual(rng1.append(rng1).name, 'foo') - self.assertIsNone(rng1.append(rng2).name) + assert rng1.append(rng2).name is None def test_append_concat_tz(self): # GH 2938 diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 22869fca35931..9872a1982a770 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -164,7 +164,7 @@ def test_getitem_get(self): # GH 5652 for s in [Series(), Series(index=list('abc'))]: result = s.get(None) - self.assertIsNone(result) + assert result is None def test_iloc(self): diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py index d45a6ba347c3e..3df32992a4d74 100644 --- a/pandas/tests/series/test_io.py +++ b/pandas/tests/series/test_io.py @@ -34,8 +34,8 @@ def test_from_csv(self): self.series.to_csv(path) series = Series.from_csv(path) - self.assertIsNone(series.name) - self.assertIsNone(series.index.name) + assert series.name is None + assert series.index.name is None assert_series_equal(self.series, series, check_names=False) self.assertTrue(series.name is None) self.assertTrue(series.index.name is None) diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 486f129b6814c..430be97845fcb 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -373,17 +373,17 @@ def test_first_last_valid(self): self.assertEqual(index, ts.index[-6]) ts[:] = np.nan - self.assertIsNone(ts.last_valid_index()) - self.assertIsNone(ts.first_valid_index()) + assert ts.last_valid_index() is None + assert ts.first_valid_index() is None ser = Series([], index=[]) - self.assertIsNone(ser.last_valid_index()) - self.assertIsNone(ser.first_valid_index()) + assert ser.last_valid_index() is None + assert ser.first_valid_index() is None # GH12800 empty = Series() - self.assertIsNone(empty.last_valid_index()) - self.assertIsNone(empty.first_valid_index()) + assert empty.last_valid_index() is None + assert empty.first_valid_index() is None def test_mpl_compat_hack(self): result = self.ts[:, np.newaxis] @@ -860,7 +860,7 @@ def test_setops_preserve_freq(self): result = rng[:50].union(rng[60:100]) self.assertEqual(result.name, rng.name) - self.assertIsNone(result.freq) + assert result.freq is None self.assertEqual(result.tz, rng.tz) result = rng[:50].intersection(rng[25:75]) @@ -870,12 +870,12 @@ def test_setops_preserve_freq(self): nofreq = DatetimeIndex(list(rng[25:75]), name='other') result = rng[:50].union(nofreq) - self.assertIsNone(result.name) + assert result.name is None self.assertEqual(result.freq, rng.freq) self.assertEqual(result.tz, rng.tz) result = rng[:50].intersection(nofreq) - self.assertIsNone(result.name) + assert result.name is None self.assertEqual(result.freq, rng.freq) self.assertEqual(result.tz, rng.tz) diff --git a/pandas/tests/sparse/test_indexing.py b/pandas/tests/sparse/test_indexing.py index d0e5196570adc..cf91e41624276 100644 --- a/pandas/tests/sparse/test_indexing.py +++ b/pandas/tests/sparse/test_indexing.py @@ -303,20 +303,20 @@ def test_get(self): s = pd.SparseSeries([1, np.nan, np.nan, 3, np.nan]) self.assertEqual(s.get(0), 1) self.assertTrue(np.isnan(s.get(1))) - self.assertIsNone(s.get(5)) + assert s.get(5) is None s = pd.SparseSeries([1, np.nan, 0, 3, 0], index=list('ABCDE')) self.assertEqual(s.get('A'), 1) self.assertTrue(np.isnan(s.get('B'))) self.assertEqual(s.get('C'), 0) - self.assertIsNone(s.get('XX')) + assert s.get('XX') is None s = pd.SparseSeries([1, np.nan, 0, 3, 0], index=list('ABCDE'), fill_value=0) self.assertEqual(s.get('A'), 1) self.assertTrue(np.isnan(s.get('B'))) self.assertEqual(s.get('C'), 0) - self.assertIsNone(s.get('XX')) + assert s.get('XX') is None def test_take(self): orig = pd.Series([1, np.nan, np.nan, 3, np.nan], diff --git a/pandas/tests/sparse/test_series.py b/pandas/tests/sparse/test_series.py index dcac0f599fdeb..2fd7ac3d13b98 100644 --- a/pandas/tests/sparse/test_series.py +++ b/pandas/tests/sparse/test_series.py @@ -435,7 +435,7 @@ def _check_getitem(sp, dense): def test_get_get_value(self): tm.assert_almost_equal(self.bseries.get(10), self.bseries[10]) - self.assertIsNone(self.bseries.get(len(self.bseries) + 1)) + assert self.bseries.get(len(self.bseries) + 1) is None dt = self.btseries.index[10] result = self.btseries.get(dt) diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index b26c015133697..2b9afb8e1dd6b 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -931,7 +931,7 @@ def test_rename_categories(self): res = cat.rename_categories([1, 2, 3], inplace=True) # and now inplace - self.assertIsNone(res) + assert res is None tm.assert_numpy_array_equal(cat.__array__(), np.array([1, 2, 3, 1], dtype=np.int64)) tm.assert_index_equal(cat.categories, Index([1, 2, 3])) @@ -959,7 +959,7 @@ def test_reorder_categories(self): # inplace == True res = cat.reorder_categories(["c", "b", "a"], inplace=True) - self.assertIsNone(res) + assert res is None tm.assert_categorical_equal(cat, new) # not all "old" included in "new" @@ -1000,7 +1000,7 @@ def test_add_categories(self): # inplace == True res = cat.add_categories("d", inplace=True) tm.assert_categorical_equal(cat, new) - self.assertIsNone(res) + assert res is None # new is in old categories def f(): @@ -1040,7 +1040,7 @@ def test_remove_categories(self): # inplace == True res = cat.remove_categories("c", inplace=True) tm.assert_categorical_equal(cat, new) - self.assertIsNone(res) + assert res is None # removal is not in categories def f(): @@ -1062,7 +1062,7 @@ def test_remove_unused_categories(self): res = c.remove_unused_categories(inplace=True) tm.assert_index_equal(c.categories, exp_categories_dropped) - self.assertIsNone(res) + assert res is None # with NaN values (GH11599) c = Categorical(["a", "b", "c", np.nan], diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index af56f0c33df2e..24248d735adb0 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -74,7 +74,7 @@ def test_copy_names(self): getattr(self.panel, attr).name = None cp = self.panel.copy() getattr(cp, attr).name = 'foo' - self.assertIsNone(getattr(self.panel, attr).name) + assert getattr(self.panel, attr).name is None def test_iter(self): tm.equalContents(list(self.panel), self.panel.items) diff --git a/pandas/tests/tseries/test_frequencies.py b/pandas/tests/tseries/test_frequencies.py index e3ab01499e676..c9de997cdf067 100644 --- a/pandas/tests/tseries/test_frequencies.py +++ b/pandas/tests/tseries/test_frequencies.py @@ -545,12 +545,12 @@ def _check_tick(self, base_delta, code): index = _dti([b + base_delta * 7] + [b + base_delta * j for j in range( 3)]) - self.assertIsNone(frequencies.infer_freq(index)) + assert frequencies.infer_freq(index) is None index = _dti([b + base_delta * j for j in range(3)] + [b + base_delta * 7]) - self.assertIsNone(frequencies.infer_freq(index)) + assert frequencies.infer_freq(index) is None def test_weekly(self): days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] @@ -690,7 +690,7 @@ def test_infer_freq_tz_transition(self): index = date_range("2013-11-03", periods=5, freq="3H").tz_localize("America/Chicago") - self.assertIsNone(index.inferred_freq) + assert index.inferred_freq is None def test_infer_freq_businesshour(self): # GH 7905 diff --git a/pandas/tests/tseries/test_offsets.py b/pandas/tests/tseries/test_offsets.py index 335a7f3513da9..ff38d5ec46a44 100644 --- a/pandas/tests/tseries/test_offsets.py +++ b/pandas/tests/tseries/test_offsets.py @@ -147,7 +147,7 @@ def test_apply_out_of_range(self): result = Timestamp('20080101') + offset assert isinstance(result, datetime) - self.assertIsNone(result.tzinfo) + assert result.tzinfo is None tm._skip_if_no_pytz() tm._skip_if_no_dateutil() diff --git a/pandas/util/testing.py b/pandas/util/testing.py index d6f3e00b7594d..b28bd6a696bda 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1066,11 +1066,6 @@ def assertIs(first, second, msg=''): assert a is b, "%s: %r is not %r" % (msg.format(a, b), a, b) -def assertIsNone(expr, msg=''): - """Checks that 'expr' is None""" - return assertIs(expr, None, msg) - - def assert_categorical_equal(left, right, check_dtype=True, obj='Categorical', check_category_order=True): """Test that Categoricals are equivalent.
Title is self-explanatory. Partially addresses #15990.
https://api.github.com/repos/pandas-dev/pandas/pulls/16102
2017-04-23T21:10:23Z
2017-04-23T23:19:42Z
2017-04-23T23:19:42Z
2017-04-24T01:25:30Z
MAINT: Remove assertIn from testing
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index f32e001ea984a..1a3de7b463a19 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -138,7 +138,7 @@ def test_set_index_nonuniq(self): 'E': np.random.randn(5)}) with assertRaisesRegexp(ValueError, 'Index has duplicate keys'): df.set_index('A', verify_integrity=True, inplace=True) - self.assertIn('A', df) + assert 'A' in df def test_set_index_bug(self): # GH1590 diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 5b3a0a9e01f35..636194d32ad46 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -734,7 +734,7 @@ def test_filter_regex_search(self): # regex filtered = fcopy.filter(regex='[A]+') self.assertEqual(len(filtered.columns), 2) - self.assertIn('AA', filtered) + assert 'AA' in filtered # doesn't have to be at beginning df = DataFrame({'aBBa': [1, 2], diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 64edc52508216..6a49c88f17526 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -156,16 +156,16 @@ def test_to_records_index_name(self): df = DataFrame(np.random.randn(3, 3)) df.index.name = 'X' rs = df.to_records() - self.assertIn('X', rs.dtype.fields) + assert 'X' in rs.dtype.fields df = DataFrame(np.random.randn(3, 3)) rs = df.to_records() - self.assertIn('index', rs.dtype.fields) + assert 'index' in rs.dtype.fields df.index = MultiIndex.from_tuples([('a', 'x'), ('a', 'y'), ('b', 'z')]) df.index.names = ['A', None] rs = df.to_records() - self.assertIn('level_0', rs.dtype.fields) + assert 'level_0' in rs.dtype.fields def test_to_records_with_unicode_index(self): # GH13172 diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 780cb3d0457bd..12c5b33fcbce9 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -422,7 +422,7 @@ def test_setitem(self): # not sure what else to do here series = self.frame['A'][::2] self.frame['col5'] = series - self.assertIn('col5', self.frame) + assert 'col5' in self.frame self.assertEqual(len(series), 15) self.assertEqual(len(self.frame), 30) @@ -600,7 +600,7 @@ def test_setitem_corner(self): index=np.arange(3)) del df['B'] df['B'] = [1., 2., 3.] - self.assertIn('B', df) + assert 'B' in df self.assertEqual(len(df.columns), 2) df['A'] = 'beginning' diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index ce756ca188bf0..18639990662b0 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -831,7 +831,7 @@ def test_combineSeries(self): for key, s in compat.iteritems(self.frame): assert_series_equal(larger_added[key], s + series[key]) - self.assertIn('E', larger_added) + assert 'E' in larger_added self.assertTrue(np.isnan(larger_added['E']).all()) # vs mix (upcast) as needed diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index be55efac2992b..efbdc05ba23c8 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -171,7 +171,7 @@ def test_repr_column_name_unicode_truncation_bug(self): ' the File through the code..')}) result = repr(df) - self.assertIn('StringCol', result) + assert 'StringCol' in result def test_latex_repr(self): result = r"""\begin{tabular}{llll} diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index 2df2e23c3f877..0fd1df0b733f8 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -909,7 +909,7 @@ def test_to_csv_compression_gzip(self): text = f.read().decode('utf8') f.close() for col in df.columns: - self.assertIn(col, text) + assert col in text def test_to_csv_compression_bz2(self): # GH7615 @@ -932,7 +932,7 @@ def test_to_csv_compression_bz2(self): text = f.read().decode('utf8') f.close() for col in df.columns: - self.assertIn(col, text) + assert col in text def test_to_csv_compression_xz(self): # GH11852 diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 752c0689b0660..05fe1c6f58e9a 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2483,14 +2483,14 @@ def test_groupby_series_with_name(self): result = self.df.groupby(self.df['A']).mean() result2 = self.df.groupby(self.df['A'], as_index=False).mean() self.assertEqual(result.index.name, 'A') - self.assertIn('A', result2) + assert 'A' in result2 result = self.df.groupby([self.df['A'], self.df['B']]).mean() result2 = self.df.groupby([self.df['A'], self.df['B']], as_index=False).mean() self.assertEqual(result.index.names, ('A', 'B')) - self.assertIn('A', result2) - self.assertIn('B', result2) + assert 'A' in result2 + assert 'B' in result2 def test_seriesgroupby_name_attr(self): # GH 6265 @@ -3357,10 +3357,10 @@ def test_groupby_with_small_elem(self): 'change': [1234, 5678]}, index=pd.DatetimeIndex(['2014-09-10', '2013-10-10'])) grouped = df.groupby([pd.TimeGrouper(freq='M'), 'event']) - self.assertEqual(len(grouped.groups), 2) - self.assertEqual(grouped.ngroups, 2) - self.assertIn((pd.Timestamp('2014-09-30'), 'start'), grouped.groups) - self.assertIn((pd.Timestamp('2013-10-31'), 'start'), grouped.groups) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (pd.Timestamp('2014-09-30'), 'start') in grouped.groups + assert (pd.Timestamp('2013-10-31'), 'start') in grouped.groups res = grouped.get_group((pd.Timestamp('2014-09-30'), 'start')) tm.assert_frame_equal(res, df.iloc[[0], :]) @@ -3372,10 +3372,10 @@ def test_groupby_with_small_elem(self): index=pd.DatetimeIndex(['2014-09-10', '2013-10-10', '2014-09-15'])) grouped = df.groupby([pd.TimeGrouper(freq='M'), 'event']) - self.assertEqual(len(grouped.groups), 2) - self.assertEqual(grouped.ngroups, 2) - self.assertIn((pd.Timestamp('2014-09-30'), 'start'), grouped.groups) - self.assertIn((pd.Timestamp('2013-10-31'), 'start'), grouped.groups) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (pd.Timestamp('2014-09-30'), 'start') in grouped.groups + assert (pd.Timestamp('2013-10-31'), 'start') in grouped.groups res = grouped.get_group((pd.Timestamp('2014-09-30'), 'start')) tm.assert_frame_equal(res, df.iloc[[0, 2], :]) @@ -3388,11 +3388,11 @@ def test_groupby_with_small_elem(self): index=pd.DatetimeIndex(['2014-09-10', '2013-10-10', '2014-08-05'])) grouped = df.groupby([pd.TimeGrouper(freq='M'), 'event']) - self.assertEqual(len(grouped.groups), 3) - self.assertEqual(grouped.ngroups, 3) - self.assertIn((pd.Timestamp('2014-09-30'), 'start'), grouped.groups) - self.assertIn((pd.Timestamp('2013-10-31'), 'start'), grouped.groups) - self.assertIn((pd.Timestamp('2014-08-31'), 'start'), grouped.groups) + assert len(grouped.groups) == 3 + assert grouped.ngroups == 3 + assert (pd.Timestamp('2014-09-30'), 'start') in grouped.groups + assert (pd.Timestamp('2013-10-31'), 'start') in grouped.groups + assert (pd.Timestamp('2014-08-31'), 'start') in grouped.groups res = grouped.get_group((pd.Timestamp('2014-09-30'), 'start')) tm.assert_frame_equal(res, df.iloc[[0], :]) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 7cef5eeb94915..93fc855178800 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -101,7 +101,7 @@ def test_reasonable_keyerror(self): try: index.get_loc('1/1/2000') except KeyError as e: - self.assertIn('2000', str(e)) + assert '2000' in str(e) def test_roundtrip_pickle_with_tz(self): diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 2eff8a12dee77..235c8f1de1fae 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -632,7 +632,7 @@ def test_nonunique_contains(self): for idx in map(DatetimeIndex, ([0, 1, 0], [0, 0, -1], [0, -1, -1], ['2015', '2015', '2016'], ['2015', '2015', '2014'])): - tm.assertIn(idx[0], idx) + assert idx[0] in idx def test_order(self): # with freq diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 9a166aa3340e3..7db7410d79349 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -857,10 +857,10 @@ def test_add_string(self): def test_iadd_string(self): index = pd.Index(['a', 'b', 'c']) # doesn't fail test unless there is a check before `+=` - self.assertIn('a', index) + assert 'a' in index index += '_x' - self.assertIn('a_x', index) + assert 'a_x' in index def test_difference(self): @@ -963,8 +963,8 @@ def test_summary(self): ind = Index(['{other}%s', "~:{range}:0"], name='A') result = ind.summary() # shouldn't be formatted accidentally. - self.assertIn('~:{range}:0', result) - self.assertIn('{other}%s', result) + assert '~:{range}:0' in result + assert '{other}%s' in result def test_format(self): self._check_method_works(Index.format) diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 5000a71dfc756..98fce437d26c8 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -1597,8 +1597,8 @@ def test_union(self): # other = Index(['A', 'B', 'C']) # result = other.union(self.index) - # self.assertIn(('foo', 'one'), result) - # self.assertIn('B', result) + # assert ('foo', 'one') in result + # assert 'B' in result # result2 = self.index.union(other) # self.assertTrue(result.equals(result2)) diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index 5201af3af3531..adf164977205f 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -561,7 +561,7 @@ def test_nonunique_contains(self): for idx in map(TimedeltaIndex, ([0, 1, 0], [0, 0, -1], [0, -1, -1], ['00:01:00', '00:01:00', '00:02:00'], ['00:01:00', '00:01:00', '00:00:01'])): - tm.assertIn(idx[0], idx) + assert idx[0] in idx def test_unknown_attribute(self): # see gh-9680 diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index c0d83c580d1d1..b776d3c2d08ea 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -373,15 +373,15 @@ def test_cache_updating(self): df['A'] # cache series with catch_warnings(record=True): df.ix["Hello Friend"] = df.ix[0] - self.assertIn("Hello Friend", df['A'].index) - self.assertIn("Hello Friend", df['B'].index) + assert "Hello Friend" in df['A'].index + assert "Hello Friend" in df['B'].index with catch_warnings(record=True): panel = tm.makePanel() panel.ix[0] # get first item into cache panel.ix[:, :, 'A+1'] = panel.ix[:, :, 'A'] + 1 - self.assertIn("A+1", panel.ix[0].columns) - self.assertIn("A+1", panel.ix[1].columns) + assert "A+1" in panel.ix[0].columns + assert "A+1" in panel.ix[1].columns # 5216 # make sure that we don't try to set a dead cache diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index ea796a497bd19..ba59add4305d8 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -959,7 +959,7 @@ def test_wide_repr_named(self): self.assertTrue(len(wider_repr) < len(wide_repr)) for line in wide_repr.splitlines()[1::13]: - self.assertIn('DataFrame Index', line) + assert 'DataFrame Index' in line reset_option('display.expand_frame_repr') @@ -981,7 +981,7 @@ def test_wide_repr_multiindex(self): self.assertTrue(len(wider_repr) < len(wide_repr)) for line in wide_repr.splitlines()[1::13]: - self.assertIn('Level 0 Level 1', line) + assert 'Level 0 Level 1' in line reset_option('display.expand_frame_repr') @@ -1875,9 +1875,9 @@ def test_float_trim_zeros(self): if line.startswith('dtype:'): continue if _three_digit_exp(): - self.assertIn('+010', line) + assert '+010' in line else: - self.assertIn('+10', line) + assert '+10' in line def test_datetimeindex(self): diff --git a/pandas/tests/io/parser/c_parser_only.py b/pandas/tests/io/parser/c_parser_only.py index 6d3dc8f637012..f4ca632e09f39 100644 --- a/pandas/tests/io/parser/c_parser_only.py +++ b/pandas/tests/io/parser/c_parser_only.py @@ -33,7 +33,7 @@ def test_buffer_overflow(self): try: self.read_table(StringIO(malf)) except Exception as err: - self.assertIn(cperr, str(err)) + assert cperr in str(err) def test_buffer_rd_bytes(self): # see gh-12098: src->buffer in the C parser can be freed twice leading diff --git a/pandas/tests/io/parser/parse_dates.py b/pandas/tests/io/parser/parse_dates.py index cdc4f9fa9d84f..b7147cd77f4f6 100644 --- a/pandas/tests/io/parser/parse_dates.py +++ b/pandas/tests/io/parser/parse_dates.py @@ -135,7 +135,7 @@ def test_multiple_date_cols_int_cast(self): # it works! df = self.read_csv(StringIO(data), header=None, parse_dates=date_spec, date_parser=conv.parse_date_time) - self.assertIn('nominal', df) + assert 'nominal' in df def test_multiple_date_col_timestamp_parse(self): data = """05/31/2012,15:30:00.029,1306.25,1,E,0,,1306.25 @@ -530,7 +530,7 @@ def test_parse_date_time(self): df = self.read_csv(StringIO(data), sep=',', header=0, parse_dates=datecols, date_parser=conv.parse_date_time) - self.assertIn('date_time', df) + assert 'date_time' in df self.assertEqual(df.date_time.loc[0], datetime(2001, 1, 5, 10, 0, 0)) data = ("KORD,19990127, 19:00:00, 18:56:00, 0.8100\n" @@ -558,7 +558,7 @@ def test_parse_date_fields(self): df = self.read_csv(StringIO(data), sep=',', header=0, parse_dates=datecols, date_parser=conv.parse_date_fields) - self.assertIn('ymd', df) + assert 'ymd' in df self.assertEqual(df.ymd.loc[0], datetime(2001, 1, 10)) def test_datetime_six_col(self): @@ -585,7 +585,7 @@ def test_datetime_six_col(self): df = self.read_csv(StringIO(data), sep=',', header=0, parse_dates=datecols, date_parser=conv.parse_all_fields) - self.assertIn('ymdHMS', df) + assert 'ymdHMS' in df self.assertEqual(df.ymdHMS.loc[0], datetime(2001, 1, 5, 10, 0, 0)) def test_datetime_fractional_seconds(self): @@ -598,7 +598,7 @@ def test_datetime_fractional_seconds(self): df = self.read_csv(StringIO(data), sep=',', header=0, parse_dates=datecols, date_parser=conv.parse_all_fields) - self.assertIn('ymdHMS', df) + assert 'ymdHMS' in df self.assertEqual(df.ymdHMS.loc[0], datetime(2001, 1, 5, 10, 0, 0, microsecond=123456)) self.assertEqual(df.ymdHMS.loc[1], datetime(2001, 1, 5, 10, 0, 0, @@ -611,7 +611,7 @@ def test_generic(self): df = self.read_csv(StringIO(data), sep=',', header=0, parse_dates=datecols, date_parser=dateconverter) - self.assertIn('ym', df) + assert 'ym' in df self.assertEqual(df.ym.loc[0], date(2001, 1, 1)) def test_dateparser_resolution_if_not_ns(self): diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 866ed2cf2f359..e7eaab098fe4d 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -566,10 +566,10 @@ def test_gold_canyon(self): with open(self.banklist_data, 'r') as f: raw_text = f.read() - self.assertIn(gc, raw_text) + assert gc in raw_text df = self.read_html(self.banklist_data, 'Gold Canyon', attrs={'id': 'table'})[0] - self.assertIn(gc, df.to_string()) + assert gc in df.to_string() def test_different_number_of_rows(self): expected = """<table border="1" class="dataframe"> diff --git a/pandas/tests/reshape/test_join.py b/pandas/tests/reshape/test_join.py index aa42f190926ae..7e39806b42cbf 100644 --- a/pandas/tests/reshape/test_join.py +++ b/pandas/tests/reshape/test_join.py @@ -153,15 +153,15 @@ def test_handle_overlap(self): joined = merge(self.df, self.df2, on='key2', suffixes=['.foo', '.bar']) - self.assertIn('key1.foo', joined) - self.assertIn('key1.bar', joined) + assert 'key1.foo' in joined + assert 'key1.bar' in joined def test_handle_overlap_arbitrary_key(self): joined = merge(self.df, self.df2, left_on='key2', right_on='key1', suffixes=['.foo', '.bar']) - self.assertIn('key1.foo', joined) - self.assertIn('key2.bar', joined) + assert 'key1.foo' in joined + assert 'key2.bar' in joined def test_join_on(self): target = self.target @@ -251,7 +251,7 @@ def test_join_with_len0(self): # nothing to merge merged = self.target.join(self.source.reindex([]), on='C') for col in self.source: - self.assertIn(col, merged) + assert col in merged self.assertTrue(merged[col].isnull().all()) merged2 = self.target.join(self.source.reindex([]), on='C', diff --git a/pandas/tests/reshape/test_merge.py b/pandas/tests/reshape/test_merge.py index 8ddeb4bdda14a..73d0346546b97 100644 --- a/pandas/tests/reshape/test_merge.py +++ b/pandas/tests/reshape/test_merge.py @@ -128,8 +128,8 @@ def test_merge_overlap(self): merged = merge(self.left, self.left, on='key') exp_len = (self.left['key'].value_counts() ** 2).sum() self.assertEqual(len(merged), exp_len) - self.assertIn('v1_x', merged) - self.assertIn('v1_y', merged) + assert 'v1_x' in merged + assert 'v1_y' in merged def test_merge_different_column_key_names(self): left = DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'], diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py index 50c8bcbb68fcb..1635d90189b50 100644 --- a/pandas/tests/scalar/test_period.py +++ b/pandas/tests/scalar/test_period.py @@ -54,7 +54,7 @@ def test_period_cons_quarterly(self): for month in MONTHS: freq = 'Q-%s' % month exp = Period('1989Q3', freq=freq) - self.assertIn('1989Q3', str(exp)) + assert '1989Q3' in str(exp) stamp = exp.to_timestamp('D', how='end') p = Period(stamp, freq=freq) self.assertEqual(p, exp) @@ -544,14 +544,14 @@ def test_hash(self): def test_repr(self): p = Period('Jan-2000') - self.assertIn('2000-01', repr(p)) + assert '2000-01' in repr(p) p = Period('2000-12-15') - self.assertIn('2000-12-15', repr(p)) + assert '2000-12-15' in repr(p) def test_repr_nat(self): p = Period('nat', freq='M') - self.assertIn(repr(tslib.NaT), repr(p)) + assert repr(tslib.NaT) in repr(p) def test_millisecond_repr(self): p = Period('2000-01-01 12:15:02.123') diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index 055da8b2cc07f..c1d5a069c248b 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -1133,24 +1133,24 @@ def test_nanosecond_string_parsing(self): expected_repr = '2013-05-01 07:15:45.123456789' expected_value = 1367392545123456789 self.assertEqual(ts.value, expected_value) - self.assertIn(expected_repr, repr(ts)) + assert expected_repr in repr(ts) ts = Timestamp('2013-05-01 07:15:45.123456789+09:00', tz='Asia/Tokyo') self.assertEqual(ts.value, expected_value - 9 * 3600 * 1000000000) - self.assertIn(expected_repr, repr(ts)) + assert expected_repr in repr(ts) ts = Timestamp('2013-05-01 07:15:45.123456789', tz='UTC') self.assertEqual(ts.value, expected_value) - self.assertIn(expected_repr, repr(ts)) + assert expected_repr in repr(ts) ts = Timestamp('2013-05-01 07:15:45.123456789', tz='US/Eastern') self.assertEqual(ts.value, expected_value + 4 * 3600 * 1000000000) - self.assertIn(expected_repr, repr(ts)) + assert expected_repr in repr(ts) # GH 10041 ts = Timestamp('20130501T071545.123456789') self.assertEqual(ts.value, expected_value) - self.assertIn(expected_repr, repr(ts)) + assert expected_repr in repr(ts) def test_nanosecond_timestamp(self): # GH 7610 @@ -1365,7 +1365,7 @@ def test_timestamp_repr(self): iso8601 = '1850-01-01 01:23:45.012345' stamp = Timestamp(iso8601, tz='US/Eastern') result = repr(stamp) - self.assertIn(iso8601, result) + assert iso8601 in result def test_timestamp_from_ordinal(self): @@ -1440,7 +1440,7 @@ def test_to_html_timestamp(self): df = DataFrame(np.random.randn(10, 4), index=rng) result = df.to_html() - self.assertIn('2000-01-01', result) + assert '2000-01-01' in result def test_series_map_box_timestamps(self): # #2689, #2627 diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index a7b8d285bbe54..17a270c3a9346 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -118,10 +118,10 @@ def test_reset_index(self): ser.name = 'value' df = ser.reset_index() - self.assertIn('value', df) + assert 'value' in df df = ser.reset_index(name='value2') - self.assertIn('value2', df) + assert 'value2' in df # check inplace s = ser.reset_index(drop=True) diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 1181e3a44f295..22869fca35931 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -2397,7 +2397,7 @@ def test_indexing_over_size_cutoff(self): pos = n * 3 timestamp = df.index[pos] - self.assertIn(timestamp, df.index) + assert timestamp in df.index # it works! df.loc[timestamp] diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 2f7bf6902f5af..e7c1b22216dcb 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -459,7 +459,7 @@ def test_fillna_invalid_method(self): try: self.ts.fillna(method='ffil') except ValueError as inst: - self.assertIn('ffil', str(inst)) + assert 'ffil' in str(inst) def test_ffill(self): ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5)) diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index a80c5edcc21bd..b4ad90f6f35af 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -95,12 +95,12 @@ def test_repr(self): # 0 as name ser = Series(np.random.randn(100), name=0) rep_str = repr(ser) - self.assertIn("Name: 0", rep_str) + assert "Name: 0" in rep_str # tidy repr ser = Series(np.random.randn(1001), name=0) rep_str = repr(ser) - self.assertIn("Name: 0", rep_str) + assert "Name: 0" in rep_str ser = Series(["a\n\r\tb"], name="a\n\r\td", index=["a\n\r\tf"]) self.assertFalse("\t" in repr(ser)) diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index bafb8ebfd7145..486f129b6814c 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -796,7 +796,7 @@ def test_to_csv_numpy_16_bug(self): frame.to_csv(buf) result = buf.getvalue() - self.assertIn('2000-01-01', result) + assert '2000-01-01' in result def test_series_map_box_timedelta(self): # GH 11349 diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py index c9ac4f36e7769..40ff2421a9f63 100644 --- a/pandas/tests/tseries/test_timezones.py +++ b/pandas/tests/tseries/test_timezones.py @@ -372,7 +372,7 @@ def test_utc_box_timestamp_and_localize(self): rng = date_range('3/13/2012', '3/14/2012', freq='H', tz='utc') rng_eastern = rng.tz_convert(self.tzstr('US/Eastern')) # test not valid for dateutil timezones. - # self.assertIn('EDT', repr(rng_eastern[0].tzinfo)) + # assert 'EDT' in repr(rng_eastern[0].tzinfo) self.assertTrue('EDT' in repr(rng_eastern[0].tzinfo) or 'tzfile' in repr(rng_eastern[0].tzinfo)) @@ -683,7 +683,7 @@ def test_index_with_timezone_repr(self): rng_eastern = rng.tz_localize(self.tzstr('US/Eastern')) rng_repr = repr(rng_eastern) - self.assertIn('2010-04-13 00:00:00', rng_repr) + assert '2010-04-13 00:00:00' in rng_repr def test_index_astype_asobject_tzinfos(self): # #1345 diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 7565cbb859201..d6f3e00b7594d 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -894,7 +894,7 @@ def _check_types(l, r, obj='Index'): assert_attr_equal('dtype', l, r, obj=obj) # allow string-like to have different inferred_types if l.inferred_type in ('string', 'unicode'): - assertIn(r.inferred_type, ('string', 'unicode')) + assert r.inferred_type in ('string', 'unicode') else: assert_attr_equal('inferred_type', l, r, obj=obj) @@ -1066,12 +1066,6 @@ def assertIs(first, second, msg=''): assert a is b, "%s: %r is not %r" % (msg.format(a, b), a, b) -def assertIn(first, second, msg=''): - """Checks that 'first' is in 'second'""" - a, b = first, second - assert a in b, "%s: %r is not in %r" % (msg.format(a, b), a, b) - - def assertIsNone(expr, msg=''): """Checks that 'expr' is None""" return assertIs(expr, None, msg)
Title is self-explanatory. Partially addresses #15990.
https://api.github.com/repos/pandas-dev/pandas/pulls/16101
2017-04-23T19:32:24Z
2017-04-23T20:38:02Z
2017-04-23T20:38:02Z
2017-04-23T20:39:04Z
TST: fix various deprecation warnings in tests suite
diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py index 738ddb89db652..1a5ba3ccad400 100644 --- a/pandas/tests/frame/test_quantile.py +++ b/pandas/tests/frame/test_quantile.py @@ -431,7 +431,7 @@ def test_quantile_empty(self): # res = df.quantile(0.5) # datetimes - df = DataFrame(columns=['a', 'b'], dtype='datetime64') + df = DataFrame(columns=['a', 'b'], dtype='datetime64[ns]') # FIXME (gives NaNs instead of NaT in 0.18.1 or 0.19.0) # res = df.quantile(0.5, numeric_only=False) diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 3b8bbf239d941..96bf2b605ffa1 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -752,5 +752,6 @@ def test_from_custom_template(tmpdir): def test_shim(): # https://github.com/pandas-dev/pandas/pull/16059 # Remove in 0.21 - with pytest.warns(FutureWarning): + with tm.assert_produces_warning(FutureWarning, + check_stacklevel=False): from pandas.formats.style import Styler as _styler # noqa diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 07abd0190a417..9b8569e8680e4 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -245,7 +245,7 @@ def test_parallel_coordinates(self): def test_parallel_coordinates_with_sorted_labels(self): """ For #15908 """ - from pandas.tools.plotting import parallel_coordinates + from pandas.plotting import parallel_coordinates df = DataFrame({"feat": [i for i in range(30)], "class": [2 for _ in range(10)] +
https://api.github.com/repos/pandas-dev/pandas/pulls/16100
2017-04-23T13:57:10Z
2017-04-23T14:18:29Z
2017-04-23T14:18:29Z
2017-04-23T14:30:25Z
API: expose dtypes in pandas.api.types
diff --git a/pandas/api/types/__init__.py b/pandas/api/types/__init__.py index dcf010dcf4bc2..8bda0c75f8540 100644 --- a/pandas/api/types/__init__.py +++ b/pandas/api/types/__init__.py @@ -1,6 +1,10 @@ """ public toolkit API """ from pandas.core.dtypes.api import * # noqa +from pandas.core.dtypes.dtypes import (CategoricalDtype, # noqa + DatetimeTZDtype, + PeriodDtype, + IntervalDtype) from pandas.core.dtypes.concat import union_categoricals # noqa from pandas._libs.lib import infer_dtype # noqa del np # noqa diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index 3b9148a1c91c6..6b37501045d40 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -33,10 +33,12 @@ class TestTypes(Base, tm.TestCase): 'is_list_like', 'is_hashable', 'is_named_tuple', 'is_sequence', 'pandas_dtype', 'union_categoricals', 'infer_dtype'] + dtypes = ['CategoricalDtype', 'DatetimeTZDtype', + 'PeriodDtype', 'IntervalDtype'] def test_types(self): - self.check(types, self.allowed) + self.check(types, self.allowed + self.dtypes) def check_deprecation(self, fold, fnew): with tm.assert_produces_warning(DeprecationWarning):
xref #16015 xref https://github.com/apache/arrow/pull/585 xref https://github.com/pandas-dev/pandas/issues/16042 xref https://github.com/pandas-dev/pandas/pull/15541#issuecomment-286008496
https://api.github.com/repos/pandas-dev/pandas/pulls/16099
2017-04-23T13:24:32Z
2017-04-24T11:43:12Z
2017-04-24T11:43:12Z
2017-04-24T11:44:24Z
MAINT: Remove assertNotIn from testing
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index f925022b6bd7f..f32e001ea984a 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -500,16 +500,16 @@ def test_rename_nocopy(self): def test_rename_inplace(self): self.frame.rename(columns={'C': 'foo'}) - self.assertIn('C', self.frame) - self.assertNotIn('foo', self.frame) + assert 'C' in self.frame + assert 'foo' not in self.frame c_id = id(self.frame['C']) frame = self.frame.copy() frame.rename(columns={'C': 'foo'}, inplace=True) - self.assertNotIn('C', frame) - self.assertIn('foo', frame) - self.assertNotEqual(id(frame['foo']), c_id) + assert 'C' not in frame + assert 'foo' in frame + assert id(frame['foo']) != c_id def test_rename_bug(self): # GH 5344 @@ -778,8 +778,9 @@ def test_set_index_names(self): def test_rename_objects(self): renamed = self.mixed_frame.rename(columns=str.upper) - self.assertIn('FOO', renamed) - self.assertNotIn('foo', renamed) + + assert 'FOO' in renamed + assert 'foo' not in renamed def test_assign_columns(self): self.frame['hi'] = 'there' diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 703b93b9ec950..cd98460d8609c 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -190,10 +190,10 @@ def test_corrwith(self): dropped = a.corrwith(b, axis=0, drop=True) tm.assert_almost_equal(dropped['A'], a['A'].corr(b['A'])) - self.assertNotIn('B', dropped) + assert 'B' not in dropped dropped = a.corrwith(b, axis=1, drop=True) - self.assertNotIn(a.index[-1], dropped.index) + assert a.index[-1] not in dropped.index # non time-series data index = ['a', 'b', 'c', 'd', 'e'] diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 2f914472a1152..5b3a0a9e01f35 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -14,9 +14,7 @@ date_range, isnull) import pandas as pd -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_frame_equal from pandas.errors import PerformanceWarning import pandas.util.testing as tm @@ -287,15 +285,15 @@ def test_reindex_like(self): assert_frame_equal(other, self.frame.reindex_like(other)) def test_reindex_columns(self): - newFrame = self.frame.reindex(columns=['A', 'B', 'E']) + new_frame = self.frame.reindex(columns=['A', 'B', 'E']) - assert_series_equal(newFrame['B'], self.frame['B']) - self.assertTrue(np.isnan(newFrame['E']).all()) - self.assertNotIn('C', newFrame) + tm.assert_series_equal(new_frame['B'], self.frame['B']) + assert np.isnan(new_frame['E']).all() + assert 'C' not in new_frame - # length zero - newFrame = self.frame.reindex(columns=[]) - self.assertTrue(newFrame.empty) + # Length zero + new_frame = self.frame.reindex(columns=[]) + assert new_frame.empty def test_reindex_columns_method(self): @@ -659,33 +657,33 @@ def test_align_series_combinations(self): tm.assert_frame_equal(res2, exp1) def test_filter(self): - # items + # Items filtered = self.frame.filter(['A', 'B', 'E']) - self.assertEqual(len(filtered.columns), 2) - self.assertNotIn('E', filtered) + assert len(filtered.columns) == 2 + assert 'E' not in filtered filtered = self.frame.filter(['A', 'B', 'E'], axis='columns') - self.assertEqual(len(filtered.columns), 2) - self.assertNotIn('E', filtered) + assert len(filtered.columns) == 2 + assert 'E' not in filtered - # other axis + # Other axis idx = self.frame.index[0:4] filtered = self.frame.filter(idx, axis='index') expected = self.frame.reindex(index=idx) - assert_frame_equal(filtered, expected) + tm.assert_frame_equal(filtered, expected) # like fcopy = self.frame.copy() fcopy['AA'] = 1 filtered = fcopy.filter(like='A') - self.assertEqual(len(filtered.columns), 2) - self.assertIn('AA', filtered) + assert len(filtered.columns) == 2 + assert 'AA' in filtered # like with ints in column names df = DataFrame(0., index=[0, 1, 2], columns=[0, 1, '_A', '_B']) filtered = df.filter(like='_') - self.assertEqual(len(filtered.columns), 2) + assert len(filtered.columns) == 2 # regex with ints in column names # from PR #10384 @@ -693,41 +691,41 @@ def test_filter(self): expected = DataFrame( 0., index=[0, 1, 2], columns=pd.Index([1, 2], dtype=object)) filtered = df.filter(regex='^[0-9]+$') - assert_frame_equal(filtered, expected) + tm.assert_frame_equal(filtered, expected) expected = DataFrame(0., index=[0, 1, 2], columns=[0, '0', 1, '1']) # shouldn't remove anything filtered = expected.filter(regex='^[0-9]+$') - assert_frame_equal(filtered, expected) + tm.assert_frame_equal(filtered, expected) # pass in None - with assertRaisesRegexp(TypeError, 'Must pass'): + with tm.assertRaisesRegexp(TypeError, 'Must pass'): self.frame.filter() - with assertRaisesRegexp(TypeError, 'Must pass'): + with tm.assertRaisesRegexp(TypeError, 'Must pass'): self.frame.filter(items=None) - with assertRaisesRegexp(TypeError, 'Must pass'): + with tm.assertRaisesRegexp(TypeError, 'Must pass'): self.frame.filter(axis=1) # test mutually exclusive arguments - with assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$', like='bbi') - with assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$', axis=1) - with assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], regex='e$') - with assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], like='bbi', axis=0) - with assertRaisesRegexp(TypeError, 'mutually exclusive'): + with tm.assertRaisesRegexp(TypeError, 'mutually exclusive'): self.frame.filter(items=['one', 'three'], like='bbi') # objects filtered = self.mixed_frame.filter(like='foo') - self.assertIn('foo', filtered) + assert 'foo' in filtered # unicode columns, won't ascii-encode df = self.frame.rename(columns={'B': u('\u2202')}) filtered = df.filter(like='C') - self.assertTrue('C' in filtered) + assert 'C' in filtered def test_filter_regex_search(self): fcopy = self.frame.copy() @@ -857,10 +855,10 @@ def test_reindex_boolean(self): def test_reindex_objects(self): reindexed = self.mixed_frame.reindex(columns=['foo', 'A', 'B']) - self.assertIn('foo', reindexed) + assert 'foo' in reindexed reindexed = self.mixed_frame.reindex(columns=['A', 'B']) - self.assertNotIn('foo', reindexed) + assert 'foo' not in reindexed def test_reindex_corner(self): index = Index(['a', 'b', 'c']) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index d253fc2049462..3bcc058316f77 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -210,8 +210,8 @@ def test_constructor_dict(self): 'col2': self.ts2}) # col2 is padded with NaN - self.assertEqual(len(self.ts1), 30) - self.assertEqual(len(self.ts2), 25) + assert len(self.ts1) == 30 + assert len(self.ts2) == 25 tm.assert_series_equal(self.ts1, frame['col1'], check_names=False) @@ -223,12 +223,12 @@ def test_constructor_dict(self): 'col2': self.ts2}, columns=['col2', 'col3', 'col4']) - self.assertEqual(len(frame), len(self.ts2)) - self.assertNotIn('col1', frame) - self.assertTrue(isnull(frame['col3']).all()) + assert len(frame) == len(self.ts2) + assert 'col1' not in frame + assert isnull(frame['col3']).all() # Corner cases - self.assertEqual(len(DataFrame({})), 0) + assert len(DataFrame({})) == 0 # mix dict and array, wrong size - no spec for which error should raise # first @@ -242,14 +242,14 @@ def test_constructor_dict(self): # empty dict plus index idx = Index([0, 1, 2]) frame = DataFrame({}, index=idx) - self.assertIs(frame.index, idx) + assert frame.index is idx # empty with index and columns idx = Index([0, 1, 2]) frame = DataFrame({}, index=idx, columns=idx) - self.assertIs(frame.index, idx) - self.assertIs(frame.columns, idx) - self.assertEqual(len(frame._series), 3) + assert frame.index is idx + assert frame.columns is idx + assert len(frame._series) == 3 # with dict of empty list and Series frame = DataFrame({'A': [], 'B': []}, columns=['A', 'B']) @@ -1533,11 +1533,11 @@ def test_from_records_to_records(self): # what to do? records = indexed_frame.to_records() - self.assertEqual(len(records.dtype.names), 3) + assert len(records.dtype.names) == 3 records = indexed_frame.to_records(index=False) - self.assertEqual(len(records.dtype.names), 2) - self.assertNotIn('index', records.dtype.names) + assert len(records.dtype.names) == 2 + assert 'index' not in records.dtype.names def test_from_records_nones(self): tuples = [(1, 2, None, 3), diff --git a/pandas/tests/frame/test_mutate_columns.py b/pandas/tests/frame/test_mutate_columns.py index a7da704e73764..dfaeaea49cf75 100644 --- a/pandas/tests/frame/test_mutate_columns.py +++ b/pandas/tests/frame/test_mutate_columns.py @@ -7,9 +7,7 @@ from pandas import DataFrame, Series, Index, MultiIndex -from pandas.util.testing import (assert_series_equal, - assert_frame_equal, - assertRaisesRegexp) +from pandas.util.testing import assert_frame_equal, assertRaisesRegexp import pandas.util.testing as tm @@ -163,7 +161,7 @@ def test_insert(self): def test_delitem(self): del self.frame['A'] - self.assertNotIn('A', self.frame) + assert 'A' not in self.frame def test_delitem_multiindex(self): midx = MultiIndex.from_product([['A', 'B'], [1, 2]]) @@ -194,15 +192,14 @@ def test_pop(self): self.frame.columns.name = 'baz' self.frame.pop('A') - self.assertNotIn('A', self.frame) + assert 'A' not in self.frame self.frame['foo'] = 'bar' self.frame.pop('foo') - self.assertNotIn('foo', self.frame) + assert 'foo' not in self.frame # TODO self.assertEqual(self.frame.columns.name, 'baz') - # 10912 - # inplace ops cause caching issue + # gh-10912: inplace ops cause caching issue a = DataFrame([[1, 2, 3], [4, 5, 6]], columns=[ 'A', 'B', 'C'], index=['X', 'Y']) b = a.pop('B') @@ -211,11 +208,11 @@ def test_pop(self): # original frame expected = DataFrame([[1, 3], [4, 6]], columns=[ 'A', 'C'], index=['X', 'Y']) - assert_frame_equal(a, expected) + tm.assert_frame_equal(a, expected) # result expected = Series([2, 5], index=['X', 'Y'], name='B') + 1 - assert_series_equal(b, expected) + tm.assert_series_equal(b, expected) def test_pop_non_unique_cols(self): df = DataFrame({0: [0, 1], 1: [0, 1], 2: [4, 5]}) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 695d3aa7ebe3a..9a166aa3340e3 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -851,8 +851,8 @@ def test_add_string(self): index = Index(['a', 'b', 'c']) index2 = index + 'foo' - self.assertNotIn('a', index2) - self.assertIn('afoo', index2) + assert 'a' not in index2 + assert 'afoo' in index2 def test_iadd_string(self): index = pd.Index(['a', 'b', 'c']) diff --git a/pandas/tests/indexes/test_interval.py b/pandas/tests/indexes/test_interval.py index 53b5c01c40899..c34d93cb21b0f 100644 --- a/pandas/tests/indexes/test_interval.py +++ b/pandas/tests/indexes/test_interval.py @@ -458,20 +458,20 @@ def test_get_indexer_subintervals(self): tm.assert_numpy_array_equal(actual, expected) def test_contains(self): - # only endpoints are valid + # Only endpoints are valid. i = IntervalIndex.from_arrays([0, 1], [1, 2]) - # invalid - self.assertNotIn(0, i) - self.assertNotIn(1, i) - self.assertNotIn(2, i) + # Invalid + assert 0 not in i + assert 1 not in i + assert 2 not in i - # valid - self.assertIn(Interval(0, 1), i) - self.assertIn(Interval(0, 2), i) - self.assertIn(Interval(0, 0.5), i) - self.assertNotIn(Interval(3, 5), i) - self.assertNotIn(Interval(-1, 0, closed='left'), i) + # Valid + assert Interval(0, 1) in i + assert Interval(0, 2) in i + assert Interval(0, 0.5) in i + assert Interval(3, 5) not in i + assert Interval(-1, 0, closed='left') not in i def testcontains(self): # can select values that are IN the range of a value @@ -509,7 +509,7 @@ def test_non_contiguous(self): expected = np.array([0, -1, 1], dtype='intp') tm.assert_numpy_array_equal(actual, expected) - self.assertNotIn(1.5, index) + assert 1.5 not in index def test_union(self): other = IntervalIndex.from_arrays([2], [3]) @@ -651,11 +651,12 @@ def test_datetime(self): expected = pd.date_range('2000-01-01T12:00', periods=2) tm.assert_index_equal(idx.mid, expected) - self.assertNotIn(pd.Timestamp('2000-01-01T12'), idx) - self.assertNotIn(pd.Timestamp('2000-01-01T12'), idx) + assert pd.Timestamp('2000-01-01T12') not in idx + assert pd.Timestamp('2000-01-01T12') not in idx target = pd.date_range('1999-12-31T12:00', periods=7, freq='12H') actual = idx.get_indexer(target) + expected = np.array([-1, -1, 0, 0, 1, 1, -1], dtype='intp') tm.assert_numpy_array_equal(actual, expected) diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index c671a33e2f171..5000a71dfc756 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -1058,9 +1058,9 @@ def test_from_tuples_index_values(self): self.assertTrue((result.values == self.index.values).all()) def test_contains(self): - self.assertIn(('foo', 'two'), self.index) - self.assertNotIn(('bar', 'two'), self.index) - self.assertNotIn(None, self.index) + assert ('foo', 'two') in self.index + assert ('bar', 'two') not in self.index + assert None not in self.index def test_contains_top_level(self): midx = MultiIndex.from_product([['A', 'B'], [1, 2]]) @@ -1287,15 +1287,15 @@ def test_truncate(self): labels=[major_labels, minor_labels]) result = index.truncate(before=1) - self.assertNotIn('foo', result.levels[0]) - self.assertIn(1, result.levels[0]) + assert 'foo' not in result.levels[0] + assert 1 in result.levels[0] result = index.truncate(after=1) - self.assertNotIn(2, result.levels[0]) - self.assertIn(1, result.levels[0]) + assert 2 not in result.levels[0] + assert 1 in result.levels[0] result = index.truncate(before=1, after=2) - self.assertEqual(len(result.levels[0]), 2) + assert len(result.levels[0]) == 2 # after < before pytest.raises(ValueError, index.truncate, 3, 1) diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index 97c4a1df95963..5201af3af3531 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -564,10 +564,10 @@ def test_nonunique_contains(self): tm.assertIn(idx[0], idx) def test_unknown_attribute(self): - # GH 9680 + # see gh-9680 tdi = pd.timedelta_range(start=0, periods=10, freq='1s') ts = pd.Series(np.random.normal(size=10), index=tdi) - self.assertNotIn('foo', ts.__dict__.keys()) + assert 'foo' not in ts.__dict__.keys() pytest.raises(AttributeError, lambda: ts.foo) def test_order(self): diff --git a/pandas/tests/indexing/test_indexing_slow.py b/pandas/tests/indexing/test_indexing_slow.py index 42b50e37f0492..21cdbb17f52ce 100644 --- a/pandas/tests/indexing/test_indexing_slow.py +++ b/pandas/tests/indexing/test_indexing_slow.py @@ -27,10 +27,10 @@ def validate(mi, df, key): mask &= df.iloc[:, i] == k if not mask.any(): - self.assertNotIn(key[:i + 1], mi.index) + assert key[:i + 1] not in mi.index continue - self.assertIn(key[:i + 1], mi.index) + assert key[:i + 1] in mi.index right = df[mask].copy() if i + 1 != len(key): # partial key diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 3784840fbfd28..ea796a497bd19 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -183,15 +183,15 @@ def test_repr_truncation(self): for line, value in lzip(r.split('\n'), df['B']): if adj.len(value) + 1 > max_len: - self.assertIn('...', line) + assert '...' in line else: - self.assertNotIn('...', line) + assert '...' not in line with option_context("display.max_colwidth", 999999): - self.assertNotIn('...', repr(df)) + assert '...' not in repr(df) with option_context("display.max_colwidth", max_len + 2): - self.assertNotIn('...', repr(df)) + assert '...' not in repr(df) def test_repr_chop_threshold(self): df = DataFrame([[0.1, 0.5], [0.5, -0.1]]) diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index 8b71fb047456e..90c6db1dcc7fb 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -1466,7 +1466,7 @@ def test_to_html_with_no_bold(self): def test_to_html_columns_arg(self): frame = DataFrame(tm.getSeriesData()) result = frame.to_html(columns=['A']) - self.assertNotIn('<th>B</th>', result) + assert '<th>B</th>' not in result def test_to_html_multiindex(self): columns = MultiIndex.from_tuples(list(zip(np.arange(2).repeat(2), @@ -1660,7 +1660,7 @@ def test_to_html_index(self): ' </tr>\n' ' </tbody>\n' '</table>') - self.assertEqual(df.to_html(), expected_with_index) + assert df.to_html() == expected_with_index expected_without_index = ('<table border="1" class="dataframe">\n' ' <thead>\n' @@ -1690,8 +1690,8 @@ def test_to_html_index(self): '</table>') result = df.to_html(index=False) for i in index: - self.assertNotIn(i, result) - self.assertEqual(result, expected_without_index) + assert i not in result + assert result == expected_without_index df.index = Index(['foo', 'bar', 'baz'], name='idx') expected_with_index = ('<table border="1" class="dataframe">\n' ' <thead>\n' @@ -1729,8 +1729,8 @@ def test_to_html_index(self): ' </tr>\n' ' </tbody>\n' '</table>') - self.assertEqual(df.to_html(), expected_with_index) - self.assertEqual(df.to_html(index=False), expected_without_index) + assert df.to_html() == expected_with_index + assert df.to_html(index=False) == expected_without_index tuples = [('foo', 'car'), ('foo', 'bike'), ('bar', 'car')] df.index = MultiIndex.from_tuples(tuples) @@ -1768,13 +1768,13 @@ def test_to_html_index(self): ' </tr>\n' ' </tbody>\n' '</table>') - self.assertEqual(df.to_html(), expected_with_index) + assert df.to_html() == expected_with_index result = df.to_html(index=False) for i in ['foo', 'bar', 'car', 'bike']: - self.assertNotIn(i, result) + assert i not in result # must be the same result as normal index - self.assertEqual(result, expected_without_index) + assert result == expected_without_index df.index = MultiIndex.from_tuples(tuples, names=['idx1', 'idx2']) expected_with_index = ('<table border="1" class="dataframe">\n' @@ -1817,8 +1817,8 @@ def test_to_html_index(self): ' </tr>\n' ' </tbody>\n' '</table>') - self.assertEqual(df.to_html(), expected_with_index) - self.assertEqual(df.to_html(index=False), expected_without_index) + assert df.to_html() == expected_with_index + assert df.to_html(index=False) == expected_without_index def test_to_html_with_classes(self): df = DataFrame() diff --git a/pandas/tests/io/parser/parse_dates.py b/pandas/tests/io/parser/parse_dates.py index 6dd92783eac60..cdc4f9fa9d84f 100644 --- a/pandas/tests/io/parser/parse_dates.py +++ b/pandas/tests/io/parser/parse_dates.py @@ -60,26 +60,26 @@ def func(*date_cols): prefix='X', parse_dates={'nominal': [1, 2], 'actual': [1, 3]}) - self.assertIn('nominal', df) - self.assertIn('actual', df) - self.assertNotIn('X1', df) - self.assertNotIn('X2', df) - self.assertNotIn('X3', df) + assert 'nominal' in df + assert 'actual' in df + assert 'X1' not in df + assert 'X2' not in df + assert 'X3' not in df d = datetime(1999, 1, 27, 19, 0) - self.assertEqual(df.loc[0, 'nominal'], d) + assert df.loc[0, 'nominal'] == d df = self.read_csv(StringIO(data), header=None, date_parser=func, parse_dates={'nominal': [1, 2], 'actual': [1, 3]}, keep_date_col=True) - self.assertIn('nominal', df) - self.assertIn('actual', df) + assert 'nominal' in df + assert 'actual' in df - self.assertIn(1, df) - self.assertIn(2, df) - self.assertIn(3, df) + assert 1 in df + assert 2 in df + assert 3 in df data = """\ KORD,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000 @@ -92,23 +92,23 @@ def func(*date_cols): df = self.read_csv(StringIO(data), header=None, prefix='X', parse_dates=[[1, 2], [1, 3]]) - self.assertIn('X1_X2', df) - self.assertIn('X1_X3', df) - self.assertNotIn('X1', df) - self.assertNotIn('X2', df) - self.assertNotIn('X3', df) + assert 'X1_X2' in df + assert 'X1_X3' in df + assert 'X1' not in df + assert 'X2' not in df + assert 'X3' not in df d = datetime(1999, 1, 27, 19, 0) - self.assertEqual(df.loc[0, 'X1_X2'], d) + assert df.loc[0, 'X1_X2'] == d df = self.read_csv(StringIO(data), header=None, parse_dates=[[1, 2], [1, 3]], keep_date_col=True) - self.assertIn('1_2', df) - self.assertIn('1_3', df) - self.assertIn(1, df) - self.assertIn(2, df) - self.assertIn(3, df) + assert '1_2' in df + assert '1_3' in df + assert 1 in df + assert 2 in df + assert 3 in df data = '''\ KORD,19990127 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000 @@ -120,7 +120,7 @@ def func(*date_cols): df = self.read_csv(StringIO(data), sep=',', header=None, parse_dates=[1], index_col=1) d = datetime(1999, 1, 27, 19, 0) - self.assertEqual(df.index[0], d) + assert df.index[0] == d def test_multiple_date_cols_int_cast(self): data = ("KORD,19990127, 19:00:00, 18:56:00, 0.8100\n" @@ -402,7 +402,7 @@ def test_multiple_date_cols_chunked(self): chunks = list(reader) - self.assertNotIn('nominalTime', df) + assert 'nominalTime' not in df tm.assert_frame_equal(chunks[0], df[:2]) tm.assert_frame_equal(chunks[1], df[2:4]) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 153ac749b4b17..d077dd879d44a 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -439,19 +439,18 @@ def test_contains(self): store['a'] = tm.makeTimeSeries() store['b'] = tm.makeDataFrame() store['foo/bar'] = tm.makeDataFrame() - self.assertIn('a', store) - self.assertIn('b', store) - self.assertNotIn('c', store) - self.assertIn('foo/bar', store) - self.assertIn('/foo/bar', store) - self.assertNotIn('/foo/b', store) - self.assertNotIn('bar', store) - - # GH 2694 - # tables.NaturalNameWarning + assert 'a' in store + assert 'b' in store + assert 'c' not in store + assert 'foo/bar' in store + assert '/foo/bar' in store + assert '/foo/b' not in store + assert 'bar' not in store + + # gh-2694: tables.NaturalNameWarning with catch_warnings(record=True): store['node())'] = tm.makeDataFrame() - self.assertIn('node())', store) + assert 'node())' in store def test_versioning(self): @@ -4288,7 +4287,7 @@ def _check_roundtrip_table(self, obj, comparator, compression=False): comparator(retrieved, obj) def test_multiple_open_close(self): - # GH 4409, open & close multiple times + # gh-4409: open & close multiple times with ensure_clean_path(self.path) as path: @@ -4297,11 +4296,12 @@ def test_multiple_open_close(self): # single store = HDFStore(path) - self.assertNotIn('CLOSED', str(store)) - self.assertTrue(store.is_open) + assert 'CLOSED' not in str(store) + assert store.is_open + store.close() - self.assertIn('CLOSED', str(store)) - self.assertFalse(store.is_open) + assert 'CLOSED' in str(store) + assert not store.is_open with ensure_clean_path(self.path) as path: @@ -4321,22 +4321,22 @@ def f(): store1 = HDFStore(path) store2 = HDFStore(path) - self.assertNotIn('CLOSED', str(store1)) - self.assertNotIn('CLOSED', str(store2)) - self.assertTrue(store1.is_open) - self.assertTrue(store2.is_open) + assert 'CLOSED' not in str(store1) + assert 'CLOSED' not in str(store2) + assert store1.is_open + assert store2.is_open store1.close() - self.assertIn('CLOSED', str(store1)) - self.assertFalse(store1.is_open) - self.assertNotIn('CLOSED', str(store2)) - self.assertTrue(store2.is_open) + assert 'CLOSED' in str(store1) + assert not store1.is_open + assert 'CLOSED' not in str(store2) + assert store2.is_open store2.close() - self.assertIn('CLOSED', str(store1)) - self.assertIn('CLOSED', str(store2)) - self.assertFalse(store1.is_open) - self.assertFalse(store2.is_open) + assert 'CLOSED' in str(store1) + assert 'CLOSED' in str(store2) + assert not store1.is_open + assert not store2.is_open # nested close store = HDFStore(path, mode='w') @@ -4345,12 +4345,12 @@ def f(): store2 = HDFStore(path) store2.append('df2', df) store2.close() - self.assertIn('CLOSED', str(store2)) - self.assertFalse(store2.is_open) + assert 'CLOSED' in str(store2) + assert not store2.is_open store.close() - self.assertIn('CLOSED', str(store)) - self.assertFalse(store.is_open) + assert 'CLOSED' in str(store) + assert not store.is_open # double closing store = HDFStore(path, mode='w') @@ -4358,12 +4358,12 @@ def f(): store2 = HDFStore(path) store.close() - self.assertIn('CLOSED', str(store)) - self.assertFalse(store.is_open) + assert 'CLOSED' in str(store) + assert not store.is_open store2.close() - self.assertIn('CLOSED', str(store2)) - self.assertFalse(store2.is_open) + assert 'CLOSED' in str(store2) + assert not store2.is_open # ops on a closed store with ensure_clean_path(self.path) as path: diff --git a/pandas/tests/scalar/test_interval.py b/pandas/tests/scalar/test_interval.py index 717ef38a5b447..bd73a7d173962 100644 --- a/pandas/tests/scalar/test_interval.py +++ b/pandas/tests/scalar/test_interval.py @@ -26,19 +26,19 @@ def test_repr(self): self.assertEqual(str(interval_left), "[0, 1)") def test_contains(self): - self.assertIn(0.5, self.interval) - self.assertIn(1, self.interval) - self.assertNotIn(0, self.interval) + assert 0.5 in self.interval + assert 1 in self.interval + assert 0 not in self.interval pytest.raises(TypeError, lambda: self.interval in self.interval) interval = Interval(0, 1, closed='both') - self.assertIn(0, interval) - self.assertIn(1, interval) + assert 0 in interval + assert 1 in interval interval = Interval(0, 1, closed='neither') - self.assertNotIn(0, interval) - self.assertIn(0.5, interval) - self.assertNotIn(1, interval) + assert 0 not in interval + assert 0.5 in interval + assert 1 not in interval def test_equal(self): self.assertEqual(Interval(0, 1), Interval(0, 1, closed='right')) diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py index ae351b9d1cab9..055da8b2cc07f 100644 --- a/pandas/tests/scalar/test_timestamp.py +++ b/pandas/tests/scalar/test_timestamp.py @@ -310,40 +310,40 @@ def test_repr(self): tz_repr = tz date_only = Timestamp(date) - self.assertIn(date, repr(date_only)) - self.assertNotIn(tz_repr, repr(date_only)) - self.assertNotIn(freq_repr, repr(date_only)) - self.assertEqual(date_only, eval(repr(date_only))) + assert date in repr(date_only) + assert tz_repr not in repr(date_only) + assert freq_repr not in repr(date_only) + assert date_only == eval(repr(date_only)) date_tz = Timestamp(date, tz=tz) - self.assertIn(date, repr(date_tz)) - self.assertIn(tz_repr, repr(date_tz)) - self.assertNotIn(freq_repr, repr(date_tz)) - self.assertEqual(date_tz, eval(repr(date_tz))) + assert date in repr(date_tz) + assert tz_repr in repr(date_tz) + assert freq_repr not in repr(date_tz) + assert date_tz == eval(repr(date_tz)) date_freq = Timestamp(date, freq=freq) - self.assertIn(date, repr(date_freq)) - self.assertNotIn(tz_repr, repr(date_freq)) - self.assertIn(freq_repr, repr(date_freq)) - self.assertEqual(date_freq, eval(repr(date_freq))) + assert date in repr(date_freq) + assert tz_repr not in repr(date_freq) + assert freq_repr in repr(date_freq) + assert date_freq == eval(repr(date_freq)) date_tz_freq = Timestamp(date, tz=tz, freq=freq) - self.assertIn(date, repr(date_tz_freq)) - self.assertIn(tz_repr, repr(date_tz_freq)) - self.assertIn(freq_repr, repr(date_tz_freq)) - self.assertEqual(date_tz_freq, eval(repr(date_tz_freq))) + assert date in repr(date_tz_freq) + assert tz_repr in repr(date_tz_freq) + assert freq_repr in repr(date_tz_freq) + assert date_tz_freq == eval(repr(date_tz_freq)) - # this can cause the tz field to be populated, but it's redundant to - # information in the datestring + # This can cause the tz field to be populated, but it's redundant to + # include this information in the date-string. tm._skip_if_no_pytz() import pytz # noqa date_with_utc_offset = Timestamp('2014-03-13 00:00:00-0400', tz=None) - self.assertIn('2014-03-13 00:00:00-0400', repr(date_with_utc_offset)) - self.assertNotIn('tzoffset', repr(date_with_utc_offset)) - self.assertIn('pytz.FixedOffset(-240)', repr(date_with_utc_offset)) + assert '2014-03-13 00:00:00-0400' in repr(date_with_utc_offset) + assert 'tzoffset' not in repr(date_with_utc_offset) + assert 'pytz.FixedOffset(-240)' in repr(date_with_utc_offset) expr = repr(date_with_utc_offset).replace("'pytz.FixedOffset(-240)'", 'pytz.FixedOffset(-240)') - self.assertEqual(date_with_utc_offset, eval(expr)) + assert date_with_utc_offset == eval(expr) def test_bounds_with_different_units(self): out_of_bounds_dates = ('1677-09-21', '2262-04-12', ) diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py index 1003e84a1a942..1181e3a44f295 100644 --- a/pandas/tests/series/test_indexing.py +++ b/pandas/tests/series/test_indexing.py @@ -653,22 +653,20 @@ def test_slice(self): numSliceEnd = self.series[-10:] objSlice = self.objSeries[10:20] - self.assertNotIn(self.series.index[9], numSlice.index) - self.assertNotIn(self.objSeries.index[9], objSlice.index) + assert self.series.index[9] not in numSlice.index + assert self.objSeries.index[9] not in objSlice.index - self.assertEqual(len(numSlice), len(numSlice.index)) - self.assertEqual(self.series[numSlice.index[0]], - numSlice[numSlice.index[0]]) + assert len(numSlice) == len(numSlice.index) + assert self.series[numSlice.index[0]] == numSlice[numSlice.index[0]] - self.assertEqual(numSlice.index[1], self.series.index[11]) + assert numSlice.index[1] == self.series.index[11] + assert tm.equalContents(numSliceEnd, np.array(self.series)[-10:]) - self.assertTrue(tm.equalContents(numSliceEnd, np.array(self.series)[ - -10:])) - - # test return view + # Test return view. sl = self.series[10:20] sl[:] = 0 - self.assertTrue((self.series[10:20] == 0).all()) + + assert (self.series[10:20] == 0).all() def test_slice_can_reorder_not_uniquely_indexed(self): s = Series(1, index=['a', 'a', 'b', 'b', 'c']) diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index 188b96638344c..a80c5edcc21bd 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -37,21 +37,26 @@ def test_multilevel_name_print(self): self.assertEqual(repr(s), expected) def test_name_printing(self): - # test small series + # Test small Series. s = Series([0, 1, 2]) + s.name = "test" - self.assertIn("Name: test", repr(s)) + assert "Name: test" in repr(s) + s.name = None - self.assertNotIn("Name:", repr(s)) - # test big series (diff code path) + assert "Name:" not in repr(s) + + # Test big Series (diff code path). s = Series(lrange(0, 1000)) + s.name = "test" - self.assertIn("Name: test", repr(s)) + assert "Name: test" in repr(s) + s.name = None - self.assertNotIn("Name:", repr(s)) + assert "Name:" not in repr(s) s = Series(index=date_range('20010101', '20020101'), name='test') - self.assertIn("Name: test", repr(s)) + assert "Name: test" in repr(s) def test_repr(self): str(self.ts) diff --git a/pandas/tests/sparse/test_frame.py b/pandas/tests/sparse/test_frame.py index d5df744648ff3..ccb72d1f0d788 100644 --- a/pandas/tests/sparse/test_frame.py +++ b/pandas/tests/sparse/test_frame.py @@ -545,15 +545,15 @@ def test_delitem(self): C = self.frame['C'] del self.frame['B'] - self.assertNotIn('B', self.frame) + assert 'B' not in self.frame tm.assert_sp_series_equal(self.frame['A'], A) tm.assert_sp_series_equal(self.frame['C'], C) del self.frame['D'] - self.assertNotIn('D', self.frame) + assert 'D' not in self.frame del self.frame['A'] - self.assertNotIn('A', self.frame) + assert 'A' not in self.frame def test_set_columns(self): self.frame.columns = self.frame.columns @@ -829,22 +829,22 @@ def _check_frame(frame): # length zero length_zero = frame.reindex([]) - self.assertEqual(len(length_zero), 0) - self.assertEqual(len(length_zero.columns), len(frame.columns)) - self.assertEqual(len(length_zero['A']), 0) + assert len(length_zero) == 0 + assert len(length_zero.columns) == len(frame.columns) + assert len(length_zero['A']) == 0 # frame being reindexed has length zero length_n = length_zero.reindex(index) - self.assertEqual(len(length_n), len(frame)) - self.assertEqual(len(length_n.columns), len(frame.columns)) - self.assertEqual(len(length_n['A']), len(frame)) + assert len(length_n) == len(frame) + assert len(length_n.columns) == len(frame.columns) + assert len(length_n['A']) == len(frame) # reindex columns reindexed = frame.reindex(columns=['A', 'B', 'Z']) - self.assertEqual(len(reindexed.columns), 3) + assert len(reindexed.columns) == 3 tm.assert_almost_equal(reindexed['Z'].fill_value, frame.default_fill_value) - self.assertTrue(np.isnan(reindexed['Z'].sp_values).all()) + assert np.isnan(reindexed['Z'].sp_values).all() _check_frame(self.frame) _check_frame(self.iframe) @@ -854,11 +854,11 @@ def _check_frame(frame): # with copy=False reindexed = self.frame.reindex(self.frame.index, copy=False) reindexed['F'] = reindexed['A'] - self.assertIn('F', self.frame) + assert 'F' in self.frame reindexed = self.frame.reindex(self.frame.index) reindexed['G'] = reindexed['A'] - self.assertNotIn('G', self.frame) + assert 'G' not in self.frame def test_reindex_fill_value(self): rng = bdate_range('20110110', periods=20) diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index d91aab6bc3ceb..5814ae3494b44 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -45,8 +45,8 @@ class CheckImmutable(object): mutable_regex = re.compile('does not support mutable operations') def check_mutable_error(self, *args, **kwargs): - # pass whatever functions you normally would to assertRaises (after the - # Exception kind) + # Pass whatever function you normally would to assertRaisesRegexp + # (after the Exception kind). tm.assertRaisesRegexp(TypeError, self.mutable_regex, *args, **kwargs) def test_no_mutable_funcs(self): @@ -70,6 +70,7 @@ def delslice(): self.check_mutable_error(delslice) mutable_methods = getattr(self, "mutable_methods", []) + for meth in mutable_methods: self.check_mutable_error(getattr(self.container, meth)) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 703c8cc80e8f9..af56f0c33df2e 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -205,22 +205,22 @@ def test_set_axis(self): self.panel.items = new_items if hasattr(self.panel, '_item_cache'): - self.assertNotIn('ItemA', self.panel._item_cache) - self.assertIs(self.panel.items, new_items) + assert 'ItemA' not in self.panel._item_cache + assert self.panel.items is new_items # TODO: unused? item = self.panel[0] # noqa self.panel.major_axis = new_major - self.assertIs(self.panel[0].index, new_major) - self.assertIs(self.panel.major_axis, new_major) + assert self.panel[0].index is new_major + assert self.panel.major_axis is new_major # TODO: unused? item = self.panel[0] # noqa self.panel.minor_axis = new_minor - self.assertIs(self.panel[0].columns, new_minor) - self.assertIs(self.panel.minor_axis, new_minor) + assert self.panel[0].columns is new_minor + assert self.panel.minor_axis is new_minor def test_get_axis_number(self): self.assertEqual(self.panel._get_axis_number('items'), 0) @@ -447,10 +447,10 @@ def test_delitem_and_pop(self): expected = self.panel['ItemA'] result = self.panel.pop('ItemA') assert_frame_equal(expected, result) - self.assertNotIn('ItemA', self.panel.items) + assert 'ItemA' not in self.panel.items del self.panel['ItemB'] - self.assertNotIn('ItemB', self.panel.items) + assert 'ItemB' not in self.panel.items pytest.raises(Exception, self.panel.__delitem__, 'ItemB') values = np.empty((3, 3, 3)) @@ -464,18 +464,18 @@ def test_delitem_and_pop(self): panelc = panel.copy() del panelc[0] - assert_frame_equal(panelc[1], panel[1]) - assert_frame_equal(panelc[2], panel[2]) + tm.assert_frame_equal(panelc[1], panel[1]) + tm.assert_frame_equal(panelc[2], panel[2]) panelc = panel.copy() del panelc[1] - assert_frame_equal(panelc[0], panel[0]) - assert_frame_equal(panelc[2], panel[2]) + tm.assert_frame_equal(panelc[0], panel[0]) + tm.assert_frame_equal(panelc[2], panel[2]) panelc = panel.copy() del panelc[2] - assert_frame_equal(panelc[1], panel[1]) - assert_frame_equal(panelc[0], panel[0]) + tm.assert_frame_equal(panelc[1], panel[1]) + tm.assert_frame_equal(panelc[0], panel[0]) def test_setitem(self): with catch_warnings(record=True): diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py index f55452b44731c..33b17bc04cd79 100644 --- a/pandas/tests/test_panel4d.py +++ b/pandas/tests/test_panel4d.py @@ -182,16 +182,16 @@ def test_set_axis(self): self.panel4d.labels = new_labels if hasattr(self.panel4d, '_item_cache'): - self.assertNotIn('l1', self.panel4d._item_cache) - self.assertIs(self.panel4d.labels, new_labels) + assert 'l1' not in self.panel4d._item_cache + assert self.panel4d.labels is new_labels self.panel4d.major_axis = new_major - self.assertIs(self.panel4d[0].major_axis, new_major) - self.assertIs(self.panel4d.major_axis, new_major) + assert self.panel4d[0].major_axis is new_major + assert self.panel4d.major_axis is new_major self.panel4d.minor_axis = new_minor - self.assertIs(self.panel4d[0].minor_axis, new_minor) - self.assertIs(self.panel4d.minor_axis, new_minor) + assert self.panel4d[0].minor_axis is new_minor + assert self.panel4d.minor_axis is new_minor def test_get_axis_number(self): self.assertEqual(self.panel4d._get_axis_number('labels'), 0) @@ -315,10 +315,10 @@ def test_delitem_and_pop(self): expected = self.panel4d['l2'] result = self.panel4d.pop('l2') assert_panel_equal(expected, result) - self.assertNotIn('l2', self.panel4d.labels) + assert 'l2' not in self.panel4d.labels del self.panel4d['l3'] - self.assertNotIn('l3', self.panel4d.labels) + assert 'l3' not in self.panel4d.labels pytest.raises(Exception, self.panel4d.__delitem__, 'l3') values = np.empty((4, 4, 4, 4)) @@ -333,27 +333,27 @@ def test_delitem_and_pop(self): # did we delete the right row? panel4dc = panel4d.copy() del panel4dc[0] - assert_panel_equal(panel4dc[1], panel4d[1]) - assert_panel_equal(panel4dc[2], panel4d[2]) - assert_panel_equal(panel4dc[3], panel4d[3]) + tm.assert_panel_equal(panel4dc[1], panel4d[1]) + tm.assert_panel_equal(panel4dc[2], panel4d[2]) + tm.assert_panel_equal(panel4dc[3], panel4d[3]) panel4dc = panel4d.copy() del panel4dc[1] - assert_panel_equal(panel4dc[0], panel4d[0]) - assert_panel_equal(panel4dc[2], panel4d[2]) - assert_panel_equal(panel4dc[3], panel4d[3]) + tm.assert_panel_equal(panel4dc[0], panel4d[0]) + tm.assert_panel_equal(panel4dc[2], panel4d[2]) + tm.assert_panel_equal(panel4dc[3], panel4d[3]) panel4dc = panel4d.copy() del panel4dc[2] - assert_panel_equal(panel4dc[1], panel4d[1]) - assert_panel_equal(panel4dc[0], panel4d[0]) - assert_panel_equal(panel4dc[3], panel4d[3]) + tm.assert_panel_equal(panel4dc[1], panel4d[1]) + tm.assert_panel_equal(panel4dc[0], panel4d[0]) + tm.assert_panel_equal(panel4dc[3], panel4d[3]) panel4dc = panel4d.copy() del panel4dc[3] - assert_panel_equal(panel4dc[1], panel4d[1]) - assert_panel_equal(panel4dc[2], panel4d[2]) - assert_panel_equal(panel4dc[0], panel4d[0]) + tm.assert_panel_equal(panel4dc[1], panel4d[1]) + tm.assert_panel_equal(panel4dc[2], panel4d[2]) + tm.assert_panel_equal(panel4dc[0], panel4d[0]) def test_setitem(self): with catch_warnings(record=True): diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 7f62d319aa096..7565cbb859201 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1072,12 +1072,6 @@ def assertIn(first, second, msg=''): assert a in b, "%s: %r is not in %r" % (msg.format(a, b), a, b) -def assertNotIn(first, second, msg=''): - """Checks that 'first' is not in 'second'""" - a, b = first, second - assert a not in b, "%s: %r is in %r" % (msg.format(a, b), a, b) - - def assertIsNone(expr, msg=''): """Checks that 'expr' is None""" return assertIs(expr, None, msg) @@ -2500,40 +2494,79 @@ def assertRaisesRegexp(_exception, _regexp, _callable=None, *args, **kwargs): class _AssertRaisesContextmanager(object): """ - Handles the behind the scenes work - for assertRaises and assertRaisesRegexp + Context manager behind assertRaisesRegexp. """ - def __init__(self, exception, regexp=None, *args, **kwargs): + def __init__(self, exception, regexp=None): + """ + Initialize an _AssertRaisesContextManager instance. + + Parameters + ---------- + exception : class + The expected Exception class. + regexp : str, default None + The regex to compare against the Exception message. + """ + self.exception = exception + if regexp is not None and not hasattr(regexp, "search"): regexp = re.compile(regexp, re.DOTALL) + self.regexp = regexp def __enter__(self): return self - def __exit__(self, exc_type, exc_value, traceback): + def __exit__(self, exc_type, exc_value, trace_back): expected = self.exception - if not exc_type: - name = getattr(expected, "__name__", str(expected)) - raise AssertionError("{0} not raised.".format(name)) - if issubclass(exc_type, expected): - return self.handle_success(exc_type, exc_value, traceback) - return self.handle_failure(exc_type, exc_value, traceback) - - def handle_failure(*args, **kwargs): - # Failed, so allow Exception to bubble up - return False - def handle_success(self, exc_type, exc_value, traceback): - if self.regexp is not None: - val = str(exc_value) - if not self.regexp.search(val): - e = AssertionError('"%s" does not match "%s"' % - (self.regexp.pattern, str(val))) - raise_with_traceback(e, traceback) - return True + if not exc_type: + exp_name = getattr(expected, "__name__", str(expected)) + raise AssertionError("{0} not raised.".format(exp_name)) + + return self.exception_matches(exc_type, exc_value, trace_back) + + def exception_matches(self, exc_type, exc_value, trace_back): + """ + Check that the Exception raised matches the expected Exception + and expected error message regular expression. + + Parameters + ---------- + exc_type : class + The type of Exception raised. + exc_value : Exception + The instance of `exc_type` raised. + trace_back : stack trace object + The traceback object associated with `exc_value`. + + Returns + ------- + is_matched : bool + Whether or not the Exception raised matches the expected + Exception class and expected error message regular expression. + + Raises + ------ + AssertionError : The error message provided does not match + the expected error message regular expression. + """ + + if issubclass(exc_type, self.exception): + if self.regexp is not None: + val = str(exc_value) + + if not self.regexp.search(val): + e = AssertionError('"%s" does not match "%s"' % + (self.regexp.pattern, str(val))) + raise_with_traceback(e, trace_back) + + return True + else: + # Failed, so allow Exception to bubble up. + return False @contextmanager
Title is self-explanatory. Partially addresses #15990.
https://api.github.com/repos/pandas-dev/pandas/pulls/16096
2017-04-22T08:48:02Z
2017-04-23T13:57:46Z
2017-04-23T13:57:46Z
2017-04-23T18:18:18Z
API: raise notImplementedError on to_json(orient='table') for a DataFrame with a MultiIndex
diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py index 7149ab497a00d..28ea8298cee9e 100644 --- a/pandas/io/json/json.py +++ b/pandas/io/json/json.py @@ -6,7 +6,7 @@ from pandas._libs.tslib import iNaT from pandas.compat import StringIO, long, u from pandas import compat, isnull -from pandas import Series, DataFrame, to_datetime +from pandas import Series, DataFrame, to_datetime, MultiIndex from pandas.io.common import get_filepath_or_buffer, _get_handle from pandas.core.common import AbstractMethodError from pandas.io.formats.printing import pprint_thing @@ -138,6 +138,11 @@ def __init__(self, obj, orient, date_format, double_precision, self.schema = build_table_schema(obj) + # NotImplementd on a column MultiIndex + if obj.ndim == 2 and isinstance(obj.columns, MultiIndex): + raise NotImplementedError( + "orient='table' is not supported for MultiIndex") + # TODO: Do this timedelta properly in objToJSON.c See GH #15137 if ((obj.ndim == 1) and (obj.name in set(obj.index.names)) or len(obj.columns & obj.index.names)): diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index d2c3b47aba042..882c9b9bd42f6 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -1,7 +1,10 @@ # -*- coding: utf-8 -*- import pytest -from pandas import compat + +import numpy as np import pandas as pd + +from pandas import compat import pandas.io.formats.printing as printing import pandas.io.formats.format as fmt import pandas.util.testing as tm @@ -166,6 +169,18 @@ def test_publishes(self): 'application/vnd.dataresource+json'} self.assertEqual(set(arg.keys()), expected) + def test_publishes_not_implemented(self): + # column MultiIndex + # GH 15996 + midx = pd.MultiIndex.from_product([['A', 'B'], ['a', 'b', 'c']]) + df = pd.DataFrame(np.random.randn(5, len(midx)), columns=midx) + + make_patch = self.mock.patch('IPython.display.display') + opt = pd.option_context('display.html.table_schema', True) + with opt, make_patch as mock_display: # noqa + with pytest.raises(NotImplementedError): + df._ipython_display_() + def test_config_on(self): df = pd.DataFrame({"A": [1, 2]}) with pd.option_context("display.html.table_schema", True):
xref #15996
https://api.github.com/repos/pandas-dev/pandas/pulls/16095
2017-04-22T01:52:43Z
2017-04-22T02:18:12Z
2017-04-22T02:18:12Z
2017-04-22T12:22:16Z