diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py index 805ed960c2cf1..cd967ecafd8b4 100644 --- a/pandas/computation/tests/test_eval.py +++ b/pandas/computation/tests/test_eval.py @@ -1580,7 +1580,7 @@ def test_unary_functions(self): expr = "{0}(a)".format(fn) got = self.eval(expr) expect = getattr(np, fn)(a) - pd.util.testing.assert_almost_equal(got, expect) + tm.assert_series_equal(got, expect, check_names=False) def test_binary_functions(self): df = DataFrame({'a': np.random.randn(10), @@ -1601,7 +1601,7 @@ def test_df_use_case(self): parser=self.parser, inplace=True) got = df.e expect = np.arctan2(np.sin(df.a), df.b) - pd.util.testing.assert_almost_equal(got, expect) + tm.assert_series_equal(got, expect, check_names=False) def test_df_arithmetic_subexpression(self): df = DataFrame({'a': np.random.randn(10), @@ -1611,7 +1611,7 @@ def test_df_arithmetic_subexpression(self): parser=self.parser, inplace=True) got = df.e expect = np.sin(df.a + df.b) - pd.util.testing.assert_almost_equal(got, expect) + tm.assert_series_equal(got, expect, check_names=False) def check_result_type(self, dtype, expect_dtype): df = DataFrame({'a': np.random.randn(10).astype(dtype)}) @@ -1623,7 +1623,7 @@ def check_result_type(self, dtype, expect_dtype): expect = np.sin(df.a) self.assertEqual(expect.dtype, got.dtype) self.assertEqual(expect_dtype, got.dtype) - pd.util.testing.assert_almost_equal(got, expect) + tm.assert_series_equal(got, expect, check_names=False) def test_result_types(self): self.check_result_type(np.int32, np.float64) diff --git a/pandas/io/tests/test_cparser.py b/pandas/io/tests/test_cparser.py index 52cb56bea1122..ce6fce7b792b5 100644 --- a/pandas/io/tests/test_cparser.py +++ b/pandas/io/tests/test_cparser.py @@ -130,8 +130,8 @@ def test_integer_thousands_alt(self): thousands='.', header=None) result = reader.read() - expected = [123456, 12500] - tm.assert_almost_equal(result[0], expected) + expected = DataFrame([123456, 12500]) + tm.assert_frame_equal(result, expected) def test_skip_bad_lines(self): # too many lines, see #2430 for why diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py index c073ee3334e55..24a73b3825a70 100644 --- a/pandas/sparse/tests/test_sparse.py +++ b/pandas/sparse/tests/test_sparse.py @@ -440,7 +440,8 @@ def _compare(idx): # Corner case sp = SparseSeries(np.ones(10) * nan) - assert_almost_equal(sp.take([0, 1, 2, 3, 4]), np.repeat(nan, 5)) + exp = pd.Series(np.repeat(nan, 5)) + tm.assert_series_equal(sp.take([0, 1, 2, 3, 4]), exp) def test_setitem(self): self.bseries[5] = 7. @@ -1872,8 +1873,10 @@ def test_setitem(self): assert_sp_frame_equal(self.panel['ItemE'], self.panel['ItemC']) assert_sp_frame_equal(self.panel['ItemF'], self.panel['ItemC']) - assert_almost_equal(self.panel.items, ['ItemA', 'ItemB', 'ItemC', - 'ItemD', 'ItemE', 'ItemF']) + + expected = pd.Index(['ItemA', 'ItemB', 'ItemC', + 'ItemD', 'ItemE', 'ItemF']) + tm.assert_index_equal(self.panel.items, expected) self.assertRaises(Exception, self.panel.__setitem__, 'item6', 1) @@ -1890,11 +1893,12 @@ def _check_loc(item, major, minor, val=1.5): def test_delitem_pop(self): del self.panel['ItemB'] - assert_almost_equal(self.panel.items, ['ItemA', 'ItemC', 'ItemD']) + tm.assert_index_equal(self.panel.items, + pd.Index(['ItemA', 'ItemC', 'ItemD'])) crackle = self.panel['ItemC'] pop = self.panel.pop('ItemC') self.assertIs(pop, crackle) - assert_almost_equal(self.panel.items, ['ItemA', 'ItemD']) + tm.assert_almost_equal(self.panel.items, pd.Index(['ItemA', 'ItemD'])) self.assertRaises(KeyError, self.panel.__delitem__, 'ItemC') diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 884a147d7509f..2d7ba6c704e41 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -10,8 +10,7 @@ from pandas import DataFrame, Series, Index, MultiIndex, RangeIndex import pandas as pd -from pandas.util.testing import (assert_almost_equal, - assert_series_equal, +from pandas.util.testing import (assert_series_equal, assert_frame_equal, assertRaisesRegexp) @@ -447,7 +446,7 @@ def test_reset_index(self): stacked.index.labels)): values = lev.take(lab) name = names[i] - assert_almost_equal(values, deleveled[name]) + tm.assert_index_equal(values, Index(deleveled[name])) stacked.index.names = [None, None] deleveled2 = stacked.reset_index() diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 87c263e129361..70e8d3bcf4582 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -28,8 +28,7 @@ from pandas.core.dtypes import DatetimeTZDtype -from pandas.util.testing import (assert_almost_equal, - assert_numpy_array_equal, +from pandas.util.testing import (assert_numpy_array_equal, assert_series_equal, assert_frame_equal, assertRaisesRegexp) @@ -359,7 +358,7 @@ def test_constructor_dict_block(self): expected = [[4., 3., 2., 1.]] df = DataFrame({'d': [4.], 'c': [3.], 'b': [2.], 'a': [1.]}, columns=['d', 'c', 'b', 'a']) - assert_almost_equal(df.values, expected) + tm.assert_numpy_array_equal(df.values, expected) def test_constructor_dict_cast(self): # cast float tests diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 6077c8e6f63ee..55631ad831441 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -1555,7 +1555,7 @@ def testit(df): 'mask_c': [False, True, False, True]}) df['mask'] = df.lookup(df.index, 'mask_' + df['label']) exp_mask = alt(df, df.index, 'mask_' + df['label']) - assert_almost_equal(df['mask'], exp_mask) + tm.assert_series_equal(df['mask'], pd.Series(exp_mask, name='mask')) self.assertEqual(df['mask'].dtype, np.bool_) with tm.assertRaises(KeyError): @@ -2070,7 +2070,9 @@ def test_xs_corner(self): df['E'] = 3. xs = df.xs(0) - assert_almost_equal(xs, [1., 'foo', 2., 'bar', 3.]) + exp = pd.Series([1., 'foo', 2., 'bar', 3.], + index=list('ABCDE'), name=0) + tm.assert_series_equal(xs, exp) # no columns but Index(dtype=object) df = DataFrame(index=['a', 'b', 'c']) diff --git a/pandas/tests/frame/test_mutate_columns.py b/pandas/tests/frame/test_mutate_columns.py index 1546d18a224cd..0d58dd5402aff 100644 --- a/pandas/tests/frame/test_mutate_columns.py +++ b/pandas/tests/frame/test_mutate_columns.py @@ -7,8 +7,7 @@ from pandas import DataFrame, Series -from pandas.util.testing import (assert_almost_equal, - assert_series_equal, +from pandas.util.testing import (assert_series_equal, assert_frame_equal, assertRaisesRegexp) @@ -125,12 +124,12 @@ def test_insert(self): df.insert(0, 'foo', df['a']) self.assert_numpy_array_equal(df.columns, ['foo', 'c', 'b', 'a']) - assert_almost_equal(df['a'], df['foo']) + tm.assert_series_equal(df['a'], df['foo'], check_names=False) df.insert(2, 'bar', df['c']) self.assert_numpy_array_equal(df.columns, ['foo', 'c', 'bar', 'b', 'a']) - assert_almost_equal(df['c'], df['bar']) + tm.assert_almost_equal(df['c'], df['bar'], check_names=False) # diff dtype diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 40ef3188e50f7..a9dfe07c20856 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -960,10 +960,10 @@ def test_rank(self): filled = self.ts.fillna(np.inf) # rankdata returns a ndarray - exp = Series(rankdata(filled), index=filled.index) + exp = Series(rankdata(filled), index=filled.index, name='ts') exp[mask] = np.nan - assert_almost_equal(ranks, exp) + tm.assert_series_equal(ranks, exp) iseries = Series(np.arange(5).repeat(2)) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index c5783779c67c8..1289c0da14dd5 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -16,7 +16,7 @@ from pandas.compat import lrange, range, zip, OrderedDict, long from pandas import compat -from pandas.util.testing import assert_series_equal, assert_almost_equal +from pandas.util.testing import assert_series_equal import pandas.util.testing as tm from .common import TestData @@ -213,7 +213,7 @@ def test_constructor_maskedarray(self): def test_constructor_default_index(self): s = Series([0, 1, 2]) - assert_almost_equal(s.index, np.arange(3)) + tm.assert_index_equal(s.index, pd.Index(np.arange(3))) def test_constructor_corner(self): df = tm.makeTimeDataFrame() diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index d36cc0c303dfe..11977341df77c 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -139,13 +139,15 @@ def test_div(self): assert_series_equal(result, expected) def test_operators(self): - def _check_op(series, other, op, pos_only=False): + def _check_op(series, other, op, pos_only=False, + check_dtype=True): left = np.abs(series) if pos_only else series right = np.abs(other) if pos_only else other cython_or_numpy = op(left, right) python = left.combine(right, op) - tm.assert_almost_equal(cython_or_numpy, python) + tm.assert_series_equal(cython_or_numpy, python, + check_dtype=check_dtype) def check(series, other): simple_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'mod'] @@ -169,15 +171,15 @@ def check(series, other): check(self.ts, self.ts[::2]) check(self.ts, 5) - def check_comparators(series, other): - _check_op(series, other, operator.gt) - _check_op(series, other, operator.ge) - _check_op(series, other, operator.eq) - _check_op(series, other, operator.lt) - _check_op(series, other, operator.le) + def check_comparators(series, other, check_dtype=True): + _check_op(series, other, operator.gt, check_dtype=check_dtype) + _check_op(series, other, operator.ge, check_dtype=check_dtype) + _check_op(series, other, operator.eq, check_dtype=check_dtype) + _check_op(series, other, operator.lt, check_dtype=check_dtype) + _check_op(series, other, operator.le, check_dtype=check_dtype) check_comparators(self.ts, 5) - check_comparators(self.ts, self.ts + 1) + check_comparators(self.ts, self.ts + 1, check_dtype=False) def test_operators_empty_int_corner(self): s1 = Series([], [], dtype=np.int32) @@ -1245,10 +1247,14 @@ def test_operators_frame(self): # rpow does not work with DataFrame df = DataFrame({'A': self.ts}) - tm.assert_almost_equal(self.ts + self.ts, self.ts + df['A']) - tm.assert_almost_equal(self.ts ** self.ts, self.ts ** df['A']) - tm.assert_almost_equal(self.ts < self.ts, self.ts < df['A']) - tm.assert_almost_equal(self.ts / self.ts, self.ts / df['A']) + tm.assert_series_equal(self.ts + self.ts, self.ts + df['A'], + check_names=False) + tm.assert_series_equal(self.ts ** self.ts, self.ts ** df['A'], + check_names=False) + tm.assert_series_equal(self.ts < self.ts, self.ts < df['A'], + check_names=False) + tm.assert_series_equal(self.ts / self.ts, self.ts / df['A'], + check_names=False) def test_operators_combine(self): def _check_fill(meth, op, a, b, fill_value=0): diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py index c175630748b38..840aabc15b75e 100644 --- a/pandas/tests/test_groupby.py +++ b/pandas/tests/test_groupby.py @@ -960,10 +960,13 @@ def test_aggregate_item_by_item(self): # GH5782 # odd comparisons can result here, so cast to make easy - assert_almost_equal( - result.xs('foo'), np.array([foo] * K).astype('float64')) - assert_almost_equal( - result.xs('bar'), np.array([bar] * K).astype('float64')) + exp = pd.Series(np.array([foo] * K), index=list('BCD'), + dtype=np.float64, name='foo') + tm.assert_series_equal(result.xs('foo'), exp) + + exp = pd.Series(np.array([bar] * K), index=list('BCD'), + dtype=np.float64, name='bar') + tm.assert_almost_equal(result.xs('bar'), exp) def aggfun(ser): return ser.size @@ -1390,7 +1393,8 @@ def test_frame_groupby(self): for name, group in grouped: mean = group.mean() for idx in group.index: - assert_almost_equal(transformed.xs(idx), mean) + tm.assert_series_equal(transformed.xs(idx), mean, + check_names=False) # iterate for weekday, group in grouped: diff --git a/pandas/tests/test_internals.py b/pandas/tests/test_internals.py index 69e05e1f4e7ca..72bad407ded9f 100644 --- a/pandas/tests/test_internals.py +++ b/pandas/tests/test_internals.py @@ -702,7 +702,7 @@ def test_reindex_items(self): reindexed = mgr.reindex_axis(['g', 'c', 'a', 'd'], axis=0) self.assertEqual(reindexed.nblocks, 2) - assert_almost_equal(reindexed.items, ['g', 'c', 'a', 'd']) + tm.assert_index_equal(reindexed.items, pd.Index(['g', 'c', 'a', 'd'])) assert_almost_equal( mgr.get('g', fastpath=False), reindexed.get('g', fastpath=False)) assert_almost_equal( @@ -746,7 +746,8 @@ def test_get_numeric_data(self): mgr.set('obj', np.array([1, 2, 3], dtype=np.object_)) numeric = mgr.get_numeric_data() - assert_almost_equal(numeric.items, ['int', 'float', 'complex', 'bool']) + tm.assert_index_equal(numeric.items, + pd.Index(['int', 'float', 'complex', 'bool'])) assert_almost_equal( mgr.get('float', fastpath=False), numeric.get('float', fastpath=False)) @@ -762,7 +763,8 @@ def test_get_numeric_data(self): mgr.get('float').internal_values(), np.array([100., 200., 300.])) numeric2 = mgr.get_numeric_data(copy=True) - assert_almost_equal(numeric.items, ['int', 'float', 'complex', 'bool']) + tm.assert_index_equal(numeric.items, + pd.Index(['int', 'float', 'complex', 'bool'])) numeric2.set('float', np.array([1000., 2000., 3000.])) assert_almost_equal( mgr.get('float', fastpath=False), np.array([100., 200., 300.])) @@ -776,9 +778,9 @@ def test_get_bool_data(self): mgr.set('obj', np.array([True, False, True], dtype=np.object_)) bools = mgr.get_bool_data() - assert_almost_equal(bools.items, ['bool']) - assert_almost_equal( - mgr.get('bool', fastpath=False), bools.get('bool', fastpath=False)) + tm.assert_index_equal(bools.items, pd.Index(['bool'])) + assert_almost_equal(mgr.get('bool', fastpath=False), + bools.get('bool', fastpath=False)) assert_almost_equal( mgr.get('bool').internal_values(), bools.get('bool').internal_values()) @@ -946,23 +948,25 @@ def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value): reindexed = mgr.reindex_axis(new_labels, axis, fill_value=fill_value) - assert_almost_equal(com.take_nd(mat, indexer, axis, - fill_value=fill_value), - reindexed.as_matrix()) - assert_almost_equal(reindexed.axes[axis], new_labels) + tm.assert_numpy_array_equal(com.take_nd(mat, indexer, axis, + fill_value=fill_value), + reindexed.as_matrix()) + tm.assert_index_equal(reindexed.axes[axis], new_labels) for mgr in self.MANAGERS: for ax in range(mgr.ndim): for fill_value in (None, np.nan, 100.): - yield assert_reindex_axis_is_ok, mgr, ax, [], fill_value + yield (assert_reindex_axis_is_ok, mgr, ax, + pd.Index([]), fill_value) yield (assert_reindex_axis_is_ok, mgr, ax, mgr.axes[ax], fill_value) yield (assert_reindex_axis_is_ok, mgr, ax, mgr.axes[ax][[0, 0, 0]], fill_value) yield (assert_reindex_axis_is_ok, mgr, ax, - ['foo', 'bar', 'baz'], fill_value) + pd.Index(['foo', 'bar', 'baz']), fill_value) yield (assert_reindex_axis_is_ok, mgr, ax, - ['foo', mgr.axes[ax][0], 'baz'], fill_value) + pd.Index(['foo', mgr.axes[ax][0], 'baz']), + fill_value) if mgr.shape[ax] >= 3: yield (assert_reindex_axis_is_ok, mgr, ax, @@ -973,6 +977,7 @@ def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value): mgr.axes[ax][[0, 1, 2, 0, 1, 2]], fill_value) def test_reindex_indexer(self): + def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value): mat = mgr.as_matrix() @@ -980,18 +985,19 @@ def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value=fill_value) reindexed = mgr.reindex_indexer(new_labels, indexer, axis, fill_value=fill_value) - assert_almost_equal(reindexed_mat, reindexed.as_matrix()) - assert_almost_equal(reindexed.axes[axis], new_labels) + tm.assert_numpy_array_equal(reindexed_mat, reindexed.as_matrix()) + tm.assert_index_equal(reindexed.axes[axis], new_labels) for mgr in self.MANAGERS: for ax in range(mgr.ndim): for fill_value in (None, np.nan, 100.): - yield (assert_reindex_indexer_is_ok, mgr, ax, [], [], - fill_value) - yield (assert_reindex_indexer_is_ok, mgr, ax, mgr.axes[ax], + yield (assert_reindex_indexer_is_ok, mgr, ax, + pd.Index([]), [], fill_value) + yield (assert_reindex_indexer_is_ok, mgr, ax, + mgr.axes[ax], np.arange(mgr.shape[ax]), fill_value) + yield (assert_reindex_indexer_is_ok, mgr, ax, + pd.Index(['foo'] * mgr.shape[ax]), np.arange(mgr.shape[ax]), fill_value) - yield (assert_reindex_indexer_is_ok, mgr, ax, ['foo'] * - mgr.shape[ax], np.arange(mgr.shape[ax]), fill_value) yield (assert_reindex_indexer_is_ok, mgr, ax, mgr.axes[ax][::-1], np.arange(mgr.shape[ax]), @@ -999,16 +1005,19 @@ def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, yield (assert_reindex_indexer_is_ok, mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax])[::-1], fill_value) yield (assert_reindex_indexer_is_ok, mgr, ax, - ['foo', 'bar', 'baz'], [0, 0, 0], fill_value) + pd.Index(['foo', 'bar', 'baz']), + [0, 0, 0], fill_value) yield (assert_reindex_indexer_is_ok, mgr, ax, - ['foo', 'bar', 'baz'], [-1, 0, -1], fill_value) + pd.Index(['foo', 'bar', 'baz']), + [-1, 0, -1], fill_value) yield (assert_reindex_indexer_is_ok, mgr, ax, - ['foo', mgr.axes[ax][0], 'baz'], [-1, -1, -1], - fill_value) + pd.Index(['foo', mgr.axes[ax][0], 'baz']), + [-1, -1, -1], fill_value) if mgr.shape[ax] >= 3: yield (assert_reindex_indexer_is_ok, mgr, ax, - ['foo', 'bar', 'baz'], [0, 1, 2], fill_value) + pd.Index(['foo', 'bar', 'baz']), + [0, 1, 2], fill_value) # test_get_slice(slice_like, axis) # take(indexer, axis) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 9f8d672723954..3430109939f77 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -849,7 +849,8 @@ def _check_counts(frame, axis=0): self.frame['D'] = 'foo' result = self.frame.count(level=0, numeric_only=True) - assert_almost_equal(result.columns, ['A', 'B', 'C']) + tm.assert_index_equal(result.columns, + pd.Index(['A', 'B', 'C'], name='exp')) def test_count_level_series(self): index = MultiIndex(levels=[['foo', 'bar', 'baz'], ['one', 'two', diff --git a/pandas/tests/test_stats.py b/pandas/tests/test_stats.py index 56f6a80e58eea..85ce1d5127512 100644 --- a/pandas/tests/test_stats.py +++ b/pandas/tests/test_stats.py @@ -9,9 +9,7 @@ from pandas import Series, DataFrame from pandas.compat import product -from pandas.util.testing import (assert_frame_equal, - assert_series_equal, - assert_almost_equal) +from pandas.util.testing import (assert_frame_equal, assert_series_equal) import pandas.util.testing as tm @@ -34,7 +32,7 @@ def test_rank_tie_methods(self): def _check(s, expected, method='average'): result = s.rank(method=method) - assert_almost_equal(result, expected) + tm.assert_series_equal(result, Series(expected)) dtypes = [None, object] disabled = set([(object, 'first')]) @@ -87,6 +85,7 @@ def test_rank_methods_frame(self): sprank = np.apply_along_axis( rankdata, ax, vals, m if m != 'first' else 'ordinal') + sprank = sprank.astype(np.float64) expected = DataFrame(sprank, columns=cols) if LooseVersion(scipy.__version__) >= '0.17.0': diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index f0bb002a1c96d..54d6b29daf4b1 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -127,33 +127,35 @@ def test_count(self): values = ['foo', 'foofoo', NA, 'foooofooofommmfoo'] result = strings.str_count(values, 'f[o]+') - exp = [1, 2, NA, 4] + exp = Series([1, 2, NA, 4]) tm.assert_almost_equal(result, exp) result = Series(values).str.count('f[o]+') tm.assertIsInstance(result, Series) - tm.assert_almost_equal(result, exp) + tm.assert_series_equal(result, exp) # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_count(mixed, 'a') - xp = [1, NA, 0, NA, NA, 0, NA, NA, NA] - tm.assert_almost_equal(rs, xp) + xp = np.array([1, NA, 0, NA, NA, 0, NA, NA, NA]) + tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.count('a') + xp = Series([1, NA, 0, NA, NA, 0, NA, NA, NA]) tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = [u('foo'), u('foofoo'), NA, u('foooofooofommmfoo')] result = strings.str_count(values, 'f[o]+') - exp = [1, 2, NA, 4] - tm.assert_almost_equal(result, exp) + exp = np.array([1, 2, NA, 4]) + tm.assert_numpy_array_equal(result, exp) result = Series(values).str.count('f[o]+') + exp = Series([1, 2, NA, 4]) tm.assertIsInstance(result, Series) - tm.assert_almost_equal(result, exp) + tm.assert_series_equal(result, exp) def test_contains(self): values = ['foo', NA, 'fooommm__foo', 'mmm_', 'foommm[_]+bar'] @@ -187,12 +189,12 @@ def test_contains(self): # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_contains(mixed, 'o') - xp = [False, NA, False, NA, NA, True, NA, NA, NA] + xp = Series([False, NA, False, NA, NA, True, NA, NA, NA]) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.contains('o') tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = [u('foo'), NA, u('fooommm__foo'), u('mmm_')] @@ -227,12 +229,12 @@ def test_startswith(self): # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_startswith(mixed, 'f') - xp = [False, NA, False, NA, NA, True, NA, NA, NA] + xp = Series([False, NA, False, NA, NA, True, NA, NA, NA]) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.startswith('f') tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('foo_nom'), u('nom'), u('bar_foo'), NA, @@ -255,12 +257,12 @@ def test_endswith(self): # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_endswith(mixed, 'f') - xp = [False, NA, False, NA, NA, False, NA, NA, NA] + xp = Series([False, NA, False, NA, NA, False, NA, NA, NA]) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.endswith('f') tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('foo_nom'), u('nom'), u('bar_foo'), NA, @@ -310,9 +312,9 @@ def test_lower_upper(self): 2.]) mixed = mixed.str.upper() rs = Series(mixed).str.lower() - xp = ['a', NA, 'b', NA, NA, 'foo', NA, NA, NA] + xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('nom'), u('nom')]) @@ -389,7 +391,7 @@ def test_replace(self): None, 1, 2.]) rs = Series(mixed).str.replace('BAD[_]*', '') - xp = ['a', NA, 'b', NA, NA, 'foo', NA, NA, NA] + xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA]) tm.assertIsInstance(rs, Series) tm.assert_almost_equal(rs, xp) @@ -426,9 +428,9 @@ def test_repeat(self): 2.]) rs = Series(mixed).str.repeat(3) - xp = ['aaa', NA, 'bbb', NA, NA, 'foofoofoo', NA, NA, NA] + xp = Series(['aaa', NA, 'bbb', NA, NA, 'foofoofoo', NA, NA, NA]) tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = Series([u('a'), u('b'), NA, u('c'), NA, u('d')]) @@ -456,9 +458,10 @@ def test_deprecated_match(self): with tm.assert_produces_warning(): rs = Series(mixed).str.match('.*(BAD[_]+).*(BAD)') - xp = [('BAD_', 'BAD'), NA, ('BAD_', 'BAD'), NA, NA, [], NA, NA, NA] + xp = Series([('BAD_', 'BAD'), NA, ('BAD_', 'BAD'), + NA, NA, [], NA, NA, NA]) tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = Series([u('fooBAD__barBAD'), NA, u('foo')]) @@ -489,9 +492,9 @@ def test_match(self): with tm.assert_produces_warning(): rs = Series(mixed).str.match('.*(BAD[_]+).*(BAD)', as_indexer=True) - xp = [True, NA, True, NA, NA, False, NA, NA, NA] + xp = Series([True, NA, True, NA, NA, False, NA, NA, NA]) tm.assertIsInstance(rs, Series) - tm.assert_almost_equal(rs, xp) + tm.assert_series_equal(rs, xp) # unicode values = Series([u('fooBAD__barBAD'), NA, u('foo')]) diff --git a/pandas/tests/test_testing.py b/pandas/tests/test_testing.py index 7c3ba2ee8b556..19598a54c6585 100644 --- a/pandas/tests/test_testing.py +++ b/pandas/tests/test_testing.py @@ -116,6 +116,14 @@ def test_assert_almost_equal_inf(self): self._assert_not_almost_equal_both(np.inf, 0) + def test_assert_almost_equal_pandas(self): + self.assert_almost_equal(pd.Index([1., 1.1]), + pd.Index([1., 1.100001])) + self.assert_almost_equal(pd.Series([1., 1.1]), + pd.Series([1., 1.100001])) + self.assert_almost_equal(pd.DataFrame({'a': [1., 1.1]}), + pd.DataFrame({'a': [1., 1.100001]})) + class TestUtilTesting(tm.TestCase): _multiprocess_can_split_ = True diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 0b8de24a1bd42..cc4a6ba61306d 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -908,8 +908,9 @@ def get_result(obj, window, min_periods=None, freq=None, center=False): assert_almost_equal(series_result[-1], static_comp(trunc_series)) - assert_almost_equal(frame_result.xs(last_date), - trunc_frame.apply(static_comp)) + assert_series_equal(frame_result.xs(last_date), + trunc_frame.apply(static_comp), + check_names=False) # GH 7925 if has_center: @@ -984,11 +985,11 @@ def test_ewma(self): def test_ewma_nan_handling(self): s = Series([1.] + [np.nan] * 5 + [1.]) result = s.ewm(com=5).mean() - assert_almost_equal(result, [1.] * len(s)) + tm.assert_series_equal(result, Series([1.] * len(s))) s = Series([np.nan] * 2 + [1.] + [np.nan] * 2 + [1.]) result = s.ewm(com=5).mean() - assert_almost_equal(result, [np.nan] * 2 + [1.] * 4) + tm.assert_series_equal(result, Series([np.nan] * 2 + [1.] * 4)) # GH 7603 s0 = Series([np.nan, 1., 101.]) diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index fdf38a0869a0b..77ee54d84bf3d 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -609,12 +609,19 @@ def test_merge_different_column_key_names(self): merged = left.merge(right, left_on='lkey', right_on='rkey', how='outer', sort=True) - assert_almost_equal(merged['lkey'], - ['bar', 'baz', 'foo', 'foo', 'foo', 'foo', np.nan]) - assert_almost_equal(merged['rkey'], - ['bar', np.nan, 'foo', 'foo', 'foo', 'foo', 'qux']) - assert_almost_equal(merged['value_x'], [2, 3, 1, 1, 4, 4, np.nan]) - assert_almost_equal(merged['value_y'], [6, np.nan, 5, 8, 5, 8, 7]) + exp = pd.Series(['bar', 'baz', 'foo', 'foo', 'foo', 'foo', np.nan], + name='lkey') + tm.assert_series_equal(merged['lkey'], exp) + + exp = pd.Series(['bar', np.nan, 'foo', 'foo', 'foo', 'foo', 'qux'], + name='rkey') + tm.assert_series_equal(merged['rkey'], exp) + + exp = pd.Series([2, 3, 1, 1, 4, 4, np.nan], name='value_x') + tm.assert_series_equal(merged['value_x'], exp) + + exp = pd.Series([6, np.nan, 5, 8, 5, 8, 7], name='value_y') + tm.assert_series_equal(merged['value_y'], exp) def test_merge_copy(self): left = DataFrame({'a': 0, 'b': 1}, index=lrange(10)) diff --git a/pandas/tools/tests/test_tile.py b/pandas/tools/tests/test_tile.py index 63dc769f2ed75..55f27e1466a92 100644 --- a/pandas/tools/tests/test_tile.py +++ b/pandas/tools/tests/test_tile.py @@ -63,10 +63,10 @@ def test_cut_corner(self): def test_cut_out_of_range_more(self): # #1511 - s = Series([0, -1, 0, 1, -3]) + s = Series([0, -1, 0, 1, -3], name='x') ind = cut(s, [0, 1], labels=False) - exp = [np.nan, np.nan, np.nan, 0, np.nan] - tm.assert_almost_equal(ind, exp) + exp = Series([np.nan, np.nan, np.nan, 0, np.nan], name='x') + tm.assert_series_equal(ind, exp) def test_labels(self): arr = np.tile(np.arange(0, 1.01, 0.1), 4) diff --git a/pandas/tseries/tests/test_timedeltas.py b/pandas/tseries/tests/test_timedeltas.py index d5a057d25e752..4bdd0ed462852 100644 --- a/pandas/tseries/tests/test_timedeltas.py +++ b/pandas/tseries/tests/test_timedeltas.py @@ -670,8 +670,8 @@ def conv(v): # pass thru result = to_timedelta(np.array([np.timedelta64(1, 's')])) - expected = np.array([np.timedelta64(1, 's')]) - tm.assert_almost_equal(result, expected) + expected = pd.Index(np.array([np.timedelta64(1, 's')])) + tm.assert_index_equal(result, expected) # ints result = np.timedelta64(0, 'ns') diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 915fd08e2c0c6..d434b19317dfc 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -102,9 +102,21 @@ def assertNotAlmostEquals(self, *args, **kwargs): return deprecate('assertNotAlmostEquals', self.assertNotAlmostEqual)(*args, **kwargs) -# NOTE: don't pass an NDFrame or index to this function - may not handle it -# well. -assert_almost_equal = _testing.assert_almost_equal +def assert_almost_equal(left, right, check_exact=False, **kwargs): + if isinstance(left, pd.Index): + return assert_index_equal(left, right, check_exact=check_exact, + **kwargs) + + elif isinstance(left, pd.Series): + return assert_series_equal(left, right, check_exact=check_exact, + **kwargs) + + elif isinstance(left, pd.DataFrame): + return assert_frame_equal(left, right, check_exact=check_exact, + **kwargs) + + return _testing.assert_almost_equal(left, right, **kwargs) + assert_dict_equal = _testing.assert_dict_equal @@ -714,9 +726,9 @@ def _get_ilevel_values(index, level): msg = '{0} values are different ({1} %)'.format(obj, np.round(diff, 5)) raise_assert_detail(obj, msg, left, right) else: - assert_almost_equal(left.values, right.values, - check_less_precise=check_less_precise, - obj=obj, lobj=left, robj=right) + _testing.assert_almost_equal(left.values, right.values, + check_less_precise=check_less_precise, + obj=obj, lobj=left, robj=right) # metadata comparison if check_names: @@ -766,7 +778,10 @@ def isiterable(obj): return hasattr(obj, '__iter__') def is_sorted(seq): - return assert_almost_equal(seq, np.sort(np.array(seq))) + if isinstance(seq, (Index, Series)): + seq = seq.values + # sorting does not change precisions + return assert_numpy_array_equal(seq, np.sort(np.array(seq))) def assertIs(first, second, msg=''): @@ -865,7 +880,7 @@ def assert_numpy_array_equal(left, right, # compare shape and values if array_equivalent(left, right, strict_nan=strict_nan): - return + return True if err_msg is None: # show detailed error @@ -965,19 +980,23 @@ def assert_series_equal(left, right, check_dtype=True, obj='{0}'.format(obj)) elif check_datetimelike_compat: # we want to check only if we have compat dtypes - # e.g. integer and M|m are NOT compat, but we can simply check the values in that case - if is_datetimelike_v_numeric(left, right) or is_datetimelike_v_object(left, right) or needs_i8_conversion(left) or needs_i8_conversion(right): - - # datetimelike may have different objects (e.g. datetime.datetime vs Timestamp) but will compare equal + # e.g. integer and M|m are NOT compat, but we can simply check + # the values in that case + if (is_datetimelike_v_numeric(left, right) or + is_datetimelike_v_object(left, right) or + needs_i8_conversion(left) or + needs_i8_conversion(right)): + + # datetimelike may have different objects (e.g. datetime.datetime + # vs Timestamp) but will compare equal if not Index(left.values).equals(Index(right.values)): - raise AssertionError( - '[datetimelike_compat=True] {0} is not equal to {1}.'.format(left.values, - right.values)) + msg = '[datetimelike_compat=True] {0} is not equal to {1}.' + raise AssertionError(msg.format(left.values, right.values)) else: assert_numpy_array_equal(left.values, right.values) else: - assert_almost_equal(left.get_values(), right.get_values(), - check_less_precise, obj='{0}'.format(obj)) + _testing.assert_almost_equal(left.get_values(), right.get_values(), + check_less_precise, obj='{0}'.format(obj)) # metadata comparison if check_names: