diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index b48395efaf5c8..f72cf8cdaafe9 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -74,29 +74,29 @@ def test_corr_non_numeric(self): tm.assert_frame_equal(result, expected) @td.skip_if_no_scipy - def test_corr_nooverlap(self): + @pytest.mark.parametrize('meth', ['pearson', 'kendall', 'spearman']) + def test_corr_nooverlap(self, meth): # nothing in common - for meth in ['pearson', 'kendall', 'spearman']: - df = DataFrame({'A': [1, 1.5, 1, np.nan, np.nan, np.nan], - 'B': [np.nan, np.nan, np.nan, 1, 1.5, 1], - 'C': [np.nan, np.nan, np.nan, np.nan, - np.nan, np.nan]}) - rs = df.corr(meth) - assert isna(rs.loc['A', 'B']) - assert isna(rs.loc['B', 'A']) - assert rs.loc['A', 'A'] == 1 - assert rs.loc['B', 'B'] == 1 - assert isna(rs.loc['C', 'C']) + df = DataFrame({'A': [1, 1.5, 1, np.nan, np.nan, np.nan], + 'B': [np.nan, np.nan, np.nan, 1, 1.5, 1], + 'C': [np.nan, np.nan, np.nan, np.nan, + np.nan, np.nan]}) + rs = df.corr(meth) + assert isna(rs.loc['A', 'B']) + assert isna(rs.loc['B', 'A']) + assert rs.loc['A', 'A'] == 1 + assert rs.loc['B', 'B'] == 1 + assert isna(rs.loc['C', 'C']) @td.skip_if_no_scipy - def test_corr_constant(self): + @pytest.mark.parametrize('meth', ['pearson', 'spearman']) + def test_corr_constant(self, meth): # constant --> all NA - for meth in ['pearson', 'spearman']: - df = DataFrame({'A': [1, 1, 1, np.nan, np.nan, np.nan], - 'B': [np.nan, np.nan, np.nan, 1, 1, 1]}) - rs = df.corr(meth) - assert isna(rs.values).all() + df = DataFrame({'A': [1, 1, 1, np.nan, np.nan, np.nan], + 'B': [np.nan, np.nan, np.nan, 1, 1, 1]}) + rs = df.corr(meth) + assert isna(rs.values).all() def test_corr_int(self): # dtypes other than float64 #1761 @@ -658,21 +658,21 @@ def test_numeric_only_flag(self, meth): pytest.raises(TypeError, lambda: getattr(df2, meth)( axis=1, numeric_only=False)) - def test_mixed_ops(self): + @pytest.mark.parametrize('op', ['mean', 'std', 'var', + 'skew', 'kurt', 'sem']) + def test_mixed_ops(self, op): # 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 + + with pd.option_context('use_bottleneck', False): result = getattr(df, op)() assert len(result) == 2 - with pd.option_context('use_bottleneck', False): - result = getattr(df, op)() - assert len(result) == 2 - def test_cumsum(self): self.tsframe.loc[5:10, 0] = nan self.tsframe.loc[10:15, 1] = nan diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index e038588b76ffd..46c33000fb9ce 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -120,16 +120,15 @@ def test_apply_standard_nonunique(self): rs = df.T.apply(lambda s: s[0], axis=0) assert_series_equal(rs, xp) - def test_with_string_args(self): - - for arg in ['sum', 'mean', 'min', 'max', 'std']: - result = self.frame.apply(arg) - expected = getattr(self.frame, arg)() - tm.assert_series_equal(result, expected) + @pytest.mark.parametrize('arg', ['sum', 'mean', 'min', 'max', 'std']) + def test_with_string_args(self, arg): + result = self.frame.apply(arg) + expected = getattr(self.frame, arg)() + tm.assert_series_equal(result, expected) - result = self.frame.apply(arg, axis=1) - expected = getattr(self.frame, arg)(axis=1) - tm.assert_series_equal(result, expected) + result = self.frame.apply(arg, axis=1) + expected = getattr(self.frame, arg)(axis=1) + tm.assert_series_equal(result, expected) def test_apply_broadcast_deprecated(self): with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 004fb4eb0c128..0bc74c6890ee9 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -674,29 +674,12 @@ def _check_align(self, a, b, axis, fill_axis, how, method, limit=None): assert_frame_equal(aa, ea) assert_frame_equal(ab, eb) - def test_align_fill_method_inner(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('inner', meth, ax, fax) - - def test_align_fill_method_outer(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('outer', meth, ax, fax) - - def test_align_fill_method_left(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('left', meth, ax, fax) - - def test_align_fill_method_right(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('right', meth, ax, fax) + @pytest.mark.parametrize('meth', ['pad', 'bfill']) + @pytest.mark.parametrize('ax', [0, 1, None]) + @pytest.mark.parametrize('fax', [0, 1]) + @pytest.mark.parametrize('how', ['inner', 'outer', 'left', 'right']) + def test_align_fill_method(self, how, meth, ax, fax): + self._check_align_fill(how, meth, ax, fax) def _check_align_fill(self, kind, meth, ax, fax): left = self.frame.iloc[0:4, :10] diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index fdf50805ad818..1702b2e7d29a4 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -72,18 +72,18 @@ def test_operators(self): assert (df + df).equals(df) assert_frame_equal(df + df, df) - def test_ops_np_scalar(self): - vals, xs = np.random.rand(5, 3), [nan, 7, -23, 2.718, -3.14, np.inf] + @pytest.mark.parametrize('other', [nan, 7, -23, 2.718, -3.14, np.inf]) + def test_ops_np_scalar(self, other): + vals = np.random.randn(5, 3) f = lambda x: DataFrame(x, index=list('ABCDE'), columns=['jim', 'joe', 'jolie']) df = f(vals) - for x in xs: - assert_frame_equal(df / np.array(x), f(vals / x)) - assert_frame_equal(np.array(x) * df, f(vals * x)) - assert_frame_equal(df + np.array(x), f(vals + x)) - assert_frame_equal(np.array(x) - df, f(x - vals)) + assert_frame_equal(df / np.array(other), f(vals / other)) + assert_frame_equal(np.array(other) * df, f(vals * other)) + assert_frame_equal(df + np.array(other), f(vals + other)) + assert_frame_equal(np.array(other) - df, f(other - vals)) def test_operators_boolean(self): @@ -116,41 +116,40 @@ def test_operators_boolean(self): True, index=[1], columns=['A']) assert_frame_equal(result, DataFrame(1, index=[1], columns=['A'])) - def f(): - DataFrame(1.0, index=[1], columns=['A']) | DataFrame( - True, index=[1], columns=['A']) - pytest.raises(TypeError, f) + df1 = DataFrame(1.0, index=[1], columns=['A']) + df2 = DataFrame(True, index=[1], columns=['A']) + with pytest.raises(TypeError): + df1 | df2 - def f(): - DataFrame('foo', index=[1], columns=['A']) | DataFrame( - True, index=[1], columns=['A']) - pytest.raises(TypeError, f) + df1 = DataFrame('foo', index=[1], columns=['A']) + df2 = DataFrame(True, index=[1], columns=['A']) + with pytest.raises(TypeError): + df1 | df2 - def test_operators_none_as_na(self): + @pytest.mark.parametrize('op', [operator.add, operator.sub, + operator.mul, operator.truediv]) + def test_operators_none_as_na(self, op): df = DataFrame({"col1": [2, 5.0, 123, None], "col2": [1, 2, 3, 4]}, dtype=object) - ops = [operator.add, operator.sub, operator.mul, operator.truediv] - # since filling converts dtypes from object, changed expected to be # object - for op in ops: - filled = df.fillna(np.nan) - result = op(df, 3) - expected = op(filled, 3).astype(object) - expected[com.isna(expected)] = None - assert_frame_equal(result, expected) + filled = df.fillna(np.nan) + result = op(df, 3) + expected = op(filled, 3).astype(object) + expected[com.isna(expected)] = None + assert_frame_equal(result, expected) - result = op(df, df) - expected = op(filled, filled).astype(object) - expected[com.isna(expected)] = None - assert_frame_equal(result, expected) + result = op(df, df) + expected = op(filled, filled).astype(object) + expected[com.isna(expected)] = None + assert_frame_equal(result, expected) - result = op(df, df.fillna(7)) - assert_frame_equal(result, expected) + result = op(df, df.fillna(7)) + assert_frame_equal(result, expected) - result = op(df.fillna(7), df) - assert_frame_equal(result, expected, check_dtype=False) + result = op(df.fillna(7), df) + assert_frame_equal(result, expected, check_dtype=False) def test_comparison_invalid(self): @@ -978,8 +977,11 @@ def test_boolean_comparison(self): result = df.values > b_r assert_numpy_array_equal(result, expected.values) - pytest.raises(ValueError, df.__gt__, b_c) - pytest.raises(ValueError, df.values.__gt__, b_c) + with pytest.raises(ValueError): + df > b_c + + with pytest.raises(ValueError): + df.values > b_c # == expected = DataFrame([[False, False], [True, False], [False, False]]) @@ -998,7 +1000,9 @@ def test_boolean_comparison(self): result = df.values == b_r assert_numpy_array_equal(result, expected.values) - pytest.raises(ValueError, lambda: df == b_c) + with pytest.raises(ValueError): + df == b_c + assert df.values.shape != b_c.shape # with alignment diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index a226f8de3c8bd..a02f78bfaf8a5 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -1029,11 +1029,10 @@ def test_bool_arith_expr(self, parser, engine): expect = self.frame.a[self.frame.a < 1] + self.frame.b assert_series_equal(res, expect) - def test_invalid_type_for_operator_raises(self, parser, engine): + @pytest.mark.parametrize('op', ['+', '-', '*', '/']) + def test_invalid_type_for_operator_raises(self, parser, engine, op): df = DataFrame({'a': [1, 2], 'b': ['c', 'd']}) - ops = '+', '-', '*', '/' - for op in ops: - with tm.assert_raises_regex(TypeError, - r"unsupported operand type\(s\) " - "for .+: '.+' and '.+'"): - df.eval('a {0} b'.format(op), engine=engine, parser=parser) + with tm.assert_raises_regex(TypeError, + r"unsupported operand type\(s\) " + "for .+: '.+' and '.+'"): + df.eval('a {0} b'.format(op), engine=engine, parser=parser) diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index dd83a94b7062a..68d799c55637c 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -547,14 +547,12 @@ def test_regex_replace_numeric_to_object_conversion(self): assert_frame_equal(res, expec) assert res.a.dtype == np.object_ - def test_replace_regex_metachar(self): - metachars = '[]', '()', r'\d', r'\w', r'\s' - - for metachar in metachars: - df = DataFrame({'a': [metachar, 'else']}) - result = df.replace({'a': {metachar: 'paren'}}) - expected = DataFrame({'a': ['paren', 'else']}) - assert_frame_equal(result, expected) + @pytest.mark.parametrize('metachar', ['[]', '()', r'\d', r'\w', r'\s']) + def test_replace_regex_metachar(self, metachar): + df = DataFrame({'a': [metachar, 'else']}) + result = df.replace({'a': {metachar: 'paren'}}) + expected = DataFrame({'a': ['paren', 'else']}) + assert_frame_equal(result, expected) def test_replace(self): self.tsframe['A'][:5] = nan diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index ebf6c5e37b916..2f90d24f652ca 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -855,21 +855,21 @@ def _test_stack_with_multiindex(multiindex): dtype=df.dtypes[0]) assert_frame_equal(result, expected) - def test_stack_preserve_categorical_dtype(self): + @pytest.mark.parametrize('ordered', [False, True]) + @pytest.mark.parametrize('labels', [list("yxz"), list("yxy")]) + def test_stack_preserve_categorical_dtype(self, ordered, labels): # GH13854 - for ordered in [False, True]: - for labels in [list("yxz"), list("yxy")]: - cidx = pd.CategoricalIndex(labels, categories=list("xyz"), - ordered=ordered) - df = DataFrame([[10, 11, 12]], columns=cidx) - result = df.stack() - - # `MutliIndex.from_product` preserves categorical dtype - - # it's tested elsewhere. - midx = pd.MultiIndex.from_product([df.index, cidx]) - expected = Series([10, 11, 12], index=midx) - - tm.assert_series_equal(result, expected) + cidx = pd.CategoricalIndex(labels, categories=list("xyz"), + ordered=ordered) + df = DataFrame([[10, 11, 12]], columns=cidx) + result = df.stack() + + # `MutliIndex.from_product` preserves categorical dtype - + # it's tested elsewhere. + midx = pd.MultiIndex.from_product([df.index, cidx]) + expected = Series([10, 11, 12], index=midx) + + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("level", [0, 'baz']) def test_unstack_swaplevel_sortlevel(self, level): diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index eccd86a888fb9..0e0ea51479e81 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1038,9 +1038,10 @@ def test_add_raises(self): dt1 + dt2 boxes = [lambda x: x, lambda x: pd.Series([x]), lambda x: pd.Index([x])] + ids = ['identity', 'Series', 'Index'] - @pytest.mark.parametrize('lbox', boxes) - @pytest.mark.parametrize('rbox', boxes) + @pytest.mark.parametrize('lbox', boxes, ids=ids) + @pytest.mark.parametrize('rbox', boxes, ids=ids) def test_add_timestamp_raises(self, rbox, lbox): # GH # 17983 ts = pd.Timestamp('2017') diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 840c80d6775a5..ed3191cf849c0 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -237,6 +237,23 @@ def test_rename_axis_inplace(self): assert no_return is None assert_series_equal(result, expected) + def test_set_axis_inplace_axes(self, axis_series): + # GH14636 + ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype='int64') + + expected = ser.copy() + expected.index = list('abcd') + + # inplace=True + # The FutureWarning comes from the fact that we would like to have + # inplace default to False some day + for inplace, warn in [(None, FutureWarning), (True, None)]: + result = ser.copy() + kwargs = {'inplace': inplace} + with tm.assert_produces_warning(warn): + result.set_axis(list('abcd'), axis=axis_series, **kwargs) + tm.assert_series_equal(result, expected) + def test_set_axis_inplace(self): # GH14636 @@ -245,17 +262,6 @@ def test_set_axis_inplace(self): expected = s.copy() expected.index = list('abcd') - for axis in 0, 'index': - # inplace=True - # The FutureWarning comes from the fact that we would like to have - # inplace default to False some day - for inplace, warn in (None, FutureWarning), (True, None): - result = s.copy() - kwargs = {'inplace': inplace} - with tm.assert_produces_warning(warn): - result.set_axis(list('abcd'), axis=axis, **kwargs) - tm.assert_series_equal(result, expected) - # inplace=False result = s.set_axis(list('abcd'), axis=0, inplace=False) tm.assert_series_equal(expected, result) @@ -266,7 +272,7 @@ def test_set_axis_inplace(self): tm.assert_series_equal(result, expected) # wrong values for the "axis" parameter - for axis in 2, 'foo': + for axis in [2, 'foo']: with tm.assert_raises_regex(ValueError, 'No axis named'): s.set_axis(list('abcd'), axis=axis, inplace=False) @@ -276,7 +282,7 @@ def test_set_axis_prior_to_deprecation_signature(self): expected = s.copy() expected.index = list('abcd') - for axis in 0, 'index': + for axis in [0, 'index']: with tm.assert_produces_warning(FutureWarning): result = s.set_axis(0, list('abcd'), inplace=False) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index 47798d0ddd7f5..7a02ce3a1fb2e 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -255,12 +255,9 @@ def get_dir(s): # trying to set a copy with pd.option_context('chained_assignment', 'raise'): - - def f(): + with pytest.raises(com.SettingWithCopyError): s.dt.hour[0] = 5 - pytest.raises(com.SettingWithCopyError, f) - def test_dt_namespace_accessor_categorical(self): # GH 19468 dti = DatetimeIndex(['20171111', '20181212']).repeat(2) @@ -420,12 +417,14 @@ def test_dt_accessor_api(self): s = Series(date_range('2000-01-01', periods=3)) assert isinstance(s.dt, DatetimeProperties) - for s in [Series(np.arange(5)), Series(list('abcde')), - Series(np.random.randn(5))]: - with tm.assert_raises_regex(AttributeError, - "only use .dt accessor"): - s.dt - assert not hasattr(s, 'dt') + @pytest.mark.parametrize('ser', [Series(np.arange(5)), + Series(list('abcde')), + Series(np.random.randn(5))]) + def test_dt_accessor_invalid(self, ser): + # GH#9322 check that series with incorrect dtypes don't have attr + with tm.assert_raises_regex(AttributeError, "only use .dt accessor"): + ser.dt + assert not hasattr(ser, 'dt') def test_between(self): s = Series(bdate_range('1/1/2000', periods=20).astype(object)) diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index ecb74622edf10..fad2b025dd3e4 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -136,10 +136,14 @@ def test_categorical_comparisons(self): assert ((~(f == a) == (f != a)).all()) # non-equality is not comparable - pytest.raises(TypeError, lambda: a < b) - pytest.raises(TypeError, lambda: b < a) - pytest.raises(TypeError, lambda: a > b) - pytest.raises(TypeError, lambda: b > a) + with pytest.raises(TypeError): + a < b + with pytest.raises(TypeError): + b < a + with pytest.raises(TypeError): + a > b + with pytest.raises(TypeError): + b > a def test_comparison_tuples(self): # GH11339 @@ -204,20 +208,21 @@ def test_comparison_operators_with_nas(self): # expected = f(val, s.dropna()).reindex(s.index) # assert_series_equal(result, expected) - # boolean &, |, ^ should work with object arrays and propagate NAs + @pytest.mark.parametrize('bool_op', [operator.and_, + operator.or_, operator.xor]) + def test_bool_operators_with_nas(self, bool_op): + # boolean &, |, ^ should work with object arrays and propagate NAs + ser = Series(bdate_range('1/1/2000', periods=10), dtype=object) + ser[::2] = np.nan - ops = ['and_', 'or_', 'xor'] mask = ser.isna() - for bool_op in ops: - func = getattr(operator, bool_op) - - filled = ser.fillna(ser[0]) + filled = ser.fillna(ser[0]) - result = func(ser < ser[9], ser > ser[3]) + result = bool_op(ser < ser[9], ser > ser[3]) - expected = func(filled < filled[9], filled > filled[3]) - expected[mask] = False - assert_series_equal(result, expected) + expected = bool_op(filled < filled[9], filled > filled[3]) + expected[mask] = False + assert_series_equal(result, expected) def test_comparison_object_numeric_nas(self): ser = Series(np.random.randn(10), dtype=object) @@ -248,27 +253,26 @@ def test_comparison_invalid(self): def test_unequal_categorical_comparison_raises_type_error(self): # unequal comparison should raise for unordered cats cat = Series(Categorical(list("abc"))) - - def f(): + with pytest.raises(TypeError): cat > "b" - pytest.raises(TypeError, f) cat = Series(Categorical(list("abc"), ordered=False)) - - def f(): + with pytest.raises(TypeError): cat > "b" - pytest.raises(TypeError, f) - # 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 = Series(Categorical(list("abc"), ordered=True)) - pytest.raises(TypeError, lambda: cat < "d") - pytest.raises(TypeError, lambda: cat > "d") - pytest.raises(TypeError, lambda: "d" < cat) - pytest.raises(TypeError, lambda: "d" > cat) + with pytest.raises(TypeError): + cat < "d" + with pytest.raises(TypeError): + cat > "d" + with pytest.raises(TypeError): + "d" < cat + with pytest.raises(TypeError): + "d" > cat tm.assert_series_equal(cat == "d", Series([False, False, False])) tm.assert_series_equal(cat != "d", Series([True, True, True])) @@ -365,11 +369,13 @@ def test_nat_comparisons_scalar(self, dtype, data): def test_comparison_different_length(self): a = Series(['a', 'b', 'c']) b = Series(['b', 'a']) - pytest.raises(ValueError, a.__lt__, b) + with pytest.raises(ValueError): + a < b a = Series([1, 2]) b = Series([2, 3, 4]) - pytest.raises(ValueError, a.__eq__, b) + with pytest.raises(ValueError): + a == b def test_comparison_label_based(self): @@ -448,7 +454,8 @@ def test_comparison_label_based(self): assert_series_equal(result, expected) for v in [np.nan, 'foo']: - pytest.raises(TypeError, lambda: t | v) + with pytest.raises(TypeError): + t | v for v in [False, 0]: result = Series([True, False, True], index=index) | v @@ -465,7 +472,8 @@ def test_comparison_label_based(self): expected = Series([False, False, False], index=index) assert_series_equal(result, expected) for v in [np.nan]: - pytest.raises(TypeError, lambda: t & v) + with pytest.raises(TypeError): + t & v def test_comparison_flex_basic(self): left = pd.Series(np.random.randn(10)) @@ -930,12 +938,14 @@ def test_operators_datetimelike_with_timezones(self): result = dt1 - td1[0] exp = (dt1.dt.tz_localize(None) - td1[0]).dt.tz_localize(tz) assert_series_equal(result, exp) - pytest.raises(TypeError, lambda: td1[0] - dt1) + with pytest.raises(TypeError): + td1[0] - dt1 result = dt2 - td2[0] exp = (dt2.dt.tz_localize(None) - td2[0]).dt.tz_localize(tz) assert_series_equal(result, exp) - pytest.raises(TypeError, lambda: td2[0] - dt2) + with pytest.raises(TypeError): + td2[0] - dt2 result = dt1 + td1 exp = (dt1.dt.tz_localize(None) + td1).dt.tz_localize(tz) @@ -953,8 +963,10 @@ def test_operators_datetimelike_with_timezones(self): exp = (dt2.dt.tz_localize(None) - td2).dt.tz_localize(tz) assert_series_equal(result, exp) - pytest.raises(TypeError, lambda: td1 - dt1) - pytest.raises(TypeError, lambda: td2 - dt2) + with pytest.raises(TypeError): + td1 - dt1 + with pytest.raises(TypeError): + td2 - dt2 def test_sub_single_tz(self): # GH12290 @@ -1483,11 +1495,16 @@ def test_operators_bitwise(self): expected = Series([1, 1, 3, 3], dtype='int32') assert_series_equal(res, expected) - pytest.raises(TypeError, lambda: s_1111 & 'a') - pytest.raises(TypeError, lambda: s_1111 & ['a', 'b', 'c', 'd']) - pytest.raises(TypeError, lambda: s_0123 & np.NaN) - pytest.raises(TypeError, lambda: s_0123 & 3.14) - pytest.raises(TypeError, lambda: s_0123 & [0.1, 4, 3.14, 2]) + with pytest.raises(TypeError): + s_1111 & 'a' + with pytest.raises(TypeError): + s_1111 & ['a', 'b', 'c', 'd'] + with pytest.raises(TypeError): + s_0123 & np.NaN + with pytest.raises(TypeError): + s_0123 & 3.14 + with pytest.raises(TypeError): + s_0123 & [0.1, 4, 3.14, 2] # s_0123 will be all false now because of reindexing like s_tft if compat.PY3: @@ -1530,14 +1547,16 @@ def test_scalar_na_cmp_corners(self): def tester(a, b): return a & b - pytest.raises(TypeError, tester, s, datetime(2005, 1, 1)) + with pytest.raises(TypeError): + s & datetime(2005, 1, 1) s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)]) s[::2] = np.nan expected = Series(True, index=s.index) expected[::2] = False - assert_series_equal(tester(s, list(s)), expected) + result = s & list(s) + assert_series_equal(result, expected) d = DataFrame({'A': s}) # TODO: Fix this exception - needs to be fixed! (see GH5035) @@ -1587,7 +1606,25 @@ def test_operators_reverse_object(self, op): expected = op(1., arr.astype(float)) assert_series_equal(result.astype(float), expected) - def test_operators_combine(self): + pairings = [] + for op in ['add', 'sub', 'mul', 'pow', 'truediv', 'floordiv']: + fv = 0 + lop = getattr(Series, op) + lequiv = getattr(operator, op) + rop = getattr(Series, 'r' + op) + # bind op at definition time... + requiv = lambda x, y, op=op: getattr(operator, op)(y, x) + pairings.append((lop, lequiv, fv)) + pairings.append((rop, requiv, fv)) + if compat.PY3: + pairings.append((Series.div, operator.truediv, 1)) + pairings.append((Series.rdiv, lambda x, y: operator.truediv(y, x), 1)) + else: + pairings.append((Series.div, operator.div, 1)) + pairings.append((Series.rdiv, lambda x, y: operator.div(y, x), 1)) + + @pytest.mark.parametrize('op, equiv_op, fv', pairings) + def test_operators_combine(self, op, equiv_op, fv): def _check_fill(meth, op, a, b, fill_value=0): exp_index = a.index.union(b.index) a = a.reindex(exp_index) @@ -1619,32 +1656,12 @@ def _check_fill(meth, op, a, b, fill_value=0): a = Series([nan, 1., 2., 3., nan], index=np.arange(5)) b = Series([nan, 1, nan, 3, nan, 4.], index=np.arange(6)) - pairings = [] - for op in ['add', 'sub', 'mul', 'pow', 'truediv', 'floordiv']: - fv = 0 - lop = getattr(Series, op) - lequiv = getattr(operator, op) - rop = getattr(Series, 'r' + op) - # bind op at definition time... - requiv = lambda x, y, op=op: getattr(operator, op)(y, x) - pairings.append((lop, lequiv, fv)) - pairings.append((rop, requiv, fv)) - - if compat.PY3: - pairings.append((Series.div, operator.truediv, 1)) - pairings.append((Series.rdiv, lambda x, y: operator.truediv(y, x), - 1)) - else: - pairings.append((Series.div, operator.div, 1)) - pairings.append((Series.rdiv, lambda x, y: operator.div(y, x), 1)) - - for op, equiv_op, fv in pairings: - result = op(a, b) - exp = equiv_op(a, b) - assert_series_equal(result, exp) - _check_fill(op, equiv_op, a, b, fill_value=fv) - # should accept axis=0 or axis='rows' - op(a, b, axis=0) + result = op(a, b) + exp = equiv_op(a, b) + assert_series_equal(result, exp) + _check_fill(op, equiv_op, a, b, fill_value=fv) + # should accept axis=0 or axis='rows' + op(a, b, axis=0) def test_operators_na_handling(self): from decimal import Decimal diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index 63726f27914f3..62b59b5d405c9 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd import pandas.util.testing as tm @@ -72,22 +73,23 @@ def test_between(self): # --------------------------------------------------------------------- # NaT support - """ - # ToDo: Enable when support period dtype + @pytest.mark.xfail(reason="PeriodDtype Series not supported yet", + strict=True) def test_NaT_scalar(self): - series = Series([0, 1000, 2000, iNaT], dtype='period[D]') + series = Series([0, 1000, 2000, pd._libs.iNaT], dtype='period[D]') val = series[3] - assert isna(val) + assert pd.isna(val) series[2] = val - assert isna(series[2]) + assert pd.isna(series[2]) + @pytest.mark.xfail(reason="PeriodDtype Series not supported yet", + strict=True) def test_NaT_cast(self): result = Series([np.nan]).astype('period[D]') - expected = Series([NaT]) + expected = Series([pd.NaT]) tm.assert_series_equal(result, expected) - """ def test_set_none_nan(self): # currently Period is stored as object dtype, not as NaT diff --git a/pandas/tests/series/test_quantile.py b/pandas/tests/series/test_quantile.py index 3c93ff1d3f31e..df8799cf5c900 100644 --- a/pandas/tests/series/test_quantile.py +++ b/pandas/tests/series/test_quantile.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + import numpy as np import pandas as pd @@ -113,31 +115,30 @@ def test_quantile_nan(self): tm.assert_series_equal(res, pd.Series([np.nan, np.nan], index=[0.2, 0.3])) - def test_quantile_box(self): - cases = [[pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), - pd.Timestamp('2011-01-03')], - [pd.Timestamp('2011-01-01', tz='US/Eastern'), - pd.Timestamp('2011-01-02', tz='US/Eastern'), - pd.Timestamp('2011-01-03', tz='US/Eastern')], - [pd.Timedelta('1 days'), pd.Timedelta('2 days'), - pd.Timedelta('3 days')], - # NaT - [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), - pd.Timestamp('2011-01-03'), pd.NaT], - [pd.Timestamp('2011-01-01', tz='US/Eastern'), - pd.Timestamp('2011-01-02', tz='US/Eastern'), - pd.Timestamp('2011-01-03', tz='US/Eastern'), pd.NaT], - [pd.Timedelta('1 days'), pd.Timedelta('2 days'), - pd.Timedelta('3 days'), pd.NaT]] - - for case in cases: - s = pd.Series(case, name='XXX') - res = s.quantile(0.5) - assert res == case[1] + @pytest.mark.parametrize('case', [ + [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), + pd.Timestamp('2011-01-03')], + [pd.Timestamp('2011-01-01', tz='US/Eastern'), + pd.Timestamp('2011-01-02', tz='US/Eastern'), + pd.Timestamp('2011-01-03', tz='US/Eastern')], + [pd.Timedelta('1 days'), pd.Timedelta('2 days'), + pd.Timedelta('3 days')], + # NaT + [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), + pd.Timestamp('2011-01-03'), pd.NaT], + [pd.Timestamp('2011-01-01', tz='US/Eastern'), + pd.Timestamp('2011-01-02', tz='US/Eastern'), + pd.Timestamp('2011-01-03', tz='US/Eastern'), pd.NaT], + [pd.Timedelta('1 days'), pd.Timedelta('2 days'), + pd.Timedelta('3 days'), pd.NaT]]) + def test_quantile_box(self, case): + s = pd.Series(case, name='XXX') + res = s.quantile(0.5) + assert res == case[1] - res = s.quantile([0.5]) - exp = pd.Series([case[1]], index=[0.5], name='XXX') - tm.assert_series_equal(res, exp) + res = s.quantile([0.5]) + exp = pd.Series([case[1]], index=[0.5], name='XXX') + tm.assert_series_equal(res, exp) def test_datetime_timedelta_quantiles(self): # covers #9694 diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 376b4d71f81e8..72492de4b1247 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -78,7 +78,8 @@ def test_shift(self): assert_series_equal(shifted2, shifted3) assert_series_equal(ps, shifted2.shift(-1, 'B')) - pytest.raises(ValueError, ps.shift, freq='D') + with pytest.raises(ValueError): + ps.shift(freq='D') # legacy support shifted4 = ps.shift(1, freq='B') @@ -109,7 +110,8 @@ def test_shift(self): # incompat tz s2 = Series(date_range('2000-01-01 09:00:00', periods=5, tz='CET'), name='foo') - pytest.raises(TypeError, lambda: s - s2) + with pytest.raises(TypeError): + s - s2 def test_shift2(self): ts = Series(np.random.randn(5), @@ -168,7 +170,8 @@ def test_tshift(self): shifted3 = ps.tshift(freq=BDay()) assert_series_equal(shifted, shifted3) - pytest.raises(ValueError, ps.tshift, freq='M') + with pytest.raises(ValueError): + ps.tshift(freq='M') # DatetimeIndex shifted = self.ts.tshift(1) @@ -187,7 +190,8 @@ def test_tshift(self): assert_series_equal(unshifted, inferred_ts) no_freq = self.ts[[0, 5, 7]] - pytest.raises(ValueError, no_freq.tshift) + with pytest.raises(ValueError): + no_freq.tshift() def test_truncate(self): offset = BDay() @@ -459,7 +463,8 @@ def test_empty_series_ops(self): assert_series_equal(a, a + b) assert_series_equal(a, a - b) assert_series_equal(a, b + a) - pytest.raises(TypeError, lambda x, y: x - y, b, a) + with pytest.raises(TypeError): + b - a def test_contiguous_boolean_preserve_freq(self): rng = date_range('1/1/2000', '3/1/2000', freq='B') @@ -791,16 +796,19 @@ def test_between_time_raises(self): def test_between_time_types(self): # GH11818 rng = date_range('1/1/2000', '1/5/2000', freq='5min') - pytest.raises(ValueError, rng.indexer_between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + with pytest.raises(ValueError): + rng.indexer_between_time(datetime(2010, 1, 2, 1), + datetime(2010, 1, 2, 5)) frame = DataFrame({'A': 0}, index=rng) - pytest.raises(ValueError, frame.between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + with pytest.raises(ValueError): + frame.between_time(datetime(2010, 1, 2, 1), + datetime(2010, 1, 2, 5)) series = Series(0, index=rng) - pytest.raises(ValueError, series.between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + with pytest.raises(ValueError): + series.between_time(datetime(2010, 1, 2, 1), + datetime(2010, 1, 2, 5)) @td.skip_if_has_locale def test_between_time_formats(self): @@ -921,40 +929,40 @@ def test_pickle(self): idx_p = tm.round_trip_pickle(idx) tm.assert_index_equal(idx, idx_p) - def test_setops_preserve_freq(self): - for tz in [None, 'Asia/Tokyo', 'US/Eastern']: - rng = date_range('1/1/2000', '1/1/2002', name='idx', tz=tz) - - result = rng[:50].union(rng[50:100]) - assert result.name == rng.name - assert result.freq == rng.freq - assert result.tz == rng.tz - - result = rng[:50].union(rng[30:100]) - assert result.name == rng.name - assert result.freq == rng.freq - assert result.tz == rng.tz - - result = rng[:50].union(rng[60:100]) - assert result.name == rng.name - assert result.freq is None - assert result.tz == rng.tz - - result = rng[:50].intersection(rng[25:75]) - assert result.name == rng.name - assert result.freqstr == 'D' - assert result.tz == rng.tz - - nofreq = DatetimeIndex(list(rng[25:75]), name='other') - result = rng[:50].union(nofreq) - assert result.name is None - assert result.freq == rng.freq - assert result.tz == rng.tz - - result = rng[:50].intersection(nofreq) - assert result.name is None - assert result.freq == rng.freq - assert result.tz == rng.tz + @pytest.mark.parametrize('tz', [None, 'Asia/Tokyo', 'US/Eastern']) + def test_setops_preserve_freq(self, tz): + rng = date_range('1/1/2000', '1/1/2002', name='idx', tz=tz) + + result = rng[:50].union(rng[50:100]) + assert result.name == rng.name + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].union(rng[30:100]) + assert result.name == rng.name + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].union(rng[60:100]) + assert result.name == rng.name + assert result.freq is None + assert result.tz == rng.tz + + result = rng[:50].intersection(rng[25:75]) + assert result.name == rng.name + assert result.freqstr == 'D' + assert result.tz == rng.tz + + nofreq = DatetimeIndex(list(rng[25:75]), name='other') + result = rng[:50].union(nofreq) + assert result.name is None + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].intersection(nofreq) + assert result.name is None + assert result.freq == rng.freq + assert result.tz == rng.tz def test_min_max(self): rng = date_range('1/1/2000', '12/31/2000')