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
TST/REF: consolidate hist tests
diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index f700b2934cd8c..e2a36dc5d6a1b 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -162,6 +162,59 @@ def test_hist_with_legend_raises(self, by): with pytest.raises(ValueError, match="Cannot use both legend and label"): s.hist(legend=True, by=by, label="c") + def test_hist_kwargs(self): + _, ax = self.plt.subplots() + ax = self.ts.plot.hist(bins=5, ax=ax) + assert len(ax.patches) == 5 + self._check_text_labels(ax.yaxis.get_label(), "Frequency") + tm.close() + + _, ax = self.plt.subplots() + ax = self.ts.plot.hist(orientation="horizontal", ax=ax) + self._check_text_labels(ax.xaxis.get_label(), "Frequency") + tm.close() + + _, ax = self.plt.subplots() + ax = self.ts.plot.hist(align="left", stacked=True, ax=ax) + tm.close() + + @td.skip_if_no_scipy + def test_hist_kde(self): + + _, ax = self.plt.subplots() + ax = self.ts.plot.hist(logy=True, ax=ax) + self._check_ax_scales(ax, yaxis="log") + xlabels = ax.get_xticklabels() + # ticks are values, thus ticklabels are blank + self._check_text_labels(xlabels, [""] * len(xlabels)) + ylabels = ax.get_yticklabels() + self._check_text_labels(ylabels, [""] * len(ylabels)) + + _check_plot_works(self.ts.plot.kde) + _check_plot_works(self.ts.plot.density) + _, ax = self.plt.subplots() + ax = self.ts.plot.kde(logy=True, ax=ax) + self._check_ax_scales(ax, yaxis="log") + xlabels = ax.get_xticklabels() + self._check_text_labels(xlabels, [""] * len(xlabels)) + ylabels = ax.get_yticklabels() + self._check_text_labels(ylabels, [""] * len(ylabels)) + + @td.skip_if_no_scipy + def test_hist_kde_color(self): + _, ax = self.plt.subplots() + ax = self.ts.plot.hist(logy=True, bins=10, color="b", ax=ax) + self._check_ax_scales(ax, yaxis="log") + assert len(ax.patches) == 10 + self._check_colors(ax.patches, facecolors=["b"] * 10) + + _, ax = self.plt.subplots() + ax = self.ts.plot.kde(logy=True, color="r", ax=ax) + self._check_ax_scales(ax, yaxis="log") + lines = ax.get_lines() + assert len(lines) == 1 + self._check_colors(lines, ["r"]) + @td.skip_if_no_mpl class TestDataFramePlots(TestPlotBase): @@ -432,6 +485,63 @@ def test_hist_with_legend_raises(self, by, column): with pytest.raises(ValueError, match="Cannot use both legend and label"): df.hist(legend=True, by=by, column=column, label="d") + def test_hist_df_kwargs(self): + df = DataFrame(np.random.randn(10, 2)) + _, ax = self.plt.subplots() + ax = df.plot.hist(bins=5, ax=ax) + assert len(ax.patches) == 10 + + def test_hist_df_with_nonnumerics(self): + # GH 9853 + with tm.RNGContext(1): + df = DataFrame(np.random.randn(10, 4), columns=["A", "B", "C", "D"]) + df["E"] = ["x", "y"] * 5 + _, ax = self.plt.subplots() + ax = df.plot.hist(bins=5, ax=ax) + assert len(ax.patches) == 20 + + _, ax = self.plt.subplots() + ax = df.plot.hist(ax=ax) # bins=10 + assert len(ax.patches) == 40 + + def test_hist_secondary_legend(self): + # GH 9610 + df = DataFrame(np.random.randn(30, 4), columns=list("abcd")) + + # primary -> secondary + _, ax = self.plt.subplots() + ax = df["a"].plot.hist(legend=True, ax=ax) + df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) + # both legends are dran on left ax + # left and right axis must be visible + self._check_legend_labels(ax, labels=["a", "b (right)"]) + assert ax.get_yaxis().get_visible() + assert ax.right_ax.get_yaxis().get_visible() + tm.close() + + # secondary -> secondary + _, ax = self.plt.subplots() + ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) + df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) + # both legends are draw on left ax + # left axis must be invisible, right axis must be visible + self._check_legend_labels(ax.left_ax, labels=["a (right)", "b (right)"]) + assert not ax.left_ax.get_yaxis().get_visible() + assert ax.get_yaxis().get_visible() + tm.close() + + # secondary -> primary + _, ax = self.plt.subplots() + ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) + # right axes is returned + df["b"].plot.hist(ax=ax, legend=True) + # both legends are draw on left ax + # left and right axis must be visible + self._check_legend_labels(ax.left_ax, labels=["a (right)", "b"]) + assert ax.left_ax.get_yaxis().get_visible() + assert ax.get_yaxis().get_visible() + tm.close() + @td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase): diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 9da2336fb9342..d5c0b3af7fac8 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -365,25 +365,6 @@ def test_pie_nan(self): result = [x.get_text() for x in ax.texts] assert result == expected - def test_hist_df_kwargs(self): - df = DataFrame(np.random.randn(10, 2)) - _, ax = self.plt.subplots() - ax = df.plot.hist(bins=5, ax=ax) - assert len(ax.patches) == 10 - - def test_hist_df_with_nonnumerics(self): - # GH 9853 - with tm.RNGContext(1): - df = DataFrame(np.random.randn(10, 4), columns=["A", "B", "C", "D"]) - df["E"] = ["x", "y"] * 5 - _, ax = self.plt.subplots() - ax = df.plot.hist(bins=5, ax=ax) - assert len(ax.patches) == 20 - - _, ax = self.plt.subplots() - ax = df.plot.hist(ax=ax) # bins=10 - assert len(ax.patches) == 40 - def test_hist_legacy(self): _check_plot_works(self.ts.hist) _check_plot_works(self.ts.hist, grid=False) @@ -468,44 +449,6 @@ def test_hist_no_overlap(self): axes = fig.axes assert len(axes) == 2 - def test_hist_secondary_legend(self): - # GH 9610 - df = DataFrame(np.random.randn(30, 4), columns=list("abcd")) - - # primary -> secondary - _, ax = self.plt.subplots() - ax = df["a"].plot.hist(legend=True, ax=ax) - df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) - # both legends are dran on left ax - # left and right axis must be visible - self._check_legend_labels(ax, labels=["a", "b (right)"]) - assert ax.get_yaxis().get_visible() - assert ax.right_ax.get_yaxis().get_visible() - tm.close() - - # secondary -> secondary - _, ax = self.plt.subplots() - ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) - df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) - # both legends are draw on left ax - # left axis must be invisible, right axis must be visible - self._check_legend_labels(ax.left_ax, labels=["a (right)", "b (right)"]) - assert not ax.left_ax.get_yaxis().get_visible() - assert ax.get_yaxis().get_visible() - tm.close() - - # secondary -> primary - _, ax = self.plt.subplots() - ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) - # right axes is returned - df["b"].plot.hist(ax=ax, legend=True) - # both legends are draw on left ax - # left and right axis must be visible - self._check_legend_labels(ax.left_ax, labels=["a (right)", "b"]) - assert ax.left_ax.get_yaxis().get_visible() - assert ax.get_yaxis().get_visible() - tm.close() - def test_df_series_secondary_legend(self): # GH 9779 df = DataFrame(np.random.randn(30, 3), columns=list("abc")) @@ -590,28 +533,6 @@ def test_plot_fails_with_dupe_color_and_style(self): _, ax = self.plt.subplots() x.plot(style="k--", color="k", ax=ax) - @td.skip_if_no_scipy - def test_hist_kde(self): - - _, ax = self.plt.subplots() - ax = self.ts.plot.hist(logy=True, ax=ax) - self._check_ax_scales(ax, yaxis="log") - xlabels = ax.get_xticklabels() - # ticks are values, thus ticklabels are blank - self._check_text_labels(xlabels, [""] * len(xlabels)) - ylabels = ax.get_yticklabels() - self._check_text_labels(ylabels, [""] * len(ylabels)) - - _check_plot_works(self.ts.plot.kde) - _check_plot_works(self.ts.plot.density) - _, ax = self.plt.subplots() - ax = self.ts.plot.kde(logy=True, ax=ax) - self._check_ax_scales(ax, yaxis="log") - xlabels = ax.get_xticklabels() - self._check_text_labels(xlabels, [""] * len(xlabels)) - ylabels = ax.get_yticklabels() - self._check_text_labels(ylabels, [""] * len(ylabels)) - @td.skip_if_no_scipy def test_kde_kwargs(self): sample_points = np.linspace(-100, 100, 20) @@ -634,37 +555,6 @@ def test_kde_missing_vals(self): # gh-14821: check if the values have any missing values assert any(~np.isnan(axes.lines[0].get_xdata())) - def test_hist_kwargs(self): - _, ax = self.plt.subplots() - ax = self.ts.plot.hist(bins=5, ax=ax) - assert len(ax.patches) == 5 - self._check_text_labels(ax.yaxis.get_label(), "Frequency") - tm.close() - - _, ax = self.plt.subplots() - ax = self.ts.plot.hist(orientation="horizontal", ax=ax) - self._check_text_labels(ax.xaxis.get_label(), "Frequency") - tm.close() - - _, ax = self.plt.subplots() - ax = self.ts.plot.hist(align="left", stacked=True, ax=ax) - tm.close() - - @td.skip_if_no_scipy - def test_hist_kde_color(self): - _, ax = self.plt.subplots() - ax = self.ts.plot.hist(logy=True, bins=10, color="b", ax=ax) - self._check_ax_scales(ax, yaxis="log") - assert len(ax.patches) == 10 - self._check_colors(ax.patches, facecolors=["b"] * 10) - - _, ax = self.plt.subplots() - ax = self.ts.plot.kde(logy=True, color="r", ax=ax) - self._check_ax_scales(ax, yaxis="log") - lines = ax.get_lines() - assert len(lines) == 1 - self._check_colors(lines, ["r"]) - def test_boxplot_series(self): _, ax = self.plt.subplots() ax = self.ts.plot.box(logy=True, ax=ax)
- [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Splitting up #38577, following @ivanovmg's comment. First step moves some `test_hist...` tests from `test_series.py` to `test_hist_method.py`, after this the remainder of `hist` tests in `test_series.py` will be duplicates to be deleted in a followup pr.
https://api.github.com/repos/pandas-dev/pandas/pulls/38618
2020-12-21T17:02:52Z
2020-12-21T22:29:14Z
2020-12-21T22:29:14Z
2020-12-21T23:07:37Z
BUG: remove unused tz keyword from PeriodIndex constructor
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 3fb57daf2a74b..f8a62c6a8e006 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -86,8 +86,6 @@ class PeriodIndex(DatetimeIndexOpsMixin): hour : int, array, or Series, default None minute : int, array, or Series, default None second : int, array, or Series, default None - tz : object, default None - Timezone for converting datetime64 data to Periods. dtype : str or PeriodDtype, default None Attributes @@ -194,7 +192,6 @@ def __new__( data=None, ordinal=None, freq=None, - tz=None, dtype=None, copy=False, name=None, diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 273d02ca27d7b..b0de16a25bcc3 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -325,11 +325,6 @@ def test_index_unique(self): tm.assert_index_equal(idx.unique(), expected) assert idx.nunique() == 3 - idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN", tz="US/Eastern") - expected = PeriodIndex([2000, 2007, 2009], freq="A-JUN", tz="US/Eastern") - tm.assert_index_equal(idx.unique(), expected) - assert idx.nunique() == 3 - def test_shift(self): # This is tested in test_arithmetic pass
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38615
2020-12-21T15:48:10Z
2020-12-22T18:36:20Z
2020-12-22T18:36:20Z
2020-12-22T19:05:58Z
BUG: disallow scalar in CategoricalIndex construtor
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index fbd2c2b5345fc..3a8fa7798a2d5 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -170,7 +170,7 @@ Bug fixes Categorical ^^^^^^^^^^^ - +- Bug in :class:`CategoricalIndex` incorrectly failing to raise ``TypeError`` when scalar data is passed (:issue:`38614`) - Bug in ``CategoricalIndex.reindex`` failed when ``Index`` passed with elements all in category (:issue:`28690`) - diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 059c36a901297..9062667298d7c 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -186,11 +186,7 @@ def __new__( name = maybe_extract_name(name, data, cls) if is_scalar(data): - # don't allow scalars - # if data is None, then categories must be provided - if data is not None or categories is None: - raise cls._scalar_data_error(data) - data = [] + raise cls._scalar_data_error(data) data = Categorical( data, categories=categories, ordered=ordered, dtype=dtype, copy=copy diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 00fca00c5b4a0..2119600887ba4 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -91,7 +91,7 @@ def test_insert(self): tm.assert_index_equal(result, expected, exact=True) # test empty - result = CategoricalIndex(categories=categories).insert(0, "a") + result = CategoricalIndex([], categories=categories).insert(0, "a") expected = CategoricalIndex(["a"], categories=categories) tm.assert_index_equal(result, expected, exact=True) diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py index ee3f85da22781..aeb31b710ddbb 100644 --- a/pandas/tests/indexes/categorical/test_constructors.py +++ b/pandas/tests/indexes/categorical/test_constructors.py @@ -6,6 +6,11 @@ class TestCategoricalIndexConstructors: + def test_construction_disallows_scalar(self): + msg = "must be called with a collection of some kind" + with pytest.raises(TypeError, match=msg): + CategoricalIndex(categories=list("abcd"), ordered=False) + def test_construction(self): ci = CategoricalIndex(list("aabbca"), categories=list("abcd"), ordered=False) @@ -20,7 +25,7 @@ def test_construction(self): assert not result.ordered # empty - result = CategoricalIndex(categories=categories) + result = CategoricalIndex([], categories=categories) tm.assert_index_equal(result.categories, Index(categories)) tm.assert_numpy_array_equal(result.codes, np.array([], dtype="int8")) assert not result.ordered
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38614
2020-12-21T15:46:02Z
2020-12-23T15:53:26Z
2020-12-23T15:53:26Z
2021-01-04T13:29:49Z
CI: move py38 slow to azure #38429
diff --git a/.travis.yml b/.travis.yml index 1ddd886699d38..31edc4872e907 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,12 +35,6 @@ matrix: fast_finish: true include: - - env: - - JOB="3.8, slow" ENV_FILE="ci/deps/travis-38-slow.yaml" PATTERN="slow" SQL="1" - services: - - mysql - - postgresql - - env: - JOB="3.7, locale" ENV_FILE="ci/deps/travis-37-locale.yaml" PATTERN="((not slow and not network and not clipboard) or (single and db))" LOCALE_OVERRIDE="zh_CN.UTF-8" SQL="1" services: diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index 8e44db0b4bcd4..4cb4eaf95f6f5 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -43,6 +43,11 @@ jobs: CONDA_PY: "38" PATTERN: "not slow and not network and not clipboard" + py38_slow: + ENV_FILE: ci/deps/azure-38-slow.yaml + CONDA_PY: "38" + PATTERN: "slow" + py38_locale: ENV_FILE: ci/deps/azure-38-locale.yaml CONDA_PY: "38" diff --git a/ci/deps/travis-38-slow.yaml b/ci/deps/azure-38-slow.yaml similarity index 100% rename from ci/deps/travis-38-slow.yaml rename to ci/deps/azure-38-slow.yaml
xref #38429 We're not testing databases on py38 slow currently. Keep the issue open until we figure out what to do with its SQL tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/38613
2020-12-21T15:38:23Z
2020-12-21T20:02:00Z
2020-12-21T20:02:00Z
2020-12-28T21:19:40Z
Backport PR #38532 on branch 1.2.x (BUG: Regression in logical ops raising ValueError with Categorical columns with unused categories)
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index e2521cedb64cc..372dfa0f8ad42 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -859,7 +859,7 @@ Other - Bug in :meth:`RangeIndex.difference` returning :class:`Int64Index` in some cases where it should return :class:`RangeIndex` (:issue:`38028`) - Fixed bug in :func:`assert_series_equal` when comparing a datetime-like array with an equivalent non extension dtype array (:issue:`37609`) - Bug in :func:`.is_bool_dtype` would raise when passed a valid string such as ``"boolean"`` (:issue:`38386`) - +- Fixed regression in logical operators raising ``ValueError`` when columns of :class:`DataFrame` are a :class:`CategoricalIndex` with unused categories (:issue:`38367`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index d8b5dba424cbf..7b14a5c636abe 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -309,11 +309,11 @@ def should_reindex_frame_op( if fill_value is None and level is None and axis is default_axis: # TODO: any other cases we should handle here? - cols = left.columns.intersection(right.columns) # Intersection is always unique so we have to check the unique columns left_uniques = left.columns.unique() right_uniques = right.columns.unique() + cols = left_uniques.intersection(right_uniques) if len(cols) and not (cols.equals(left_uniques) and cols.equals(right_uniques)): # TODO: is there a shortcut available when len(cols) == 0? return True diff --git a/pandas/tests/frame/test_logical_ops.py b/pandas/tests/frame/test_logical_ops.py index efabc666993ee..dca12c632a418 100644 --- a/pandas/tests/frame/test_logical_ops.py +++ b/pandas/tests/frame/test_logical_ops.py @@ -4,7 +4,7 @@ import numpy as np import pytest -from pandas import DataFrame, Series +from pandas import CategoricalIndex, DataFrame, Interval, Series, isnull import pandas._testing as tm @@ -162,3 +162,24 @@ def test_logical_with_nas(self): result = d["a"].fillna(False, downcast=False) | d["b"] expected = Series([True, True]) tm.assert_series_equal(result, expected) + + def test_logical_ops_categorical_columns(self): + # GH#38367 + intervals = [Interval(1, 2), Interval(3, 4)] + data = DataFrame( + [[1, np.nan], [2, np.nan]], + columns=CategoricalIndex( + intervals, categories=intervals + [Interval(5, 6)] + ), + ) + mask = DataFrame( + [[False, False], [False, False]], columns=data.columns, dtype=bool + ) + result = mask | isnull(data) + expected = DataFrame( + [[False, True], [False, True]], + columns=CategoricalIndex( + intervals, categories=intervals + [Interval(5, 6)] + ), + ) + tm.assert_frame_equal(result, expected)
Backport PR #38532: BUG: Regression in logical ops raising ValueError with Categorical columns with unused categories
https://api.github.com/repos/pandas-dev/pandas/pulls/38612
2020-12-21T13:57:37Z
2020-12-21T15:28:45Z
2020-12-21T15:28:45Z
2020-12-21T15:28:46Z
Backport PR #38539 on branch 1.2.x (BUG: fix array conversion from Arrow for slided array)
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index e2521cedb64cc..4816e45861f4c 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -747,6 +747,7 @@ I/O - :meth:`DataFrame.to_html` was ignoring ``formatters`` argument for ``ExtensionDtype`` columns (:issue:`36525`) - Bumped minimum xarray version to 0.12.3 to avoid reference to the removed ``Panel`` class (:issue:`27101`) - :meth:`DataFrame.to_csv` was re-opening file-like handles that also implement ``os.PathLike`` (:issue:`38125`) +- Bug in the conversion of a sliced ``pyarrow.Table`` with missing values to a DataFrame (:issue:`38525`) Period ^^^^^^ diff --git a/pandas/core/arrays/_arrow_utils.py b/pandas/core/arrays/_arrow_utils.py index c89f5554d0715..959a13d9c107d 100644 --- a/pandas/core/arrays/_arrow_utils.py +++ b/pandas/core/arrays/_arrow_utils.py @@ -30,7 +30,7 @@ def pyarrow_array_to_numpy_and_mask(arr, dtype): bitmask = buflist[0] if bitmask is not None: mask = pyarrow.BooleanArray.from_buffers( - pyarrow.bool_(), len(arr), [None, bitmask] + pyarrow.bool_(), len(arr), [None, bitmask], offset=arr.offset ) mask = np.asarray(mask) else: diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py index ca6fb1cf9dca0..8bb32dec2cc0e 100644 --- a/pandas/tests/arrays/masked/test_arrow_compat.py +++ b/pandas/tests/arrays/masked/test_arrow_compat.py @@ -52,3 +52,15 @@ def test_arrow_from_arrow_uint(): expected = pd.array([1, 2, 3, 4, None], dtype="UInt32") tm.assert_extension_array_equal(result, expected) + + +@td.skip_if_no("pyarrow", min_version="0.16.0") +def test_arrow_sliced(): + # https://github.com/pandas-dev/pandas/issues/38525 + import pyarrow as pa + + df = pd.DataFrame({"a": pd.array([0, None, 2, 3, None], dtype="Int64")}) + table = pa.table(df) + result = table.slice(2, None).to_pandas() + expected = df.iloc[2:].reset_index(drop=True) + tm.assert_frame_equal(result, expected)
Backport PR #38539: BUG: fix array conversion from Arrow for slided array
https://api.github.com/repos/pandas-dev/pandas/pulls/38611
2020-12-21T13:57:25Z
2020-12-21T15:28:26Z
2020-12-21T15:28:26Z
2020-12-21T15:28:26Z
Revert "REF: use astype_nansafe in Index.astype"
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 6e2bbc5e3a0e6..2a5d6db41a56d 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -33,7 +33,6 @@ from pandas.util._decorators import Appender, cache_readonly, doc from pandas.core.dtypes.cast import ( - astype_nansafe, find_common_type, maybe_cast_to_integer_array, maybe_promote, @@ -694,21 +693,22 @@ def astype(self, dtype, copy=True): if is_dtype_equal(self.dtype, dtype): return self.copy() if copy else self - if needs_i8_conversion(dtype) and is_float_dtype(self.dtype): - # We can't put this into astype_nansafe bc astype_nansafe allows - # casting np.nan to NaT - raise TypeError( - f"Cannot convert {type(self).__name__} to dtype {dtype}; integer " - "values are required for conversion" + elif is_categorical_dtype(dtype): + from pandas.core.indexes.category import CategoricalIndex + + return CategoricalIndex( + self._values, name=self.name, dtype=dtype, copy=copy ) + elif is_extension_array_dtype(dtype): + return Index(np.asarray(self), name=self.name, dtype=dtype, copy=copy) + try: - casted = astype_nansafe(self._values, dtype=dtype, copy=True) - except TypeError as err: + casted = self._values.astype(dtype, copy=copy) + except (TypeError, ValueError) as err: raise TypeError( f"Cannot cast {type(self).__name__} to dtype {dtype}" ) from err - return Index(casted, name=self.name, dtype=dtype) _index_shared_docs[ diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index d6f91c9a06739..91d27d9922aa5 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -7,10 +7,12 @@ from pandas._typing import Dtype, DtypeObj, Label from pandas.util._decorators import doc +from pandas.core.dtypes.cast import astype_nansafe from pandas.core.dtypes.common import ( is_bool, is_bool_dtype, is_dtype_equal, + is_extension_array_dtype, is_float, is_float_dtype, is_integer_dtype, @@ -19,6 +21,8 @@ is_scalar, is_signed_integer_dtype, is_unsigned_integer_dtype, + needs_i8_conversion, + pandas_dtype, ) from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna @@ -328,6 +332,21 @@ def inferred_type(self) -> str: """ return "floating" + @doc(Index.astype) + def astype(self, dtype, copy=True): + dtype = pandas_dtype(dtype) + if needs_i8_conversion(dtype): + raise TypeError( + f"Cannot convert Float64Index to dtype {dtype}; integer " + "values are required for conversion" + ) + elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype): + # TODO(jreback); this can change once we have an EA Index type + # GH 13149 + arr = astype_nansafe(self._values, dtype=dtype) + return Int64Index(arr, name=self.name) + return super().astype(dtype, copy=copy) + # ---------------------------------------------------------------- # Indexing Methods diff --git a/pandas/tests/indexes/object/test_astype.py b/pandas/tests/indexes/object/test_astype.py new file mode 100644 index 0000000000000..42c7b8eb4aeec --- /dev/null +++ b/pandas/tests/indexes/object/test_astype.py @@ -0,0 +1,10 @@ +from pandas import Index +import pandas.testing as tm + + +def test_astype_str_from_bytes(): + # https://github.com/pandas-dev/pandas/issues/38607 + idx = Index(["あ", b"a"], dtype="object") + result = idx.astype(str) + expected = Index(["あ", "a"], dtype="object") + tm.assert_index_equal(result, expected)
Reverts pandas-dev/pandas#38518
https://api.github.com/repos/pandas-dev/pandas/pulls/38610
2020-12-21T13:33:19Z
2020-12-21T17:27:18Z
2020-12-21T17:27:17Z
2020-12-21T17:34:05Z
TST: GH30999 Add match=msg to all "with pytest.raises" in pandas/tests/io/pytables/test_store.py
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index b35414724d946..274efda55414c 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -483,11 +483,12 @@ def test_mode(self, setup_path): def check(mode): + msg = r"[\S]* does not exist" with ensure_clean_path(setup_path) as path: # constructor if mode in ["r", "r+"]: - with pytest.raises(IOError): + with pytest.raises(IOError, match=msg): HDFStore(path, mode=mode) else: @@ -499,7 +500,7 @@ def check(mode): # context if mode in ["r", "r+"]: - with pytest.raises(IOError): + with pytest.raises(IOError, match=msg): with HDFStore(path, mode=mode) as store: pass else: @@ -510,7 +511,7 @@ def check(mode): # conv write if mode in ["r", "r+"]: - with pytest.raises(IOError): + with pytest.raises(IOError, match=msg): df.to_hdf(path, "df", mode=mode) df.to_hdf(path, "df", mode="w") else: @@ -549,8 +550,12 @@ def test_reopen_handle(self, setup_path): store = HDFStore(path, mode="a") store["a"] = tm.makeTimeSeries() + msg = ( + r"Re-opening the file \[[\S]*\] with mode \[a\] will delete the " + "current file!" + ) # invalid mode change - with pytest.raises(PossibleDataLossError): + with pytest.raises(PossibleDataLossError, match=msg): store.open("w") store.close() @@ -713,7 +718,8 @@ def test_getattr(self, setup_path): # errors for x in ["d", "mode", "path", "handle", "complib"]: - with pytest.raises(AttributeError): + msg = f"'HDFStore' object has no attribute '{x}'" + with pytest.raises(AttributeError, match=msg): getattr(store, x) # not stores @@ -734,17 +740,18 @@ def test_put(self, setup_path): store.put("c", df[:10], format="table") # not OK, not a table - with pytest.raises(ValueError): + msg = "Can only append to Tables" + with pytest.raises(ValueError, match=msg): store.put("b", df[10:], append=True) # node does not currently exist, test _is_table_type returns False # in this case _maybe_remove(store, "f") - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): store.put("f", df[10:], append=True) # can't put to a table (use append instead) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): store.put("c", df[10:], append=True) # overwrite table @@ -787,7 +794,8 @@ def test_put_compression(self, setup_path): tm.assert_frame_equal(store["c"], df) # can't compress if format='fixed' - with pytest.raises(ValueError): + msg = "Compression not supported on Fixed format stores" + with pytest.raises(ValueError, match=msg): store.put("b", df, format="fixed", complib="zlib") @td.skip_if_windows_python_3 @@ -797,7 +805,8 @@ def test_put_compression_blosc(self, setup_path): with ensure_clean_store(setup_path) as store: # can't compress if format='fixed' - with pytest.raises(ValueError): + msg = "Compression not supported on Fixed format stores" + with pytest.raises(ValueError, match=msg): store.put("b", df, format="fixed", complib="blosc") store.put("c", df, format="table", complib="blosc") @@ -1329,7 +1338,11 @@ def test_append_frame_column_oriented(self, setup_path): tm.assert_frame_equal(expected, result) # this isn't supported - with pytest.raises(TypeError): + msg = re.escape( + "passing a filterable condition to a non-table indexer " + "[Filter: Not Initialized]" + ) + with pytest.raises(TypeError, match=msg): store.select("df1", "columns=A and index>df.index[4]") def test_append_with_different_block_ordering(self, setup_path): @@ -1367,12 +1380,18 @@ def test_append_with_different_block_ordering(self, setup_path): # store additional fields in different blocks df["int16_2"] = Series([1] * len(df), dtype="int16") - with pytest.raises(ValueError): + msg = re.escape( + "cannot match existing table structure for [int16] on appending data" + ) + with pytest.raises(ValueError, match=msg): store.append("df", df) # store multiple additional fields in different blocks df["float_3"] = Series([1.0] * len(df), dtype="float64") - with pytest.raises(ValueError): + msg = re.escape( + "cannot match existing table structure for [A,B] on appending data" + ) + with pytest.raises(ValueError, match=msg): store.append("df", df) def test_append_with_strings(self, setup_path): @@ -1410,7 +1429,14 @@ def check_col(key, name, size): df_new = DataFrame( [[124, "abcdefqhij"], [346, "abcdefghijklmnopqrtsuvwxyz"]] ) - with pytest.raises(ValueError): + msg = ( + r"Trying to store a string with len \[26\] in " + r"\[values_block_1\] column but\n" + r"this column has a limit of \[15\]!\n" + "Consider using min_itemsize to preset the sizes on these " + "columns" + ) + with pytest.raises(ValueError, match=msg): store.append("df_new", df_new) # min_itemsize on Series index (GH 11412) @@ -1488,7 +1514,10 @@ def check_col(key, name, size): # invalid min_itemsize keys df = DataFrame(["foo", "foo", "foo", "barh", "barh", "barh"], columns=["A"]) _maybe_remove(store, "df") - with pytest.raises(ValueError): + msg = re.escape( + "min_itemsize has the key [foo] which is not an axis or data_column" + ) + with pytest.raises(ValueError, match=msg): store.append("df", df, min_itemsize={"foo": 20, "foobar": 20}) def test_append_with_empty_string(self, setup_path): @@ -1718,7 +1747,8 @@ def col(t, column): # try to index a non-table _maybe_remove(store, "f2") store.put("f2", df) - with pytest.raises(TypeError): + msg = "cannot create table index on a Fixed format store" + with pytest.raises(TypeError, match=msg): store.create_table_index("f2") def test_create_table_index_data_columns_argument(self, setup_path): @@ -1800,9 +1830,15 @@ def test_column_multiindex(self, setup_path): store["df1"], expected, check_index_type=True, check_column_type=True ) - with pytest.raises(ValueError): + msg = re.escape( + "cannot use a multi-index on axis [1] with data_columns ['A']" + ) + with pytest.raises(ValueError, match=msg): store.put("df2", df, format="table", data_columns=["A"]) - with pytest.raises(ValueError): + msg = re.escape( + "cannot use a multi-index on axis [1] with data_columns True" + ) + with pytest.raises(ValueError, match=msg): store.put("df3", df, format="table", data_columns=True) # appending multi-column on existing table (see GH 6167) @@ -1874,7 +1910,8 @@ def make_index(names=None): columns=["a", "b"], index=make_index(["date", "a", "t"]), ) - with pytest.raises(ValueError): + msg = "duplicate names/columns in the multi-index when storing as a table" + with pytest.raises(ValueError, match=msg): store.append("df", df) # dup within level @@ -1884,7 +1921,7 @@ def make_index(names=None): columns=["a", "b"], index=make_index(["date", "date", "date"]), ) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): store.append("df", df) # fully names @@ -1945,9 +1982,17 @@ def test_pass_spec_to_storer(self, setup_path): with ensure_clean_store(setup_path) as store: store.put("df", df) - with pytest.raises(TypeError): + msg = ( + "cannot pass a column specification when reading a Fixed format " + "store. this store must be selected in its entirety" + ) + with pytest.raises(TypeError, match=msg): store.select("df", columns=["A"]) - with pytest.raises(TypeError): + msg = ( + "cannot pass a where specification when reading from a Fixed " + "format store. this store must be selected in its entirety" + ) + with pytest.raises(TypeError, match=msg): store.select("df", where=[("columns=A")]) def test_append_misc(self, setup_path): @@ -2010,13 +2055,14 @@ def test_append_raise(self, setup_path): df = tm.makeDataFrame() df["invalid"] = [["a"]] * len(df) assert df.dtypes["invalid"] == np.object_ - with pytest.raises(TypeError): + msg = re.escape("object of type 'int' has no len()") + with pytest.raises(TypeError, match=msg): store.append("df", df) # multiple invalid columns df["invalid2"] = [["a"]] * len(df) df["invalid3"] = [["a"]] * len(df) - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): store.append("df", df) # datetime with embedded nans as object @@ -2026,15 +2072,21 @@ def test_append_raise(self, setup_path): s[0:5] = np.nan df["invalid"] = s assert df.dtypes["invalid"] == np.object_ - with pytest.raises(TypeError): + msg = "too many timezones in this block, create separate data columns" + with pytest.raises(TypeError, match=msg): store.append("df", df) # directly ndarray - with pytest.raises(TypeError): + msg = "value must be None, Series, or DataFrame" + with pytest.raises(TypeError, match=msg): store.append("df", np.arange(10)) # series directly - with pytest.raises(TypeError): + msg = re.escape( + "cannot properly create the storer for: " + "[group->df,value-><class 'pandas.core.series.Series'>]" + ) + with pytest.raises(TypeError, match=msg): store.append("df", Series(np.arange(10))) # appending an incompatible table @@ -2042,7 +2094,12 @@ def test_append_raise(self, setup_path): store.append("df", df) df["foo"] = "foo" - with pytest.raises(ValueError): + msg = re.escape( + "invalid combination of [non_index_axes] on appending data " + "[(1, ['A', 'B', 'C', 'D', 'foo'])] vs current table " + "[(1, ['A', 'B', 'C', 'D'])]" + ) + with pytest.raises(ValueError, match=msg): store.append("df", df) def test_table_index_incompatible_dtypes(self, setup_path): @@ -2051,7 +2108,8 @@ def test_table_index_incompatible_dtypes(self, setup_path): with ensure_clean_store(setup_path) as store: store.put("frame", df1, format="table") - with pytest.raises(TypeError): + msg = re.escape("incompatible kind in col [integer - datetime64]") + with pytest.raises(TypeError, match=msg): store.put("frame", df2, format="table", append=True) def test_table_values_dtypes_roundtrip(self, setup_path): @@ -2066,7 +2124,15 @@ def test_table_values_dtypes_roundtrip(self, setup_path): tm.assert_series_equal(df2.dtypes, store["df_i8"].dtypes) # incompatible dtype - with pytest.raises(ValueError): + msg = re.escape( + "invalid combination of [values_axes] on appending data " + "[name->values_block_0,cname->values_block_0," + "dtype->float64,kind->float,shape->(1, 3)] vs " + "current table [name->values_block_0," + "cname->values_block_0,dtype->int64,kind->integer," + "shape->None]" + ) + with pytest.raises(ValueError, match=msg): store.append("df_i8", df1) # check creation/storage/retrieval of float32 (a bit hacky to @@ -2142,7 +2208,8 @@ def test_unimplemented_dtypes_table_columns(self, setup_path): for n, f in dtypes: df = tm.makeDataFrame() df[n] = f - with pytest.raises(TypeError): + msg = re.escape(f"[{n}] is not implemented as a table column") + with pytest.raises(TypeError, match=msg): store.append(f"df1_{n}", df) # frame @@ -2154,7 +2221,8 @@ def test_unimplemented_dtypes_table_columns(self, setup_path): with ensure_clean_store(setup_path) as store: # this fails because we have a date in the object block...... - with pytest.raises(TypeError): + msg = "object of type 'int' has no len()" + with pytest.raises(TypeError, match=msg): store.append("df_unimplemented", df) def test_calendar_roundtrip_issue(self, setup_path): @@ -2287,14 +2355,22 @@ def test_invalid_terms(self, setup_path): store.put("df", df, format="table") # some invalid terms - with pytest.raises(TypeError): + msg = re.escape( + "__init__() missing 1 required positional argument: 'where'" + ) + with pytest.raises(TypeError, match=msg): Term() # more invalid - with pytest.raises(ValueError): + msg = re.escape( + "cannot process expression [df.index[3]], " + "[2000-01-06 00:00:00] is not a valid condition" + ) + with pytest.raises(ValueError, match=msg): store.select("df", "df.index[3]") - with pytest.raises(SyntaxError): + msg = "invalid syntax" + with pytest.raises(SyntaxError, match=msg): store.select("df", "index>") # from the docs @@ -2321,7 +2397,14 @@ def test_invalid_terms(self, setup_path): ) dfq.to_hdf(path, "dfq", format="table") - with pytest.raises(ValueError): + msg = ( + r"The passed where expression: A>0 or C>0\n\s*" + r"contains an invalid variable reference\n\s*" + r"all of the variable references must be a reference to\n\s*" + r"an axis \(e.g. 'index' or 'columns'\), or a data_column\n\s*" + r"The currently defined references are: index,columns\n" + ) + with pytest.raises(ValueError, match=msg): read_hdf(path, "dfq", where="A>0 or C>0") def test_same_name_scoping(self, setup_path): @@ -2917,10 +3000,11 @@ def test_select_iterator(self, setup_path): df = tm.makeTimeDataFrame(500) df.to_hdf(path, "df_non_table") - with pytest.raises(TypeError): + msg = "can only use an iterator or chunksize on a table" + with pytest.raises(TypeError, match=msg): read_hdf(path, "df_non_table", chunksize=100) - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): read_hdf(path, "df_non_table", iterator=True) with ensure_clean_path(setup_path) as path: @@ -3264,7 +3348,8 @@ def test_frame_select(self, setup_path): # invalid terms df = tm.makeTimeDataFrame() store.append("df_time", df) - with pytest.raises(ValueError): + msg = "could not convert string to Timestamp" + with pytest.raises(ValueError, match=msg): store.select("df_time", "index>0") # can't select if not written as table @@ -3311,7 +3396,8 @@ def test_frame_select_complex(self, setup_path): tm.assert_frame_equal(result, expected) # invert not implemented in numexpr :( - with pytest.raises(NotImplementedError): + msg = "cannot use an invert condition when passing to numexpr" + with pytest.raises(NotImplementedError, match=msg): store.select("df", '~(string="bar")') # invert ok for filters @@ -3397,12 +3483,13 @@ def test_invalid_filtering(self, setup_path): with ensure_clean_store(setup_path) as store: store.put("df", df, format="table") + msg = "unable to collapse Joint Filters" # not implemented - with pytest.raises(NotImplementedError): + with pytest.raises(NotImplementedError, match=msg): store.select("df", "columns=['A'] | columns=['B']") # in theory we could deal with this - with pytest.raises(NotImplementedError): + with pytest.raises(NotImplementedError, match=msg): store.select("df", "columns=['A','B'] & columns=['C']") def test_string_select(self, setup_path): @@ -3467,7 +3554,10 @@ def test_read_column(self, setup_path): ): store.select_column("df", "foo") - with pytest.raises(Exception): + msg = re.escape( + "select_column() got an unexpected keyword argument 'where'" + ) + with pytest.raises(TypeError, match=msg): store.select_column("df", "index", where=["index>5"]) # valid @@ -3476,7 +3566,11 @@ def test_read_column(self, setup_path): assert isinstance(result, Series) # not a data indexable column - with pytest.raises(ValueError): + msg = re.escape( + "column [values_block_0] can not be extracted individually; " + "it is not data indexable" + ) + with pytest.raises(ValueError, match=msg): store.select_column("df", "values_block_0") # a data column @@ -3587,16 +3681,17 @@ def test_coordinates(self, setup_path): tm.assert_frame_equal(result, expected) # invalid - with pytest.raises(ValueError): + msg = "cannot process expression" + with pytest.raises(ValueError, match=msg): store.select("df", where=np.arange(len(df), dtype="float64")) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): store.select("df", where=np.arange(len(df) + 1)) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): store.select("df", where=np.arange(len(df)), start=5) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): store.select("df", where=np.arange(len(df)), start=5, stop=10) # selection with filter @@ -3633,15 +3728,20 @@ def test_append_to_multiple(self, setup_path): with ensure_clean_store(setup_path) as store: # exceptions - with pytest.raises(ValueError): + msg = "append_to_multiple requires a selector that is in passed dict" + with pytest.raises(ValueError, match=msg): store.append_to_multiple( {"df1": ["A", "B"], "df2": None}, df, selector="df3" ) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): store.append_to_multiple({"df1": None, "df2": None}, df, selector="df3") - with pytest.raises(ValueError): + msg = ( + "append_to_multiple must have a dictionary specified as the way to " + "split the value" + ) + with pytest.raises(ValueError, match=msg): store.append_to_multiple("df1", df, "df1") # regular operation @@ -3687,7 +3787,9 @@ def test_append_to_multiple_dropna_false(self, setup_path): {"df1a": ["A", "B"], "df2a": None}, df, selector="df1a", dropna=False ) - with pytest.raises(ValueError): + # TODO Update error message to desired message for this case + msg = "Cannot select as multiple after appending with dropna=False" + with pytest.raises(ValueError, match=msg): store.select_as_multiple(["df1a", "df2a"]) assert not store.select("df1a").index.equals(store.select("df2a").index) @@ -3727,18 +3829,19 @@ def test_select_as_multiple(self, setup_path): with ensure_clean_store(setup_path) as store: + msg = "keys must be a list/tuple" # no tables stored - with pytest.raises(Exception): + with pytest.raises(TypeError, match=msg): store.select_as_multiple(None, where=["A>0", "B>0"], selector="df1") store.append("df1", df1, data_columns=["A", "B"]) store.append("df2", df2) # exceptions - with pytest.raises(Exception): + with pytest.raises(TypeError, match=msg): store.select_as_multiple(None, where=["A>0", "B>0"], selector="df1") - with pytest.raises(Exception): + with pytest.raises(TypeError, match=msg): store.select_as_multiple([None], where=["A>0", "B>0"], selector="df1") msg = "'No object named df3 in the file'" @@ -3784,7 +3887,8 @@ def test_select_as_multiple(self, setup_path): # test exception for diff rows store.append("df3", tm.makeTimeDataFrame(nper=50)) - with pytest.raises(ValueError): + msg = "all tables must have exactly the same nrows!" + with pytest.raises(ValueError, match=msg): store.select_as_multiple( ["df1", "df3"], where=["A>0", "B>0"], selector="df1" ) @@ -4019,11 +4123,13 @@ def test_multiple_open_close(self, setup_path): with ensure_clean_path(setup_path) as path: if pytables._table_file_open_policy_is_strict: - # multiples store1 = HDFStore(path) - - with pytest.raises(ValueError): + msg = ( + r"The file [\S]* is already opened\. Please close it before " + r"reopening in write mode\." + ) + with pytest.raises(ValueError, match=msg): HDFStore(path) store1.close() @@ -4086,42 +4192,44 @@ def test_multiple_open_close(self, setup_path): store = HDFStore(path) store.close() - with pytest.raises(ClosedFileError): + msg = r"[\S]* file is not open!" + with pytest.raises(ClosedFileError, match=msg): store.keys() - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): "df" in store - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): len(store) - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): store["df"] - with pytest.raises(AttributeError): - store.df - - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): store.select("df") - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): store.get("df") - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): store.append("df2", df) - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): store.put("df3", df) - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): store.get_storer("df2") - with pytest.raises(ClosedFileError): + with pytest.raises(ClosedFileError, match=msg): store.remove("df2") - with pytest.raises(ClosedFileError, match="file is not open"): + with pytest.raises(ClosedFileError, match=msg): store.select("df") + msg = "'HDFStore' object has no attribute 'df'" + with pytest.raises(AttributeError, match=msg): + store.df + def test_pytables_native_read(self, datapath, setup_path): with ensure_clean_store( datapath("io", "data", "legacy_hdf/pytables_native.h5"), mode="r" @@ -4338,7 +4446,10 @@ def test_append_with_diff_col_name_types_raises_value_error(self, setup_path): store.append(name, df) for d in (df2, df3, df4, df5): - with pytest.raises(ValueError): + msg = re.escape( + "cannot match existing table structure for [0] on appending data" + ) + with pytest.raises(ValueError, match=msg): store.append(name, d) def test_query_with_nested_special_character(self, setup_path): @@ -4460,7 +4571,10 @@ def test_categorical(self, setup_path): df3 = df.copy() df3["s"] = df3["s"].cat.remove_unused_categories() - with pytest.raises(ValueError): + msg = ( + "cannot append a categorical with different categories to the existing" + ) + with pytest.raises(ValueError, match=msg): store.append("df3", df3) # Remove, and make sure meta data is removed (its a recursive @@ -4529,7 +4643,8 @@ def test_duplicate_column_name(self, setup_path): df = DataFrame(columns=["a", "a"], data=[[0, 0]]) with ensure_clean_path(setup_path) as path: - with pytest.raises(ValueError): + msg = "Columns index has to be unique for fixed format" + with pytest.raises(ValueError, match=msg): df.to_hdf(path, "df", format="fixed") df.to_hdf(path, "df", format="table") @@ -4655,24 +4770,28 @@ def test_read_hdf_errors(self, setup_path): df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) with ensure_clean_path(setup_path) as path: - with pytest.raises(IOError): + msg = r"File [\S]* does not exist" + with pytest.raises(IOError, match=msg): read_hdf(path, "key") df.to_hdf(path, "df") store = HDFStore(path, mode="r") store.close() - with pytest.raises(IOError): + msg = "The HDFStore must be open for reading." + with pytest.raises(IOError, match=msg): read_hdf(store, "df") def test_read_hdf_generic_buffer_errors(self): - with pytest.raises(NotImplementedError): + msg = "Support for generic buffers has not been implemented." + with pytest.raises(NotImplementedError, match=msg): read_hdf(BytesIO(b""), "df") def test_invalid_complib(self, setup_path): df = DataFrame(np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE")) with tm.ensure_clean(setup_path) as path: - with pytest.raises(ValueError): + msg = r"complib only supports \[.*\] compression." + with pytest.raises(ValueError, match=msg): df.to_hdf(path, "df", complib="foolib") # GH10443 @@ -4688,7 +4807,8 @@ def test_read_nokey(self, setup_path): tm.assert_frame_equal(df, reread) df.to_hdf(path, "df2", mode="a") - with pytest.raises(ValueError): + msg = "key must be provided when HDF5 file contains multiple datasets." + with pytest.raises(ValueError, match=msg): read_hdf(path) def test_read_nokey_table(self, setup_path): @@ -4701,15 +4821,19 @@ def test_read_nokey_table(self, setup_path): tm.assert_frame_equal(df, reread) df.to_hdf(path, "df2", mode="a", format="table") - with pytest.raises(ValueError): + msg = "key must be provided when HDF5 file contains multiple datasets." + with pytest.raises(ValueError, match=msg): read_hdf(path) def test_read_nokey_empty(self, setup_path): with ensure_clean_path(setup_path) as path: store = HDFStore(path) store.close() - - with pytest.raises(ValueError): + msg = re.escape( + "Dataset(s) incompatible with Pandas data types, not table, or no " + "datasets found in HDF5 file." + ) + with pytest.raises(ValueError, match=msg): read_hdf(path) def test_read_from_pathlib_path(self, setup_path): @@ -4788,14 +4912,16 @@ def test_query_compare_column_type(self, setup_path): # non strings to string column always fail for v in [2.1, True, Timestamp("2014-01-01"), pd.Timedelta(1, "s")]: query = f"date {op} v" - with pytest.raises(TypeError): + msg = f"Cannot compare {v} of type {type(v)} to string column" + with pytest.raises(TypeError, match=msg): store.select("test", where=query) # strings to other columns must be convertible to type v = "a" for col in ["int", "float", "real_date"]: query = f"{col} {op} v" - with pytest.raises(ValueError): + msg = "could not convert string to " + with pytest.raises(ValueError, match=msg): store.select("test", where=query) for v, col in zip(
This pull request xref #30999 to remove bare `pytest.raises`. It doesn't close that issue as I have only addressed one file: `pandas/tests/io/pytables/test_store.py`. In that file there were 80 instances of bare `pytest.raises`. `test_append_to_multiple_dropna_false` is marked as failing because it isn't raising the `ValueError` that it should. Because of this, I didn't know what the message should be, and reading through the code didn't help me figure it out. I wrote a draft error message and added a `TODO` (line 3790) and I hope that's the best way to handle it. In `test_multiple_open_close` there were several assertions that `ClosedFileError` is raised with the same error message, with one in the middle that asserts that an `AttributeError` is raised with a different error message. I moved the one for the `AttributeError` to the end of the list (line 4229) to organize the assertions a little better and make clear that the `msg` parameter is the same for all the `ClosedFileError`s. I did not add a whatsnew entry since it only changes the tests. Let me know if I should add one (and I am a bit unclear on how, i.e. what version this would end up in). - [ ] xref #30999 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38609
2020-12-21T12:52:25Z
2020-12-22T23:17:29Z
2020-12-22T23:17:29Z
2020-12-24T17:14:23Z
REF: simplify CategoricalIndex.__new__
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 27110fe1f8439..413309b3d01ad 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -298,7 +298,13 @@ class Categorical(NDArrayBackedExtensionArray, PandasObject, ObjectStringArrayMi _can_hold_na = True def __init__( - self, values, categories=None, ordered=None, dtype=None, fastpath=False + self, + values, + categories=None, + ordered=None, + dtype=None, + fastpath=False, + copy: bool = True, ): dtype = CategoricalDtype._from_values_or_dtype( @@ -359,9 +365,9 @@ def __init__( dtype = CategoricalDtype(categories, dtype.ordered) elif is_categorical_dtype(values.dtype): - old_codes = extract_array(values).codes + old_codes = extract_array(values)._codes codes = recode_for_categories( - old_codes, values.dtype.categories, dtype.categories + old_codes, values.dtype.categories, dtype.categories, copy=copy ) else: @@ -389,7 +395,7 @@ def _constructor(self) -> Type["Categorical"]: @classmethod def _from_sequence(cls, scalars, *, dtype=None, copy=False): - return Categorical(scalars, dtype=dtype) + return Categorical(scalars, dtype=dtype, copy=copy) def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: """ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 76b1c061cc827..ecf77a9987bee 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -15,7 +15,6 @@ is_categorical_dtype, is_scalar, ) -from pandas.core.dtypes.dtypes import CategoricalDtype from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna from pandas.core import accessor @@ -184,28 +183,18 @@ def __new__( cls, data=None, categories=None, ordered=None, dtype=None, copy=False, name=None ): - dtype = CategoricalDtype._from_values_or_dtype(data, categories, ordered, dtype) - name = maybe_extract_name(name, data, cls) - if not is_categorical_dtype(data): + if is_scalar(data): # don't allow scalars # if data is None, then categories must be provided - if is_scalar(data): - if data is not None or categories is None: - raise cls._scalar_data_error(data) - data = [] - - assert isinstance(dtype, CategoricalDtype), dtype - data = extract_array(data, extract_numpy=True) + if data is not None or categories is None: + raise cls._scalar_data_error(data) + data = [] - if not isinstance(data, Categorical): - data = Categorical(data, dtype=dtype) - elif isinstance(dtype, CategoricalDtype) and dtype != data.dtype: - # we want to silently ignore dtype='category' - data = data._set_dtype(dtype) - - data = data.copy() if copy else data + data = Categorical( + data, categories=categories, ordered=ordered, dtype=dtype, copy=copy + ) return cls._simple_new(data, name=name) diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 753c15bde6bba..25b5be2ccc918 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -699,3 +699,14 @@ def test_categorical_extension_array_nullable(self, nulls_fixture): result = Categorical(arr) expected = Categorical(Series([pd.NA, pd.NA], dtype="object")) tm.assert_categorical_equal(result, expected) + + def test_from_sequence_copy(self): + cat = Categorical(np.arange(5).repeat(2)) + result = Categorical._from_sequence(cat, dtype=None, copy=False) + + # more generally, we'd be OK with a view + assert result._codes is cat._codes + + result = Categorical._from_sequence(cat, dtype=None, copy=True) + + assert not np.shares_memory(result._codes, cat._codes) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 3bab57e1d265e..00fca00c5b4a0 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -304,7 +304,7 @@ def test_ensure_copied_data(self, index): assert _base(index.values) is not _base(result.values) result = CategoricalIndex(index.values, copy=False) - assert _base(index.values) is _base(result.values) + assert result._data._codes is index._data._codes def test_frame_repr(self): df = pd.DataFrame({"A": [1, 2, 3]}, index=CategoricalIndex(["a", "b", "c"]))
Part of a larger goal of making `Index.__new__` share code with `Series.__init__` and `pd.array`
https://api.github.com/repos/pandas-dev/pandas/pulls/38605
2020-12-21T04:15:14Z
2020-12-22T14:09:21Z
2020-12-22T14:09:21Z
2020-12-28T16:04:23Z
Backport PR #38598 on branch 1.2.x (BUG: Temporarily pin the version of Sphinx to 3.3.1 in requirements.)
diff --git a/environment.yml b/environment.yml index b99b856187fb6..1ac190830c132 100644 --- a/environment.yml +++ b/environment.yml @@ -31,7 +31,7 @@ dependencies: # documentation - gitpython # obtain contributors from git for whatsnew - gitdb - - sphinx + - sphinx=3.3.1 # documentation (jupyter notebooks) - nbconvert>=5.4.1 diff --git a/requirements-dev.txt b/requirements-dev.txt index 17ca6b8401501..137c0db5f4408 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,7 +17,7 @@ pycodestyle pyupgrade gitpython gitdb -sphinx +sphinx==3.3.1 nbconvert>=5.4.1 nbsphinx pandoc
Backport PR #38598: BUG: Temporarily pin the version of Sphinx to 3.3.1 in requirements.
https://api.github.com/repos/pandas-dev/pandas/pulls/38603
2020-12-21T02:59:51Z
2020-12-21T12:17:18Z
2020-12-21T12:17:18Z
2020-12-21T12:17:19Z
BUG: Temporarily pin the version of Sphinx to 3.3.1 in requirements.
diff --git a/environment.yml b/environment.yml index 600a20b153ed3..a23e7906a42a0 100644 --- a/environment.yml +++ b/environment.yml @@ -31,7 +31,7 @@ dependencies: # documentation - gitpython # obtain contributors from git for whatsnew - gitdb - - sphinx + - sphinx=3.3.1 # documentation (jupyter notebooks) - nbconvert>=5.4.1 diff --git a/requirements-dev.txt b/requirements-dev.txt index d45e87b1785b0..084952fbdf5ef 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,7 +17,7 @@ pycodestyle pyupgrade gitpython gitdb -sphinx +sphinx==3.3.1 nbconvert>=5.4.1 nbsphinx pandoc
A recent change in Sphinx v3.4.0 is breaking pandas' CI *Build documentation* step. Until this is resolved, we can temporarily pin Sphinx to the previous version (3.3.1). _Submitted in response to @jreback in https://github.com/pandas-dev/pandas/issues/38593#issuecomment-748690637_ ------ Here's some info that might help for getting this sorted, long term: Sphinx Changelog: Release 3.4.0 (released Dec 20, 2020) https://www.sphinx-doc.org/en/master/changes.html#release-3-4-0-released-dec-20-2020 CI build logs from some passing and failing builds: * A successful build using Sphinx 3.3.1 - https://pastebin.com/raw/jLwVAJsP * A failing build using Sphinx 3.4.0 - https://pastebin.com/raw/bpHTm2DD * A here's a diff between these two logs - https://pastebin.com/psJ5hqP8 While passing and failing builds both emit warnings, the following warnings are exclusive to the failing builds under Sphinx 3.4.0: ``` /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessDay.rst:18: WARNING: autosummary: failed to import base /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessDay.rst:18: WARNING: autosummary: failed to import offset /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessDay.rst:40: WARNING: autosummary: failed to import __call__ /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessDay.rst:40: WARNING: autosummary: failed to import rollback /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessDay.rst:40: WARNING: autosummary: failed to import rollforward /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthBegin.rst:18: WARNING: autosummary: failed to import base /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthBegin.rst:36: WARNING: autosummary: failed to import __call__ /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthBegin.rst:36: WARNING: autosummary: failed to import rollback /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthBegin.rst:36: WARNING: autosummary: failed to import rollforward /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthEnd.rst:18: WARNING: autosummary: failed to import base /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthEnd.rst:36: WARNING: autosummary: failed to import __call__ /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthEnd.rst:36: WARNING: autosummary: failed to import rollback /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.BusinessMonthEnd.rst:36: WARNING: autosummary: failed to import rollforward /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthBegin.rst:18: WARNING: autosummary: failed to import base /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthBegin.rst:18: WARNING: autosummary: failed to import cbday_roll /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthBegin.rst:18: WARNING: autosummary: failed to import month_roll /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthBegin.rst:18: WARNING: autosummary: failed to import offset /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthBegin.rst:43: WARNING: autosummary: failed to import __call__ /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthBegin.rst:43: WARNING: autosummary: failed to import rollback /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthBegin.rst:43: WARNING: autosummary: failed to import rollforward /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthEnd.rst:18: WARNING: autosummary: failed to import base /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthEnd.rst:18: WARNING: autosummary: failed to import cbday_roll /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthEnd.rst:18: WARNING: autosummary: failed to import month_roll /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthEnd.rst:18: WARNING: autosummary: failed to import offset /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthEnd.rst:43: WARNING: autosummary: failed to import __call__ /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthEnd.rst:43: WARNING: autosummary: failed to import rollback /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessMonthEnd.rst:43: WARNING: autosummary: failed to import rollforward /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessDay.rst:18: WARNING: autosummary: failed to import base /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessDay.rst:18: WARNING: autosummary: failed to import offset /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessDay.rst:40: WARNING: autosummary: failed to import __call__ /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessDay.rst:40: WARNING: autosummary: failed to import rollback /home/runner/work/pandas/pandas/doc/source/docstring of pandas._libs.tslibs.offsets.CustomBusinessDay.rst:40: WARNING: autosummary: failed to import rollforward ```
https://api.github.com/repos/pandas-dev/pandas/pulls/38598
2020-12-21T00:31:14Z
2020-12-21T02:59:11Z
2020-12-21T02:59:11Z
2020-12-21T02:59:21Z
DEPR: allowing subclass-specific keywords in pd.Index.__new__
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index fbd2c2b5345fc..53f254aee2e0e 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -143,7 +143,7 @@ Other API changes Deprecations ~~~~~~~~~~~~ - +- Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`,:issue:`21311`,:issue:`22315`,:issue:`26974`) - - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2a5d6db41a56d..bad477885ddab 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -252,6 +252,15 @@ def __new__( cls, data=None, dtype=None, copy=False, name=None, tupleize_cols=True, **kwargs ) -> "Index": + if kwargs: + warnings.warn( + "Passing keywords other than 'data', 'dtype', 'copy', 'name', " + "'tupleize_cols' is deprecated and will raise TypeError in a " + "future version. Use the specific Index subclass directly instead", + FutureWarning, + stacklevel=2, + ) + from pandas.core.indexes.range import RangeIndex name = maybe_extract_name(name, data, cls) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 220cd5363e78f..ba4cffe0533a0 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -147,7 +147,7 @@ def __array_wrap__(self, result, context=None): if not is_period_dtype(self.dtype) and attrs["freq"]: # no need to infer if freq is None attrs["freq"] = "infer" - return Index(result, **attrs) + return type(self)(result, **attrs) # ------------------------------------------------------------------------ diff --git a/pandas/core/resample.py b/pandas/core/resample.py index b8b372e7666b8..e432ec6cb54a2 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1966,6 +1966,10 @@ def _asfreq_compat(index, freq): new_index: Index if isinstance(index, PeriodIndex): new_index = index.asfreq(freq=freq) - else: - new_index = Index([], dtype=index.dtype, freq=freq, name=index.name) + elif isinstance(index, DatetimeIndex): + new_index = DatetimeIndex([], dtype=index.dtype, freq=freq, name=index.name) + elif isinstance(index, TimedeltaIndex): + new_index = TimedeltaIndex([], dtype=index.dtype, freq=freq, name=index.name) + else: # pragma: no cover + raise TypeError(type(index)) return new_index diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index c22f6806e932e..d5c5e8edb9efe 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -12,6 +12,7 @@ from typing import ( TYPE_CHECKING, Any, + Callable, Dict, List, Optional, @@ -2045,15 +2046,19 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): if self.freq is not None: kwargs["freq"] = _ensure_decoded(self.freq) + factory: Union[Type[Index], Type[DatetimeIndex]] = Index + if is_datetime64_dtype(values.dtype) or is_datetime64tz_dtype(values.dtype): + factory = DatetimeIndex + # making an Index instance could throw a number of different errors try: - new_pd_index = Index(values, **kwargs) + new_pd_index = factory(values, **kwargs) except ValueError: # if the output freq is different that what we recorded, # it should be None (see also 'doc example part 2') if "freq" in kwargs: kwargs["freq"] = None - new_pd_index = Index(values, **kwargs) + new_pd_index = factory(values, **kwargs) new_pd_index = _set_tz(new_pd_index, self.tz) return new_pd_index, new_pd_index @@ -2736,8 +2741,14 @@ def _alias_to_class(self, alias): return alias return self._reverse_index_map.get(alias, Index) - def _get_index_factory(self, klass): - if klass == DatetimeIndex: + def _get_index_factory(self, attrs): + index_class = self._alias_to_class( + _ensure_decoded(getattr(attrs, "index_class", "")) + ) + + factory: Callable + + if index_class == DatetimeIndex: def f(values, freq=None, tz=None): # data are already in UTC, localize and convert if tz present @@ -2747,16 +2758,34 @@ def f(values, freq=None, tz=None): result = result.tz_localize("UTC").tz_convert(tz) return result - return f - elif klass == PeriodIndex: + factory = f + elif index_class == PeriodIndex: def f(values, freq=None, tz=None): parr = PeriodArray._simple_new(values, freq=freq) return PeriodIndex._simple_new(parr, name=None) - return f + factory = f + else: + factory = index_class + + kwargs = {} + if "freq" in attrs: + kwargs["freq"] = attrs["freq"] + if index_class is Index: + # DTI/PI would be gotten by _alias_to_class + factory = TimedeltaIndex + + if "tz" in attrs: + if isinstance(attrs["tz"], bytes): + # created by python2 + kwargs["tz"] = attrs["tz"].decode("utf-8") + else: + # created by python3 + kwargs["tz"] = attrs["tz"] + assert index_class is DatetimeIndex # just checking - return klass + return factory, kwargs def validate_read(self, columns, where): """ @@ -2928,22 +2957,8 @@ def read_index_node( name = _ensure_str(node._v_attrs.name) name = _ensure_decoded(name) - index_class = self._alias_to_class( - _ensure_decoded(getattr(node._v_attrs, "index_class", "")) - ) - factory = self._get_index_factory(index_class) - - kwargs = {} - if "freq" in node._v_attrs: - kwargs["freq"] = node._v_attrs["freq"] - - if "tz" in node._v_attrs: - if isinstance(node._v_attrs["tz"], bytes): - # created by python2 - kwargs["tz"] = node._v_attrs["tz"].decode("utf-8") - else: - # created by python3 - kwargs["tz"] = node._v_attrs["tz"] + attrs = node._v_attrs + factory, kwargs = self._get_index_factory(attrs) if kind == "date": index = factory( diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 5205ca3777fc0..10e69ddcd5f80 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -254,7 +254,8 @@ def test_grouper_creation_bug(self): ) result = s.groupby(pd.Grouper(level="three", freq="M")).sum() expected = Series( - [28], index=Index([Timestamp("2013-01-31")], freq="M", name="three") + [28], + index=pd.DatetimeIndex([Timestamp("2013-01-31")], freq="M", name="three"), ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py index 76fc82c6288eb..c8d6d09577c2b 100644 --- a/pandas/tests/groupby/test_quantile.py +++ b/pandas/tests/groupby/test_quantile.py @@ -271,7 +271,7 @@ def test_columns_groupby_quantile(): [9.6, 8.4, 10.6, 9.4], ], index=list("XYZ"), - columns=Index( + columns=pd.MultiIndex.from_tuples( [("A", 0.8), ("A", 0.2), ("B", 0.8), ("B", 0.2)], names=["col", None] ), ) diff --git a/pandas/tests/indexes/base_class/test_constructors.py b/pandas/tests/indexes/base_class/test_constructors.py index 02b32c46e7d6f..b3229b4eda030 100644 --- a/pandas/tests/indexes/base_class/test_constructors.py +++ b/pandas/tests/indexes/base_class/test_constructors.py @@ -2,6 +2,7 @@ import pytest from pandas import Index, MultiIndex +import pandas._testing as tm class TestIndexConstructor: @@ -29,7 +30,8 @@ def test_construction_list_mixed_tuples(self, index_vals): def test_constructor_wrong_kwargs(self): # GH #19348 with pytest.raises(TypeError, match="Unexpected keyword arguments {'foo'}"): - Index([], foo="bar") + with tm.assert_produces_warning(FutureWarning): + Index([], foo="bar") @pytest.mark.xfail(reason="see GH#21311: Index doesn't enforce dtype argument") def test_constructor_cast(self): diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py index ee3f85da22781..3bd2ac20962d2 100644 --- a/pandas/tests/indexes/categorical/test_constructors.py +++ b/pandas/tests/indexes/categorical/test_constructors.py @@ -129,10 +129,14 @@ def test_construction_with_categorical_dtype(self): CategoricalIndex(data, categories=cats, dtype=dtype) with pytest.raises(ValueError, match=msg): - Index(data, categories=cats, dtype=dtype) + with tm.assert_produces_warning(FutureWarning): + # passing subclass-specific kwargs to pd.Index + Index(data, categories=cats, dtype=dtype) with pytest.raises(ValueError, match=msg): CategoricalIndex(data, ordered=ordered, dtype=dtype) with pytest.raises(ValueError, match=msg): - Index(data, ordered=ordered, dtype=dtype) + with tm.assert_produces_warning(FutureWarning): + # passing subclass-specific kwargs to pd.Index + Index(data, ordered=ordered, dtype=dtype) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 698da83d9e4ad..3f30a1a076eda 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -374,7 +374,9 @@ def test_construction_index_with_mixed_timezones_with_NaT(self): assert result.tz is None # all NaT with tz - result = Index([pd.NaT, pd.NaT], tz="Asia/Tokyo", name="idx") + with tm.assert_produces_warning(FutureWarning): + # subclass-specific kwargs to pd.Index + result = Index([pd.NaT, pd.NaT], tz="Asia/Tokyo", name="idx") exp = DatetimeIndex([pd.NaT, pd.NaT], tz="Asia/Tokyo", name="idx") tm.assert_index_equal(result, exp, exact=True) @@ -462,16 +464,18 @@ def test_construction_dti_with_mixed_timezones(self): with pytest.raises(ValueError, match=msg): # passing tz should results in DatetimeIndex, then mismatch raises # TypeError - Index( - [ - pd.NaT, - Timestamp("2011-01-01 10:00"), - pd.NaT, - Timestamp("2011-01-02 10:00", tz="US/Eastern"), - ], - tz="Asia/Tokyo", - name="idx", - ) + with tm.assert_produces_warning(FutureWarning): + # subclass-specific kwargs to pd.Index + Index( + [ + pd.NaT, + Timestamp("2011-01-01 10:00"), + pd.NaT, + Timestamp("2011-01-02 10:00", tz="US/Eastern"), + ], + tz="Asia/Tokyo", + name="idx", + ) def test_construction_base_constructor(self): arr = [Timestamp("2011-01-01"), pd.NaT, Timestamp("2011-01-03")] diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py index 8b4cafc17a202..6182df8429e8b 100644 --- a/pandas/tests/indexes/interval/test_constructors.py +++ b/pandas/tests/indexes/interval/test_constructors.py @@ -36,6 +36,7 @@ class ConstructorTests: get_kwargs_from_breaks to the expected format. """ + @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize( "breaks", [ @@ -80,6 +81,7 @@ def test_constructor_dtype(self, constructor, breaks, subtype): result = constructor(dtype=dtype, **result_kwargs) tm.assert_index_equal(result, expected) + @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50]) def test_constructor_nan(self, constructor, breaks, closed): # GH 18421 @@ -93,6 +95,7 @@ def test_constructor_nan(self, constructor, breaks, closed): assert result.dtype.subtype == expected_subtype tm.assert_numpy_array_equal(np.array(result), expected_values) + @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize( "breaks", [ @@ -378,6 +381,7 @@ def test_constructor_errors(self, constructor): with pytest.raises(TypeError, match=msg): constructor([0, 1]) + @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize( "data, closed", [ diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py index bb34760e28d96..52acb3d0797c6 100644 --- a/pandas/tests/indexes/multi/test_equivalence.py +++ b/pandas/tests/indexes/multi/test_equivalence.py @@ -185,10 +185,16 @@ def test_identical(idx): mi2 = mi2.set_names(["new1", "new2"]) assert mi.identical(mi2) - mi3 = Index(mi.tolist(), names=mi.names) + with tm.assert_produces_warning(FutureWarning): + # subclass-specific keywords to pd.Index + mi3 = Index(mi.tolist(), names=mi.names) + msg = r"Unexpected keyword arguments {'names'}" with pytest.raises(TypeError, match=msg): - Index(mi.tolist(), names=mi.names, tupleize_cols=False) + with tm.assert_produces_warning(FutureWarning): + # subclass-specific keywords to pd.Index + Index(mi.tolist(), names=mi.names, tupleize_cols=False) + mi4 = Index(mi.tolist(), tupleize_cols=False) assert mi.identical(mi3) assert not mi.identical(mi4) diff --git a/pandas/tests/indexes/multi/test_names.py b/pandas/tests/indexes/multi/test_names.py index 891380b35a8be..2689e24502b5b 100644 --- a/pandas/tests/indexes/multi/test_names.py +++ b/pandas/tests/indexes/multi/test_names.py @@ -56,7 +56,9 @@ def test_take_preserve_name(idx): def test_copy_names(): # Check that adding a "names" parameter to the copy is honored # GH14302 - multi_idx = pd.Index([(1, 2), (3, 4)], names=["MyName1", "MyName2"]) + with tm.assert_produces_warning(FutureWarning): + # subclass-specific kwargs to pd.Index + multi_idx = pd.Index([(1, 2), (3, 4)], names=["MyName1", "MyName2"]) multi_idx1 = multi_idx.copy() assert multi_idx.equals(multi_idx1) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 372a1d290bca0..e5bb78604207f 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -335,6 +335,7 @@ def test_constructor_dtypes_to_timedelta(self, cast_index, vals): index = Index(vals) assert isinstance(index, TimedeltaIndex) + @pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") @pytest.mark.parametrize("attr", ["values", "asi8"]) @pytest.mark.parametrize("klass", [Index, DatetimeIndex]) def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): @@ -2255,6 +2256,7 @@ def test_index_subclass_constructor_wrong_kwargs(index_maker): index_maker(foo="bar") +@pytest.mark.filterwarnings("ignore:Passing keywords other:FutureWarning") def test_deprecated_fastpath(): msg = "[Uu]nexpected keyword argument" with pytest.raises(TypeError, match=msg): diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index ff1632e33c0fb..e391b76ddbd15 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -57,7 +57,7 @@ def test_index_groupby(self): idx.groupby(to_groupby), {1.0: idx[[0, 5]], 2.0: idx[[1, 4]]} ) - to_groupby = Index( + to_groupby = pd.DatetimeIndex( [ datetime(2011, 11, 1), datetime(2011, 12, 1), diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index bde7e9991bbed..15f58006426f4 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -506,7 +506,9 @@ def test_insert_index_period(self, insert, coerced_val, coerced_dtype): else: msg = r"Unexpected keyword arguments {'freq'}" with pytest.raises(TypeError, match=msg): - pd.Index(data, freq="M") + with tm.assert_produces_warning(FutureWarning): + # passing keywords to pd.Index + pd.Index(data, freq="M") def test_insert_index_complex128(self): pytest.xfail("Test not implemented") diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index dba4b9214e50c..06e7c96277fd6 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -705,18 +705,14 @@ def test_read_json_table_orient_raises(self, index_nm, vals, recwarn): "idx", [ pd.Index(range(4)), - pd.Index( - pd.date_range( - "2020-08-30", - freq="d", - periods=4, - ), - freq=None, - ), - pd.Index( - pd.date_range("2020-08-30", freq="d", periods=4, tz="US/Central"), - freq=None, - ), + pd.date_range( + "2020-08-30", + freq="d", + periods=4, + )._with_freq(None), + pd.date_range( + "2020-08-30", freq="d", periods=4, tz="US/Central" + )._with_freq(None), pd.MultiIndex.from_product( [ pd.date_range("2020-08-30", freq="d", periods=2, tz="US/Central"),
- [x] closes #21311, closes #14093, closes #22315, closes #26974 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38597
2020-12-21T00:26:41Z
2020-12-22T23:45:30Z
2020-12-22T23:45:29Z
2020-12-23T00:08:31Z
CLN: Remove _get_roll_func
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 0fc6c8a23f5f2..b52b7d384036b 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -335,14 +335,14 @@ def mean(self, *args, **kwargs): """ nv.validate_window_func("mean", args, kwargs) if self.times is not None: - window_func = self._get_roll_func("ewma_time") + window_func = window_aggregations.ewma_time window_func = partial( window_func, times=self.times, halflife=self.halflife, ) else: - window_func = self._get_roll_func("ewma") + window_func = window_aggregations.ewma window_func = partial( window_func, com=self.com, @@ -371,7 +371,7 @@ def var(self, bias: bool = False, *args, **kwargs): Exponential weighted moving variance. """ nv.validate_window_func("var", args, kwargs) - window_func = self._get_roll_func("ewmcov") + window_func = window_aggregations.ewmcov window_func = partial( window_func, com=self.com, diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index e6185f8ae0679..96eaa163b9a5d 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -316,26 +316,6 @@ def _insert_on_column(self, result: "DataFrame", obj: "DataFrame"): # insert at the end result[name] = extra_col - def _get_roll_func(self, func_name: str) -> Callable[..., Any]: - """ - Wrap rolling function to check values passed. - - Parameters - ---------- - func_name : str - Cython function used to calculate rolling statistics - - Returns - ------- - func : callable - """ - window_func = getattr(window_aggregations, func_name, None) - if window_func is None: - raise ValueError( - f"we do not support this function in window_aggregations.{func_name}" - ) - return window_func - @property def _index_array(self): # TODO: why do we get here with e.g. MultiIndex? @@ -1153,21 +1133,21 @@ def aggregate(self, func, *args, **kwargs): @Appender(_shared_docs["sum"]) def sum(self, *args, **kwargs): nv.validate_window_func("sum", args, kwargs) - window_func = self._get_roll_func("roll_weighted_sum") + window_func = window_aggregations.roll_weighted_sum return self._apply(window_func, name="sum", **kwargs) @Substitution(name="window") @Appender(_shared_docs["mean"]) def mean(self, *args, **kwargs): nv.validate_window_func("mean", args, kwargs) - window_func = self._get_roll_func("roll_weighted_mean") + window_func = window_aggregations.roll_weighted_mean return self._apply(window_func, name="mean", **kwargs) @Substitution(name="window", versionadded="\n.. versionadded:: 1.0.0\n") @Appender(_shared_docs["var"]) def var(self, ddof: int = 1, *args, **kwargs): nv.validate_window_func("var", args, kwargs) - window_func = partial(self._get_roll_func("roll_weighted_var"), ddof=ddof) + window_func = partial(window_aggregations.roll_weighted_var, ddof=ddof) kwargs.pop("name", None) return self._apply(window_func, name="var", **kwargs) @@ -1221,7 +1201,7 @@ class RollingAndExpandingMixin(BaseWindow): ) def count(self): - window_func = self._get_roll_func("roll_sum") + window_func = window_aggregations.roll_sum return self._apply(window_func, name="count") _shared_docs["apply"] = dedent( @@ -1331,7 +1311,7 @@ def _generate_cython_apply_func( from pandas import Series window_func = partial( - self._get_roll_func("roll_apply"), + window_aggregations.roll_apply, args=args, kwargs=kwargs, raw=raw, @@ -1347,7 +1327,7 @@ def apply_func(values, begin, end, min_periods, raw=raw): def sum(self, *args, **kwargs): nv.validate_window_func("sum", args, kwargs) - window_func = self._get_roll_func("roll_sum") + window_func = window_aggregations.roll_sum return self._apply(window_func, name="sum", **kwargs) _shared_docs["max"] = dedent( @@ -1363,7 +1343,7 @@ def sum(self, *args, **kwargs): def max(self, *args, **kwargs): nv.validate_window_func("max", args, kwargs) - window_func = self._get_roll_func("roll_max") + window_func = window_aggregations.roll_max return self._apply(window_func, name="max", **kwargs) _shared_docs["min"] = dedent( @@ -1405,12 +1385,12 @@ def max(self, *args, **kwargs): def min(self, *args, **kwargs): nv.validate_window_func("min", args, kwargs) - window_func = self._get_roll_func("roll_min") + window_func = window_aggregations.roll_min return self._apply(window_func, name="min", **kwargs) def mean(self, *args, **kwargs): nv.validate_window_func("mean", args, kwargs) - window_func = self._get_roll_func("roll_mean") + window_func = window_aggregations.roll_mean return self._apply(window_func, name="mean", **kwargs) _shared_docs["median"] = dedent( @@ -1451,14 +1431,14 @@ def mean(self, *args, **kwargs): ) def median(self, **kwargs): - window_func = self._get_roll_func("roll_median_c") + window_func = window_aggregations.roll_median_c # GH 32865. Move max window size calculation to # the median function implementation return self._apply(window_func, name="median", **kwargs) def std(self, ddof: int = 1, *args, **kwargs): nv.validate_window_func("std", args, kwargs) - window_func = self._get_roll_func("roll_var") + window_func = window_aggregations.roll_var def zsqrt_func(values, begin, end, min_periods): return zsqrt(window_func(values, begin, end, min_periods, ddof=ddof)) @@ -1471,7 +1451,7 @@ def zsqrt_func(values, begin, end, min_periods): def var(self, ddof: int = 1, *args, **kwargs): nv.validate_window_func("var", args, kwargs) - window_func = partial(self._get_roll_func("roll_var"), ddof=ddof) + window_func = partial(window_aggregations.roll_var, ddof=ddof) return self._apply( window_func, name="var", @@ -1490,7 +1470,7 @@ def var(self, ddof: int = 1, *args, **kwargs): """ def skew(self, **kwargs): - window_func = self._get_roll_func("roll_skew") + window_func = window_aggregations.roll_skew return self._apply( window_func, name="skew", @@ -1583,7 +1563,7 @@ def sem(self, ddof: int = 1, *args, **kwargs): ) def kurt(self, **kwargs): - window_func = self._get_roll_func("roll_kurt") + window_func = window_aggregations.roll_kurt return self._apply( window_func, name="kurt", @@ -1646,12 +1626,12 @@ def kurt(self, **kwargs): def quantile(self, quantile: float, interpolation: str = "linear", **kwargs): if quantile == 1.0: - window_func = self._get_roll_func("roll_max") + window_func = window_aggregations.roll_max elif quantile == 0.0: - window_func = self._get_roll_func("roll_min") + window_func = window_aggregations.roll_min else: window_func = partial( - self._get_roll_func("roll_quantile"), + window_aggregations.roll_quantile, quantile=quantile, interpolation=interpolation, )
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38596
2020-12-20T23:30:06Z
2020-12-21T17:08:06Z
2020-12-21T17:08:06Z
2020-12-21T18:20:56Z
CLN: Window _constructors definitions
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 0fc6c8a23f5f2..d2de7010fe536 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -273,10 +273,6 @@ def __init__( self.halflife = None self.com = get_center_of_mass(com, span, halflife, alpha) - @property - def _constructor(self): - return ExponentialMovingWindow - def _get_window_indexer(self) -> BaseIndexer: """ Return an indexer class that will compute the window start and end bounds @@ -508,6 +504,10 @@ class ExponentialMovingWindowGroupby(BaseWindowGroupby, ExponentialMovingWindow) Provide an exponential moving window groupby implementation. """ + @property + def _constructor(self): + return ExponentialMovingWindow + def _get_window_indexer(self) -> GroupbyIndexer: """ Return an indexer class that will compute the window start and end bounds diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 94875ba86db65..f5f4dba59965c 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -64,10 +64,6 @@ class Expanding(RollingAndExpandingMixin): def __init__(self, obj, min_periods=1, center=None, axis=0, **kwargs): super().__init__(obj=obj, min_periods=min_periods, center=center, axis=axis) - @property - def _constructor(self): - return Expanding - def _get_window_indexer(self) -> BaseIndexer: """ Return an indexer class that will compute the window start and end bounds @@ -281,6 +277,10 @@ class ExpandingGroupby(BaseWindowGroupby, Expanding): Provide a expanding groupby implementation. """ + @property + def _constructor(self): + return Expanding + def _get_window_indexer(self) -> GroupbyIndexer: """ Return an indexer class that will compute the window start and end bounds diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index e6185f8ae0679..67a0cc294fe0e 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1009,10 +1009,6 @@ class Window(BaseWindow): 2013-01-01 09:00:06 4.0 """ - @property - def _constructor(self): - return Window - def validate(self): super().validate() @@ -1884,10 +1880,6 @@ def _on(self) -> Index: "must be a column (of DataFrame), an Index or None" ) - @property - def _constructor(self): - return Rolling - def validate(self): super().validate() @@ -2143,6 +2135,10 @@ class RollingGroupby(BaseWindowGroupby, Rolling): Provide a rolling groupby implementation. """ + @property + def _constructor(self): + return Rolling + def _get_window_indexer(self) -> GroupbyIndexer: """ Return an indexer class that will compute the window start and end bounds
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Redefined in more appropriate locations.
https://api.github.com/repos/pandas-dev/pandas/pulls/38595
2020-12-20T23:13:19Z
2020-12-21T17:09:30Z
2020-12-21T17:09:30Z
2020-12-21T18:21:03Z
DOC: Add datatest package to list of third-party extension accessors.
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index e88875a9f679c..390cf214bad00 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -474,15 +474,16 @@ A directory of projects providing :ref:`extension accessors <extending.register-accessors>`. This is for users to discover new accessors and for library authors to coordinate on the namespace. -=============== ========== ========================= =============================================================== -Library Accessor Classes Description -=============== ========== ========================= =============================================================== -`cyberpandas`_ ``ip`` ``Series`` Provides common operations for working with IP addresses. -`pdvega`_ ``vgplot`` ``Series``, ``DataFrame`` Provides plotting functions from the Altair_ library. -`pandas_path`_ ``path`` ``Index``, ``Series`` Provides `pathlib.Path`_ functions for Series. -`pint-pandas`_ ``pint`` ``Series``, ``DataFrame`` Provides units support for numeric Series and DataFrames. -`composeml`_ ``slice`` ``DataFrame`` Provides a generator for enhanced data slicing. -=============== ========== ========================= =============================================================== +=============== ============ ==================================== =============================================================== +Library Accessor Classes Description +=============== ============ ==================================== =============================================================== +`cyberpandas`_ ``ip`` ``Series`` Provides common operations for working with IP addresses. +`pdvega`_ ``vgplot`` ``Series``, ``DataFrame`` Provides plotting functions from the Altair_ library. +`pandas_path`_ ``path`` ``Index``, ``Series`` Provides `pathlib.Path`_ functions for Series. +`pint-pandas`_ ``pint`` ``Series``, ``DataFrame`` Provides units support for numeric Series and DataFrames. +`composeml`_ ``slice`` ``DataFrame`` Provides a generator for enhanced data slicing. +`datatest`_ ``validate`` ``Series``, ``DataFrame``, ``Index`` Provides validation, differences, and acceptance managers. +=============== ============ ==================================== =============================================================== .. _cyberpandas: https://cyberpandas.readthedocs.io/en/latest .. _pdvega: https://altair-viz.github.io/pdvega/ @@ -492,3 +493,4 @@ Library Accessor Classes Description .. _pathlib.Path: https://docs.python.org/3/library/pathlib.html .. _pint-pandas: https://github.com/hgrecco/pint-pandas .. _composeml: https://github.com/FeatureLabs/compose +.. _datatest: https://datatest.readthedocs.io/
This change adds the `datatest` package to the list of third-party extension accessors. Since `datatest` supports more than `pandas`, I wasn't sure if it was appropriate to add it to the **Data cleaning and validation** section, so I only added it to the accessors list for now. Unfortunately, the "Classes" column was not wide enough--so this patch affects all rows in the table. This shouldn't happen again as the column is now wide enough to accommodate all of the classes that support extension accessors.
https://api.github.com/repos/pandas-dev/pandas/pulls/38593
2020-12-20T20:03:46Z
2020-12-21T16:33:14Z
2020-12-21T16:33:14Z
2020-12-21T16:33:20Z
TST/REF: collect tests by method
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 077c3ebc56ac4..1aa22fd9bda46 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -8,8 +8,6 @@ from pandas import DataFrame, DatetimeIndex, Index, Timestamp, date_range, offsets import pandas._testing as tm -randn = np.random.randn - class TestDatetimeIndex: def test_time_loc(self): # GH8667 @@ -355,10 +353,3 @@ def test_to_frame_datetime_tz(self): result = idx.to_frame() expected = DataFrame(idx, index=idx) tm.assert_frame_equal(result, expected) - - def test_split_non_utc(self): - # GH 14042 - indices = date_range("2016-01-01 00:00:00+0200", freq="S", periods=10) - result = np.split(indices, indices_or_sections=[])[0] - expected = indices._with_freq(None) - tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_npfuncs.py b/pandas/tests/indexes/datetimes/test_npfuncs.py new file mode 100644 index 0000000000000..301466c0da41c --- /dev/null +++ b/pandas/tests/indexes/datetimes/test_npfuncs.py @@ -0,0 +1,13 @@ +import numpy as np + +from pandas import date_range +import pandas._testing as tm + + +class TestSplit: + def test_split_non_utc(self): + # GH#14042 + indices = date_range("2016-01-01 00:00:00+0200", freq="S", periods=10) + result = np.split(indices, indices_or_sections=[])[0] + expected = indices._with_freq(None) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index b4c30cb6d4cd2..2022bca514540 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -26,6 +26,13 @@ class TestSeriesGetitemScalars: + def test_getitem_negative_out_of_bounds(self): + ser = Series(tm.rands_array(5, 10), index=tm.rands_array(10, 10)) + + msg = "index -11 is out of bounds for axis 0 with size 10" + with pytest.raises(IndexError, match=msg): + ser[-11] + def test_getitem_out_of_bounds_indexerror(self, datetime_series): # don't segfault, GH#495 msg = r"index \d+ is out of bounds for axis 0 with size \d+" @@ -186,6 +193,17 @@ def test_getitem_slice_date(self, slc, positions): expected = ser.take(positions) tm.assert_series_equal(result, expected) + def test_getitem_slice_float_raises(self, datetime_series): + msg = ( + "cannot do slice indexing on DatetimeIndex with these indexers " + r"\[{key}\] of type float" + ) + with pytest.raises(TypeError, match=msg.format(key=r"4\.0")): + datetime_series[4.0:10.0] + + with pytest.raises(TypeError, match=msg.format(key=r"4\.5")): + datetime_series[4.5:10.0] + class TestSeriesGetitemListLike: @pytest.mark.parametrize("box", [list, np.array, Index, pd.Series]) @@ -461,3 +479,14 @@ def test_getitem_1tuple_slice_without_multiindex(): result = ser[key] expected = ser[key[0]] tm.assert_series_equal(result, expected) + + +def test_getitem_preserve_name(datetime_series): + result = datetime_series[datetime_series > 0] + assert result.name == datetime_series.name + + result = datetime_series[[0, 2, 4]] + assert result.name == datetime_series.name + + result = datetime_series[5:10] + assert result.name == datetime_series.name diff --git a/pandas/tests/series/indexing/test_numeric.py b/pandas/tests/series/indexing/test_numeric.py index 2ad21d8221e25..4caf6d03d8d80 100644 --- a/pandas/tests/series/indexing/test_numeric.py +++ b/pandas/tests/series/indexing/test_numeric.py @@ -1,5 +1,4 @@ import numpy as np -import pytest from pandas import DataFrame, Index, Series import pandas._testing as tm @@ -30,16 +29,6 @@ def test_slice_float64(): tm.assert_frame_equal(result, expected) -def test_getitem_negative_out_of_bounds(): - s = Series(tm.rands_array(5, 10), index=tm.rands_array(10, 10)) - - msg = "index -11 is out of bounds for axis 0 with size 10" - with pytest.raises(IndexError, match=msg): - s[-11] - with pytest.raises(IndexError, match=msg): - s[-11] = "foo" - - def test_getitem_setitem_slice_bug(): s = Series(range(10), index=list(range(10))) result = s[-12:] @@ -69,20 +58,3 @@ def test_getitem_setitem_slice_integers(): s[:4] = 0 assert (s[:4] == 0).all() assert not (s[4:] == 0).any() - - -def test_slice_float_get_set(datetime_series): - msg = ( - "cannot do slice indexing on DatetimeIndex with these indexers " - r"\[{key}\] of type float" - ) - with pytest.raises(TypeError, match=msg.format(key=r"4\.0")): - datetime_series[4.0:10.0] - - with pytest.raises(TypeError, match=msg.format(key=r"4\.0")): - datetime_series[4.0:10.0] = 0 - - with pytest.raises(TypeError, match=msg.format(key=r"4\.5")): - datetime_series[4.5:10.0] - with pytest.raises(TypeError, match=msg.format(key=r"4\.5")): - datetime_series[4.5:10.0] = 0 diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 119019da529e4..5f09283249fe3 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -12,8 +12,8 @@ date_range, period_range, ) +import pandas._testing as tm from pandas.core.indexing import IndexingError -import pandas.testing as tm from pandas.tseries.offsets import BDay @@ -84,6 +84,28 @@ def test_setitem_na_period_dtype_casts_to_nat(self, na_val): assert ser[4] is NaT +class TestSetitemScalarIndexer: + def test_setitem_negative_out_of_bounds(self): + ser = Series(tm.rands_array(5, 10), index=tm.rands_array(10, 10)) + + msg = "index -11 is out of bounds for axis 0 with size 10" + with pytest.raises(IndexError, match=msg): + ser[-11] = "foo" + + +class TestSetitemSlices: + def test_setitem_slice_float_raises(self, datetime_series): + msg = ( + "cannot do slice indexing on DatetimeIndex with these indexers " + r"\[{key}\] of type float" + ) + with pytest.raises(TypeError, match=msg.format(key=r"4\.0")): + datetime_series[4.0:10.0] = 0 + + with pytest.raises(TypeError, match=msg.format(key=r"4\.5")): + datetime_series[4.5:10.0] = 0 + + class TestSetitemBooleanMask: def test_setitem_boolean(self, string_series): mask = string_series > string_series.median() diff --git a/pandas/tests/series/methods/test_is_unique.py b/pandas/tests/series/methods/test_is_unique.py new file mode 100644 index 0000000000000..c696d365662ea --- /dev/null +++ b/pandas/tests/series/methods/test_is_unique.py @@ -0,0 +1,41 @@ +import numpy as np +import pytest + +from pandas import Series +from pandas.core.construction import create_series_with_explicit_dtype + + +@pytest.mark.parametrize( + "data, expected", + [ + (np.random.randint(0, 10, size=1000), False), + (np.arange(1000), True), + ([], True), + ([np.nan], True), + (["foo", "bar", np.nan], True), + (["foo", "foo", np.nan], False), + (["foo", "bar", np.nan, np.nan], False), + ], +) +def test_is_unique(data, expected): + # GH#11946 / GH#25180 + ser = create_series_with_explicit_dtype(data, dtype_if_empty=object) + assert ser.is_unique is expected + + +def test_is_unique_class_ne(capsys): + # GH#20661 + class Foo: + def __init__(self, val): + self._value = val + + def __ne__(self, other): + raise Exception("NEQ not supported") + + with capsys.disabled(): + li = [Foo(i) for i in range(5)] + ser = Series(li, index=list(range(5))) + + ser.is_unique + captured = capsys.readouterr() + assert len(captured.err) == 0 diff --git a/pandas/tests/series/methods/test_nunique.py b/pandas/tests/series/methods/test_nunique.py new file mode 100644 index 0000000000000..d2d94183aa21b --- /dev/null +++ b/pandas/tests/series/methods/test_nunique.py @@ -0,0 +1,21 @@ +import numpy as np + +from pandas import Categorical, Series + + +def test_nunique(): + # basics.rst doc example + series = Series(np.random.randn(500)) + series[20:500] = np.nan + series[10:20] = 5000 + result = series.nunique() + assert result == 11 + + +def test_nunique_categorical(): + # GH#18051 + ser = Series(Categorical([])) + assert ser.nunique() == 0 + + ser = Series(Categorical([np.nan])) + assert ser.nunique() == 0 diff --git a/pandas/tests/series/methods/test_unique.py b/pandas/tests/series/methods/test_unique.py new file mode 100644 index 0000000000000..b777d9ba1676a --- /dev/null +++ b/pandas/tests/series/methods/test_unique.py @@ -0,0 +1,49 @@ +import numpy as np + +from pandas import Categorical, Series +import pandas._testing as tm + + +class TestUnique: + def test_unique_data_ownership(self): + # it works! GH#1807 + Series(Series(["a", "c", "b"]).unique()).sort_values() + + def test_unique(self): + # GH#714 also, dtype=float + ser = Series([1.2345] * 100) + ser[::2] = np.nan + result = ser.unique() + assert len(result) == 2 + + # explicit f4 dtype + ser = Series([1.2345] * 100, dtype="f4") + ser[::2] = np.nan + result = ser.unique() + assert len(result) == 2 + + def test_unique_nan_object_dtype(self): + # NAs in object arrays GH#714 + ser = Series(["foo"] * 100, dtype="O") + ser[::2] = np.nan + result = ser.unique() + assert len(result) == 2 + + def test_unique_none(self): + # decision about None + ser = Series([1, 2, 3, None, None, None], dtype=object) + result = ser.unique() + expected = np.array([1, 2, 3, None], dtype=object) + tm.assert_numpy_array_equal(result, expected) + + def test_unique_categorical(self): + # GH#18051 + cat = Categorical([]) + ser = Series(cat) + result = ser.unique() + tm.assert_categorical_equal(result, cat) + + cat = Categorical([np.nan]) + ser = Series(cat) + result = ser.unique() + tm.assert_categorical_equal(result, cat) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index ea0e1203e22ed..2f255d92d86e3 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -9,16 +9,6 @@ class TestSeriesMisc: - def test_getitem_preserve_name(self, datetime_series): - result = datetime_series[datetime_series > 0] - assert result.name == datetime_series.name - - result = datetime_series[[0, 2, 4]] - assert result.name == datetime_series.name - - result = datetime_series[5:10] - assert result.name == datetime_series.name - def test_tab_completion(self): # GH 9910 s = Series(list("abcd")) diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index 865ae565b6501..d59f0c05c7462 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -94,21 +94,6 @@ def cmp(a, b): result = ser.astype("object").astype(CategoricalDtype()) tm.assert_series_equal(result, roundtrip_expected) - def test_astype_categorical_invalid_conversions(self): - # invalid conversion (these are NOT a dtype) - cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) - ser = Series(np.random.RandomState(0).randint(0, 10000, 100)).sort_values() - ser = pd.cut(ser, range(0, 10500, 500), right=False, labels=cat) - - msg = ( - "dtype '<class 'pandas.core.arrays.categorical.Categorical'>' " - "not understood" - ) - with pytest.raises(TypeError, match=msg): - ser.astype(Categorical) - with pytest.raises(TypeError, match=msg): - ser.astype("object").astype(Categorical) - def test_series_to_categorical(self): # see gh-16524: test conversion of Series to Categorical series = Series(["a", "b", "c"]) diff --git a/pandas/tests/series/test_duplicates.py b/pandas/tests/series/test_duplicates.py deleted file mode 100644 index 672be981fd7d3..0000000000000 --- a/pandas/tests/series/test_duplicates.py +++ /dev/null @@ -1,97 +0,0 @@ -import numpy as np -import pytest - -from pandas import Categorical, Series -import pandas._testing as tm -from pandas.core.construction import create_series_with_explicit_dtype - - -def test_nunique(): - # basics.rst doc example - series = Series(np.random.randn(500)) - series[20:500] = np.nan - series[10:20] = 5000 - result = series.nunique() - assert result == 11 - - # GH 18051 - s = Series(Categorical([])) - assert s.nunique() == 0 - s = Series(Categorical([np.nan])) - assert s.nunique() == 0 - - -def test_numpy_unique(datetime_series): - # it works! - np.unique(datetime_series) - - -def test_unique(): - # GH714 also, dtype=float - s = Series([1.2345] * 100) - s[::2] = np.nan - result = s.unique() - assert len(result) == 2 - - s = Series([1.2345] * 100, dtype="f4") - s[::2] = np.nan - result = s.unique() - assert len(result) == 2 - - # NAs in object arrays #714 - s = Series(["foo"] * 100, dtype="O") - s[::2] = np.nan - result = s.unique() - assert len(result) == 2 - - # decision about None - s = Series([1, 2, 3, None, None, None], dtype=object) - result = s.unique() - expected = np.array([1, 2, 3, None], dtype=object) - tm.assert_numpy_array_equal(result, expected) - - # GH 18051 - s = Series(Categorical([])) - tm.assert_categorical_equal(s.unique(), Categorical([])) - s = Series(Categorical([np.nan])) - tm.assert_categorical_equal(s.unique(), Categorical([np.nan])) - - -def test_unique_data_ownership(): - # it works! #1807 - Series(Series(["a", "c", "b"]).unique()).sort_values() - - -@pytest.mark.parametrize( - "data, expected", - [ - (np.random.randint(0, 10, size=1000), False), - (np.arange(1000), True), - ([], True), - ([np.nan], True), - (["foo", "bar", np.nan], True), - (["foo", "foo", np.nan], False), - (["foo", "bar", np.nan, np.nan], False), - ], -) -def test_is_unique(data, expected): - # GH11946 / GH25180 - s = create_series_with_explicit_dtype(data, dtype_if_empty=object) - assert s.is_unique is expected - - -def test_is_unique_class_ne(capsys): - # GH 20661 - class Foo: - def __init__(self, val): - self._value = val - - def __ne__(self, other): - raise Exception("NEQ not supported") - - with capsys.disabled(): - li = [Foo(i) for i in range(5)] - s = Series(li, index=list(range(5))) - s.is_unique - captured = capsys.readouterr() - assert len(captured.err) == 0 diff --git a/pandas/tests/series/test_npfuncs.py b/pandas/tests/series/test_npfuncs.py index 645a849015c23..a0b672fffa84a 100644 --- a/pandas/tests/series/test_npfuncs.py +++ b/pandas/tests/series/test_npfuncs.py @@ -14,3 +14,8 @@ def test_ptp(self): arr = np.random.randn(N) ser = Series(arr) assert np.ptp(ser) == np.ptp(arr) + + +def test_numpy_unique(datetime_series): + # it works! + np.unique(datetime_series) diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index bcd6a7a7308a3..271ac31d303ae 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -167,7 +167,7 @@ def test_binary_ufunc_scalar(ufunc, sparse, flip, arrays_for_binary_ufunc): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize("ufunc", [np.divmod]) # any others? +@pytest.mark.parametrize("ufunc", [np.divmod]) # TODO: any others? @pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS) @pytest.mark.parametrize("shuffle", SHUFFLE) @pytest.mark.filterwarnings("ignore:divide by zero:RuntimeWarning")
https://api.github.com/repos/pandas-dev/pandas/pulls/38589
2020-12-20T03:15:04Z
2020-12-21T14:47:07Z
2020-12-21T14:47:06Z
2020-12-21T15:33:29Z
TST: Added tests for ABC classes
diff --git a/pandas/tests/dtypes/test_generic.py b/pandas/tests/dtypes/test_generic.py index 6c38c8ff19c15..1d0c871eaa0a8 100644 --- a/pandas/tests/dtypes/test_generic.py +++ b/pandas/tests/dtypes/test_generic.py @@ -1,6 +1,7 @@ from warnings import catch_warnings import numpy as np +import pytest from pandas.core.dtypes import generic as gt @@ -43,6 +44,66 @@ def test_abc_types(self): assert isinstance(self.timedelta_array, gt.ABCTimedeltaArray) assert not isinstance(self.timedelta_index, gt.ABCTimedeltaArray) + abc_pairs = [ + ("ABCInt64Index", pd.Int64Index([1, 2, 3])), + ("ABCUInt64Index", pd.UInt64Index([1, 2, 3])), + ("ABCFloat64Index", pd.Float64Index([1, 2, 3])), + ("ABCMultiIndex", multi_index), + ("ABCDatetimeIndex", datetime_index), + ("ABCRangeIndex", pd.RangeIndex(3)), + ("ABCTimedeltaIndex", timedelta_index), + ("ABCIntervalIndex", pd.interval_range(start=0, end=3)), + ("ABCPeriodArray", pd.arrays.PeriodArray([2000, 2001, 2002], freq="D")), + ("ABCPandasArray", pd.arrays.PandasArray(np.array([0, 1, 2]))), + ("ABCPeriodIndex", period_index), + ("ABCCategoricalIndex", categorical_df.index), + ("ABCSeries", pd.Series([1, 2, 3])), + ("ABCDataFrame", df), + ("ABCCategorical", categorical), + ("ABCDatetimeArray", datetime_array), + ("ABCTimedeltaArray", timedelta_array), + ] + + @pytest.mark.parametrize("abctype1, inst", abc_pairs) + @pytest.mark.parametrize("abctype2, _", abc_pairs) + def test_abc_pairs(self, abctype1, abctype2, inst, _): + # GH 38588 + if abctype1 == abctype2: + assert isinstance(inst, getattr(gt, abctype2)) + else: + assert not isinstance(inst, getattr(gt, abctype2)) + + abc_subclasses = { + "ABCIndex": [ + abctype + for abctype, _ in abc_pairs + if "Index" in abctype and abctype != "ABCIndex" + ], + "ABCNDFrame": ["ABCSeries", "ABCDataFrame"], + "ABCExtensionArray": [ + "ABCCategorical", + "ABCDatetimeArray", + "ABCPeriodArray", + "ABCTimedeltaArray", + ], + } + + @pytest.mark.parametrize("parent, subs", abc_subclasses.items()) + @pytest.mark.parametrize("abctype, inst", abc_pairs) + def test_abc_hierarchy(self, parent, subs, abctype, inst): + # GH 38588 + if abctype in subs: + assert isinstance(inst, getattr(gt, parent)) + else: + assert not isinstance(inst, getattr(gt, parent)) + + @pytest.mark.parametrize("abctype", [e for e in gt.__dict__ if e.startswith("ABC")]) + def test_abc_coverage(self, abctype): + # GH 38588 + assert ( + abctype in (e for e, _ in self.abc_pairs) or abctype in self.abc_subclasses + ) + def test_setattr_warnings(): # GH7175 - GOTCHA: You can't use dot notation to add a column...
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry `test_abc_types` is a subset of the tests added and can be removed in a followup.
https://api.github.com/repos/pandas-dev/pandas/pulls/38588
2020-12-19T22:28:46Z
2020-12-21T14:43:47Z
2020-12-21T14:43:47Z
2020-12-27T23:59:35Z
ENH: Raise ParserWarning when length of names does not match length of data
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index dd95f9088e3da..21383f8eba712 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -246,6 +246,7 @@ Other enhancements - Improved error message when ``usecols`` and ``names`` do not match for :func:`read_csv` and ``engine="c"`` (:issue:`29042`) - Improved consistency of error messages when passing an invalid ``win_type`` argument in :ref:`Window methods <api.window>` (:issue:`15969`) - :func:`read_sql_query` now accepts a ``dtype`` argument to cast the columnar data from the SQL database based on user input (:issue:`10285`) +- :func:`read_csv` now raising ``ParserWarning`` if length of header or given names does not match length of data when ``usecols`` is not specified (:issue:`21768`) - Improved integer type mapping from pandas to SQLAlchemy when using :meth:`DataFrame.to_sql` (:issue:`35076`) - :func:`to_numeric` now supports downcasting of nullable ``ExtensionDtype`` objects (:issue:`33013`) - Added support for dict-like names in :class:`MultiIndex.set_names` and :class:`MultiIndex.rename` (:issue:`20421`) diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 2a86ff13a2edc..f914e0601fb89 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -23,6 +23,7 @@ from pandas._libs.parsers import STR_NA_VALUES from pandas._libs.tslibs import parsing from pandas._typing import ( + ArrayLike, DtypeArg, FilePathOrBuffer, final, @@ -803,6 +804,29 @@ def _do_date_conversions(self, names, data): return names, data + def _check_data_length(self, columns: list[str], data: list[ArrayLike]) -> None: + """Checks if length of data is equal to length of column names. + + One set of trailing commas is allowed. self.index_col not False + results in a ParserError previously when lengths do not match. + + Parameters + ---------- + columns: list of column names + data: list of array-likes containing the data column-wise. + """ + if not self.index_col and len(columns) != len(data) and columns: + if len(columns) == len(data) - 1 and np.all( + (is_object_dtype(data[-1]) and data[-1] == "") | isna(data[-1]) + ): + return + warnings.warn( + "Length of header or names does not match length of data. This leads " + "to a loss of data with index_col=False.", + ParserWarning, + stacklevel=6, + ) + def _evaluate_usecols(self, usecols, names): """ Check whether or not the 'usecols' parameter diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index 5c1f8f94a72da..110211125514e 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -300,6 +300,8 @@ def read(self, nrows=None): # columns as list alldata = [x[1] for x in data_tups] + if self.usecols is None: + self._check_data_length(names, alldata) data = {k: v for k, (i, v) in zip(names, data_tups)} diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 670868c6f4261..0d41d2972e799 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -292,6 +292,8 @@ def _exclude_implicit_index(self, alldata): offset = len(self.index_col) # type: ignore[has-type] len_alldata = len(alldata) + self._check_data_length(names, alldata) + return { name: alldata[i + offset] for i, name in enumerate(names) if i < len_alldata }, names diff --git a/pandas/tests/io/parser/common/__init__.py b/pandas/tests/io/parser/common/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py index ceb770ce72b78..5b7df02603b74 100644 --- a/pandas/tests/io/parser/common/test_chunksize.py +++ b/pandas/tests/io/parser/common/test_chunksize.py @@ -143,10 +143,7 @@ def test_read_chunksize_jagged_names(all_parsers): parser = all_parsers data = "\n".join(["0"] * 7 + [",".join(["0"] * 10)]) - # error: List item 0 has incompatible type "float"; expected "int" - expected = DataFrame( - [[0] + [np.nan] * 9] * 7 + [[0] * 10] # type: ignore[list-item] - ) + expected = DataFrame([[0] + [np.nan] * 9] * 7 + [[0] * 10]) with parser.read_csv(StringIO(data), names=range(10), chunksize=4) as reader: result = concat(reader) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py index 8fa2d7f7b8d65..a1c76e2740dbe 100644 --- a/pandas/tests/io/parser/common/test_common_basic.py +++ b/pandas/tests/io/parser/common/test_common_basic.py @@ -15,6 +15,7 @@ from pandas.errors import ( EmptyDataError, ParserError, + ParserWarning, ) from pandas import ( @@ -685,7 +686,8 @@ def test_no_header_two_extra_columns(all_parsers): ref = DataFrame([["foo", "bar", "baz"]], columns=column_names) stream = StringIO("foo,bar,baz,bam,blah") parser = all_parsers - df = parser.read_csv(stream, header=None, names=column_names, index_col=False) + with tm.assert_produces_warning(ParserWarning): + df = parser.read_csv(stream, header=None, names=column_names, index_col=False) tm.assert_frame_equal(df, ref) diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py index b86dc5ef85fc6..16649be5b8a58 100644 --- a/pandas/tests/io/parser/usecols/test_usecols_basic.py +++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py @@ -383,7 +383,9 @@ def test_usecols_indices_out_of_bounds(all_parsers, names): a,b 1,2 """ - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning( + FutureWarning, check_stacklevel=False, raise_on_extra_warnings=False + ): result = parser.read_csv(StringIO(data), usecols=[0, 2], names=names, header=0) expected = DataFrame({"a": [1], "b": [None]}) if names is None and parser.engine == "python":
- [x] closes #21768 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry @gfyoung Raising ParserWarning now. Could change to FutureWarning, if we would like to deprecate for 2.0 As long as we are only raising a ParserWarning I am inclined to raise for trailing commas too.
https://api.github.com/repos/pandas-dev/pandas/pulls/38587
2020-12-19T21:24:03Z
2021-06-16T02:14:24Z
2021-06-16T02:14:23Z
2021-06-16T08:45:24Z
TYP: Added cast to ABC EA types
diff --git a/pandas/core/dtypes/generic.py b/pandas/core/dtypes/generic.py index be78ee7e08421..47a6009590d8b 100644 --- a/pandas/core/dtypes/generic.py +++ b/pandas/core/dtypes/generic.py @@ -5,6 +5,7 @@ if TYPE_CHECKING: from pandas import ( + Categorical, CategoricalIndex, DataFrame, DatetimeIndex, @@ -19,6 +20,13 @@ TimedeltaIndex, UInt64Index, ) + from pandas.core.arrays import ( + DatetimeArray, + ExtensionArray, + PandasArray, + PeriodArray, + TimedeltaArray, + ) from pandas.core.generic import NDFrame @@ -111,16 +119,32 @@ def _check(cls, inst) -> bool: "Type[DataFrame]", create_pandas_abc_type("ABCDataFrame", "_typ", ("dataframe",)) ) -ABCCategorical = create_pandas_abc_type("ABCCategorical", "_typ", ("categorical")) -ABCDatetimeArray = create_pandas_abc_type("ABCDatetimeArray", "_typ", ("datetimearray")) -ABCTimedeltaArray = create_pandas_abc_type( - "ABCTimedeltaArray", "_typ", ("timedeltaarray") -) -ABCPeriodArray = create_pandas_abc_type("ABCPeriodArray", "_typ", ("periodarray",)) -ABCExtensionArray = create_pandas_abc_type( - "ABCExtensionArray", - "_typ", - # Note: IntervalArray and SparseArray are included bc they have _typ="extension" - {"extension", "categorical", "periodarray", "datetimearray", "timedeltaarray"}, -) -ABCPandasArray = create_pandas_abc_type("ABCPandasArray", "_typ", ("npy_extension",)) +ABCCategorical = cast( + "Type[Categorical]", + create_pandas_abc_type("ABCCategorical", "_typ", ("categorical")), +) +ABCDatetimeArray = cast( + "Type[DatetimeArray]", + create_pandas_abc_type("ABCDatetimeArray", "_typ", ("datetimearray")), +) +ABCTimedeltaArray = cast( + "Type[TimedeltaArray]", + create_pandas_abc_type("ABCTimedeltaArray", "_typ", ("timedeltaarray")), +) +ABCPeriodArray = cast( + "Type[PeriodArray]", + create_pandas_abc_type("ABCPeriodArray", "_typ", ("periodarray",)), +) +ABCExtensionArray = cast( + "Type[ExtensionArray]", + create_pandas_abc_type( + "ABCExtensionArray", + "_typ", + # Note: IntervalArray and SparseArray are included bc they have _typ="extension" + {"extension", "categorical", "periodarray", "datetimearray", "timedeltaarray"}, + ), +) +ABCPandasArray = cast( + "Type[PandasArray]", + create_pandas_abc_type("ABCPandasArray", "_typ", ("npy_extension",)), +)
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This is the last set of ABCs to cast. Going out with a whimper, mypy didn't identify any new issues.
https://api.github.com/repos/pandas-dev/pandas/pulls/38586
2020-12-19T21:12:24Z
2020-12-21T18:15:40Z
2020-12-21T18:15:40Z
2020-12-27T23:59:27Z
REF: implement construct_2d_arraylike_from_scalar
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 034fd927a8017..e2dee1e0ba524 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1523,6 +1523,28 @@ def find_common_type(types: List[DtypeObj]) -> DtypeObj: return np.find_common_type(types, []) +def construct_2d_arraylike_from_scalar( + value: Scalar, length: int, width: int, dtype: np.dtype, copy: bool +) -> np.ndarray: + + if dtype.kind in ["m", "M"]: + value = maybe_unbox_datetimelike(value, dtype) + + # Attempt to coerce to a numpy array + try: + arr = np.array(value, dtype=dtype, copy=copy) + except (ValueError, TypeError) as err: + raise TypeError( + f"DataFrame constructor called with incompatible data and dtype: {err}" + ) from err + + if arr.ndim != 0: + raise ValueError("DataFrame constructor not properly called!") + + shape = (length, width) + return np.full(shape, arr) + + def construct_1d_arraylike_from_scalar( value: Scalar, length: int, dtype: Optional[DtypeObj] ) -> ArrayLike: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f2e833dfe7790..7ab7942bdf3e6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -85,6 +85,7 @@ from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, + construct_2d_arraylike_from_scalar, find_common_type, infer_dtype_from_scalar, invalidate_string_dtypes, @@ -92,7 +93,6 @@ maybe_convert_platform, maybe_downcast_to_dtype, maybe_infer_to_datetimelike, - maybe_unbox_datetimelike, validate_numeric_casting, ) from pandas.core.dtypes.common import ( @@ -592,6 +592,7 @@ def __init__( # For data is a scalar extension dtype if is_extension_array_dtype(dtype): + # TODO(EA2D): special case not needed with 2D EAs values = [ construct_1d_arraylike_from_scalar(data, len(index), dtype) @@ -599,24 +600,9 @@ def __init__( ] mgr = arrays_to_mgr(values, columns, index, columns, dtype=None) else: - if dtype.kind in ["m", "M"]: - data = maybe_unbox_datetimelike(data, dtype) - - # Attempt to coerce to a numpy array - try: - arr = np.array(data, dtype=dtype, copy=copy) - except (ValueError, TypeError) as err: - exc = TypeError( - "DataFrame constructor called with " - f"incompatible data and dtype: {err}" - ) - raise exc from err - - if arr.ndim != 0: - raise ValueError("DataFrame constructor not properly called!") - - shape = (len(index), len(columns)) - values = np.full(shape, arr) + values = construct_2d_arraylike_from_scalar( + data, len(index), len(columns), dtype, copy + ) mgr = init_ndarray( values, index, columns, dtype=values.dtype, copy=False
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38583
2020-12-19T15:51:13Z
2020-12-21T23:46:19Z
2020-12-21T23:46:19Z
2020-12-22T00:13:10Z
BUG: MultiIndex.dtypes to handle when no level names
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 78e7a8516178a..5312dfe84cfd8 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -707,7 +707,12 @@ def dtypes(self) -> "Series": """ from pandas import Series - return Series({level.name: level.dtype for level in self.levels}) + return Series( + { + f"level_{idx}" if level.name is None else level.name: level.dtype + for idx, level in enumerate(self.levels) + } + ) @property def shape(self) -> Shape: diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 83cebf90623fe..d43ee3330ef08 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -45,6 +45,25 @@ def test_get_dtypes(): tm.assert_series_equal(expected, idx_multitype.dtypes) +def test_get_dtypes_no_level_name(): + # Test MultiIndex.dtypes (# GH38580 ) + idx_multitype = MultiIndex.from_product( + [ + [1, 2, 3], + ["a", "b", "c"], + pd.date_range("20200101", periods=2, tz="UTC"), + ], + ) + expected = pd.Series( + { + "level_0": np.dtype("int64"), + "level_1": np.dtype("O"), + "level_2": DatetimeTZDtype(tz="utc"), + } + ) + tm.assert_series_equal(expected, idx_multitype.dtypes) + + def test_get_level_number_out_of_bounds(multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data
- [X] closes #38580 - [X] tests added / passed - [X] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38582
2020-12-19T14:00:12Z
2020-12-21T14:49:13Z
2020-12-21T14:49:13Z
2020-12-24T18:37:22Z
DOC:fix of DOCUMENTATION
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index e4b19d844dcab..bc7def817c973 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1091,11 +1091,9 @@ cdef class _Timedelta(timedelta): >>> td.isoformat() 'P6DT0H50M3.010010012S' >>> pd.Timedelta(hours=1, seconds=10).isoformat() - 'P0DT0H0M10S' - >>> pd.Timedelta(hours=1, seconds=10).isoformat() - 'P0DT0H0M10S' + 'P0DT1H0M10S' >>> pd.Timedelta(days=500.5).isoformat() - 'P500DT12H0MS' + 'P500DT12H0M0S' """ components = self.components seconds = (f'{components.seconds}.'
- [ ] closes #38311 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ Timedelta.isoformat DOC had duplicates i have deleted one of them. And their was two lines with wrong output that i have also fixed.] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38579
2020-12-19T09:01:08Z
2020-12-19T10:23:41Z
2020-12-19T10:23:41Z
2020-12-19T11:01:16Z
TST/REF: io/parser/(test_dtypes.py, test_usecols.py)
diff --git a/pandas/tests/io/parser/dtypes/test_categorical.py b/pandas/tests/io/parser/dtypes/test_categorical.py new file mode 100644 index 0000000000000..2f569424a82f5 --- /dev/null +++ b/pandas/tests/io/parser/dtypes/test_categorical.py @@ -0,0 +1,294 @@ +""" +Tests dtype specification during parsing +for all of the parsers defined in parsers.py +""" +from io import StringIO +import os + +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import CategoricalDtype + +import pandas as pd +from pandas import Categorical, DataFrame, Timestamp +import pandas._testing as tm + + +@pytest.mark.parametrize( + "dtype", + [ + "category", + CategoricalDtype(), + {"a": "category", "b": "category", "c": CategoricalDtype()}, + ], +) +def test_categorical_dtype(all_parsers, dtype): + # see gh-10153 + parser = all_parsers + data = """a,b,c +1,a,3.4 +1,a,3.4 +2,b,4.5""" + expected = DataFrame( + { + "a": Categorical(["1", "1", "2"]), + "b": Categorical(["a", "a", "b"]), + "c": Categorical(["3.4", "3.4", "4.5"]), + } + ) + actual = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(actual, expected) + + +@pytest.mark.parametrize("dtype", [{"b": "category"}, {1: "category"}]) +def test_categorical_dtype_single(all_parsers, dtype): + # see gh-10153 + parser = all_parsers + data = """a,b,c +1,a,3.4 +1,a,3.4 +2,b,4.5""" + expected = DataFrame( + {"a": [1, 1, 2], "b": Categorical(["a", "a", "b"]), "c": [3.4, 3.4, 4.5]} + ) + actual = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(actual, expected) + + +def test_categorical_dtype_unsorted(all_parsers): + # see gh-10153 + parser = all_parsers + data = """a,b,c +1,b,3.4 +1,b,3.4 +2,a,4.5""" + expected = DataFrame( + { + "a": Categorical(["1", "1", "2"]), + "b": Categorical(["b", "b", "a"]), + "c": Categorical(["3.4", "3.4", "4.5"]), + } + ) + actual = parser.read_csv(StringIO(data), dtype="category") + tm.assert_frame_equal(actual, expected) + + +def test_categorical_dtype_missing(all_parsers): + # see gh-10153 + parser = all_parsers + data = """a,b,c +1,b,3.4 +1,nan,3.4 +2,a,4.5""" + expected = DataFrame( + { + "a": Categorical(["1", "1", "2"]), + "b": Categorical(["b", np.nan, "a"]), + "c": Categorical(["3.4", "3.4", "4.5"]), + } + ) + actual = parser.read_csv(StringIO(data), dtype="category") + tm.assert_frame_equal(actual, expected) + + +@pytest.mark.slow +def test_categorical_dtype_high_cardinality_numeric(all_parsers): + # see gh-18186 + parser = all_parsers + data = np.sort([str(i) for i in range(524289)]) + expected = DataFrame({"a": Categorical(data, ordered=True)}) + + actual = parser.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_utf16(all_parsers, csv_dir_path): + # see gh-10153 + pth = os.path.join(csv_dir_path, "utf16_ex.txt") + parser = all_parsers + encoding = "utf-16" + sep = "\t" + + expected = parser.read_csv(pth, sep=sep, encoding=encoding) + expected = expected.apply(Categorical) + + actual = parser.read_csv(pth, sep=sep, encoding=encoding, dtype="category") + tm.assert_frame_equal(actual, expected) + + +def test_categorical_dtype_chunksize_infer_categories(all_parsers): + # see gh-10153 + parser = all_parsers + data = """a,b +1,a +1,b +1,b +2,c""" + expecteds = [ + DataFrame({"a": [1, 1], "b": Categorical(["a", "b"])}), + DataFrame({"a": [1, 2], "b": Categorical(["b", "c"])}, index=[2, 3]), + ] + with parser.read_csv( + StringIO(data), dtype={"b": "category"}, chunksize=2 + ) as actuals: + for actual, expected in zip(actuals, expecteds): + tm.assert_frame_equal(actual, expected) + + +def test_categorical_dtype_chunksize_explicit_categories(all_parsers): + # see gh-10153 + parser = all_parsers + data = """a,b +1,a +1,b +1,b +2,c""" + cats = ["a", "b", "c"] + expecteds = [ + DataFrame({"a": [1, 1], "b": Categorical(["a", "b"], categories=cats)}), + DataFrame( + {"a": [1, 2], "b": Categorical(["b", "c"], categories=cats)}, + index=[2, 3], + ), + ] + dtype = CategoricalDtype(cats) + with parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) as actuals: + for actual, expected in zip(actuals, expecteds): + tm.assert_frame_equal(actual, expected) + + +def test_categorical_dtype_latin1(all_parsers, csv_dir_path): + # see gh-10153 + pth = os.path.join(csv_dir_path, "unicode_series.csv") + parser = all_parsers + encoding = "latin-1" + + expected = parser.read_csv(pth, header=None, encoding=encoding) + expected[1] = Categorical(expected[1]) + + actual = parser.read_csv(pth, header=None, encoding=encoding, dtype={1: "category"}) + tm.assert_frame_equal(actual, expected) + + +@pytest.mark.parametrize("ordered", [False, True]) +@pytest.mark.parametrize( + "categories", + [["a", "b", "c"], ["a", "c", "b"], ["a", "b", "c", "d"], ["c", "b", "a"]], +) +def test_categorical_category_dtype(all_parsers, categories, ordered): + parser = all_parsers + data = """a,b +1,a +1,b +1,b +2,c""" + expected = DataFrame( + { + "a": [1, 1, 1, 2], + "b": Categorical( + ["a", "b", "b", "c"], categories=categories, ordered=ordered + ), + } + ) + + dtype = {"b": CategoricalDtype(categories=categories, ordered=ordered)} + result = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(result, expected) + + +def test_categorical_category_dtype_unsorted(all_parsers): + parser = all_parsers + data = """a,b +1,a +1,b +1,b +2,c""" + dtype = CategoricalDtype(["c", "b", "a"]) + expected = DataFrame( + { + "a": [1, 1, 1, 2], + "b": Categorical(["a", "b", "b", "c"], categories=["c", "b", "a"]), + } + ) + + result = parser.read_csv(StringIO(data), dtype={"b": dtype}) + tm.assert_frame_equal(result, expected) + + +def test_categorical_coerces_numeric(all_parsers): + parser = all_parsers + dtype = {"b": CategoricalDtype([1, 2, 3])} + + data = "b\n1\n1\n2\n3" + expected = DataFrame({"b": Categorical([1, 1, 2, 3])}) + + result = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(result, expected) + + +def test_categorical_coerces_datetime(all_parsers): + parser = all_parsers + dti = pd.DatetimeIndex(["2017-01-01", "2018-01-01", "2019-01-01"], freq=None) + dtype = {"b": CategoricalDtype(dti)} + + data = "b\n2017-01-01\n2018-01-01\n2019-01-01" + expected = DataFrame({"b": Categorical(dtype["b"].categories)}) + + result = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(result, expected) + + +def test_categorical_coerces_timestamp(all_parsers): + parser = all_parsers + dtype = {"b": CategoricalDtype([Timestamp("2014")])} + + data = "b\n2014-01-01\n2014-01-01T00:00:00" + expected = DataFrame({"b": Categorical([Timestamp("2014")] * 2)}) + + result = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(result, expected) + + +def test_categorical_coerces_timedelta(all_parsers): + parser = all_parsers + dtype = {"b": CategoricalDtype(pd.to_timedelta(["1H", "2H", "3H"]))} + + data = "b\n1H\n2H\n3H" + expected = DataFrame({"b": Categorical(dtype["b"].categories)}) + + result = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data", + [ + "b\nTrue\nFalse\nNA\nFalse", + "b\ntrue\nfalse\nNA\nfalse", + "b\nTRUE\nFALSE\nNA\nFALSE", + "b\nTrue\nFalse\nNA\nFALSE", + ], +) +def test_categorical_dtype_coerces_boolean(all_parsers, data): + # see gh-20498 + parser = all_parsers + dtype = {"b": CategoricalDtype([False, True])} + expected = DataFrame({"b": Categorical([True, False, None, False])}) + + result = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(result, expected) + + +def test_categorical_unexpected_categories(all_parsers): + parser = all_parsers + dtype = {"b": CategoricalDtype(["a", "b", "d", "e"])} + + data = "b\nd\na\nc\nd" # Unexpected c + expected = DataFrame({"b": Categorical(list("dacd"), dtype=dtype["b"])}) + + result = parser.read_csv(StringIO(data), dtype=dtype) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py new file mode 100644 index 0000000000000..e416d8dcdd905 --- /dev/null +++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py @@ -0,0 +1,167 @@ +""" +Tests dtype specification during parsing +for all of the parsers defined in parsers.py +""" +from io import StringIO + +import numpy as np +import pytest + +from pandas.errors import ParserWarning + +import pandas as pd +from pandas import DataFrame +import pandas._testing as tm + + +@pytest.mark.parametrize("dtype", [str, object]) +@pytest.mark.parametrize("check_orig", [True, False]) +def test_dtype_all_columns(all_parsers, dtype, check_orig): + # see gh-3795, gh-6607 + parser = all_parsers + + df = DataFrame( + np.random.rand(5, 2).round(4), + columns=list("AB"), + index=["1A", "1B", "1C", "1D", "1E"], + ) + + with tm.ensure_clean("__passing_str_as_dtype__.csv") as path: + df.to_csv(path) + + result = parser.read_csv(path, dtype=dtype, index_col=0) + + if check_orig: + expected = df.copy() + result = result.astype(float) + else: + expected = df.astype(str) + + tm.assert_frame_equal(result, expected) + + +def test_dtype_per_column(all_parsers): + parser = all_parsers + data = """\ +one,two +1,2.5 +2,3.5 +3,4.5 +4,5.5""" + expected = DataFrame( + [[1, "2.5"], [2, "3.5"], [3, "4.5"], [4, "5.5"]], columns=["one", "two"] + ) + expected["one"] = expected["one"].astype(np.float64) + expected["two"] = expected["two"].astype(object) + + result = parser.read_csv(StringIO(data), dtype={"one": np.float64, 1: str}) + tm.assert_frame_equal(result, expected) + + +def test_invalid_dtype_per_column(all_parsers): + parser = all_parsers + data = """\ +one,two +1,2.5 +2,3.5 +3,4.5 +4,5.5""" + + with pytest.raises(TypeError, match="data type [\"']foo[\"'] not understood"): + parser.read_csv(StringIO(data), dtype={"one": "foo", 1: "int"}) + + +def test_raise_on_passed_int_dtype_with_nas(all_parsers): + # see gh-2631 + parser = all_parsers + data = """YEAR, DOY, a +2001,106380451,10 +2001,,11 +2001,106380451,67""" + + msg = ( + "Integer column has NA values" + if parser.engine == "c" + else "Unable to convert column DOY" + ) + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), dtype={"DOY": np.int64}, skipinitialspace=True) + + +def test_dtype_with_converters(all_parsers): + parser = all_parsers + data = """a,b +1.1,2.2 +1.2,2.3""" + + # Dtype spec ignored if converted specified. + with tm.assert_produces_warning(ParserWarning): + result = parser.read_csv( + StringIO(data), dtype={"a": "i8"}, converters={"a": lambda x: str(x)} + ) + expected = DataFrame({"a": ["1.1", "1.2"], "b": [2.2, 2.3]}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype", list(np.typecodes["AllInteger"] + np.typecodes["Float"]) +) +def test_numeric_dtype(all_parsers, dtype): + data = "0\n1" + parser = all_parsers + expected = DataFrame([0, 1], dtype=dtype) + + result = parser.read_csv(StringIO(data), header=None, dtype=dtype) + tm.assert_frame_equal(expected, result) + + +def test_boolean_dtype(all_parsers): + parser = all_parsers + data = "\n".join( + [ + "a", + "True", + "TRUE", + "true", + "1", + "1.0", + "False", + "FALSE", + "false", + "0", + "0.0", + "NaN", + "nan", + "NA", + "null", + "NULL", + ] + ) + + result = parser.read_csv(StringIO(data), dtype="boolean") + expected = DataFrame( + { + "a": pd.array( + [ + True, + True, + True, + True, + True, + False, + False, + False, + False, + False, + None, + None, + None, + None, + None, + ], + dtype="boolean", + ) + } + ) + + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/dtypes/test_empty.py b/pandas/tests/io/parser/dtypes/test_empty.py new file mode 100644 index 0000000000000..57d729fb4b7fc --- /dev/null +++ b/pandas/tests/io/parser/dtypes/test_empty.py @@ -0,0 +1,172 @@ +""" +Tests dtype specification during parsing +for all of the parsers defined in parsers.py +""" +from io import StringIO + +import numpy as np +import pytest + +from pandas import Categorical, DataFrame, Index, MultiIndex, Series, concat +import pandas._testing as tm + + +def test_dtype_all_columns_empty(all_parsers): + # see gh-12048 + parser = all_parsers + result = parser.read_csv(StringIO("A,B"), dtype=str) + + expected = DataFrame({"A": [], "B": []}, index=[], dtype=str) + tm.assert_frame_equal(result, expected) + + +def test_empty_pass_dtype(all_parsers): + parser = all_parsers + + data = "one,two" + result = parser.read_csv(StringIO(data), dtype={"one": "u1"}) + + expected = DataFrame( + {"one": np.empty(0, dtype="u1"), "two": np.empty(0, dtype=object)}, + index=Index([], dtype=object), + ) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_index_pass_dtype(all_parsers): + parser = all_parsers + + data = "one,two" + result = parser.read_csv( + StringIO(data), index_col=["one"], dtype={"one": "u1", 1: "f"} + ) + + expected = DataFrame( + {"two": np.empty(0, dtype="f")}, index=Index([], dtype="u1", name="one") + ) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_multi_index_pass_dtype(all_parsers): + parser = all_parsers + + data = "one,two,three" + result = parser.read_csv( + StringIO(data), index_col=["one", "two"], dtype={"one": "u1", 1: "f8"} + ) + + exp_idx = MultiIndex.from_arrays( + [np.empty(0, dtype="u1"), np.empty(0, dtype=np.float64)], + names=["one", "two"], + ) + expected = DataFrame({"three": np.empty(0, dtype=object)}, index=exp_idx) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_mangled_column_pass_dtype_by_names(all_parsers): + parser = all_parsers + + data = "one,one" + result = parser.read_csv(StringIO(data), dtype={"one": "u1", "one.1": "f"}) + + expected = DataFrame( + {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, + index=Index([], dtype=object), + ) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_mangled_column_pass_dtype_by_indexes(all_parsers): + parser = all_parsers + + data = "one,one" + result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"}) + + expected = DataFrame( + {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, + index=Index([], dtype=object), + ) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_dup_column_pass_dtype_by_indexes(all_parsers): + # see gh-9424 + parser = all_parsers + expected = concat( + [Series([], name="one", dtype="u1"), Series([], name="one.1", dtype="f")], + axis=1, + ) + expected.index = expected.index.astype(object) + + data = "one,one" + result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"}) + tm.assert_frame_equal(result, expected) + + +def test_empty_with_dup_column_pass_dtype_by_indexes_raises(all_parsers): + # see gh-9424 + parser = all_parsers + expected = concat( + [Series([], name="one", dtype="u1"), Series([], name="one.1", dtype="f")], + axis=1, + ) + expected.index = expected.index.astype(object) + + with pytest.raises(ValueError, match="Duplicate names"): + data = "" + parser.read_csv(StringIO(data), names=["one", "one"], dtype={0: "u1", 1: "f"}) + + +@pytest.mark.parametrize( + "dtype,expected", + [ + (np.float64, DataFrame(columns=["a", "b"], dtype=np.float64)), + ( + "category", + DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[]), + ), + ( + {"a": "category", "b": "category"}, + DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[]), + ), + ("datetime64[ns]", DataFrame(columns=["a", "b"], dtype="datetime64[ns]")), + ( + "timedelta64[ns]", + DataFrame( + { + "a": Series([], dtype="timedelta64[ns]"), + "b": Series([], dtype="timedelta64[ns]"), + }, + index=[], + ), + ), + ( + {"a": np.int64, "b": np.int32}, + DataFrame( + {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, + index=[], + ), + ), + ( + {0: np.int64, 1: np.int32}, + DataFrame( + {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, + index=[], + ), + ), + ( + {"a": np.int64, 1: np.int32}, + DataFrame( + {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, + index=[], + ), + ), + ], +) +def test_empty_dtype(all_parsers, dtype, expected): + # see gh-14712 + parser = all_parsers + data = "a,b" + + result = parser.read_csv(StringIO(data), header=0, dtype=dtype) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py deleted file mode 100644 index 1e68e54b413b0..0000000000000 --- a/pandas/tests/io/parser/test_dtypes.py +++ /dev/null @@ -1,605 +0,0 @@ -""" -Tests dtype specification during parsing -for all of the parsers defined in parsers.py -""" -from io import StringIO -import os - -import numpy as np -import pytest - -from pandas.errors import ParserWarning - -from pandas.core.dtypes.dtypes import CategoricalDtype - -import pandas as pd -from pandas import Categorical, DataFrame, Index, MultiIndex, Series, Timestamp, concat -import pandas._testing as tm - - -@pytest.mark.parametrize("dtype", [str, object]) -@pytest.mark.parametrize("check_orig", [True, False]) -def test_dtype_all_columns(all_parsers, dtype, check_orig): - # see gh-3795, gh-6607 - parser = all_parsers - - df = DataFrame( - np.random.rand(5, 2).round(4), - columns=list("AB"), - index=["1A", "1B", "1C", "1D", "1E"], - ) - - with tm.ensure_clean("__passing_str_as_dtype__.csv") as path: - df.to_csv(path) - - result = parser.read_csv(path, dtype=dtype, index_col=0) - - if check_orig: - expected = df.copy() - result = result.astype(float) - else: - expected = df.astype(str) - - tm.assert_frame_equal(result, expected) - - -def test_dtype_all_columns_empty(all_parsers): - # see gh-12048 - parser = all_parsers - result = parser.read_csv(StringIO("A,B"), dtype=str) - - expected = DataFrame({"A": [], "B": []}, index=[], dtype=str) - tm.assert_frame_equal(result, expected) - - -def test_dtype_per_column(all_parsers): - parser = all_parsers - data = """\ -one,two -1,2.5 -2,3.5 -3,4.5 -4,5.5""" - expected = DataFrame( - [[1, "2.5"], [2, "3.5"], [3, "4.5"], [4, "5.5"]], columns=["one", "two"] - ) - expected["one"] = expected["one"].astype(np.float64) - expected["two"] = expected["two"].astype(object) - - result = parser.read_csv(StringIO(data), dtype={"one": np.float64, 1: str}) - tm.assert_frame_equal(result, expected) - - -def test_invalid_dtype_per_column(all_parsers): - parser = all_parsers - data = """\ -one,two -1,2.5 -2,3.5 -3,4.5 -4,5.5""" - - with pytest.raises(TypeError, match="data type [\"']foo[\"'] not understood"): - parser.read_csv(StringIO(data), dtype={"one": "foo", 1: "int"}) - - -@pytest.mark.parametrize( - "dtype", - [ - "category", - CategoricalDtype(), - {"a": "category", "b": "category", "c": CategoricalDtype()}, - ], -) -def test_categorical_dtype(all_parsers, dtype): - # see gh-10153 - parser = all_parsers - data = """a,b,c -1,a,3.4 -1,a,3.4 -2,b,4.5""" - expected = DataFrame( - { - "a": Categorical(["1", "1", "2"]), - "b": Categorical(["a", "a", "b"]), - "c": Categorical(["3.4", "3.4", "4.5"]), - } - ) - actual = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(actual, expected) - - -@pytest.mark.parametrize("dtype", [{"b": "category"}, {1: "category"}]) -def test_categorical_dtype_single(all_parsers, dtype): - # see gh-10153 - parser = all_parsers - data = """a,b,c -1,a,3.4 -1,a,3.4 -2,b,4.5""" - expected = DataFrame( - {"a": [1, 1, 2], "b": Categorical(["a", "a", "b"]), "c": [3.4, 3.4, 4.5]} - ) - actual = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(actual, expected) - - -def test_categorical_dtype_unsorted(all_parsers): - # see gh-10153 - parser = all_parsers - data = """a,b,c -1,b,3.4 -1,b,3.4 -2,a,4.5""" - expected = DataFrame( - { - "a": Categorical(["1", "1", "2"]), - "b": Categorical(["b", "b", "a"]), - "c": Categorical(["3.4", "3.4", "4.5"]), - } - ) - actual = parser.read_csv(StringIO(data), dtype="category") - tm.assert_frame_equal(actual, expected) - - -def test_categorical_dtype_missing(all_parsers): - # see gh-10153 - parser = all_parsers - data = """a,b,c -1,b,3.4 -1,nan,3.4 -2,a,4.5""" - expected = DataFrame( - { - "a": Categorical(["1", "1", "2"]), - "b": Categorical(["b", np.nan, "a"]), - "c": Categorical(["3.4", "3.4", "4.5"]), - } - ) - actual = parser.read_csv(StringIO(data), dtype="category") - tm.assert_frame_equal(actual, expected) - - -@pytest.mark.slow -def test_categorical_dtype_high_cardinality_numeric(all_parsers): - # see gh-18186 - parser = all_parsers - data = np.sort([str(i) for i in range(524289)]) - expected = DataFrame({"a": Categorical(data, ordered=True)}) - - actual = parser.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_latin1(all_parsers, csv_dir_path): - # see gh-10153 - pth = os.path.join(csv_dir_path, "unicode_series.csv") - parser = all_parsers - encoding = "latin-1" - - expected = parser.read_csv(pth, header=None, encoding=encoding) - expected[1] = Categorical(expected[1]) - - actual = parser.read_csv(pth, header=None, encoding=encoding, dtype={1: "category"}) - tm.assert_frame_equal(actual, expected) - - -def test_categorical_dtype_utf16(all_parsers, csv_dir_path): - # see gh-10153 - pth = os.path.join(csv_dir_path, "utf16_ex.txt") - parser = all_parsers - encoding = "utf-16" - sep = "\t" - - expected = parser.read_csv(pth, sep=sep, encoding=encoding) - expected = expected.apply(Categorical) - - actual = parser.read_csv(pth, sep=sep, encoding=encoding, dtype="category") - tm.assert_frame_equal(actual, expected) - - -def test_categorical_dtype_chunksize_infer_categories(all_parsers): - # see gh-10153 - parser = all_parsers - data = """a,b -1,a -1,b -1,b -2,c""" - expecteds = [ - DataFrame({"a": [1, 1], "b": Categorical(["a", "b"])}), - DataFrame({"a": [1, 2], "b": Categorical(["b", "c"])}, index=[2, 3]), - ] - with parser.read_csv( - StringIO(data), dtype={"b": "category"}, chunksize=2 - ) as actuals: - for actual, expected in zip(actuals, expecteds): - tm.assert_frame_equal(actual, expected) - - -def test_categorical_dtype_chunksize_explicit_categories(all_parsers): - # see gh-10153 - parser = all_parsers - data = """a,b -1,a -1,b -1,b -2,c""" - cats = ["a", "b", "c"] - expecteds = [ - DataFrame({"a": [1, 1], "b": Categorical(["a", "b"], categories=cats)}), - DataFrame( - {"a": [1, 2], "b": Categorical(["b", "c"], categories=cats)}, index=[2, 3] - ), - ] - dtype = CategoricalDtype(cats) - with parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) as actuals: - for actual, expected in zip(actuals, expecteds): - tm.assert_frame_equal(actual, expected) - - -@pytest.mark.parametrize("ordered", [False, True]) -@pytest.mark.parametrize( - "categories", - [["a", "b", "c"], ["a", "c", "b"], ["a", "b", "c", "d"], ["c", "b", "a"]], -) -def test_categorical_category_dtype(all_parsers, categories, ordered): - parser = all_parsers - data = """a,b -1,a -1,b -1,b -2,c""" - expected = DataFrame( - { - "a": [1, 1, 1, 2], - "b": Categorical( - ["a", "b", "b", "c"], categories=categories, ordered=ordered - ), - } - ) - - dtype = {"b": CategoricalDtype(categories=categories, ordered=ordered)} - result = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(result, expected) - - -def test_categorical_category_dtype_unsorted(all_parsers): - parser = all_parsers - data = """a,b -1,a -1,b -1,b -2,c""" - dtype = CategoricalDtype(["c", "b", "a"]) - expected = DataFrame( - { - "a": [1, 1, 1, 2], - "b": Categorical(["a", "b", "b", "c"], categories=["c", "b", "a"]), - } - ) - - result = parser.read_csv(StringIO(data), dtype={"b": dtype}) - tm.assert_frame_equal(result, expected) - - -def test_categorical_coerces_numeric(all_parsers): - parser = all_parsers - dtype = {"b": CategoricalDtype([1, 2, 3])} - - data = "b\n1\n1\n2\n3" - expected = DataFrame({"b": Categorical([1, 1, 2, 3])}) - - result = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(result, expected) - - -def test_categorical_coerces_datetime(all_parsers): - parser = all_parsers - dti = pd.DatetimeIndex(["2017-01-01", "2018-01-01", "2019-01-01"], freq=None) - dtype = {"b": CategoricalDtype(dti)} - - data = "b\n2017-01-01\n2018-01-01\n2019-01-01" - expected = DataFrame({"b": Categorical(dtype["b"].categories)}) - - result = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(result, expected) - - -def test_categorical_coerces_timestamp(all_parsers): - parser = all_parsers - dtype = {"b": CategoricalDtype([Timestamp("2014")])} - - data = "b\n2014-01-01\n2014-01-01T00:00:00" - expected = DataFrame({"b": Categorical([Timestamp("2014")] * 2)}) - - result = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(result, expected) - - -def test_categorical_coerces_timedelta(all_parsers): - parser = all_parsers - dtype = {"b": CategoricalDtype(pd.to_timedelta(["1H", "2H", "3H"]))} - - data = "b\n1H\n2H\n3H" - expected = DataFrame({"b": Categorical(dtype["b"].categories)}) - - result = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "data", - [ - "b\nTrue\nFalse\nNA\nFalse", - "b\ntrue\nfalse\nNA\nfalse", - "b\nTRUE\nFALSE\nNA\nFALSE", - "b\nTrue\nFalse\nNA\nFALSE", - ], -) -def test_categorical_dtype_coerces_boolean(all_parsers, data): - # see gh-20498 - parser = all_parsers - dtype = {"b": CategoricalDtype([False, True])} - expected = DataFrame({"b": Categorical([True, False, None, False])}) - - result = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(result, expected) - - -def test_categorical_unexpected_categories(all_parsers): - parser = all_parsers - dtype = {"b": CategoricalDtype(["a", "b", "d", "e"])} - - data = "b\nd\na\nc\nd" # Unexpected c - expected = DataFrame({"b": Categorical(list("dacd"), dtype=dtype["b"])}) - - result = parser.read_csv(StringIO(data), dtype=dtype) - tm.assert_frame_equal(result, expected) - - -def test_empty_pass_dtype(all_parsers): - parser = all_parsers - - data = "one,two" - result = parser.read_csv(StringIO(data), dtype={"one": "u1"}) - - expected = DataFrame( - {"one": np.empty(0, dtype="u1"), "two": np.empty(0, dtype=object)}, - index=Index([], dtype=object), - ) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_index_pass_dtype(all_parsers): - parser = all_parsers - - data = "one,two" - result = parser.read_csv( - StringIO(data), index_col=["one"], dtype={"one": "u1", 1: "f"} - ) - - expected = DataFrame( - {"two": np.empty(0, dtype="f")}, index=Index([], dtype="u1", name="one") - ) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_multi_index_pass_dtype(all_parsers): - parser = all_parsers - - data = "one,two,three" - result = parser.read_csv( - StringIO(data), index_col=["one", "two"], dtype={"one": "u1", 1: "f8"} - ) - - exp_idx = MultiIndex.from_arrays( - [np.empty(0, dtype="u1"), np.empty(0, dtype=np.float64)], names=["one", "two"] - ) - expected = DataFrame({"three": np.empty(0, dtype=object)}, index=exp_idx) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_mangled_column_pass_dtype_by_names(all_parsers): - parser = all_parsers - - data = "one,one" - result = parser.read_csv(StringIO(data), dtype={"one": "u1", "one.1": "f"}) - - expected = DataFrame( - {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, - index=Index([], dtype=object), - ) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_mangled_column_pass_dtype_by_indexes(all_parsers): - parser = all_parsers - - data = "one,one" - result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"}) - - expected = DataFrame( - {"one": np.empty(0, dtype="u1"), "one.1": np.empty(0, dtype="f")}, - index=Index([], dtype=object), - ) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_dup_column_pass_dtype_by_indexes(all_parsers): - # see gh-9424 - parser = all_parsers - expected = concat( - [Series([], name="one", dtype="u1"), Series([], name="one.1", dtype="f")], - axis=1, - ) - expected.index = expected.index.astype(object) - - data = "one,one" - result = parser.read_csv(StringIO(data), dtype={0: "u1", 1: "f"}) - tm.assert_frame_equal(result, expected) - - -def test_empty_with_dup_column_pass_dtype_by_indexes_raises(all_parsers): - # see gh-9424 - parser = all_parsers - expected = concat( - [Series([], name="one", dtype="u1"), Series([], name="one.1", dtype="f")], - axis=1, - ) - expected.index = expected.index.astype(object) - - with pytest.raises(ValueError, match="Duplicate names"): - data = "" - parser.read_csv(StringIO(data), names=["one", "one"], dtype={0: "u1", 1: "f"}) - - -def test_raise_on_passed_int_dtype_with_nas(all_parsers): - # see gh-2631 - parser = all_parsers - data = """YEAR, DOY, a -2001,106380451,10 -2001,,11 -2001,106380451,67""" - - msg = ( - "Integer column has NA values" - if parser.engine == "c" - else "Unable to convert column DOY" - ) - with pytest.raises(ValueError, match=msg): - parser.read_csv(StringIO(data), dtype={"DOY": np.int64}, skipinitialspace=True) - - -def test_dtype_with_converters(all_parsers): - parser = all_parsers - data = """a,b -1.1,2.2 -1.2,2.3""" - - # Dtype spec ignored if converted specified. - with tm.assert_produces_warning(ParserWarning): - result = parser.read_csv( - StringIO(data), dtype={"a": "i8"}, converters={"a": lambda x: str(x)} - ) - expected = DataFrame({"a": ["1.1", "1.2"], "b": [2.2, 2.3]}) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "dtype,expected", - [ - (np.float64, DataFrame(columns=["a", "b"], dtype=np.float64)), - ("category", DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[])), - ( - {"a": "category", "b": "category"}, - DataFrame({"a": Categorical([]), "b": Categorical([])}, index=[]), - ), - ("datetime64[ns]", DataFrame(columns=["a", "b"], dtype="datetime64[ns]")), - ( - "timedelta64[ns]", - DataFrame( - { - "a": Series([], dtype="timedelta64[ns]"), - "b": Series([], dtype="timedelta64[ns]"), - }, - index=[], - ), - ), - ( - {"a": np.int64, "b": np.int32}, - DataFrame( - {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, - index=[], - ), - ), - ( - {0: np.int64, 1: np.int32}, - DataFrame( - {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, - index=[], - ), - ), - ( - {"a": np.int64, 1: np.int32}, - DataFrame( - {"a": Series([], dtype=np.int64), "b": Series([], dtype=np.int32)}, - index=[], - ), - ), - ], -) -def test_empty_dtype(all_parsers, dtype, expected): - # see gh-14712 - parser = all_parsers - data = "a,b" - - result = parser.read_csv(StringIO(data), header=0, dtype=dtype) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "dtype", list(np.typecodes["AllInteger"] + np.typecodes["Float"]) -) -def test_numeric_dtype(all_parsers, dtype): - data = "0\n1" - parser = all_parsers - expected = DataFrame([0, 1], dtype=dtype) - - result = parser.read_csv(StringIO(data), header=None, dtype=dtype) - tm.assert_frame_equal(expected, result) - - -def test_boolean_dtype(all_parsers): - parser = all_parsers - data = "\n".join( - [ - "a", - "True", - "TRUE", - "true", - "1", - "1.0", - "False", - "FALSE", - "false", - "0", - "0.0", - "NaN", - "nan", - "NA", - "null", - "NULL", - ] - ) - - result = parser.read_csv(StringIO(data), dtype="boolean") - expected = DataFrame( - { - "a": pd.array( - [ - True, - True, - True, - True, - True, - False, - False, - False, - False, - False, - None, - None, - None, - None, - None, - ], - dtype="boolean", - ) - } - ) - - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/usecols/test_parse_dates.py b/pandas/tests/io/parser/usecols/test_parse_dates.py new file mode 100644 index 0000000000000..c6b700c0adfff --- /dev/null +++ b/pandas/tests/io/parser/usecols/test_parse_dates.py @@ -0,0 +1,149 @@ +""" +Tests the usecols functionality during parsing +for all of the parsers defined in parsers.py +""" +from io import StringIO + +import pytest + +from pandas._libs.tslib import Timestamp + +from pandas import DataFrame, Index +import pandas._testing as tm + +_msg_validate_usecols_arg = ( + "'usecols' must either be list-like " + "of all strings, all unicode, all " + "integers or a callable." +) +_msg_validate_usecols_names = ( + "Usecols do not match columns, columns expected but not found: {0}" +) + + +@pytest.mark.parametrize("usecols", [[0, 2, 3], [3, 0, 2]]) +def test_usecols_with_parse_dates(all_parsers, usecols): + # see gh-9755 + data = """a,b,c,d,e +0,1,20140101,0900,4 +0,1,20140102,1000,4""" + parser = all_parsers + parse_dates = [[1, 2]] + + cols = { + "a": [0, 0], + "c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")], + } + expected = DataFrame(cols, columns=["c_d", "a"]) + result = parser.read_csv(StringIO(data), usecols=usecols, parse_dates=parse_dates) + tm.assert_frame_equal(result, expected) + + +def test_usecols_with_parse_dates2(all_parsers): + # see gh-13604 + parser = all_parsers + data = """2008-02-07 09:40,1032.43 +2008-02-07 09:50,1042.54 +2008-02-07 10:00,1051.65""" + + names = ["date", "values"] + usecols = names[:] + parse_dates = [0] + + index = Index( + [ + Timestamp("2008-02-07 09:40"), + Timestamp("2008-02-07 09:50"), + Timestamp("2008-02-07 10:00"), + ], + name="date", + ) + cols = {"values": [1032.43, 1042.54, 1051.65]} + expected = DataFrame(cols, index=index) + + result = parser.read_csv( + StringIO(data), + parse_dates=parse_dates, + index_col=0, + usecols=usecols, + header=None, + names=names, + ) + tm.assert_frame_equal(result, expected) + + +def test_usecols_with_parse_dates3(all_parsers): + # see gh-14792 + parser = all_parsers + data = """a,b,c,d,e,f,g,h,i,j +2016/09/21,1,1,2,3,4,5,6,7,8""" + + usecols = list("abcdefghij") + parse_dates = [0] + + cols = { + "a": Timestamp("2016-09-21"), + "b": [1], + "c": [1], + "d": [2], + "e": [3], + "f": [4], + "g": [5], + "h": [6], + "i": [7], + "j": [8], + } + expected = DataFrame(cols, columns=usecols) + + result = parser.read_csv(StringIO(data), usecols=usecols, parse_dates=parse_dates) + tm.assert_frame_equal(result, expected) + + +def test_usecols_with_parse_dates4(all_parsers): + data = "a,b,c,d,e,f,g,h,i,j\n2016/09/21,1,1,2,3,4,5,6,7,8" + usecols = list("abcdefghij") + parse_dates = [[0, 1]] + parser = all_parsers + + cols = { + "a_b": "2016/09/21 1", + "c": [1], + "d": [2], + "e": [3], + "f": [4], + "g": [5], + "h": [6], + "i": [7], + "j": [8], + } + expected = DataFrame(cols, columns=["a_b"] + list("cdefghij")) + + result = parser.read_csv(StringIO(data), usecols=usecols, parse_dates=parse_dates) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("usecols", [[0, 2, 3], [3, 0, 2]]) +@pytest.mark.parametrize( + "names", + [ + list("abcde"), # Names span all columns in original data. + list("acd"), # Names span only the selected columns. + ], +) +def test_usecols_with_parse_dates_and_names(all_parsers, usecols, names): + # see gh-9755 + s = """0,1,20140101,0900,4 +0,1,20140102,1000,4""" + parse_dates = [[1, 2]] + parser = all_parsers + + cols = { + "a": [0, 0], + "c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")], + } + expected = DataFrame(cols, columns=["c_d", "a"]) + + result = parser.read_csv( + StringIO(s), names=names, parse_dates=parse_dates, usecols=usecols + ) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/usecols/test_strings.py b/pandas/tests/io/parser/usecols/test_strings.py new file mode 100644 index 0000000000000..8cecf1fc981ee --- /dev/null +++ b/pandas/tests/io/parser/usecols/test_strings.py @@ -0,0 +1,97 @@ +""" +Tests the usecols functionality during parsing +for all of the parsers defined in parsers.py +""" +from io import StringIO + +import pytest + +from pandas import DataFrame +import pandas._testing as tm + +_msg_validate_usecols_arg = ( + "'usecols' must either be list-like " + "of all strings, all unicode, all " + "integers or a callable." +) +_msg_validate_usecols_names = ( + "Usecols do not match columns, columns expected but not found: {0}" +) + + +def test_usecols_with_unicode_strings(all_parsers): + # see gh-13219 + data = """AAA,BBB,CCC,DDD +0.056674973,8,True,a +2.613230982,2,False,b +3.568935038,7,False,a""" + parser = all_parsers + + exp_data = { + "AAA": { + 0: 0.056674972999999997, + 1: 2.6132309819999997, + 2: 3.5689350380000002, + }, + "BBB": {0: 8, 1: 2, 2: 7}, + } + expected = DataFrame(exp_data) + + result = parser.read_csv(StringIO(data), usecols=["AAA", "BBB"]) + tm.assert_frame_equal(result, expected) + + +def test_usecols_with_single_byte_unicode_strings(all_parsers): + # see gh-13219 + data = """A,B,C,D +0.056674973,8,True,a +2.613230982,2,False,b +3.568935038,7,False,a""" + parser = all_parsers + + exp_data = { + "A": { + 0: 0.056674972999999997, + 1: 2.6132309819999997, + 2: 3.5689350380000002, + }, + "B": {0: 8, 1: 2, 2: 7}, + } + expected = DataFrame(exp_data) + + result = parser.read_csv(StringIO(data), usecols=["A", "B"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("usecols", [["AAA", b"BBB"], [b"AAA", "BBB"]]) +def test_usecols_with_mixed_encoding_strings(all_parsers, usecols): + data = """AAA,BBB,CCC,DDD +0.056674973,8,True,a +2.613230982,2,False,b +3.568935038,7,False,a""" + parser = all_parsers + + with pytest.raises(ValueError, match=_msg_validate_usecols_arg): + parser.read_csv(StringIO(data), usecols=usecols) + + +@pytest.mark.parametrize("usecols", [["あああ", "いい"], ["あああ", "いい"]]) +def test_usecols_with_multi_byte_characters(all_parsers, usecols): + data = """あああ,いい,ううう,ええええ +0.056674973,8,True,a +2.613230982,2,False,b +3.568935038,7,False,a""" + parser = all_parsers + + exp_data = { + "あああ": { + 0: 0.056674972999999997, + 1: 2.6132309819999997, + 2: 3.5689350380000002, + }, + "いい": {0: 8, 1: 2, 2: 7}, + } + expected = DataFrame(exp_data) + + result = parser.read_csv(StringIO(data), usecols=usecols) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/test_usecols.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py similarity index 66% rename from pandas/tests/io/parser/test_usecols.py rename to pandas/tests/io/parser/usecols/test_usecols_basic.py index 7cdfb7d11ed83..7d81a88e09012 100644 --- a/pandas/tests/io/parser/test_usecols.py +++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py @@ -7,8 +7,6 @@ import numpy as np import pytest -from pandas._libs.tslib import Timestamp - from pandas import DataFrame, Index import pandas._testing as tm @@ -195,7 +193,10 @@ def test_usecols_with_whitespace(all_parsers): # Column selection by index. ([0, 1], DataFrame(data=[[1000, 2000], [4000, 5000]], columns=["2", "0"])), # Column selection by name. - (["0", "1"], DataFrame(data=[[2000, 3000], [5000, 6000]], columns=["0", "1"])), + ( + ["0", "1"], + DataFrame(data=[[2000, 3000], [5000, 6000]], columns=["0", "1"]), + ), ], ) def test_usecols_with_integer_like_header(all_parsers, usecols, expected): @@ -208,200 +209,6 @@ def test_usecols_with_integer_like_header(all_parsers, usecols, expected): tm.assert_frame_equal(result, expected) -@pytest.mark.parametrize("usecols", [[0, 2, 3], [3, 0, 2]]) -def test_usecols_with_parse_dates(all_parsers, usecols): - # see gh-9755 - data = """a,b,c,d,e -0,1,20140101,0900,4 -0,1,20140102,1000,4""" - parser = all_parsers - parse_dates = [[1, 2]] - - cols = { - "a": [0, 0], - "c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")], - } - expected = DataFrame(cols, columns=["c_d", "a"]) - result = parser.read_csv(StringIO(data), usecols=usecols, parse_dates=parse_dates) - tm.assert_frame_equal(result, expected) - - -def test_usecols_with_parse_dates2(all_parsers): - # see gh-13604 - parser = all_parsers - data = """2008-02-07 09:40,1032.43 -2008-02-07 09:50,1042.54 -2008-02-07 10:00,1051.65""" - - names = ["date", "values"] - usecols = names[:] - parse_dates = [0] - - index = Index( - [ - Timestamp("2008-02-07 09:40"), - Timestamp("2008-02-07 09:50"), - Timestamp("2008-02-07 10:00"), - ], - name="date", - ) - cols = {"values": [1032.43, 1042.54, 1051.65]} - expected = DataFrame(cols, index=index) - - result = parser.read_csv( - StringIO(data), - parse_dates=parse_dates, - index_col=0, - usecols=usecols, - header=None, - names=names, - ) - tm.assert_frame_equal(result, expected) - - -def test_usecols_with_parse_dates3(all_parsers): - # see gh-14792 - parser = all_parsers - data = """a,b,c,d,e,f,g,h,i,j -2016/09/21,1,1,2,3,4,5,6,7,8""" - - usecols = list("abcdefghij") - parse_dates = [0] - - cols = { - "a": Timestamp("2016-09-21"), - "b": [1], - "c": [1], - "d": [2], - "e": [3], - "f": [4], - "g": [5], - "h": [6], - "i": [7], - "j": [8], - } - expected = DataFrame(cols, columns=usecols) - - result = parser.read_csv(StringIO(data), usecols=usecols, parse_dates=parse_dates) - tm.assert_frame_equal(result, expected) - - -def test_usecols_with_parse_dates4(all_parsers): - data = "a,b,c,d,e,f,g,h,i,j\n2016/09/21,1,1,2,3,4,5,6,7,8" - usecols = list("abcdefghij") - parse_dates = [[0, 1]] - parser = all_parsers - - cols = { - "a_b": "2016/09/21 1", - "c": [1], - "d": [2], - "e": [3], - "f": [4], - "g": [5], - "h": [6], - "i": [7], - "j": [8], - } - expected = DataFrame(cols, columns=["a_b"] + list("cdefghij")) - - result = parser.read_csv(StringIO(data), usecols=usecols, parse_dates=parse_dates) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("usecols", [[0, 2, 3], [3, 0, 2]]) -@pytest.mark.parametrize( - "names", - [ - list("abcde"), # Names span all columns in original data. - list("acd"), # Names span only the selected columns. - ], -) -def test_usecols_with_parse_dates_and_names(all_parsers, usecols, names): - # see gh-9755 - s = """0,1,20140101,0900,4 -0,1,20140102,1000,4""" - parse_dates = [[1, 2]] - parser = all_parsers - - cols = { - "a": [0, 0], - "c_d": [Timestamp("2014-01-01 09:00:00"), Timestamp("2014-01-02 10:00:00")], - } - expected = DataFrame(cols, columns=["c_d", "a"]) - - result = parser.read_csv( - StringIO(s), names=names, parse_dates=parse_dates, usecols=usecols - ) - tm.assert_frame_equal(result, expected) - - -def test_usecols_with_unicode_strings(all_parsers): - # see gh-13219 - data = """AAA,BBB,CCC,DDD -0.056674973,8,True,a -2.613230982,2,False,b -3.568935038,7,False,a""" - parser = all_parsers - - exp_data = { - "AAA": {0: 0.056674972999999997, 1: 2.6132309819999997, 2: 3.5689350380000002}, - "BBB": {0: 8, 1: 2, 2: 7}, - } - expected = DataFrame(exp_data) - - result = parser.read_csv(StringIO(data), usecols=["AAA", "BBB"]) - tm.assert_frame_equal(result, expected) - - -def test_usecols_with_single_byte_unicode_strings(all_parsers): - # see gh-13219 - data = """A,B,C,D -0.056674973,8,True,a -2.613230982,2,False,b -3.568935038,7,False,a""" - parser = all_parsers - - exp_data = { - "A": {0: 0.056674972999999997, 1: 2.6132309819999997, 2: 3.5689350380000002}, - "B": {0: 8, 1: 2, 2: 7}, - } - expected = DataFrame(exp_data) - - result = parser.read_csv(StringIO(data), usecols=["A", "B"]) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("usecols", [["AAA", b"BBB"], [b"AAA", "BBB"]]) -def test_usecols_with_mixed_encoding_strings(all_parsers, usecols): - data = """AAA,BBB,CCC,DDD -0.056674973,8,True,a -2.613230982,2,False,b -3.568935038,7,False,a""" - parser = all_parsers - - with pytest.raises(ValueError, match=_msg_validate_usecols_arg): - parser.read_csv(StringIO(data), usecols=usecols) - - -@pytest.mark.parametrize("usecols", [["あああ", "いい"], ["あああ", "いい"]]) -def test_usecols_with_multi_byte_characters(all_parsers, usecols): - data = """あああ,いい,ううう,ええええ -0.056674973,8,True,a -2.613230982,2,False,b -3.568935038,7,False,a""" - parser = all_parsers - - exp_data = { - "あああ": {0: 0.056674972999999997, 1: 2.6132309819999997, 2: 3.5689350380000002}, - "いい": {0: 8, 1: 2, 2: 7}, - } - expected = DataFrame(exp_data) - - result = parser.read_csv(StringIO(data), usecols=usecols) - tm.assert_frame_equal(result, expected) - - def test_empty_usecols(all_parsers): data = "a,b,c\n1,2,3\n4,5,6" expected = DataFrame()
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry #38370 adds a pyarrow engine to the csv reader. Only a fraction of the io/parser tests pass when pyarrow is used and the rest has to be xfailed/skipped, resulting in a large diff on the PR. xref https://github.com/pandas-dev/pandas/pull/38370#discussion_r539579072 suggests reorganizing the tests into classes so groups of tests can be xfailed with a single mark. I'm grouping the tests logically (not based on whether or not they pass with pyarrow) but merging this this _will_ reduce the diff in #38370 substantively. Likely I will submit a follow-on with some further reorg. I'm happy to push that to this PR if that's preferred, though. Verifying that total number of tests is unchanged: ``` (pandas-dev) andrewwieteska@Andrews-MacBook-Pro pandas % pytest pandas/tests/io/parser/test_dtypes.py pandas/tests/io/parser/test_usecols.py ========================================================================= test session starts ========================================================================= platform darwin -- Python 3.8.6, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: /Users/andrewwieteska/repos/pandas, configfile: setup.cfg plugins: forked-1.2.0, xdist-2.1.0, cov-2.10.1, asyncio-0.14.0, hypothesis-5.41.2, instafail-0.4.1 collected 372 items pandas/tests/io/parser/test_dtypes.py ......................................................................................................................... [ 32%] ............................................................................................ [ 57%] pandas/tests/io/parser/test_usecols.py ........................................................................................................................ [ 89%] ....................................... [100%] ======================================================================== 372 passed in 32.49s ========================================================================= ``` versus on master: ``` (pandas-dev) andrewwieteska@Andrews-MacBook-Pro pandas % pytest pandas/tests/io/parser/test_dtypes.py pandas/tests/io/parser/test_usecols.py ========================================================================= test session starts ========================================================================= platform darwin -- Python 3.8.6, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: /Users/andrewwieteska/repos/pandas, configfile: setup.cfg plugins: forked-1.2.0, xdist-2.1.0, cov-2.10.1, asyncio-0.14.0, hypothesis-5.41.2, instafail-0.4.1 collected 372 items pandas/tests/io/parser/test_dtypes.py ......................................................................................................................... [ 32%] ............................................................................................ [ 57%] pandas/tests/io/parser/test_usecols.py ........................................................................................................................ [ 89%] ....................................... [100%] ======================================================================== 372 passed in 32.90s ========================================================================= ```
https://api.github.com/repos/pandas-dev/pandas/pulls/38578
2020-12-19T08:08:08Z
2020-12-31T22:13:39Z
2020-12-31T22:13:39Z
2020-12-31T22:13:44Z
TST: Bare pytest raises
diff --git a/pandas/tests/arrays/boolean/test_arithmetic.py b/pandas/tests/arrays/boolean/test_arithmetic.py index 01de64568a011..72b378f75c936 100644 --- a/pandas/tests/arrays/boolean/test_arithmetic.py +++ b/pandas/tests/arrays/boolean/test_arithmetic.py @@ -46,7 +46,7 @@ def test_add_mul(left_array, right_array, opname, exp): def test_sub(left_array, right_array): - with pytest.raises(TypeError): + with tm.external_error_raised(TypeError): # numpy points to ^ operator or logical_xor function instead left_array - right_array @@ -92,13 +92,29 @@ def test_error_invalid_values(data, all_arithmetic_operators): ops = getattr(s, op) # invalid scalars - with pytest.raises(TypeError): + msg = ( + "ufunc '\\w+' did not contain a loop with signature matching types|" + "ufunc '\\w+' not supported for the input types, and the inputs could " + "not be safely coerced to any supported types|" + "\\w+ cannot perform the operation \\w+" + ) + with pytest.raises(TypeError, match=msg): ops("foo") - with pytest.raises(TypeError): + + msg = ( + "unsupported operand type\\(s\\) for|" + "Concatenation operation is not implemented for NumPy arrays" + ) + with pytest.raises(TypeError, match=msg): ops(pd.Timestamp("20180101")) # invalid array-likes if op not in ("__mul__", "__rmul__"): # TODO(extension) numpy's mul with object array sees booleans as numbers - with pytest.raises(TypeError): + msg = ( + "unsupported operand type\\(s\\) for|" + 'can only concatenate str \\(not "bool"\\) to str|' + "not all arguments converted during string formatting" + ) + with pytest.raises(TypeError, match=msg): ops(pd.Series("foo", index=s.index)) diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index c93603398977e..6e65418bde58d 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -30,7 +30,17 @@ def _check_op(self, s, op, other, op_name, exc=NotImplementedError): expected = s.combine(other, op) self.assert_series_equal(result, expected) else: - with pytest.raises(exc): + msg = ( + "unsupported operand type\\(s\\) for|" + "cannot perform [\\w_]+ with this index type: [\\w_]+|" + "Object with dtype category cannot perform the numpy op [\\w_]+|" + "cannot add [\\w_]+ and [\\w_]+|" + "can't multiply sequence by non-int of type '[\\w_]+'|" + 'can only concatenate str \\(not "[\\w_]+"\\) to str|' + "Object with dtype category cannot perform the numpy op [\\w_]+|" + "Concatenation operation is not implemented for NumPy arrays" + ) + with pytest.raises(exc, match=msg): op(s, other) def _check_divmod_op(self, s, op, other, exc=Exception): @@ -44,7 +54,12 @@ def _check_divmod_op(self, s, op, other, exc=Exception): self.assert_series_equal(result_div, expected_div) self.assert_series_equal(result_mod, expected_mod) else: - with pytest.raises(exc): + msg = ( + "'tuple' object has no attribute 'dtype'|" + "cannot perform __r?divmod__ with this index type|" + "unsupported operand type\\(s\\) for divmod\\(\\)" + ) + with pytest.raises(exc, match=msg): divmod(s, other) @@ -111,7 +126,8 @@ def test_add_series_with_extension_array(self, data): def test_error(self, data, all_arithmetic_operators): # invalid ops op_name = all_arithmetic_operators - with pytest.raises(AttributeError): + msg = "'[\\w_]+' object has no attribute '[\\w_]+'" + with pytest.raises(AttributeError, match=msg): getattr(data, op_name) @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) @@ -145,7 +161,8 @@ def _compare_other(self, s, data, op_name, other): # series s = pd.Series(data) - with pytest.raises(TypeError): + msg = "not supported between instances of '[\\w._]+' and '[\\w._]+'" + with pytest.raises(TypeError, match=msg): op(s, other) def test_compare_scalar(self, data, all_compare_operators): diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index a4e6fc0f78cbb..e77d2b2633e88 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -282,8 +282,25 @@ def test_setitem_loc_iloc_slice(self, data): self.assert_equal(result, expected) def test_setitem_slice_mismatch_length_raises(self, data): + # This class is a test mixin class, based on which test class it's mixed + # with the expected error messages can vary. This regular expression + # catches all the variants of those messages. It's formatted as a big OR + # statement: /m1|m2|m3|m4/ + + msg = ( + # pandas.core.arrays.period.PeriodArray + # pandas.core.arrays.datetimes.DatetimeArray + "cannot set using a slice indexer with a different length than the value|" + # string_arrow.ArrowStringArray + "Length of indexer and values mismatch|" + # pandas.tests.extension.decimal.array.DecimalArray + "cannot copy sequence with size \\d to array axis with dimension \\d|" + # All the rest + "could not broadcast input array from " + "shape \\(\\d,?\\) into shape \\(\\d,?\\)" + ) arr = data[:5] - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): arr[:1] = arr[:2] def test_setitem_slice_array(self, data): @@ -292,8 +309,17 @@ def test_setitem_slice_array(self, data): self.assert_extension_array_equal(arr, data[-5:]) def test_setitem_scalar_key_sequence_raise(self, data): + # Check the comment on test_setitem_slice_mismatch_length_raises for more info. + msg = ( + # pandas.core.arrays.string_arrow.ArrowStringArray + "Must pass scalars with scalar indexer|" + # pandas.core.arrays.datetimes.DatetimeArray + "Could not convert object to NumPy datetime|" + # All the rest + "setting an array element with a sequence" + ) arr = data[:5].copy() - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): arr[0] = arr[[0, 1]] def test_setitem_preserves_views(self, data): diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py index ae4523014b01d..6bf461d849b5e 100644 --- a/pandas/tests/util/test_assert_series_equal.py +++ b/pandas/tests/util/test_assert_series_equal.py @@ -292,9 +292,22 @@ def test_series_equal_exact_for_nonnumeric(): tm.assert_series_equal(s1, s2, check_exact=True) tm.assert_series_equal(s2, s1, check_exact=True) - with pytest.raises(AssertionError): + msg = """Series are different + +Series values are different \\(100\\.0 %\\) +\\[index\\]: \\[0, 1\\] +\\[left\\]: \\[a, b\\] +\\[right\\]: \\[b, a\\]""" + with pytest.raises(AssertionError, match=msg): tm.assert_series_equal(s1, s3, check_exact=True) - with pytest.raises(AssertionError): + + msg = """Series are different + +Series values are different \\(100\\.0 %\\) +\\[index\\]: \\[0, 1\\] +\\[left\\]: \\[b, a\\] +\\[right\\]: \\[a, b\\]""" + with pytest.raises(AssertionError, match=msg): tm.assert_series_equal(s3, s1, check_exact=True)
- xref #30999 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry [N/A]
https://api.github.com/repos/pandas-dev/pandas/pulls/38576
2020-12-19T05:01:24Z
2020-12-20T21:37:33Z
2020-12-20T21:37:33Z
2020-12-30T08:23:49Z
BUG: construction from dt64/td64 values with td64/dt64 dtype
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 64b9a11b1980d..7c4db6865135a 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -180,7 +180,7 @@ Datetimelike ^^^^^^^^^^^^ - Bug in :class:`DataFrame` and :class:`Series` constructors sometimes dropping nanoseconds from :class:`Timestamp` (resp. :class:`Timedelta`) ``data``, with ``dtype=datetime64[ns]`` (resp. ``timedelta64[ns]``) (:issue:`38032`) - Bug in :meth:`DataFrame.first` and :meth:`Series.first` returning two months for offset one month when first day is last calendar day (:issue:`29623`) -- +- Bug in constructing a :class:`DataFrame` or :class:`Series` with mismatched ``datetime64`` data and ``timedelta64`` dtype, or vice-versa, failing to raise ``TypeError`` (:issue:`38575`) Timedelta ^^^^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index d1c16de05ce55..80a1617e0b735 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -164,6 +164,14 @@ def maybe_unbox_datetimelike(value: Scalar, dtype: DtypeObj) -> Scalar: value = value.to_datetime64() elif isinstance(value, Timedelta): value = value.to_timedelta64() + + if (isinstance(value, np.timedelta64) and dtype.kind == "M") or ( + isinstance(value, np.datetime64) and dtype.kind == "m" + ): + # numpy allows np.array(dt64values, dtype="timedelta64[ns]") and + # vice-versa, but we do not want to allow this, so we need to + # check explicitly + raise TypeError(f"Cannot cast {repr(value)} to {dtype}") return value diff --git a/pandas/tests/dtypes/cast/test_construct_from_scalar.py b/pandas/tests/dtypes/cast/test_construct_from_scalar.py index a6f97563311a7..4ff3375d1988d 100644 --- a/pandas/tests/dtypes/cast/test_construct_from_scalar.py +++ b/pandas/tests/dtypes/cast/test_construct_from_scalar.py @@ -1,4 +1,5 @@ import numpy as np +import pytest from pandas.core.dtypes.cast import construct_1d_arraylike_from_scalar from pandas.core.dtypes.dtypes import CategoricalDtype @@ -32,3 +33,20 @@ def test_cast_1d_array_like_from_timedelta(): td = Timedelta(1) res = construct_1d_arraylike_from_scalar(td, 2, np.dtype("m8[ns]")) assert res[0] == td + + +def test_cast_1d_array_like_mismatched_datetimelike(): + td = np.timedelta64("NaT", "ns") + dt = np.datetime64("NaT", "ns") + + with pytest.raises(TypeError, match="Cannot cast"): + construct_1d_arraylike_from_scalar(td, 2, dt.dtype) + + with pytest.raises(TypeError, match="Cannot cast"): + construct_1d_arraylike_from_scalar(np.timedelta64(4, "ns"), 2, dt.dtype) + + with pytest.raises(TypeError, match="Cannot cast"): + construct_1d_arraylike_from_scalar(dt, 2, td.dtype) + + with pytest.raises(TypeError, match="Cannot cast"): + construct_1d_arraylike_from_scalar(np.datetime64(4, "ns"), 2, td.dtype) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 3d4fbc74d0e6a..5ba38016ee552 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2962,3 +2962,15 @@ def test_from_timedelta64_scalar_object(self, constructor, request): obj = constructor(td64, dtype=object) assert isinstance(get1(obj), np.timedelta64) + + @pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64]) + def test_from_scalar_datetimelike_mismatched(self, constructor, cls): + scalar = cls("NaT", "ns") + dtype = {np.datetime64: "m8[ns]", np.timedelta64: "M8[ns]"}[cls] + + with pytest.raises(TypeError, match="Cannot cast"): + constructor(scalar, dtype=dtype) + + scalar = cls(4, "ns") + with pytest.raises(TypeError, match="Cannot cast"): + constructor(scalar, dtype=dtype)
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38575
2020-12-19T04:54:05Z
2020-12-23T20:36:28Z
2020-12-23T20:36:28Z
2020-12-23T20:38:53Z
TST: fix some mpl warnings
diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index a1c62f9fce23c..f519d1e96f5b0 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -144,7 +144,9 @@ def normalize(series): df = frame.drop(class_column, axis=1).apply(normalize) if ax is None: - ax = plt.gca(xlim=[-1, 1], ylim=[-1, 1]) + ax = plt.gca() + ax.set_xlim(-1, 1) + ax.set_ylim(-1, 1) to_plot: Dict[Label, List[List]] = {} colors = get_standard_colors( @@ -260,7 +262,8 @@ def f(t): ) colors = dict(zip(classes, color_values)) if ax is None: - ax = plt.gca(xlim=(-np.pi, np.pi)) + ax = plt.gca() + ax.set_xlim(-np.pi, np.pi) for i in range(n): row = df.iloc[i].values f = function(row) @@ -440,7 +443,9 @@ def autocorrelation_plot( n = len(series) data = np.asarray(series) if ax is None: - ax = plt.gca(xlim=(1, n), ylim=(-1.0, 1.0)) + ax = plt.gca() + ax.set_xlim(1, n) + ax.set_ylim(-1.0, 1.0) mean = np.mean(data) c0 = np.sum((data - mean) ** 2) / float(n) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 1208100ed2dce..ba774e8d13cf1 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -71,10 +71,12 @@ def setup_method(self, method): def test_autocorrelation_plot(self): from pandas.plotting import autocorrelation_plot - _check_plot_works(autocorrelation_plot, series=self.ts) - _check_plot_works(autocorrelation_plot, series=self.ts.values) + # Ensure no UserWarning when making plot + with tm.assert_produces_warning(None): + _check_plot_works(autocorrelation_plot, series=self.ts) + _check_plot_works(autocorrelation_plot, series=self.ts.values) - ax = autocorrelation_plot(self.ts, label="Test") + ax = autocorrelation_plot(self.ts, label="Test") self._check_legend_labels(ax, labels=["Test"]) def test_lag_plot(self): @@ -132,8 +134,9 @@ def test_andrews_curves(self, iris): from pandas.plotting import andrews_curves df = iris - - _check_plot_works(andrews_curves, frame=df, class_column="Name") + # Ensure no UserWarning when making plot + with tm.assert_produces_warning(None): + _check_plot_works(andrews_curves, frame=df, class_column="Name") rgba = ("#556270", "#4ECDC4", "#C7F464") ax = _check_plot_works( @@ -280,7 +283,9 @@ def test_radviz(self, iris): from pandas.plotting import radviz df = iris - _check_plot_works(radviz, frame=df, class_column="Name") + # Ensure no UserWarning when making plot + with tm.assert_produces_warning(None): + _check_plot_works(radviz, frame=df, class_column="Name") rgba = ("#556270", "#4ECDC4", "#C7F464") ax = _check_plot_works(radviz, frame=df, class_column="Name", color=rgba)
- [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` This change fixes `UserWarning` being emitted in tests calling `autocorrelation_plot`, `andrews_curves`, and `radviz`. `UserWarning` was caused by calling `plt.gca(xlim=..., ylim=...)` on a potentially already existing axis, so `matplotlib` warns about this forcing new axis creation. Solution was just to explicitly use `set_xlim` and `set_ylim` instead. Does it make sense to also add to the relevant tests an assertion that no UserWarning is emitted to guarantee the new behavior?
https://api.github.com/repos/pandas-dev/pandas/pulls/38574
2020-12-19T04:17:35Z
2020-12-22T22:23:51Z
2020-12-22T22:23:51Z
2021-04-06T13:13:53Z
TST/REF: collect datetimelike factorize tests
diff --git a/pandas/tests/indexes/datetimes/methods/test_factorize.py b/pandas/tests/indexes/datetimes/methods/test_factorize.py new file mode 100644 index 0000000000000..6e095e29e47cd --- /dev/null +++ b/pandas/tests/indexes/datetimes/methods/test_factorize.py @@ -0,0 +1,102 @@ +import numpy as np + +from pandas import DatetimeIndex, Index, date_range, factorize +import pandas._testing as tm + + +class TestDatetimeIndexFactorize: + def test_factorize(self): + idx1 = DatetimeIndex( + ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"] + ) + + exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) + exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"]) + + arr, idx = idx1.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + arr, idx = idx1.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + # tz must be preserved + idx1 = idx1.tz_localize("Asia/Tokyo") + exp_idx = exp_idx.tz_localize("Asia/Tokyo") + + arr, idx = idx1.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + idx2 = DatetimeIndex( + ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"] + ) + + exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp) + exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"]) + arr, idx = idx2.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp) + exp_idx = DatetimeIndex(["2014-03", "2014-02", "2014-01"]) + arr, idx = idx2.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + def test_factorize_preserves_freq(self): + # GH#38120 freq should be preserved + idx3 = date_range("2000-01", periods=4, freq="M", tz="Asia/Tokyo") + exp_arr = np.array([0, 1, 2, 3], dtype=np.intp) + + arr, idx = idx3.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq + + arr, idx = factorize(idx3) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq + + def test_factorize_tz(self, tz_naive_fixture, index_or_series): + tz = tz_naive_fixture + # GH#13750 + base = date_range("2016-11-05", freq="H", periods=100, tz=tz) + idx = base.repeat(5) + + exp_arr = np.arange(100, dtype=np.intp).repeat(5) + + obj = index_or_series(idx) + + arr, res = obj.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + expected = base._with_freq(None) + tm.assert_index_equal(res, expected) + assert res.freq == expected.freq + + def test_factorize_dst(self, index_or_series): + # GH#13750 + idx = date_range("2016-11-06", freq="H", periods=12, tz="US/Eastern") + obj = index_or_series(idx) + + arr, res = obj.factorize() + tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp)) + tm.assert_index_equal(res, idx) + if index_or_series is Index: + assert res.freq == idx.freq + + idx = date_range("2016-06-13", freq="H", periods=12, tz="US/Eastern") + obj = index_or_series(idx) + + arr, res = obj.factorize() + tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp)) + tm.assert_index_equal(res, idx) + if index_or_series is Index: + assert res.freq == idx.freq diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 077c3ebc56ac4..c4684e857f706 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -200,102 +200,6 @@ def test_ns_index(self): new_index = date_range(start=index[0], end=index[-1], freq=index.freq) self.assert_index_parameters(new_index) - def test_factorize(self): - idx1 = DatetimeIndex( - ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"] - ) - - exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) - exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"]) - - arr, idx = idx1.factorize() - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, exp_idx) - assert idx.freq == exp_idx.freq - - arr, idx = idx1.factorize(sort=True) - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, exp_idx) - assert idx.freq == exp_idx.freq - - # tz must be preserved - idx1 = idx1.tz_localize("Asia/Tokyo") - exp_idx = exp_idx.tz_localize("Asia/Tokyo") - - arr, idx = idx1.factorize() - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, exp_idx) - assert idx.freq == exp_idx.freq - - idx2 = DatetimeIndex( - ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"] - ) - - exp_arr = np.array([2, 2, 1, 0, 2, 0], dtype=np.intp) - exp_idx = DatetimeIndex(["2014-01", "2014-02", "2014-03"]) - arr, idx = idx2.factorize(sort=True) - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, exp_idx) - assert idx.freq == exp_idx.freq - - exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp) - exp_idx = DatetimeIndex(["2014-03", "2014-02", "2014-01"]) - arr, idx = idx2.factorize() - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, exp_idx) - assert idx.freq == exp_idx.freq - - def test_factorize_preserves_freq(self): - # GH#38120 freq should be preserved - idx3 = date_range("2000-01", periods=4, freq="M", tz="Asia/Tokyo") - exp_arr = np.array([0, 1, 2, 3], dtype=np.intp) - - arr, idx = idx3.factorize() - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, idx3) - assert idx.freq == idx3.freq - - arr, idx = pd.factorize(idx3) - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, idx3) - assert idx.freq == idx3.freq - - def test_factorize_tz(self, tz_naive_fixture, index_or_series): - tz = tz_naive_fixture - # GH#13750 - base = date_range("2016-11-05", freq="H", periods=100, tz=tz) - idx = base.repeat(5) - - exp_arr = np.arange(100, dtype=np.intp).repeat(5) - - obj = index_or_series(idx) - - arr, res = obj.factorize() - tm.assert_numpy_array_equal(arr, exp_arr) - expected = base._with_freq(None) - tm.assert_index_equal(res, expected) - assert res.freq == expected.freq - - def test_factorize_dst(self, index_or_series): - # GH 13750 - idx = date_range("2016-11-06", freq="H", periods=12, tz="US/Eastern") - obj = index_or_series(idx) - - arr, res = obj.factorize() - tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp)) - tm.assert_index_equal(res, idx) - if index_or_series is Index: - assert res.freq == idx.freq - - idx = date_range("2016-06-13", freq="H", periods=12, tz="US/Eastern") - obj = index_or_series(idx) - - arr, res = obj.factorize() - tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp)) - tm.assert_index_equal(res, idx) - if index_or_series is Index: - assert res.freq == idx.freq - @pytest.mark.parametrize( "arr, expected", [ diff --git a/pandas/tests/indexes/period/test_factorize.py b/pandas/tests/indexes/period/methods/test_factorize.py similarity index 100% rename from pandas/tests/indexes/period/test_factorize.py rename to pandas/tests/indexes/period/methods/test_factorize.py diff --git a/pandas/tests/indexes/timedeltas/methods/test_factorize.py b/pandas/tests/indexes/timedeltas/methods/test_factorize.py new file mode 100644 index 0000000000000..dcf8cefba70fd --- /dev/null +++ b/pandas/tests/indexes/timedeltas/methods/test_factorize.py @@ -0,0 +1,36 @@ +import numpy as np + +from pandas import TimedeltaIndex, factorize, timedelta_range +import pandas._testing as tm + + +class TestTimedeltaIndexFactorize: + def test_factorize(self): + idx1 = TimedeltaIndex(["1 day", "1 day", "2 day", "2 day", "3 day", "3 day"]) + + exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) + exp_idx = TimedeltaIndex(["1 day", "2 day", "3 day"]) + + arr, idx = idx1.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + arr, idx = idx1.factorize(sort=True) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, exp_idx) + assert idx.freq == exp_idx.freq + + def test_factorize_preserves_freq(self): + # GH#38120 freq should be preserved + idx3 = timedelta_range("1 day", periods=4, freq="s") + exp_arr = np.array([0, 1, 2, 3], dtype=np.intp) + arr, idx = idx3.factorize() + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq + + arr, idx = factorize(idx3) + tm.assert_numpy_array_equal(arr, exp_arr) + tm.assert_index_equal(idx, idx3) + assert idx.freq == idx3.freq diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 9c9fa08dd2852..a86cd8dd11c59 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -65,36 +65,6 @@ def test_isin(self): index.isin([index[2], 5]), np.array([False, False, True, False]) ) - def test_factorize(self): - idx1 = TimedeltaIndex(["1 day", "1 day", "2 day", "2 day", "3 day", "3 day"]) - - exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) - exp_idx = TimedeltaIndex(["1 day", "2 day", "3 day"]) - - arr, idx = idx1.factorize() - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, exp_idx) - assert idx.freq == exp_idx.freq - - arr, idx = idx1.factorize(sort=True) - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, exp_idx) - assert idx.freq == exp_idx.freq - - def test_factorize_preserves_freq(self): - # GH#38120 freq should be preserved - idx3 = timedelta_range("1 day", periods=4, freq="s") - exp_arr = np.array([0, 1, 2, 3], dtype=np.intp) - arr, idx = idx3.factorize() - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, idx3) - assert idx.freq == idx3.freq - - arr, idx = pd.factorize(idx3) - tm.assert_numpy_array_equal(arr, exp_arr) - tm.assert_index_equal(idx, idx3) - assert idx.freq == idx3.freq - def test_sort_values(self): idx = TimedeltaIndex(["4d", "1d", "2d"])
https://api.github.com/repos/pandas-dev/pandas/pulls/38573
2020-12-19T02:42:21Z
2020-12-21T16:03:31Z
2020-12-21T16:03:31Z
2020-12-21T16:12:43Z
CLN: DatetimeArray.astype
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index b76051e4dce80..aa1d8f6254e2c 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -31,7 +31,6 @@ is_categorical_dtype, is_datetime64_any_dtype, is_datetime64_dtype, - is_datetime64_ns_dtype, is_datetime64tz_dtype, is_dtype_equal, is_extension_array_dtype, @@ -587,29 +586,30 @@ def astype(self, dtype, copy=True): # DatetimeLikeArrayMixin Super handles the rest. dtype = pandas_dtype(dtype) - if is_datetime64_ns_dtype(dtype) and not is_dtype_equal(dtype, self.dtype): - # GH#18951: datetime64_ns dtype but not equal means different tz - # FIXME: this doesn't match DatetimeBlock.astype, xref GH#33401 - new_tz = getattr(dtype, "tz", None) - if self.tz is None: - return self.tz_localize(new_tz) - elif new_tz is None: - result = self.tz_convert("UTC").tz_localize(None) - else: - result = self.tz_convert(new_tz) + if is_dtype_equal(dtype, self.dtype): + if copy: + return self.copy() + return self + + elif is_datetime64tz_dtype(dtype) and self.tz is None: + # FIXME: GH#33401 this does not match Series behavior + return self.tz_localize(dtype.tz) + elif is_datetime64tz_dtype(dtype): + # GH#18951: datetime64_ns dtype but not equal means different tz + result = self.tz_convert(dtype.tz) if copy: result = result.copy() - if new_tz is None: - # Do we want .astype('datetime64[ns]') to be an ndarray. - # The astype in Block._astype expects this to return an - # ndarray, but we could maybe work around it there. - result = result._data return result - elif is_datetime64tz_dtype(self.dtype) and is_dtype_equal(self.dtype, dtype): + + elif dtype == "M8[ns]": + # we must have self.tz is None, otherwise we would have gone through + # the is_dtype_equal branch above. + result = self.tz_convert("UTC").tz_localize(None) if copy: - return self.copy() - return self + result = result.copy() + return result + elif is_period_dtype(dtype): return self.to_period(freq=dtype.freq) return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy) diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index fe4eaa4b4bf19..8410f3d491891 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -324,12 +324,7 @@ def astype(self, dtype, copy: bool = True): # DatetimeLikeArrayMixin super call handles other cases dtype = pandas_dtype(dtype) - if is_dtype_equal(dtype, self.dtype): - if copy: - return self.copy() - return self - - elif dtype.kind == "m": + if dtype.kind == "m": return astype_td64_unit_conversion(self._data, dtype, copy=copy) return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy=copy)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38572
2020-12-19T00:50:08Z
2020-12-22T00:08:50Z
2020-12-22T00:08:50Z
2020-12-22T00:12:19Z
TST: Test Groupby with Categoricals consistent for Series and DataFrame results
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index ad5d2315f7e33..22a23407b2521 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1193,6 +1193,13 @@ def test_seriesgroupby_observed_apply_dict(df_cat, observed, index, data): tm.assert_series_equal(result, expected) +def test_groupby_categorical_series_dataframe_consistent(df_cat): + # GH 20416 + expected = df_cat.groupby(["A", "B"])["C"].mean() + result = df_cat.groupby(["A", "B"]).mean()["C"] + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("code", [([1, 0, 0]), ([0, 0, 0])]) def test_groupby_categorical_axis_1(code): # GH 13420
- [ ] closes https://github.com/pandas-dev/pandas/issues/20416 - [ ] 1 test added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29343
2019-11-02T12:23:32Z
2019-11-02T14:17:34Z
2019-11-02T14:17:34Z
2019-11-02T14:17:39Z
TST: add new test - check reindex() and astype() order consistency for Series
diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index 6ee120f3bec64..a28977864eb2d 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -518,3 +518,13 @@ def test_values_compatibility(self, data): result = pd.Series(data).values expected = np.array(data.astype(object)) tm.assert_numpy_array_equal(result, expected) + + def test_reindex_astype_order_consistency(self): + # GH 17444 + s = Series([1, 2, 3], index=[2, 0, 1]) + new_index = [0, 1, 2] + temp_dtype = "category" + new_dtype = str + s1 = s.reindex(new_index).astype(temp_dtype).astype(new_dtype) + s2 = s.astype(temp_dtype).reindex(new_index).astype(new_dtype) + tm.assert_series_equal(s1, s2)
check reindex() and astype() order consistency for Series - [x] closes #17444 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29342
2019-11-02T12:14:13Z
2019-11-02T14:21:06Z
2019-11-02T14:21:06Z
2019-11-02T14:21:15Z
Fix mypy error messages in pandas/test/tseries/offsets/test_offsets.py
diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 81aff4211440e..bed8d2461f65d 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -1,5 +1,5 @@ from datetime import date, datetime, time as dt_time, timedelta -from typing import Type +from typing import Dict, List, Tuple, Type import numpy as np import pytest @@ -31,6 +31,7 @@ import pandas.tseries.offsets as offsets from pandas.tseries.offsets import ( FY5253, + BaseOffset, BDay, BMonthBegin, BMonthEnd, @@ -90,6 +91,7 @@ def test_to_M8(): ##### # DateOffset Tests ##### +_ApplyCases = List[Tuple[BaseOffset, Dict[datetime, datetime]]] class Base: @@ -741,7 +743,7 @@ def test_onOffset(self): for offset, d, expected in tests: assert_onOffset(offset, d, expected) - apply_cases = [] + apply_cases = [] # type: _ApplyCases apply_cases.append( ( BDay(), @@ -2629,7 +2631,7 @@ def test_onOffset(self, case): offset, d, expected = case assert_onOffset(offset, d, expected) - apply_cases = [] + apply_cases = [] # type: _ApplyCases apply_cases.append( ( CDay(), @@ -2876,7 +2878,7 @@ def test_onOffset(self, case): offset, d, expected = case assert_onOffset(offset, d, expected) - apply_cases = [] + apply_cases = [] # type: _ApplyCases apply_cases.append( ( CBMonthEnd(), @@ -3025,7 +3027,7 @@ def test_onOffset(self, case): offset, dt, expected = case assert_onOffset(offset, dt, expected) - apply_cases = [] + apply_cases = [] # type: _ApplyCases apply_cases.append( ( CBMonthBegin(), diff --git a/setup.cfg b/setup.cfg index d4657100c1291..3207e598ff6ee 100644 --- a/setup.cfg +++ b/setup.cfg @@ -159,6 +159,3 @@ ignore_errors=True [mypy-pandas.tests.series.test_operators] ignore_errors=True - -[mypy-pandas.tests.tseries.offsets.test_offsets] -ignore_errors=True
Activate and fix mypy for test offsets - xref #28926 - [X] tests added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29340
2019-11-02T11:53:16Z
2019-11-07T20:50:12Z
2019-11-07T20:50:12Z
2019-11-07T20:50:18Z
TST: Test Series constructor with dict containing lists and explicit …
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index fb2a8dde96e2b..4cbade2669cc6 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1035,6 +1035,13 @@ def test_constructor_dict(self): expected.iloc[1] = 1 tm.assert_series_equal(result, expected) + def test_constructor_dict_list_value_explicit_dtype(self): + # GH 18625 + d = {"a": [[2], [3], [4]]} + result = Series(d, index=["a"], dtype="object") + expected = Series(d, index=["a"]) + tm.assert_series_equal(result, expected) + def test_constructor_dict_order(self): # GH19018 # initialization ordering: by insertion order if python>= 3.6, else
Add test for series constructor with dict of list with explicit dtype. - closes #18625 - 1 test added / passed
https://api.github.com/repos/pandas-dev/pandas/pulls/29339
2019-11-02T11:37:54Z
2019-11-02T14:23:49Z
2019-11-02T14:23:49Z
2019-11-02T14:23:57Z
TST: Adding to_dict numeric consistency test (#22620)
diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 17edd48e36563..e1dda1411edbd 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -612,3 +612,19 @@ def test_to_dict_wide(self): result = df.to_dict("records")[0] expected = {"A_{:d}".format(i): i for i in range(256)} assert result == expected + + def test_to_dict_orient_dtype(self): + # https://github.com/pandas-dev/pandas/issues/22620 + # Input Data + input_data = {"a": [1, 2, 3], "b": [1.0, 2.0, 3.0], "c": ["X", "Y", "Z"]} + df = DataFrame(input_data) + # Expected Dtypes + expected = {"a": int, "b": float, "c": str} + # Extracting dtypes out of to_dict operation + for df_dict in df.to_dict("records"): + result = { + "a": type(df_dict["a"]), + "b": type(df_dict["b"]), + "c": type(df_dict["c"]), + } + assert result == expected
- [x] closes #22620 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29338
2019-11-02T11:01:44Z
2019-11-05T17:18:22Z
2019-11-05T17:18:21Z
2019-11-05T17:18:37Z
CLN: clean indexes/multi.py
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index dc2abfb0cb6eb..cc838cd09b949 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -704,22 +704,23 @@ def _set_levels( # This is NOT part of the levels property because it should be # externally not allowed to set levels. User beware if you change # _levels directly - if validate and len(levels) == 0: - raise ValueError("Must set non-zero number of levels.") - if validate and level is None and len(levels) != self.nlevels: - raise ValueError("Length of levels must match number of levels.") - if validate and level is not None and len(levels) != len(level): - raise ValueError("Length of levels must match length of level.") + if validate: + if len(levels) == 0: + raise ValueError("Must set non-zero number of levels.") + if level is None and len(levels) != self.nlevels: + raise ValueError("Length of levels must match number of levels.") + if level is not None and len(levels) != len(level): + raise ValueError("Length of levels must match length of level.") if level is None: new_levels = FrozenList( ensure_index(lev, copy=copy)._shallow_copy() for lev in levels ) else: - level = [self._get_level_number(l) for l in level] + level_numbers = [self._get_level_number(lev) for lev in level] new_levels = list(self._levels) - for l, v in zip(level, levels): - new_levels[l] = ensure_index(v, copy=copy)._shallow_copy() + for lev_num, lev in zip(level_numbers, levels): + new_levels[lev_num] = ensure_index(lev, copy=copy)._shallow_copy() new_levels = FrozenList(new_levels) if verify_integrity: @@ -825,10 +826,11 @@ def labels(self): def _set_codes( self, codes, level=None, copy=False, validate=True, verify_integrity=False ): - if validate and level is None and len(codes) != self.nlevels: - raise ValueError("Length of codes must match number of levels") - if validate and level is not None and len(codes) != len(level): - raise ValueError("Length of codes must match length of levels.") + if validate: + if level is None and len(codes) != self.nlevels: + raise ValueError("Length of codes must match number of levels") + if level is not None and len(codes) != len(level): + raise ValueError("Length of codes must match length of levels.") if level is None: new_codes = FrozenList( @@ -836,11 +838,11 @@ def _set_codes( for lev, level_codes in zip(self._levels, codes) ) else: - level = [self._get_level_number(l) for l in level] + level_numbers = [self._get_level_number(lev) for lev in level] new_codes = list(self._codes) - for lev_idx, level_codes in zip(level, codes): - lev = self.levels[lev_idx] - new_codes[lev_idx] = _ensure_frozen( + for lev_num, level_codes in zip(level_numbers, codes): + lev = self.levels[lev_num] + new_codes[lev_num] = _ensure_frozen( level_codes, lev, copy=copy )._shallow_copy() new_codes = FrozenList(new_codes) @@ -1253,17 +1255,18 @@ def _set_names(self, names, level=None, validate=True): raise ValueError("Names should be list-like for a MultiIndex") names = list(names) - if validate and level is not None and len(names) != len(level): - raise ValueError("Length of names must match length of level.") - if validate and level is None and len(names) != self.nlevels: - raise ValueError( - "Length of names must match number of levels in MultiIndex." - ) + if validate: + if level is not None and len(names) != len(level): + raise ValueError("Length of names must match length of level.") + if level is None and len(names) != self.nlevels: + raise ValueError( + "Length of names must match number of levels in MultiIndex." + ) if level is None: level = range(self.nlevels) else: - level = [self._get_level_number(l) for l in level] + level = [self._get_level_number(lev) for lev in level] # set the name for lev, name in zip(level, names):
Some minor clean-ups.
https://api.github.com/repos/pandas-dev/pandas/pulls/29337
2019-11-02T09:28:29Z
2019-11-02T11:01:58Z
2019-11-02T11:01:57Z
2019-11-02T11:02:01Z
BUG: Categorical.from_codes should not warn on empty codes
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 4d065bd234e0b..20e666bbc7bdb 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -673,7 +673,7 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None): raise ValueError(msg) codes = np.asarray(codes) # #21767 - if not is_integer_dtype(codes): + if len(codes) and not is_integer_dtype(codes): msg = "codes need to be array-like integers" if is_float_dtype(codes): icodes = codes.astype("i8") diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 237ec17f56974..6eb26d26e14bd 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -526,6 +526,9 @@ def test_from_codes_with_float(self): codes = [1.0, 2.0, 0] # integer, but in float dtype dtype = CategoricalDtype(categories=["a", "b", "c"]) + # empty codes should not raise for floats + Categorical.from_codes([], dtype.categories) + with tm.assert_produces_warning(FutureWarning): cat = Categorical.from_codes(codes, dtype.categories) tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype="i1"))
Empty codes should not warn about float codes: ```python >>> pd.Categorical.from_codes([], ['a', 'b', 'c']) C:\Users\TP\Miniconda3\envs\pandas-dev\Scripts\ipython:1: FutureWarning: float codes will be disallowed in the future and raise a ValueError ```
https://api.github.com/repos/pandas-dev/pandas/pulls/29336
2019-11-02T09:08:09Z
2019-11-02T15:36:34Z
2019-11-02T15:36:34Z
2019-11-02T16:13:23Z
BUG: assignment to multiple columns when some column do not exist
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5b6f70be478c2..caf37a77f8216 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -168,6 +168,37 @@ key and type of :class:`Index`. These now consistently raise ``KeyError`` (:iss .. --------------------------------------------------------------------------- +.. _whatsnew_110.api_breaking.assignment_to_multiple_columns: + +Assignment to multiple columns of a DataFrame when some columns do not exist +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Assignment to multiple columns of a :class:`DataFrame` when some of the columns do not exist would previously assign the values to the last column. Now, new columns would be constructed with the right values. (:issue:`13658`) + +.. ipython:: python + + df = pd.DataFrame({'a': [0, 1, 2], 'b': [3, 4, 5]}) + df + +*Previous behavior*: + +.. code-block:: ipython + + In [3]: df[['a', 'c']] = 1 + In [4]: df + Out[4]: + a b + 0 1 1 + 1 1 1 + 2 1 1 + +*New behavior*: + +.. ipython:: python + + df[['a', 'c']] = 1 + df + .. _whatsnew_110.deprecations: Deprecations diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e153fdaac16e2..943c7f67aeab2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2687,6 +2687,7 @@ def _setitem_array(self, key, value): for k1, k2 in zip(key, value.columns): self[k1] = value[k2] else: + self.loc._ensure_listlike_indexer(key, axis=1) indexer = self.loc._get_listlike_indexer( key, axis=1, raise_missing=False )[1] diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index c9362a0527c06..7bd25814a12ee 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -8,6 +8,7 @@ from pandas.util._decorators import Appender from pandas.core.dtypes.common import ( + is_hashable, is_integer, is_iterator, is_list_like, @@ -581,6 +582,9 @@ def _get_setitem_indexer(self, key): """ Convert a potentially-label-based key into a positional indexer. """ + if self.name == "loc": + self._ensure_listlike_indexer(key) + if self.axis is not None: return self._convert_tuple(key, is_setter=True) @@ -611,6 +615,42 @@ def _get_setitem_indexer(self, key): raise raise IndexingError(key) from e + def _ensure_listlike_indexer(self, key, axis=None): + """ + Ensure that a list-like of column labels are all present by adding them if + they do not already exist. + + Parameters + ---------- + key : _LocIndexer key or list-like of column labels + Target labels. + axis : key axis if known + """ + column_axis = 1 + + # column only exists in 2-dimensional DataFrame + if self.ndim != 2: + return + + if isinstance(key, tuple): + # key may be a tuple if key is a _LocIndexer key + # in that case, set key to the column part of key + key = key[column_axis] + axis = column_axis + + if ( + axis == column_axis + and not isinstance(self.obj.columns, ABCMultiIndex) + and is_list_like_indexer(key) + and not com.is_bool_indexer(key) + and all(is_hashable(k) for k in key) + ): + for k in key: + try: + self.obj[k] + except KeyError: + self.obj[k] = np.nan + def __setitem__(self, key, value): if isinstance(key, tuple): key = tuple(com.apply_if_callable(x, self.obj) for x in key) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 7892030a6727e..923447889d04c 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -215,6 +215,63 @@ def test_setitem_list_of_tuples(self, float_frame): expected = Series(tuples, index=float_frame.index, name="tuples") tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "columns,box,expected", + [ + ( + ["A", "B", "C", "D"], + 7, + pd.DataFrame( + [[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["C", "D"], + [7, 8], + pd.DataFrame( + [[1, 2, 7, 8], [3, 4, 7, 8], [5, 6, 7, 8]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["A", "B", "C"], + np.array([7, 8, 9], dtype=np.int64), + pd.DataFrame( + [[7, 8, 9], [7, 8, 9], [7, 8, 9]], columns=["A", "B", "C"] + ), + ), + ( + ["B", "C", "D"], + [[7, 8, 9], [10, 11, 12], [13, 14, 15]], + pd.DataFrame( + [[1, 7, 8, 9], [3, 10, 11, 12], [5, 13, 14, 15]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["C", "A", "D"], + np.array([[7, 8, 9], [10, 11, 12], [13, 14, 15]], dtype=np.int64), + pd.DataFrame( + [[8, 2, 7, 9], [11, 4, 10, 12], [14, 6, 13, 15]], + columns=["A", "B", "C", "D"], + ), + ), + ( + ["A", "C"], + pd.DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]), + pd.DataFrame( + [[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"] + ), + ), + ], + ) + def test_setitem_list_missing_columns(self, columns, box, expected): + # GH 29334 + df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"]) + df[columns] = box + tm.assert_frame_equal(df, expected) + def test_setitem_multi_index(self): # GH7655, test that assigning to a sub-frame of a frame # with multi-index columns aligns both rows and columns @@ -459,13 +516,6 @@ def test_setitem(self, float_frame): float_frame["col6"] = series tm.assert_series_equal(series, float_frame["col6"], check_names=False) - msg = ( - r"\"None of \[Float64Index\(\[.*dtype='float64'\)\] are in the " - r"\[columns\]\"" - ) - with pytest.raises(KeyError, match=msg): - float_frame[np.random.randn(len(float_frame) + 1)] = 1 - # set ndarray arr = np.random.randn(len(float_frame)) float_frame["col9"] = arr diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 3073fe085de15..a0edf78f79a53 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -631,6 +631,64 @@ def test_loc_setitem_with_scalar_index(self, indexer, value): assert is_scalar(result) and result == "Z" + @pytest.mark.parametrize( + "index,box,expected", + [ + ( + ([0, 2], ["A", "B", "C", "D"]), + 7, + pd.DataFrame( + [[7, 7, 7, 7], [3, 4, np.nan, np.nan], [7, 7, 7, 7]], + columns=["A", "B", "C", "D"], + ), + ), + ( + (1, ["C", "D"]), + [7, 8], + pd.DataFrame( + [[1, 2, np.nan, np.nan], [3, 4, 7, 8], [5, 6, np.nan, np.nan]], + columns=["A", "B", "C", "D"], + ), + ), + ( + (1, ["A", "B", "C"]), + np.array([7, 8, 9], dtype=np.int64), + pd.DataFrame( + [[1, 2, np.nan], [7, 8, 9], [5, 6, np.nan]], + columns=["A", "B", "C"], + ), + ), + ( + (slice(1, 3, None), ["B", "C", "D"]), + [[7, 8, 9], [10, 11, 12]], + pd.DataFrame( + [[1, 2, np.nan, np.nan], [3, 7, 8, 9], [5, 10, 11, 12]], + columns=["A", "B", "C", "D"], + ), + ), + ( + (slice(1, 3, None), ["C", "A", "D"]), + np.array([[7, 8, 9], [10, 11, 12]], dtype=np.int64), + pd.DataFrame( + [[1, 2, np.nan, np.nan], [8, 4, 7, 9], [11, 6, 10, 12]], + columns=["A", "B", "C", "D"], + ), + ), + ( + (slice(None, None, None), ["A", "C"]), + pd.DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]), + pd.DataFrame( + [[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"] + ), + ), + ], + ) + def test_loc_setitem_missing_columns(self, index, box, expected): + # GH 29334 + df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"]) + df.loc[index] = box + tm.assert_frame_equal(df, expected) + def test_loc_coercion(self): # 12411
- [x] closes #13658 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Previous PR: #26534 In particular, the following code now behaves correctly. ```python import pandas as pd df = pd.DataFrame({'a': [0, 1, 2], 'b': [3, 4, 5]}) df[['a', 'c']] = 1 print(df) ``` v0.22: error master: column `'c'` is converted to index `-1`, which causes last column to be overwritten. ``` a b 0 1 1 1 1 1 2 1 1 ``` After this PR: ``` a b c 0 1 3 1 1 1 4 1 2 1 5 1 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/29334
2019-11-02T03:19:42Z
2020-03-14T20:31:22Z
2020-03-14T20:31:22Z
2020-03-24T18:38:01Z
CLN: type annotations
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index ad4b4bf8b67ee..06ba2a7e0ccfb 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1089,7 +1089,7 @@ def nsmallest(self): return self.compute("nsmallest") @staticmethod - def is_valid_dtype_n_method(dtype): + def is_valid_dtype_n_method(dtype) -> bool: """ Helper function to determine if dtype is valid for nsmallest/nlargest methods diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 304eeac87f64d..9ae7af4fe8ce3 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -495,7 +495,7 @@ def _ensure_dtype_type(value, dtype): return dtype.type(value) -def infer_dtype_from(val, pandas_dtype=False): +def infer_dtype_from(val, pandas_dtype: bool = False): """ interpret the dtype from a scalar or array. This is a convenience routines to infer dtype from a scalar or an array @@ -512,7 +512,7 @@ def infer_dtype_from(val, pandas_dtype=False): return infer_dtype_from_array(val, pandas_dtype=pandas_dtype) -def infer_dtype_from_scalar(val, pandas_dtype=False): +def infer_dtype_from_scalar(val, pandas_dtype: bool = False): """ interpret the dtype from a scalar @@ -587,7 +587,7 @@ def infer_dtype_from_scalar(val, pandas_dtype=False): return dtype, val -def infer_dtype_from_array(arr, pandas_dtype=False): +def infer_dtype_from_array(arr, pandas_dtype: bool = False): """ infer the dtype from a scalar or array diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index a902c63e20e7d..09db840ca4db0 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -1,8 +1,6 @@ """ Quantilization functions and related stuff """ -from functools import partial - import numpy as np from pandas._libs import Timedelta, Timestamp @@ -38,12 +36,12 @@ def cut( x, bins, - right=True, + right: bool = True, labels=None, - retbins=False, - precision=3, - include_lowest=False, - duplicates="raise", + retbins: bool = False, + precision: int = 3, + include_lowest: bool = False, + duplicates: str = "raise", ): """ Bin values into discrete intervals. @@ -275,7 +273,14 @@ def cut( ) -def qcut(x, q, labels=None, retbins=False, precision=3, duplicates="raise"): +def qcut( + x, + q, + labels=None, + retbins: bool = False, + precision: int = 3, + duplicates: str = "raise", +): """ Quantile-based discretization function. Discretize variable into equal-sized buckets based on rank or based on sample quantiles. For example @@ -355,12 +360,12 @@ def qcut(x, q, labels=None, retbins=False, precision=3, duplicates="raise"): def _bins_to_cuts( x, bins, - right=True, + right: bool = True, labels=None, - precision=3, - include_lowest=False, + precision: int = 3, + include_lowest: bool = False, dtype=None, - duplicates="raise", + duplicates: str = "raise", ): if duplicates not in ["raise", "drop"]: @@ -498,13 +503,15 @@ def _convert_bin_to_datelike_type(bins, dtype): return bins -def _format_labels(bins, precision, right=True, include_lowest=False, dtype=None): +def _format_labels( + bins, precision, right: bool = True, include_lowest: bool = False, dtype=None +): """ based on the dtype, return our labels """ closed = "right" if right else "left" if is_datetime64tz_dtype(dtype): - formatter = partial(Timestamp, tz=dtype.tz) + formatter = lambda x: Timestamp(x, tz=dtype.tz) adjust = lambda x: x - Timedelta("1ns") elif is_datetime64_dtype(dtype): formatter = Timestamp @@ -556,7 +563,9 @@ def _preprocess_for_cut(x): return x_is_series, series_index, name, x -def _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype): +def _postprocess_for_cut( + fac, bins, retbins: bool, x_is_series, series_index, name, dtype +): """ handles post processing for the cut method where we combine the index information if the originally passed diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 706f6159bcafe..9b8a1a76e419c 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -20,7 +20,7 @@ _INT64_MAX = np.iinfo(np.int64).max -def get_group_index(labels, shape, sort, xnull): +def get_group_index(labels, shape, sort: bool, xnull: bool): """ For the particular label_list, gets the offsets into the hypothetical list representing the totally ordered cartesian product of all possible label @@ -48,7 +48,7 @@ def get_group_index(labels, shape, sort, xnull): labels are equal at all location. """ - def _int64_cut_off(shape): + def _int64_cut_off(shape) -> int: acc = 1 for i, mul in enumerate(shape): acc *= int(mul) @@ -125,7 +125,7 @@ def get_compressed_ids(labels, sizes): return compress_group_index(ids, sort=True) -def is_int64_overflow_possible(shape): +def is_int64_overflow_possible(shape) -> bool: the_prod = 1 for x in shape: the_prod *= int(x) @@ -153,7 +153,7 @@ def decons_group_index(comp_labels, shape): return label_list[::-1] -def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull): +def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull: bool): """ reconstruct labels from observed group ids @@ -177,7 +177,7 @@ def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull): return [i8copy(lab[i]) for lab in labels] -def indexer_from_factorized(labels, shape, compress=True): +def indexer_from_factorized(labels, shape, compress: bool = True): ids = get_group_index(labels, shape, sort=True, xnull=False) if not compress: @@ -235,7 +235,7 @@ def lexsort_indexer(keys, orders=None, na_position="last"): return indexer_from_factorized(labels, shape) -def nargsort(items, kind="quicksort", ascending=True, na_position="last"): +def nargsort(items, kind="quicksort", ascending: bool = True, na_position="last"): """ This is intended to be a drop-in replacement for np.argsort which handles NaNs. It adds ascending and na_position parameters. @@ -325,7 +325,7 @@ def get_indexer_dict(label_list, keys): # sorting levels...cleverly? -def get_group_index_sorter(group_index, ngroups): +def get_group_index_sorter(group_index, ngroups: int): """ algos.groupsort_indexer implements `counting sort` and it is at least O(ngroups), where @@ -350,7 +350,7 @@ def get_group_index_sorter(group_index, ngroups): return group_index.argsort(kind="mergesort") -def compress_group_index(group_index, sort=True): +def compress_group_index(group_index, sort: bool = True): """ Group_index is offsets into cartesian product of all possible labels. This space can be huge, so this function compresses it, by computing offsets @@ -391,7 +391,13 @@ def _reorder_by_uniques(uniques, labels): return uniques, labels -def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False, verify=True): +def safe_sort( + values, + labels=None, + na_sentinel: int = -1, + assume_unique: bool = False, + verify: bool = True, +): """ Sort ``values`` and reorder corresponding ``labels``. ``values`` should be unique if ``labels`` is not None.
Separating these out from the non-CLN work going on in/around these functions.
https://api.github.com/repos/pandas-dev/pandas/pulls/29333
2019-11-02T03:03:05Z
2019-11-03T16:38:18Z
2019-11-03T16:38:18Z
2019-11-03T17:29:37Z
maybe_upcast_putmask: require other to be a scalar
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 3e92906be706c..304eeac87f64d 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -232,7 +232,7 @@ def trans(x): return result -def maybe_upcast_putmask(result, mask, other): +def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray, other): """ A safe version of putmask that potentially upcasts the result. The result is replaced with the first N elements of other, @@ -245,8 +245,8 @@ def maybe_upcast_putmask(result, mask, other): The destination array. This will be mutated in-place if no upcasting is necessary. mask : boolean ndarray - other : ndarray or scalar - The source array or value + other : scalar + The source value Returns ------- @@ -264,6 +264,10 @@ def maybe_upcast_putmask(result, mask, other): if not isinstance(result, np.ndarray): raise ValueError("The result input must be a ndarray.") + if not is_scalar(other): + # We _could_ support non-scalar other, but until we have a compelling + # use case, we assume away the possibility. + raise ValueError("other must be a scalar") if mask.any(): # Two conversions for date-like dtypes that can't be done automatically diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index b9267db76e1a8..5d4f75d93db1c 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -273,6 +273,12 @@ def _get_values( fill_value : Any fill value used """ + + # In _get_values is only called from within nanops, and in all cases + # with scalar fill_value. This guarantee is important for the + # maybe_upcast_putmask call below + assert is_scalar(fill_value) + mask = _maybe_get_mask(values, skipna, mask) if is_datetime64tz_dtype(values): diff --git a/pandas/tests/dtypes/cast/test_upcast.py b/pandas/tests/dtypes/cast/test_upcast.py index b22ed0bcd0a11..49e850f3e87b5 100644 --- a/pandas/tests/dtypes/cast/test_upcast.py +++ b/pandas/tests/dtypes/cast/test_upcast.py @@ -9,7 +9,7 @@ @pytest.mark.parametrize("result", [Series([10, 11, 12]), [10, 11, 12], (10, 11, 12)]) def test_upcast_error(result): - # GH23823 + # GH23823 require result arg to be ndarray mask = np.array([False, True, False]) other = np.array([61, 62, 63]) with pytest.raises(ValueError): @@ -17,76 +17,55 @@ def test_upcast_error(result): @pytest.mark.parametrize( - "arr, other, exp_changed, expected", + "arr, other", [ - (np.arange(1, 6), np.array([61, 62, 63]), False, np.array([1, 61, 3, 62, 63])), + (np.arange(1, 6), np.array([61, 62, 63])), + (np.arange(1, 6), np.array([61.1, 62.2, 63.3])), + (np.arange(10, 15), np.array([61, 62])), + (np.arange(10, 15), np.array([61, np.nan])), ( - np.arange(1, 6), - np.array([61.1, 62.2, 63.3]), - True, - np.array([1, 61.1, 3, 62.2, 63.3]), + np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]"), + np.arange("2018-01-01", "2018-01-04", dtype="datetime64[D]"), ), - (np.arange(1, 6), np.nan, True, np.array([1, np.nan, 3, np.nan, np.nan])), - (np.arange(10, 15), np.array([61, 62]), False, np.array([10, 61, 12, 62, 61])), ( - np.arange(10, 15), - np.array([61, np.nan]), - True, - np.array([10, 61, 12, np.nan, 61]), + np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]"), + np.arange("2018-01-01", "2018-01-03", dtype="datetime64[D]"), ), ], ) -def test_upcast(arr, other, exp_changed, expected): +def test_upcast_scalar_other(arr, other): + # for now we do not support non-scalar `other` + mask = np.array([False, True, False, True, True]) + with pytest.raises(ValueError, match="other must be a scalar"): + maybe_upcast_putmask(arr, mask, other) + + +def test_upcast(): # GH23823 + arr = np.arange(1, 6) mask = np.array([False, True, False, True, True]) - result, changed = maybe_upcast_putmask(arr, mask, other) + result, changed = maybe_upcast_putmask(arr, mask, other=np.nan) - assert changed == exp_changed + expected = np.array([1, np.nan, 3, np.nan, np.nan]) + assert changed tm.assert_numpy_array_equal(result, expected) -@pytest.mark.parametrize( - "arr, other, exp_changed, expected", - [ - ( - np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]"), - np.arange("2018-01-01", "2018-01-04", dtype="datetime64[D]"), - False, - np.array( - ["2019-01-01", "2018-01-01", "2019-01-03", "2018-01-02", "2018-01-03"], - dtype="datetime64[D]", - ), - ), - ( - np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]"), - np.nan, - False, - np.array( - [ - "2019-01-01", - np.datetime64("NaT"), - "2019-01-03", - np.datetime64("NaT"), - np.datetime64("NaT"), - ], - dtype="datetime64[D]", - ), - ), - ( - np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]"), - np.arange("2018-01-01", "2018-01-03", dtype="datetime64[D]"), - False, - np.array( - ["2019-01-01", "2018-01-01", "2019-01-03", "2018-01-02", "2018-01-01"], - dtype="datetime64[D]", - ), - ), - ], -) -def test_upcast_datetime(arr, other, exp_changed, expected): +def test_upcast_datetime(): # GH23823 + arr = np.arange("2019-01-01", "2019-01-06", dtype="datetime64[D]") mask = np.array([False, True, False, True, True]) - result, changed = maybe_upcast_putmask(arr, mask, other) + result, changed = maybe_upcast_putmask(arr, mask, other=np.nan) - assert changed == exp_changed + expected = np.array( + [ + "2019-01-01", + np.datetime64("NaT"), + "2019-01-03", + np.datetime64("NaT"), + np.datetime64("NaT"), + ], + dtype="datetime64[D]", + ) + assert not changed tm.assert_numpy_array_equal(result, expected)
ATM all places where we use `maybe_upcast_putmask` have `other` as a scalar. By making that into a requirement for the function, we can rule out the possibility of passing non-scalar other into `maybe_promote` (xref #29331). Note: there are some simplifications within maybe_upcast_putmask that this makes possible that I did not implement in this PR. cc @jreback @h-vetinari
https://api.github.com/repos/pandas-dev/pandas/pulls/29332
2019-11-02T00:56:50Z
2019-11-02T15:32:05Z
2019-11-02T15:32:05Z
2019-11-02T15:34:00Z
WEB: Fix extension of about/index
diff --git a/web/pandas/about/index.html b/web/pandas/about/index.md similarity index 100% rename from web/pandas/about/index.html rename to web/pandas/about/index.md
- [✓] closes #29325 - [✓] whatsnew: the about/index.html file is now about/index.md
https://api.github.com/repos/pandas-dev/pandas/pulls/29329
2019-11-01T22:35:44Z
2019-11-04T21:00:16Z
2019-11-04T21:00:16Z
2019-11-04T23:09:41Z
CLN: fix mypy warnings/errors
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 2a7fd079679a4..19cb71cdc5528 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -790,7 +790,7 @@ def _get_axes(group): return group.axes -def _is_indexed_like(obj, axes): +def _is_indexed_like(obj, axes) -> bool: if isinstance(obj, Series): if len(axes) > 1: return False diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py index a6c39d049c50c..4791ea2b70691 100644 --- a/pandas/core/indexes/frozen.py +++ b/pandas/core/indexes/frozen.py @@ -7,7 +7,6 @@ - .levels & .codes (FrozenNDArray) """ - import warnings import numpy as np @@ -31,7 +30,7 @@ class FrozenList(PandasObject, list): # Side note: This has to be of type list. Otherwise, # it messes up PyTables type checks. - def union(self, other): + def union(self, other) -> "FrozenList": """ Returns a FrozenList with other concatenated to the end of self. @@ -49,7 +48,7 @@ def union(self, other): other = list(other) return type(self)(super().__add__(other)) - def difference(self, other): + def difference(self, other) -> "FrozenList": """ Returns a FrozenList with elements from other removed from self. @@ -101,7 +100,9 @@ def __hash__(self): def _disabled(self, *args, **kwargs): """This method will not function because object is immutable.""" raise TypeError( - "'%s' does not support mutable operations." % self.__class__.__name__ + "'{cls}' does not support mutable operations.".format( + cls=self.__class__.__name__ + ) ) def __str__(self): @@ -132,7 +133,9 @@ def __new__(cls, data, dtype=None, copy=False): def _disabled(self, *args, **kwargs): """This method will not function because object is immutable.""" - raise TypeError("'%s' does not support mutable operations." % self.__class__) + raise TypeError( + "'{cls}' does not support mutable operations.".format(cls=self.__class__) + ) __setitem__ = __setslice__ = __delitem__ = __delslice__ = _disabled put = itemset = fill = _disabled diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py index 92fe87cddb35b..cd58ef51d1b65 100644 --- a/pandas/io/formats/css.py +++ b/pandas/io/formats/css.py @@ -11,6 +11,23 @@ class CSSWarning(UserWarning): pass +def _side_expander(prop_fmt: str): + def expand(self, prop, value): + tokens = value.split() + try: + mapping = self.SIDE_SHORTHANDS[len(tokens)] + except KeyError: + warnings.warn( + 'Could not expand "{prop}: {val}"'.format(prop=prop, val=value), + CSSWarning, + ) + return + for key, idx in zip(self.SIDES, mapping): + yield prop_fmt.format(key), tokens[idx] + + return expand + + class CSSResolver: """A callable for parsing and resolving CSS to atomic properties @@ -213,22 +230,6 @@ def atomize(self, declarations): } SIDES = ("top", "right", "bottom", "left") - def _side_expander(prop_fmt): - def expand(self, prop, value): - tokens = value.split() - try: - mapping = self.SIDE_SHORTHANDS[len(tokens)] - except KeyError: - warnings.warn( - 'Could not expand "{prop}: {val}"'.format(prop=prop, val=value), - CSSWarning, - ) - return - for key, idx in zip(self.SIDES, mapping): - yield prop_fmt.format(key), tokens[idx] - - return expand - expand_border_color = _side_expander("border-{:s}-color") expand_border_style = _side_expander("border-{:s}-style") expand_border_width = _side_expander("border-{:s}-width") diff --git a/pandas/tests/io/msgpack/test_extension.py b/pandas/tests/io/msgpack/test_extension.py index 85ed43fa01079..6d1f8cb694601 100644 --- a/pandas/tests/io/msgpack/test_extension.py +++ b/pandas/tests/io/msgpack/test_extension.py @@ -48,7 +48,7 @@ def default(obj): typecode = 123 # application specific typecode data = tobytes(obj) return ExtType(typecode, data) - raise TypeError("Unknown type object {obj!r}".format(obj)) + raise TypeError("Unknown type object {obj!r}".format(obj=obj)) def ext_hook(code, data): print("ext_hook called", code, data)
When I run `mypy pandas` locally I get a handful of complaints. This fixes about half of them. The other half are about `FixedOffset` which IIRC we are handling elsewhere. cc @simonjayhawkins
https://api.github.com/repos/pandas-dev/pandas/pulls/29327
2019-11-01T21:31:05Z
2019-11-02T14:25:57Z
2019-11-02T14:25:57Z
2019-11-02T15:11:56Z
Pr09 batch 1
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 430daa4708001..461561a80a7e5 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -219,7 +219,7 @@ def eval( More backends may be available in the future. truediv : bool, optional - Whether to use true division, like in Python >= 3 + Whether to use true division, like in Python >= 3. local_dict : dict or None, optional A dictionary of local variables, taken from locals() by default. global_dict : dict or None, optional diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index ee2f4e0f1e85d..e5cecd090e061 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -103,13 +103,13 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin): Parameters ---------- data : array-like (1-dimensional), optional - Optional datetime-like data to construct index with + Optional datetime-like data to construct index with. copy : bool - Make a copy of input ndarray + Make a copy of input ndarray. freq : str or pandas offset object, optional One of pandas date offset strings or corresponding objects. The string 'infer' can be passed in order to set the frequency of the index as the - inferred frequency upon creation + inferred frequency upon creation. start : starting value, datetime-like, optional If data is None, start is used as the start point in generating regular @@ -119,19 +119,19 @@ class DatetimeIndex(DatetimeIndexOpsMixin, Int64Index, DatetimeDelegateMixin): periods : int, optional, > 0 Number of periods to generate, if generating index. Takes precedence - over end argument + over end argument. .. deprecated:: 0.24.0 end : end time, datetime-like, optional If periods is none, generated index will extend to first conforming - time on or just past end argument + time on or just past end argument. .. deprecated:: 0.24.0 closed : str or None, default None Make the interval closed with respect to the given frequency to - the 'left', 'right', or both sides (None) + the 'left', 'right', or both sides (None). .. deprecated:: 0.24. 0 diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index dc2abfb0cb6eb..c99e42e48c346 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -882,13 +882,13 @@ def set_codes(self, codes, level=None, inplace=False, verify_integrity=True): Parameters ---------- codes : sequence or list of sequence - new codes to apply + New codes to apply. level : int, level name, or sequence of int/level names (default None) - level(s) to set (None for all levels) + Level(s) to set (None for all levels). inplace : bool - if True, mutates in place + If True, mutates in place. verify_integrity : bool (default True) - if True, checks that levels and codes are compatible + If True, checks that levels and codes are compatible. Returns ------- @@ -1717,7 +1717,7 @@ def to_hierarchical(self, n_repeat, n_shuffle=1): Parameters ---------- n_repeat : int - Number of times to repeat the labels on self + Number of times to repeat the labels on self. n_shuffle : int Controls the reordering of the labels. If the result is going to be an inner level in a MultiIndex, n_shuffle will need to be @@ -2335,11 +2335,11 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True): Parameters ---------- level : list-like, int or str, default 0 - If a string is given, must be a name of the level + If a string is given, must be a name of the level. If list-like must be names or ints of levels. ascending : bool, default True - False to sort in descending order - Can also be a list to specify a directed ordering + False to sort in descending order. + Can also be a list to specify a directed ordering. sort_remaining : sort by the remaining levels after level Returns diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 7e593ddb91d3a..ea334503a4302 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -359,7 +359,7 @@ def merge_asof( - If True, allow matching with the same 'on' value (i.e. less-than-or-equal-to / greater-than-or-equal-to) - If False, don't match the same 'on' value - (i.e., strictly less-than / strictly greater-than) + (i.e., strictly less-than / strictly greater-than). direction : 'backward' (default), 'forward', or 'nearest' Whether to search for prior, subsequent, or closest matches. diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 2cc9f8927effb..a902c63e20e7d 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -296,7 +296,7 @@ def qcut(x, q, labels=None, retbins=False, precision=3, duplicates="raise"): Whether to return the (bins, labels) or not. Can be useful if bins is given as a scalar. precision : int, optional - The precision at which to store and display the bins labels + The precision at which to store and display the bins labels. duplicates : {default 'raise', 'drop'}, optional If bin edges are not unique, raise ValueError or drop non-uniques. diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py index 05696ffd4605d..e59ed247bd87b 100644 --- a/pandas/core/tools/numeric.py +++ b/pandas/core/tools/numeric.py @@ -36,9 +36,9 @@ def to_numeric(arg, errors="raise", downcast=None): ---------- arg : scalar, list, tuple, 1-d array, or Series errors : {'ignore', 'raise', 'coerce'}, default 'raise' - - If 'raise', then invalid parsing will raise an exception - - If 'coerce', then invalid parsing will be set as NaN - - If 'ignore', then invalid parsing will return the input + - If 'raise', then invalid parsing will raise an exception. + - If 'coerce', then invalid parsing will be set as NaN. + - If 'ignore', then invalid parsing will return the input. downcast : {'integer', 'signed', 'unsigned', 'float'}, default None If not None, and if the data has been successfully cast to a numerical dtype (or if the data was numeric to begin with), diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 8574c9ad1d425..1f1ad55969d6f 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -552,9 +552,9 @@ class ExcelWriter(metaclass=abc.ABCMeta): ``io.excel.<extension>.writer``. NOTE: can only be passed as a keyword argument. date_format : str, default None - Format string for dates written into Excel files (e.g. 'YYYY-MM-DD') + Format string for dates written into Excel files (e.g. 'YYYY-MM-DD'). datetime_format : str, default None - Format string for datetime objects written into Excel files + Format string for datetime objects written into Excel files. (e.g. 'YYYY-MM-DD HH:MM:SS') mode : {'w', 'a'}, default 'w' File mode to use (write or append). diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 94f863d8970f1..35e6d53127e59 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1024,7 +1024,7 @@ def append( table(t) : table format Write as a PyTables Table structure which may perform worse but allow more flexible operations like searching - / selecting subsets of the data + / selecting subsets of the data. append : bool, default True Append the input data to the existing. data_columns : list of columns, or True, default None diff --git a/pandas/io/spss.py b/pandas/io/spss.py index 4f13349a819c3..cf682ec72f284 100644 --- a/pandas/io/spss.py +++ b/pandas/io/spss.py @@ -20,7 +20,7 @@ def read_spss( Parameters ---------- path : string or Path - File path + File path. usecols : list-like, optional Return a subset of the columns. If None, return all columns. convert_categoricals : bool, default is True diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 820aeaeb11649..e90e19649f645 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -294,7 +294,7 @@ def read_sql_query( to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. - Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'} + Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}. parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is @@ -372,7 +372,7 @@ def read_sql( to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. - Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'} + Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}. parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 0dcd8aeb4df9b..beeef3811ae5d 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -222,7 +222,7 @@ def infer_freq(index, warn=True): Parameters ---------- index : DatetimeIndex or TimedeltaIndex - if passed a Series will use the values of the series (NOT THE INDEX) + if passed a Series will use the values of the series (NOT THE INDEX). warn : bool, default True Returns
fixing PR09 missing period formatting errors in various parameter descriptions. Subset of #28602, mainly functions with single parameter's missing periods that didn't make sense to open an entire issue for. I'm periodically updating the main issue for PR09 with the current list of errors remaining as they're removed.
https://api.github.com/repos/pandas-dev/pandas/pulls/29324
2019-11-01T18:54:28Z
2019-11-01T23:16:20Z
2019-11-01T23:16:20Z
2020-01-06T16:47:26Z
release gil more
diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in index 6211734706e37..ea05c4afc8fce 100644 --- a/pandas/_libs/algos_common_helper.pxi.in +++ b/pandas/_libs/algos_common_helper.pxi.in @@ -24,6 +24,7 @@ def diff_2d(ndarray[diff_t, ndim=2] arr, Py_ssize_t periods, int axis): cdef: Py_ssize_t i, j, sx, sy, start, stop + bint f_contig = arr.flags.f_contiguous # Disable for unsupported dtype combinations, # see https://github.com/cython/cython/issues/2646 @@ -37,40 +38,41 @@ def diff_2d(ndarray[diff_t, ndim=2] arr, # We put this inside an indented else block to avoid cython build # warnings about unreachable code sx, sy = (<object>arr).shape - if arr.flags.f_contiguous: - if axis == 0: - if periods >= 0: - start, stop = periods, sx + with nogil: + if f_contig: + if axis == 0: + if periods >= 0: + start, stop = periods, sx + else: + start, stop = 0, sx + periods + for j in range(sy): + for i in range(start, stop): + out[i, j] = arr[i, j] - arr[i - periods, j] else: - start, stop = 0, sx + periods - for j in range(sy): - for i in range(start, stop): - out[i, j] = arr[i, j] - arr[i - periods, j] + if periods >= 0: + start, stop = periods, sy + else: + start, stop = 0, sy + periods + for j in range(start, stop): + for i in range(sx): + out[i, j] = arr[i, j] - arr[i, j - periods] else: - if periods >= 0: - start, stop = periods, sy + if axis == 0: + if periods >= 0: + start, stop = periods, sx + else: + start, stop = 0, sx + periods + for i in range(start, stop): + for j in range(sy): + out[i, j] = arr[i, j] - arr[i - periods, j] else: - start, stop = 0, sy + periods - for j in range(start, stop): + if periods >= 0: + start, stop = periods, sy + else: + start, stop = 0, sy + periods for i in range(sx): - out[i, j] = arr[i, j] - arr[i, j - periods] - else: - if axis == 0: - if periods >= 0: - start, stop = periods, sx - else: - start, stop = 0, sx + periods - for i in range(start, stop): - for j in range(sy): - out[i, j] = arr[i, j] - arr[i - periods, j] - else: - if periods >= 0: - start, stop = periods, sy - else: - start, stop = 0, sy + periods - for i in range(sx): - for j in range(start, stop): - out[i, j] = arr[i, j] - arr[i, j - periods] + for j in range(start, stop): + out[i, j] = arr[i, j] - arr[i, j - periods] # ---------------------------------------------------------------------- diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx index 11c56f784d378..a3e1b9694f5d2 100644 --- a/pandas/_libs/join.pyx +++ b/pandas/_libs/join.pyx @@ -29,13 +29,14 @@ def inner_join(const int64_t[:] left, const int64_t[:] right, left_sorter, left_count = groupsort_indexer(left, max_groups) right_sorter, right_count = groupsort_indexer(right, max_groups) - # First pass, determine size of result set, do not use the NA group - for i in range(1, max_groups + 1): - lc = left_count[i] - rc = right_count[i] + with nogil: + # First pass, determine size of result set, do not use the NA group + for i in range(1, max_groups + 1): + lc = left_count[i] + rc = right_count[i] - if rc > 0 and lc > 0: - count += lc * rc + if rc > 0 and lc > 0: + count += lc * rc # exclude the NA group left_pos = left_count[0] @@ -44,19 +45,20 @@ def inner_join(const int64_t[:] left, const int64_t[:] right, left_indexer = np.empty(count, dtype=np.int64) right_indexer = np.empty(count, dtype=np.int64) - for i in range(1, max_groups + 1): - lc = left_count[i] - rc = right_count[i] - - if rc > 0 and lc > 0: - for j in range(lc): - offset = position + j * rc - for k in range(rc): - left_indexer[offset + k] = left_pos + j - right_indexer[offset + k] = right_pos + k - position += lc * rc - left_pos += lc - right_pos += rc + with nogil: + for i in range(1, max_groups + 1): + lc = left_count[i] + rc = right_count[i] + + if rc > 0 and lc > 0: + for j in range(lc): + offset = position + j * rc + for k in range(rc): + left_indexer[offset + k] = left_pos + j + right_indexer[offset + k] = right_pos + k + position += lc * rc + left_pos += lc + right_pos += rc return (_get_result_indexer(left_sorter, left_indexer), _get_result_indexer(right_sorter, right_indexer)) @@ -79,12 +81,13 @@ def left_outer_join(const int64_t[:] left, const int64_t[:] right, left_sorter, left_count = groupsort_indexer(left, max_groups) right_sorter, right_count = groupsort_indexer(right, max_groups) - # First pass, determine size of result set, do not use the NA group - for i in range(1, max_groups + 1): - if right_count[i] > 0: - count += left_count[i] * right_count[i] - else: - count += left_count[i] + with nogil: + # First pass, determine size of result set, do not use the NA group + for i in range(1, max_groups + 1): + if right_count[i] > 0: + count += left_count[i] * right_count[i] + else: + count += left_count[i] # exclude the NA group left_pos = left_count[0] @@ -93,24 +96,25 @@ def left_outer_join(const int64_t[:] left, const int64_t[:] right, left_indexer = np.empty(count, dtype=np.int64) right_indexer = np.empty(count, dtype=np.int64) - for i in range(1, max_groups + 1): - lc = left_count[i] - rc = right_count[i] + with nogil: + for i in range(1, max_groups + 1): + lc = left_count[i] + rc = right_count[i] - if rc == 0: - for j in range(lc): - left_indexer[position + j] = left_pos + j - right_indexer[position + j] = -1 - position += lc - else: - for j in range(lc): - offset = position + j * rc - for k in range(rc): - left_indexer[offset + k] = left_pos + j - right_indexer[offset + k] = right_pos + k - position += lc * rc - left_pos += lc - right_pos += rc + if rc == 0: + for j in range(lc): + left_indexer[position + j] = left_pos + j + right_indexer[position + j] = -1 + position += lc + else: + for j in range(lc): + offset = position + j * rc + for k in range(rc): + left_indexer[offset + k] = left_pos + j + right_indexer[offset + k] = right_pos + k + position += lc * rc + left_pos += lc + right_pos += rc left_indexer = _get_result_indexer(left_sorter, left_indexer) right_indexer = _get_result_indexer(right_sorter, right_indexer) @@ -149,15 +153,16 @@ def full_outer_join(const int64_t[:] left, const int64_t[:] right, left_sorter, left_count = groupsort_indexer(left, max_groups) right_sorter, right_count = groupsort_indexer(right, max_groups) - # First pass, determine size of result set, do not use the NA group - for i in range(1, max_groups + 1): - lc = left_count[i] - rc = right_count[i] + with nogil: + # First pass, determine size of result set, do not use the NA group + for i in range(1, max_groups + 1): + lc = left_count[i] + rc = right_count[i] - if rc > 0 and lc > 0: - count += lc * rc - else: - count += lc + rc + if rc > 0 and lc > 0: + count += lc * rc + else: + count += lc + rc # exclude the NA group left_pos = left_count[0] @@ -166,29 +171,30 @@ def full_outer_join(const int64_t[:] left, const int64_t[:] right, left_indexer = np.empty(count, dtype=np.int64) right_indexer = np.empty(count, dtype=np.int64) - for i in range(1, max_groups + 1): - lc = left_count[i] - rc = right_count[i] - - if rc == 0: - for j in range(lc): - left_indexer[position + j] = left_pos + j - right_indexer[position + j] = -1 - position += lc - elif lc == 0: - for j in range(rc): - left_indexer[position + j] = -1 - right_indexer[position + j] = right_pos + j - position += rc - else: - for j in range(lc): - offset = position + j * rc - for k in range(rc): - left_indexer[offset + k] = left_pos + j - right_indexer[offset + k] = right_pos + k - position += lc * rc - left_pos += lc - right_pos += rc + with nogil: + for i in range(1, max_groups + 1): + lc = left_count[i] + rc = right_count[i] + + if rc == 0: + for j in range(lc): + left_indexer[position + j] = left_pos + j + right_indexer[position + j] = -1 + position += lc + elif lc == 0: + for j in range(rc): + left_indexer[position + j] = -1 + right_indexer[position + j] = right_pos + j + position += rc + else: + for j in range(lc): + offset = position + j * rc + for k in range(rc): + left_indexer[offset + k] = left_pos + j + right_indexer[offset + k] = right_pos + k + position += lc * rc + left_pos += lc + right_pos += rc return (_get_result_indexer(left_sorter, left_indexer), _get_result_indexer(right_sorter, right_indexer)) diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index a2096d389823f..d1adc7789a7a3 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -49,7 +49,7 @@ cdef inline int int_min(int a, int b): return a if a <= b else b # -def _check_minp(win, minp, N, floor=None): +def _check_minp(win, minp, N, floor=None) -> int: """ Parameters ---------- @@ -180,7 +180,8 @@ cdef class FixedWindowIndexer(WindowIndexer): def __init__(self, ndarray values, int64_t win, int64_t minp, bint left_closed, bint right_closed, object index=None, object floor=None): - cdef ndarray start_s, start_e, end_s, end_e + cdef: + ndarray[int64_t] start_s, start_e, end_s, end_e assert index is None self.is_variable = 0 @@ -298,7 +299,7 @@ cdef class VariableWindowIndexer(WindowIndexer): def get_window_indexer(values, win, minp, index, closed, floor=None, use_mock=True): """ - return the correct window indexer for the computation + Return the correct window indexer for the computation. Parameters ---------- @@ -319,7 +320,6 @@ def get_window_indexer(values, win, minp, index, closed, compat Indexer that allows us to use a standard code path with all of the indexers. - Returns ------- tuple of 1d int64 ndarrays of the offsets & data about the window @@ -365,7 +365,7 @@ def roll_count(ndarray[float64_t] values, int64_t win, int64_t minp, float64_t val, count_x = 0.0 int64_t s, e, nobs, N Py_ssize_t i, j - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output start, end, N, win, minp, _ = get_window_indexer(values, win, @@ -413,8 +413,7 @@ def roll_count(ndarray[float64_t] values, int64_t win, int64_t minp, # Rolling sum -cdef inline float64_t calc_sum(int64_t minp, int64_t nobs, - float64_t sum_x) nogil: +cdef inline float64_t calc_sum(int64_t minp, int64_t nobs, float64_t sum_x) nogil: cdef: float64_t result @@ -435,8 +434,7 @@ cdef inline void add_sum(float64_t val, int64_t *nobs, float64_t *sum_x) nogil: sum_x[0] = sum_x[0] + val -cdef inline void remove_sum(float64_t val, - int64_t *nobs, float64_t *sum_x) nogil: +cdef inline void remove_sum(float64_t val, int64_t *nobs, float64_t *sum_x) nogil: """ remove a value from the sum calc """ if notnan(val): @@ -451,7 +449,7 @@ def roll_sum(ndarray[float64_t] values, int64_t win, int64_t minp, int64_t s, e, range_endpoint int64_t nobs = 0, i, j, N bint is_variable - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output start, end, N, win, minp, is_variable = get_window_indexer(values, win, @@ -572,7 +570,7 @@ def roll_mean(ndarray[float64_t] values, int64_t win, int64_t minp, int64_t s, e bint is_variable Py_ssize_t nobs = 0, i, j, neg_ct = 0, N - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output start, end, N, win, minp, is_variable = get_window_indexer(values, win, @@ -709,7 +707,7 @@ def roll_var(ndarray[float64_t] values, int64_t win, int64_t minp, int64_t s, e bint is_variable Py_ssize_t i, j, N - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output start, end, N, win, minp, is_variable = get_window_indexer(values, win, @@ -871,7 +869,7 @@ def roll_skew(ndarray[float64_t] values, int64_t win, int64_t minp, int64_t nobs = 0, i, j, N int64_t s, e bint is_variable - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output start, end, N, win, minp, is_variable = get_window_indexer(values, win, @@ -1015,7 +1013,7 @@ def roll_kurt(ndarray[float64_t] values, int64_t win, int64_t minp, int64_t nobs = 0, i, j, N int64_t s, e bint is_variable - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output start, end, N, win, minp, is_variable = get_window_indexer(values, win, @@ -1088,7 +1086,7 @@ def roll_median_c(ndarray[float64_t] values, int64_t win, int64_t minp, Py_ssize_t i, j int64_t nobs = 0, N, s, e int midpoint - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output # we use the Fixed/Variable Indexer here as the @@ -1471,7 +1469,7 @@ def roll_quantile(ndarray[float64_t, cast=True] values, int64_t win, int64_t nobs = 0, i, j, s, e, N Py_ssize_t idx bint is_variable - ndarray[int64_t] start, end + int64_t[:] start, end ndarray[float64_t] output float64_t vlow, vhigh InterpolationType interpolation_type @@ -1589,7 +1587,7 @@ def roll_generic(object obj, float64_t *oldbuf int64_t nobs = 0, i, j, s, e, N bint is_variable - ndarray[int64_t] start, end + int64_t[:] start, end n = len(obj) if n == 0: @@ -1679,18 +1677,17 @@ def roll_generic(object obj, # Rolling sum and mean for weighted window -def roll_weighted_sum(float64_t[:] values, float64_t[:] weights, - int minp): +def roll_weighted_sum(float64_t[:] values, float64_t[:] weights, int minp): return _roll_weighted_sum_mean(values, weights, minp, avg=0) -def roll_weighted_mean(float64_t[:] values, float64_t[:] weights, - int minp): +def roll_weighted_mean(float64_t[:] values, float64_t[:] weights, int minp): return _roll_weighted_sum_mean(values, weights, minp, avg=1) -def _roll_weighted_sum_mean(float64_t[:] values, float64_t[:] weights, - int minp, bint avg): +cdef ndarray[float64_t] _roll_weighted_sum_mean(float64_t[:] values, + float64_t[:] weights, + int minp, bint avg): """ Assume len(weights) << len(values) """ @@ -1702,64 +1699,64 @@ def _roll_weighted_sum_mean(float64_t[:] values, float64_t[:] weights, in_n = len(values) win_n = len(weights) - output = np.zeros(in_n, dtype=float) - counts = np.zeros(in_n, dtype=float) + output = np.zeros(in_n, dtype=np.float64) + counts = np.zeros(in_n, dtype=np.float64) if avg: - tot_wgt = np.zeros(in_n, dtype=float) + tot_wgt = np.zeros(in_n, dtype=np.float64) minp = _check_minp(len(weights), minp, in_n) - if avg: - for win_i in range(win_n): - val_win = weights[win_i] - if val_win != val_win: - continue - - for in_i from 0 <= in_i < in_n - (win_n - win_i) + 1: - val_in = values[in_i] - if val_in == val_in: - output[in_i + (win_n - win_i) - 1] += val_in * val_win - counts[in_i + (win_n - win_i) - 1] += 1 - tot_wgt[in_i + (win_n - win_i) - 1] += val_win - - for in_i in range(in_n): - c = counts[in_i] - if c < minp: - output[in_i] = NaN - else: - w = tot_wgt[in_i] - if w == 0: + with nogil: + if avg: + for win_i in range(win_n): + val_win = weights[win_i] + if val_win != val_win: + continue + + for in_i in range(in_n - (win_n - win_i) + 1): + val_in = values[in_i] + if val_in == val_in: + output[in_i + (win_n - win_i) - 1] += val_in * val_win + counts[in_i + (win_n - win_i) - 1] += 1 + tot_wgt[in_i + (win_n - win_i) - 1] += val_win + + for in_i in range(in_n): + c = counts[in_i] + if c < minp: output[in_i] = NaN else: - output[in_i] /= tot_wgt[in_i] + w = tot_wgt[in_i] + if w == 0: + output[in_i] = NaN + else: + output[in_i] /= tot_wgt[in_i] - else: - for win_i in range(win_n): - val_win = weights[win_i] - if val_win != val_win: - continue + else: + for win_i in range(win_n): + val_win = weights[win_i] + if val_win != val_win: + continue - for in_i from 0 <= in_i < in_n - (win_n - win_i) + 1: - val_in = values[in_i] + for in_i in range(in_n - (win_n - win_i) + 1): + val_in = values[in_i] - if val_in == val_in: - output[in_i + (win_n - win_i) - 1] += val_in * val_win - counts[in_i + (win_n - win_i) - 1] += 1 + if val_in == val_in: + output[in_i + (win_n - win_i) - 1] += val_in * val_win + counts[in_i + (win_n - win_i) - 1] += 1 - for in_i in range(in_n): - c = counts[in_i] - if c < minp: - output[in_i] = NaN + for in_i in range(in_n): + c = counts[in_i] + if c < minp: + output[in_i] = NaN - return output + return np.asarray(output) # ---------------------------------------------------------------------- # Exponentially weighted moving average -def ewma(float64_t[:] vals, float64_t com, - int adjust, int ignore_na, int minp): +def ewma(float64_t[:] vals, float64_t com, int adjust, bint ignore_na, int minp): """ Compute exponentially-weighted moving average using center-of-mass. @@ -1768,12 +1765,12 @@ def ewma(float64_t[:] vals, float64_t com, vals : ndarray (float64 type) com : float64 adjust: int - ignore_na: int + ignore_na: bool minp: int Returns ------- - y : ndarray + ndarray """ cdef: @@ -1781,6 +1778,7 @@ def ewma(float64_t[:] vals, float64_t com, ndarray[float64_t] output = np.empty(N, dtype=float) float64_t alpha, old_wt_factor, new_wt, weighted_avg, old_wt, cur Py_ssize_t i, nobs + bint is_observation if N == 0: return output @@ -1797,29 +1795,30 @@ def ewma(float64_t[:] vals, float64_t com, output[0] = weighted_avg if (nobs >= minp) else NaN old_wt = 1. - for i in range(1, N): - cur = vals[i] - is_observation = (cur == cur) - nobs += int(is_observation) - if weighted_avg == weighted_avg: - - if is_observation or (not ignore_na): - - old_wt *= old_wt_factor - if is_observation: - - # avoid numerical errors on constant series - if weighted_avg != cur: - weighted_avg = ((old_wt * weighted_avg) + - (new_wt * cur)) / (old_wt + new_wt) - if adjust: - old_wt += new_wt - else: - old_wt = 1. - elif is_observation: - weighted_avg = cur + with nogil: + for i in range(1, N): + cur = vals[i] + is_observation = (cur == cur) + nobs += is_observation + if weighted_avg == weighted_avg: + + if is_observation or (not ignore_na): + + old_wt *= old_wt_factor + if is_observation: + + # avoid numerical errors on constant series + if weighted_avg != cur: + weighted_avg = ((old_wt * weighted_avg) + + (new_wt * cur)) / (old_wt + new_wt) + if adjust: + old_wt += new_wt + else: + old_wt = 1. + elif is_observation: + weighted_avg = cur - output[i] = weighted_avg if (nobs >= minp) else NaN + output[i] = weighted_avg if (nobs >= minp) else NaN return output @@ -1829,7 +1828,7 @@ def ewma(float64_t[:] vals, float64_t com, def ewmcov(float64_t[:] input_x, float64_t[:] input_y, - float64_t com, int adjust, int ignore_na, int minp, int bias): + float64_t com, int adjust, bint ignore_na, int minp, int bias): """ Compute exponentially-weighted moving variance using center-of-mass. @@ -1839,21 +1838,23 @@ def ewmcov(float64_t[:] input_x, float64_t[:] input_y, input_y : ndarray (float64 type) com : float64 adjust: int - ignore_na: int + ignore_na: bool minp: int bias: int Returns ------- - y : ndarray + ndarray """ cdef: Py_ssize_t N = len(input_x) float64_t alpha, old_wt_factor, new_wt, mean_x, mean_y, cov float64_t sum_wt, sum_wt2, old_wt, cur_x, cur_y, old_mean_x, old_mean_y + float64_t numerator, denominator Py_ssize_t i, nobs ndarray[float64_t] output + bint is_observation if <Py_ssize_t>len(input_y) != N: raise ValueError("arrays are of different lengths " @@ -1882,55 +1883,57 @@ def ewmcov(float64_t[:] input_x, float64_t[:] input_y, sum_wt2 = 1. old_wt = 1. - for i in range(1, N): - cur_x = input_x[i] - cur_y = input_y[i] - is_observation = ((cur_x == cur_x) and (cur_y == cur_y)) - nobs += int(is_observation) - if mean_x == mean_x: - if is_observation or (not ignore_na): - sum_wt *= old_wt_factor - sum_wt2 *= (old_wt_factor * old_wt_factor) - old_wt *= old_wt_factor - if is_observation: - old_mean_x = mean_x - old_mean_y = mean_y - - # avoid numerical errors on constant series - if mean_x != cur_x: - mean_x = ((old_wt * old_mean_x) + - (new_wt * cur_x)) / (old_wt + new_wt) - - # avoid numerical errors on constant series - if mean_y != cur_y: - mean_y = ((old_wt * old_mean_y) + - (new_wt * cur_y)) / (old_wt + new_wt) - cov = ((old_wt * (cov + ((old_mean_x - mean_x) * - (old_mean_y - mean_y)))) + - (new_wt * ((cur_x - mean_x) * - (cur_y - mean_y)))) / (old_wt + new_wt) - sum_wt += new_wt - sum_wt2 += (new_wt * new_wt) - old_wt += new_wt - if not adjust: - sum_wt /= old_wt - sum_wt2 /= (old_wt * old_wt) - old_wt = 1. - elif is_observation: - mean_x = cur_x - mean_y = cur_y + with nogil: - if nobs >= minp: - if not bias: - numerator = sum_wt * sum_wt - denominator = numerator - sum_wt2 - if (denominator > 0.): - output[i] = ((numerator / denominator) * cov) + for i in range(1, N): + cur_x = input_x[i] + cur_y = input_y[i] + is_observation = ((cur_x == cur_x) and (cur_y == cur_y)) + nobs += is_observation + if mean_x == mean_x: + if is_observation or (not ignore_na): + sum_wt *= old_wt_factor + sum_wt2 *= (old_wt_factor * old_wt_factor) + old_wt *= old_wt_factor + if is_observation: + old_mean_x = mean_x + old_mean_y = mean_y + + # avoid numerical errors on constant series + if mean_x != cur_x: + mean_x = ((old_wt * old_mean_x) + + (new_wt * cur_x)) / (old_wt + new_wt) + + # avoid numerical errors on constant series + if mean_y != cur_y: + mean_y = ((old_wt * old_mean_y) + + (new_wt * cur_y)) / (old_wt + new_wt) + cov = ((old_wt * (cov + ((old_mean_x - mean_x) * + (old_mean_y - mean_y)))) + + (new_wt * ((cur_x - mean_x) * + (cur_y - mean_y)))) / (old_wt + new_wt) + sum_wt += new_wt + sum_wt2 += (new_wt * new_wt) + old_wt += new_wt + if not adjust: + sum_wt /= old_wt + sum_wt2 /= (old_wt * old_wt) + old_wt = 1. + elif is_observation: + mean_x = cur_x + mean_y = cur_y + + if nobs >= minp: + if not bias: + numerator = sum_wt * sum_wt + denominator = numerator - sum_wt2 + if (denominator > 0.): + output[i] = ((numerator / denominator) * cov) + else: + output[i] = NaN else: - output[i] = NaN + output[i] = cov else: - output[i] = cov - else: - output[i] = NaN + output[i] = NaN return output
cc @mroeschke since a lot of this touches libwindow
https://api.github.com/repos/pandas-dev/pandas/pulls/29322
2019-11-01T16:58:09Z
2019-11-04T14:59:30Z
2019-11-04T14:59:30Z
2019-11-04T15:01:32Z
CLN: Consistent imports - linting rules
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index f704a1018c926..07c99b39e83e8 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -120,9 +120,15 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then # Check for imports from pandas.core.common instead of `import pandas.core.common as com` # Check for imports from collections.abc instead of `from collections import abc` MSG='Check for non-standard imports' ; echo $MSG - invgrep -R --include="*.py*" -E "from pandas.core.common import " pandas - invgrep -R --include="*.py*" -E "from collections.abc import " pandas - invgrep -R --include="*.py*" -E "from numpy import nan " pandas + invgrep -R --include="*.py*" -E "from pandas.core.common import" pandas + invgrep -R --include="*.py*" -E "from pandas.core import common" pandas + invgrep -R --include="*.py*" -E "from collections.abc import" pandas + invgrep -R --include="*.py*" -E "from numpy import nan" pandas + + # Checks for test suite + # Check for imports from pandas.util.testing instead of `import pandas.util.testing as tm` + invgrep -R --include="*.py*" -E "from pandas.util.testing import" pandas/tests + invgrep -R --include="*.py*" -E "from pandas.util import testing as tm" pandas/tests RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Check for use of exec' ; echo $MSG diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 98a090ef26f2a..c70e623778315 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -46,7 +46,7 @@ from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries from pandas.core.dtypes.missing import isna, na_value_for_dtype -from pandas.core import common as com +import pandas.core.common as com from pandas.core.construction import array, extract_array from pandas.core.indexers import validate_indices diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 45319a4d63d94..72367c8fb7a4f 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -12,7 +12,7 @@ import numpy as np import pandas as pd -from pandas.core import common as com +import pandas.core.common as com from pandas.core.computation.common import ( _BACKTICK_QUOTED_STRING, _remove_spaces_column_name, diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index a20290e77023a..a0f16789621c7 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -20,11 +20,11 @@ pandas_dtype, ) -from pandas.core import common as com from pandas.core.accessor import delegate_names from pandas.core.algorithms import unique1d from pandas.core.arrays.period import PeriodArray, period_array, validate_dtype_freq from pandas.core.base import _shared_docs +import pandas.core.common as com import pandas.core.indexes.base as ibase from pandas.core.indexes.base import _index_shared_docs, ensure_index from pandas.core.indexes.datetimelike import ( diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 60bab817705e3..bbf41fc28e9d2 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -7,11 +7,11 @@ import numpy as np from pandas import DataFrame, Index, MultiIndex, Series -from pandas.core import common as com from pandas.core.arrays.categorical import ( _factorize_from_iterable, _factorize_from_iterables, ) +import pandas.core.common as com from pandas.core.generic import NDFrame from pandas.core.index import ( _all_indexes_same, diff --git a/pandas/core/reshape/util.py b/pandas/core/reshape/util.py index 044e058904dce..d8652c9b4fac9 100644 --- a/pandas/core/reshape/util.py +++ b/pandas/core/reshape/util.py @@ -2,7 +2,7 @@ from pandas.core.dtypes.common import is_list_like -from pandas.core import common as com +import pandas.core.common as com def cartesian_product(X): diff --git a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py index 3183721eeb54f..e0206c8e7f6aa 100644 --- a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py +++ b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py @@ -2,7 +2,7 @@ import pytest from pandas import DataFrame, MultiIndex, Series -from pandas.core import common as com +import pandas.core.common as com import pandas.util.testing as tm diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index bd106ba9c36f1..274b72b0561a9 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import DataFrame, Series, Timestamp, date_range, option_context -from pandas.core import common as com +import pandas.core.common as com import pandas.util.testing as tm diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 65b2dab1b02a8..a8a0fcea7182c 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -8,7 +8,8 @@ import pandas as pd from pandas import Series, Timestamp -from pandas.core import common as com, ops +from pandas.core import ops +import pandas.core.common as com def test_get_callable_name(): diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py index 32aeb7b186827..b86aaa0ed7e1f 100644 --- a/pandas/tests/test_sorting.py +++ b/pandas/tests/test_sorting.py @@ -6,7 +6,7 @@ import pytest from pandas import DataFrame, MultiIndex, Series, array, concat, merge -from pandas.core import common as com +import pandas.core.common as com from pandas.core.sorting import ( decons_group_index, get_group_index,
- [x] closes #29272 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29318
2019-11-01T08:22:31Z
2019-11-01T14:50:59Z
2019-11-01T14:50:59Z
2019-11-01T14:51:04Z
fix bugs cause replacer's dtype not respected
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 98d861d999ea9..bfc5cac7339ca 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -466,6 +466,7 @@ Reshaping - Better error message in :func:`get_dummies` when `columns` isn't a list-like value (:issue:`28383`) - Bug :meth:`Series.pct_change` where supplying an anchored frequency would throw a ValueError (:issue:`28664`) - Bug where :meth:`DataFrame.equals` returned True incorrectly in some cases when two DataFrames had the same columns in different orders (:issue:`28839`) +- Bug in :meth:`DataFrame.replace` that caused non-numeric replacer's dtype not respected (:issue:`26632`) Sparse ^^^^^^ diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 7ace80415c846..5edb4d93e068a 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2825,6 +2825,8 @@ def _replace_coerce( if convert: block = [b.convert(numeric=False, copy=True) for b in block] return block + if convert: + return [self.convert(numeric=False, copy=True)] return self diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 0e6ba8a2c2a6a..c36dd9463c61d 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -629,7 +629,7 @@ def comp(s, regex=False): convert=convert, regex=regex, ) - if m.any(): + if m.any() or convert: new_rb = _extend_blocks(result, new_rb) else: new_rb.append(b) diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index 60b601b57e007..434ea6ea7b4f0 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -1338,5 +1338,21 @@ def test_replace_commutative(self, df, to_replace, exp): expected = pd.DataFrame(exp) result = df.replace(to_replace) + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "replacer", + [ + pd.Timestamp("20170827"), + np.int8(1), + np.int16(1), + np.float32(1), + np.float64(1), + ], + ) + def test_replace_replacer_dtype(self, replacer): + # GH26632 + df = pd.DataFrame(["a"]) + result = df.replace({"a": replacer, "b": replacer}) + expected = pd.DataFrame([replacer]) tm.assert_frame_equal(result, expected)
- [x] closes #26632 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29317
2019-11-01T07:40:33Z
2019-11-20T05:13:38Z
2019-11-20T05:13:38Z
2019-11-20T05:26:02Z
CLN: assorted cleanups
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 30c9af645da22..e3c7fef6f048f 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -379,13 +379,26 @@ ctypedef fused algos_t: uint8_t +def _validate_limit(nobs: int, limit=None) -> int: + if limit is None: + lim = nobs + else: + if not util.is_integer_object(limit): + raise ValueError('Limit must be an integer') + if limit < 1: + raise ValueError('Limit must be greater than 0') + lim = limit + + return lim + + @cython.boundscheck(False) @cython.wraparound(False) def pad(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): cdef: Py_ssize_t i, j, nleft, nright ndarray[int64_t, ndim=1] indexer - algos_t cur, next + algos_t cur, next_val int lim, fill_count = 0 nleft = len(old) @@ -393,14 +406,7 @@ def pad(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): indexer = np.empty(nright, dtype=np.int64) indexer[:] = -1 - if limit is None: - lim = nright - else: - if not util.is_integer_object(limit): - raise ValueError('Limit must be an integer') - if limit < 1: - raise ValueError('Limit must be greater than 0') - lim = limit + lim = _validate_limit(nright, limit) if nleft == 0 or nright == 0 or new[nright - 1] < old[0]: return indexer @@ -426,9 +432,9 @@ def pad(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): j += 1 break - next = old[i + 1] + next_val = old[i + 1] - while j < nright and cur <= new[j] < next: + while j < nright and cur <= new[j] < next_val: if new[j] == cur: indexer[j] = i elif fill_count < lim: @@ -438,16 +444,14 @@ def pad(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): fill_count = 0 i += 1 - cur = next + cur = next_val return indexer @cython.boundscheck(False) @cython.wraparound(False) -def pad_inplace(algos_t[:] values, - const uint8_t[:] mask, - limit=None): +def pad_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): cdef: Py_ssize_t i, N algos_t val @@ -459,14 +463,7 @@ def pad_inplace(algos_t[:] values, if N == 0: return - if limit is None: - lim = N - else: - if not util.is_integer_object(limit): - raise ValueError('Limit must be an integer') - if limit < 1: - raise ValueError('Limit must be greater than 0') - lim = limit + lim = _validate_limit(N, limit) val = values[0] for i in range(N): @@ -482,9 +479,7 @@ def pad_inplace(algos_t[:] values, @cython.boundscheck(False) @cython.wraparound(False) -def pad_2d_inplace(algos_t[:, :] values, - const uint8_t[:, :] mask, - limit=None): +def pad_2d_inplace(algos_t[:, :] values, const uint8_t[:, :] mask, limit=None): cdef: Py_ssize_t i, j, N, K algos_t val @@ -496,14 +491,7 @@ def pad_2d_inplace(algos_t[:, :] values, if N == 0: return - if limit is None: - lim = N - else: - if not util.is_integer_object(limit): - raise ValueError('Limit must be an integer') - if limit < 1: - raise ValueError('Limit must be greater than 0') - lim = limit + lim = _validate_limit(N, limit) for j in range(K): fill_count = 0 @@ -559,14 +547,7 @@ def backfill(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): indexer = np.empty(nright, dtype=np.int64) indexer[:] = -1 - if limit is None: - lim = nright - else: - if not util.is_integer_object(limit): - raise ValueError('Limit must be an integer') - if limit < 1: - raise ValueError('Limit must be greater than 0') - lim = limit + lim = _validate_limit(nright, limit) if nleft == 0 or nright == 0 or new[0] > old[nleft - 1]: return indexer @@ -612,9 +593,7 @@ def backfill(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): @cython.boundscheck(False) @cython.wraparound(False) -def backfill_inplace(algos_t[:] values, - const uint8_t[:] mask, - limit=None): +def backfill_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): cdef: Py_ssize_t i, N algos_t val @@ -626,14 +605,7 @@ def backfill_inplace(algos_t[:] values, if N == 0: return - if limit is None: - lim = N - else: - if not util.is_integer_object(limit): - raise ValueError('Limit must be an integer') - if limit < 1: - raise ValueError('Limit must be greater than 0') - lim = limit + lim = _validate_limit(N, limit) val = values[N - 1] for i in range(N - 1, -1, -1): @@ -663,14 +635,7 @@ def backfill_2d_inplace(algos_t[:, :] values, if N == 0: return - if limit is None: - lim = N - else: - if not util.is_integer_object(limit): - raise ValueError('Limit must be an integer') - if limit < 1: - raise ValueError('Limit must be greater than 0') - lim = limit + lim = _validate_limit(N, limit) for j in range(K): fill_count = 0 diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in index c3b0a84067f92..6211734706e37 100644 --- a/pandas/_libs/algos_common_helper.pxi.in +++ b/pandas/_libs/algos_common_helper.pxi.in @@ -23,7 +23,7 @@ def diff_2d(ndarray[diff_t, ndim=2] arr, ndarray[out_t, ndim=2] out, Py_ssize_t periods, int axis): cdef: - Py_ssize_t i, j, sx, sy + Py_ssize_t i, j, sx, sy, start, stop # Disable for unsupported dtype combinations, # see https://github.com/cython/cython/issues/2646 diff --git a/pandas/_libs/groupby.pxd b/pandas/_libs/groupby.pxd deleted file mode 100644 index 70ad8a62871e9..0000000000000 --- a/pandas/_libs/groupby.pxd +++ /dev/null @@ -1,6 +0,0 @@ -cdef enum InterpolationEnumType: - INTERPOLATION_LINEAR, - INTERPOLATION_LOWER, - INTERPOLATION_HIGHER, - INTERPOLATION_NEAREST, - INTERPOLATION_MIDPOINT diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 49a335218db96..0e5eaa3b7dca6 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -27,6 +27,13 @@ _int64_max = np.iinfo(np.int64).max cdef float64_t NaN = <float64_t>np.NaN +cdef enum InterpolationEnumType: + INTERPOLATION_LINEAR, + INTERPOLATION_LOWER, + INTERPOLATION_HIGHER, + INTERPOLATION_NEAREST, + INTERPOLATION_MIDPOINT + cdef inline float64_t median_linear(float64_t* a, int n) nogil: cdef: diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index eddc0beae7b8b..328b67b6722f1 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -698,8 +698,7 @@ def generate_bins_dt64(ndarray[int64_t] values, const int64_t[:] binner, @cython.boundscheck(False) @cython.wraparound(False) -def get_level_sorter(const int64_t[:] label, - const int64_t[:] starts): +def get_level_sorter(const int64_t[:] label, const int64_t[:] starts): """ argsort for a single level of a multi-index, keeping the order of higher levels unchanged. `starts` points to starts of same-key indices w.r.t @@ -1677,6 +1676,7 @@ cpdef bint is_datetime64_array(ndarray values): return validator.validate(values) +# TODO: only non-here use is in test def is_datetime_with_singletz_array(values: ndarray) -> bool: """ Check values have the same tzinfo attribute. @@ -1720,6 +1720,7 @@ cdef class AnyTimedeltaValidator(TimedeltaValidator): return is_timedelta(value) +# TODO: only non-here use is in test cpdef bint is_timedelta_or_timedelta64_array(ndarray values): """ infer with timedeltas and/or nat/none """ cdef: diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 3f12ec4c15fc7..8b9842ba087a5 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -278,7 +278,7 @@ cdef class TextReader: object true_values, false_values object handle bint na_filter, keep_default_na, verbose, has_usecols, has_mi_columns - int64_t parser_start + uint64_t parser_start list clocks char *c_encoding kh_str_starts_t *false_set @@ -710,11 +710,11 @@ cdef class TextReader: # header is now a list of lists, so field_count should use header[0] cdef: - Py_ssize_t i, start, field_count, passed_count, unnamed_count # noqa + Py_ssize_t i, start, field_count, passed_count, unnamed_count char *word object name, old_name int status - int64_t hr, data_line + uint64_t hr, data_line char *errors = "strict" StringPath path = _string_path(self.c_encoding) @@ -1015,12 +1015,14 @@ cdef class TextReader: else: end = min(start + rows, self.parser.lines) + # FIXME: dont leave commented-out # # skip footer # if footer > 0: # end -= footer num_cols = -1 - for i in range(self.parser.lines): + # Py_ssize_t cast prevents build warning + for i in range(<Py_ssize_t>self.parser.lines): num_cols = (num_cols < self.parser.line_fields[i]) * \ self.parser.line_fields[i] + \ (num_cols >= self.parser.line_fields[i]) * num_cols diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index f505c0479e944..45991293ba5bc 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -45,8 +45,7 @@ cdef class Reducer: Py_ssize_t increment, chunksize, nresults object arr, dummy, f, labels, typ, ityp, index - def __init__(self, object arr, object f, axis=1, dummy=None, - labels=None): + def __init__(self, object arr, object f, axis=1, dummy=None, labels=None): n, k = arr.shape if axis == 0: @@ -70,8 +69,9 @@ cdef class Reducer: self.dummy, self.typ, self.index, self.ityp = self._check_dummy( dummy=dummy) - def _check_dummy(self, dummy=None): - cdef object index=None, typ=None, ityp=None + cdef _check_dummy(self, dummy=None): + cdef: + object index = None, typ = None, ityp = None if dummy is None: dummy = np.empty(self.chunksize, dtype=self.arr.dtype) @@ -92,8 +92,8 @@ cdef class Reducer: if dummy.dtype != self.arr.dtype: raise ValueError('Dummy array must be same dtype') if len(dummy) != self.chunksize: - raise ValueError('Dummy array must be length %d' % - self.chunksize) + raise ValueError('Dummy array must be length {length}' + .format(length=self.chunksize)) return dummy, typ, index, ityp @@ -190,7 +190,6 @@ cdef class SeriesBinGrouper: """ cdef: Py_ssize_t nresults, ngroups - bint passed_dummy cdef public: object arr, index, dummy_arr, dummy_index @@ -199,6 +198,8 @@ cdef class SeriesBinGrouper: def __init__(self, object series, object f, object bins, object dummy): n = len(series) + assert dummy is not None # always obj[:0] + self.bins = bins self.f = f @@ -213,7 +214,6 @@ cdef class SeriesBinGrouper: self.name = getattr(series, 'name', None) self.dummy_arr, self.dummy_index = self._check_dummy(dummy) - self.passed_dummy = dummy is not None # kludge for #1688 if len(bins) > 0 and bins[-1] == len(series): @@ -221,22 +221,18 @@ cdef class SeriesBinGrouper: else: self.ngroups = len(bins) + 1 - def _check_dummy(self, dummy=None): + cdef _check_dummy(self, dummy): # both values and index must be an ndarray! - if dummy is None: - values = np.empty(0, dtype=self.arr.dtype) - index = None - else: - values = dummy.values - if values.dtype != self.arr.dtype: - raise ValueError('Dummy array must be same dtype') - if util.is_array(values) and not values.flags.contiguous: - # e.g. Categorical has no `flags` attribute - values = values.copy() - index = dummy.index.values - if not index.flags.contiguous: - index = index.copy() + values = dummy.values + if values.dtype != self.arr.dtype: + raise ValueError('Dummy array must be same dtype') + if util.is_array(values) and not values.flags.contiguous: + # e.g. Categorical has no `flags` attribute + values = values.copy() + index = dummy.index.values + if not index.flags.contiguous: + index = index.copy() return values, index @@ -320,7 +316,6 @@ cdef class SeriesGrouper: """ cdef: Py_ssize_t nresults, ngroups - bint passed_dummy cdef public: object arr, index, dummy_arr, dummy_index @@ -330,6 +325,10 @@ cdef class SeriesGrouper: Py_ssize_t ngroups, object dummy): n = len(series) + # in practice we always pass either obj[:0] or the + # safer obj._get_values(slice(None, 0)) + assert dummy is not None + self.labels = labels self.f = f @@ -344,27 +343,22 @@ cdef class SeriesGrouper: self.name = getattr(series, 'name', None) self.dummy_arr, self.dummy_index = self._check_dummy(dummy) - self.passed_dummy = dummy is not None self.ngroups = ngroups - def _check_dummy(self, dummy=None): + cdef _check_dummy(self, dummy): # both values and index must be an ndarray! - if dummy is None: - values = np.empty(0, dtype=self.arr.dtype) - index = None - else: - values = dummy.values - # GH 23683: datetimetz types are equivalent to datetime types here - if (dummy.dtype != self.arr.dtype - and values.dtype != self.arr.dtype): - raise ValueError('Dummy array must be same dtype') - if util.is_array(values) and not values.flags.contiguous: - # e.g. Categorical has no `flags` attribute - values = values.copy() - index = dummy.index.values - if not index.flags.contiguous: - index = index.copy() + values = dummy.values + # GH 23683: datetimetz types are equivalent to datetime types here + if (dummy.dtype != self.arr.dtype + and values.dtype != self.arr.dtype): + raise ValueError('Dummy array must be same dtype') + if util.is_array(values) and not values.flags.contiguous: + # e.g. Categorical has no `flags` attribute + values = values.copy() + index = dummy.index.values + if not index.flags.contiguous: + index = index.copy() return values, index @@ -377,7 +371,7 @@ cdef class SeriesGrouper: object res bint initialized = 0 Slider vslider, islider - object name, cached_typ=None, cached_ityp=None + object name, cached_typ = None, cached_ityp = None labels = self.labels counts = np.zeros(self.ngroups, dtype=np.int64) @@ -489,7 +483,7 @@ cdef class Slider: self.buf.data = self.values.data self.buf.strides[0] = self.stride - cpdef advance(self, Py_ssize_t k): + cdef advance(self, Py_ssize_t k): self.buf.data = <char*>self.buf.data + self.stride * k cdef move(self, int start, int end): @@ -499,10 +493,10 @@ cdef class Slider: self.buf.data = self.values.data + self.stride * start self.buf.shape[0] = end - start - cpdef set_length(self, Py_ssize_t length): + cdef set_length(self, Py_ssize_t length): self.buf.shape[0] = length - cpdef reset(self): + cdef reset(self): self.buf.shape[0] = self.orig_len self.buf.data = self.orig_data @@ -607,10 +601,10 @@ cdef class BlockSlider: def __dealloc__(self): free(self.base_ptrs) - cpdef move(self, int start, int end): + cdef move(self, int start, int end): cdef: ndarray arr - object index + Py_ssize_t i # move blocks for i in range(self.nblocks): @@ -629,6 +623,7 @@ cdef class BlockSlider: cdef reset(self): cdef: ndarray arr + Py_ssize_t i # reset blocks for i in range(self.nblocks): diff --git a/pandas/_libs/skiplist.pyx b/pandas/_libs/skiplist.pyx deleted file mode 100644 index eb750a478415a..0000000000000 --- a/pandas/_libs/skiplist.pyx +++ /dev/null @@ -1,7 +0,0 @@ -# Cython version of IndexableSkiplist, for implementing moving median -# with O(log n) updates -# Original author: Raymond Hettinger -# Original license: MIT -# Link: http://code.activestate.com/recipes/576930/ - -# Cython version: Wes McKinney diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index a82d5e3b58e5e..0588dfe20e2e2 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -58,7 +58,8 @@ HOUR_SECONDS = 3600 @cython.wraparound(False) @cython.boundscheck(False) cpdef int32_t get_days_in_month(int year, Py_ssize_t month) nogil: - """Return the number of days in the given month of the given year. + """ + Return the number of days in the given month of the given year. Parameters ---------- @@ -81,7 +82,8 @@ cpdef int32_t get_days_in_month(int year, Py_ssize_t month) nogil: @cython.boundscheck(False) @cython.cdivision cdef int dayofweek(int y, int m, int d) nogil: - """Find the day of week for the date described by the Y/M/D triple y, m, d + """ + Find the day of week for the date described by the Y/M/D triple y, m, d using Sakamoto's method, from wikipedia. 0 represents Monday. See [1]_. @@ -117,7 +119,8 @@ cdef int dayofweek(int y, int m, int d) nogil: cdef bint is_leapyear(int64_t year) nogil: - """Returns 1 if the given year is a leap year, 0 otherwise. + """ + Returns 1 if the given year is a leap year, 0 otherwise. Parameters ---------- @@ -134,7 +137,8 @@ cdef bint is_leapyear(int64_t year) nogil: @cython.wraparound(False) @cython.boundscheck(False) cpdef int32_t get_week_of_year(int year, int month, int day) nogil: - """Return the ordinal week-of-year for the given day. + """ + Return the ordinal week-of-year for the given day. Parameters ---------- @@ -178,7 +182,8 @@ cpdef int32_t get_week_of_year(int year, int month, int day) nogil: @cython.wraparound(False) @cython.boundscheck(False) cpdef int32_t get_day_of_year(int year, int month, int day) nogil: - """Return the ordinal day-of-year for the given day. + """ + Return the ordinal day-of-year for the given day. Parameters ---------- @@ -207,8 +212,9 @@ cpdef int32_t get_day_of_year(int year, int month, int day) nogil: return day_of_year -def get_locale_names(name_type: object, locale: object=None): - """Returns an array of localized day or month names +def get_locale_names(name_type: str, locale: object = None): + """ + Returns an array of localized day or month names. Parameters ---------- diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 98a090ef26f2a..c117cf1b07b85 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1881,8 +1881,9 @@ def diff(arr, n: int, axis: int = 0): out_arr[tuple(na_indexer)] = na if arr.ndim == 2 and arr.dtype.name in _diff_special: - f = algos.diff_2d - f(arr, out_arr, n, axis) + # TODO: can diff_2d dtype specialization troubles be fixed by defining + # out_arr inside diff_2d? + algos.diff_2d(arr, out_arr, n, axis) else: # To keep mypy happy, _res_indexer is a list while res_indexer is # a tuple, ditto for lag_indexer. diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index f4c3ac970a3ca..996c178bd7feb 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -7,7 +7,6 @@ """ from collections import OrderedDict, abc, namedtuple import copy -import functools from functools import partial from textwrap import dedent import typing @@ -1689,8 +1688,10 @@ def count(self): ) loc = (blk.mgr_locs for blk in data.blocks) - counter = partial(lib.count_level_2d, labels=ids, max_bin=ngroups, axis=1) - blk = map(make_block, map(counter, val), loc) + counted = [ + lib.count_level_2d(x, labels=ids, max_bin=ngroups, axis=1) for x in val + ] + blk = map(make_block, counted, loc) return self._wrap_agged_blocks(data.items, list(blk)) @@ -1900,7 +1901,7 @@ def _managle_lambda_list(aggfuncs: Sequence[Any]) -> Sequence[Any]: mangled_aggfuncs = [] for aggfunc in aggfuncs: if com.get_callable_name(aggfunc) == "<lambda>": - aggfunc = functools.partial(aggfunc) + aggfunc = partial(aggfunc) aggfunc.__name__ = "<lambda_{}>".format(i) i += 1 mangled_aggfuncs.append(aggfunc) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 2a7fd079679a4..17db4577f344b 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -514,7 +514,6 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): result = result[:, 0] if how in self._name_functions: - # TODO names = self._name_functions[how]() else: names = None @@ -698,7 +697,7 @@ def _get_grouper(self): """ return self - def get_iterator(self, data, axis=0): + def get_iterator(self, data: NDFrame, axis: int = 0): """ Groupby iterator @@ -707,12 +706,8 @@ def get_iterator(self, data, axis=0): Generator yielding sequence of (name, subsetted object) for each group """ - if isinstance(data, NDFrame): - slicer = lambda start, edge: data._slice(slice(start, edge), axis=axis) - length = len(data.axes[axis]) - else: - slicer = lambda start, edge: data[slice(start, edge)] - length = len(data) + slicer = lambda start, edge: data._slice(slice(start, edge), axis=axis) + length = len(data.axes[axis]) start = 0 for edge, label in zip(self.bins, self.binlabels): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index c47aaf7c773c4..21ae820cfcee6 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1276,7 +1276,6 @@ def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): Returns ------- new_blocks : list of Block - """ allow_fill = fill_tuple is not None diff --git a/pandas/core/strings.py b/pandas/core/strings.py index fcbb000acc256..f1a67d0892cad 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -123,8 +123,8 @@ def _map(f, arr, na_mask=False, na_value=np.nan, dtype=object): arr = np.asarray(arr, dtype=object) if na_mask: mask = isna(arr) + convert = not np.all(mask) try: - convert = not all(mask) result = lib.map_infer_mask(arr, f, mask.view(np.uint8), convert) except (TypeError, AttributeError) as e: # Reraise the exception if callable `f` got wrong number of args. @@ -135,6 +135,7 @@ def _map(f, arr, na_mask=False, na_value=np.nan, dtype=object): ) if len(e.args) >= 1 and re.search(p_err, e.args[0]): + # FIXME: this should be totally avoidable raise e def g(x): diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index fddbea8ed0d7a..011ea1b8e42f2 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -58,7 +58,7 @@ def hash_pandas_object( obj, index: bool = True, encoding: str = "utf8", - hash_key=None, + hash_key: str = _default_hash_key, categorize: bool = True, ): """ @@ -70,7 +70,7 @@ def hash_pandas_object( include the index in the hash (if Series/DataFrame) encoding : str, default 'utf8' encoding for data & key when strings - hash_key : str, default '_default_hash_key' + hash_key : str, default _default_hash_key hash_key for string key to encode categorize : bool, default True Whether to first categorize object arrays before hashing. This is more @@ -82,9 +82,6 @@ def hash_pandas_object( """ from pandas import Series - if hash_key is None: - hash_key = _default_hash_key - if isinstance(obj, ABCMultiIndex): return Series(hash_tuples(obj, encoding, hash_key), dtype="uint64", copy=False) @@ -140,7 +137,7 @@ def hash_pandas_object( return h -def hash_tuples(vals, encoding="utf8", hash_key=None): +def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key): """ Hash an MultiIndex / list-of-tuples efficiently @@ -148,7 +145,7 @@ def hash_tuples(vals, encoding="utf8", hash_key=None): ---------- vals : MultiIndex, list-of-tuples, or single tuple encoding : str, default 'utf8' - hash_key : str, default '_default_hash_key' + hash_key : str, default _default_hash_key Returns ------- @@ -183,7 +180,7 @@ def hash_tuples(vals, encoding="utf8", hash_key=None): return h -def hash_tuple(val, encoding: str = "utf8", hash_key=None): +def hash_tuple(val, encoding: str = "utf8", hash_key: str = _default_hash_key): """ Hash a single tuple efficiently @@ -191,7 +188,7 @@ def hash_tuple(val, encoding: str = "utf8", hash_key=None): ---------- val : single tuple encoding : str, default 'utf8' - hash_key : str, default '_default_hash_key' + hash_key : str, default _default_hash_key Returns ------- @@ -213,8 +210,8 @@ def _hash_categorical(c, encoding: str, hash_key: str): Parameters ---------- c : Categorical - encoding : str, default 'utf8' - hash_key : str, default '_default_hash_key' + encoding : str + hash_key : str Returns ------- @@ -243,7 +240,12 @@ def _hash_categorical(c, encoding: str, hash_key: str): return result -def hash_array(vals, encoding: str = "utf8", hash_key=None, categorize: bool = True): +def hash_array( + vals, + encoding: str = "utf8", + hash_key: str = _default_hash_key, + categorize: bool = True, +): """ Given a 1d array, return an array of deterministic integers. @@ -252,7 +254,7 @@ def hash_array(vals, encoding: str = "utf8", hash_key=None, categorize: bool = T vals : ndarray, Categorical encoding : str, default 'utf8' encoding for data & key when strings - hash_key : str, default '_default_hash_key' + hash_key : str, default _default_hash_key hash_key for string key to encode categorize : bool, default True Whether to first categorize object arrays before hashing. This is more @@ -267,9 +269,6 @@ def hash_array(vals, encoding: str = "utf8", hash_key=None, categorize: bool = T raise TypeError("must pass a ndarray-like") dtype = vals.dtype - if hash_key is None: - hash_key = _default_hash_key - # For categoricals, we hash the categories, then remap the codes to the # hash values. (This check is above the complex check so that we don't ask # numpy if categorical is a subdtype of complex, as it will choke). @@ -320,9 +319,17 @@ def hash_array(vals, encoding: str = "utf8", hash_key=None, categorize: bool = T return vals -def _hash_scalar(val, encoding: str = "utf8", hash_key=None): +def _hash_scalar( + val, encoding: str = "utf8", hash_key: str = _default_hash_key +) -> np.ndarray: """ - Hash scalar value + Hash scalar value. + + Parameters + ---------- + val : scalar + encoding : str, default "utf8" + hash_key : str, default _default_hash_key Returns ------- diff --git a/setup.py b/setup.py index 0dd1980088db8..c75ad5896a439 100755 --- a/setup.py +++ b/setup.py @@ -330,7 +330,6 @@ class CheckSDist(sdist_class): "pandas/_libs/missing.pyx", "pandas/_libs/reduction.pyx", "pandas/_libs/testing.pyx", - "pandas/_libs/skiplist.pyx", "pandas/_libs/sparse.pyx", "pandas/_libs/ops.pyx", "pandas/_libs/parsers.pyx", @@ -604,10 +603,6 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "_libs.ops": {"pyxfile": "_libs/ops"}, "_libs.properties": {"pyxfile": "_libs/properties", "include": []}, "_libs.reshape": {"pyxfile": "_libs/reshape", "depends": []}, - "_libs.skiplist": { - "pyxfile": "_libs/skiplist", - "depends": ["pandas/_libs/src/skiplist.h"], - }, "_libs.sparse": {"pyxfile": "_libs/sparse", "depends": _pxi_dep["sparse"]}, "_libs.tslib": { "pyxfile": "_libs/tslib",
https://api.github.com/repos/pandas-dev/pandas/pulls/29314
2019-11-01T00:06:31Z
2019-11-02T15:16:18Z
2019-11-02T15:16:18Z
2019-11-02T15:30:35Z
Backports for 0.25.3
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index 6cfda147da312..fde778449751a 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -16,6 +16,7 @@ Version 0.25 .. toctree:: :maxdepth: 2 + v0.25.3 v0.25.2 v0.25.1 v0.25.0 diff --git a/doc/source/whatsnew/v0.25.3.rst b/doc/source/whatsnew/v0.25.3.rst new file mode 100644 index 0000000000000..f73a3f956f42e --- /dev/null +++ b/doc/source/whatsnew/v0.25.3.rst @@ -0,0 +1,22 @@ +.. _whatsnew_0253: + +What's new in 0.25.3 (October 31, 2019) +--------------------------------------- + +These are the changes in pandas 0.25.3. See :ref:`release` for a full changelog +including other versions of pandas. + +.. _whatsnew_0253.bug_fixes: + +Bug fixes +~~~~~~~~~ + +Groupby/resample/rolling +^^^^^^^^^^^^^^^^^^^^^^^^ + +- Bug in :meth:`DataFrameGroupBy.quantile` where NA values in the grouping could cause segfaults or incorrect results (:issue:`28882`) + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v0.25.2..HEAD diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index e3f18572abca1..a7dce26bdceea 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -719,6 +719,11 @@ def group_quantile(ndarray[float64_t] out, ndarray[int64_t] counts, non_na_counts, sort_arr assert values.shape[0] == N + + if not (0 <= q <= 1): + raise ValueError("'q' must be between 0 and 1. Got" + " '{}' instead".format(q)) + inter_methods = { 'linear': INTERPOLATION_LINEAR, 'lower': INTERPOLATION_LOWER, @@ -736,6 +741,9 @@ def group_quantile(ndarray[float64_t] out, with nogil: for i in range(N): lab = labels[i] + if lab == -1: # NA group label + continue + counts[lab] += 1 if not mask[i]: non_na_counts[lab] += 1 diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 45444ffa0c8bd..1674a9f794fd9 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -2935,7 +2935,7 @@ def _next_iter_line(self, row_num): if self.warn_bad_lines or self.error_bad_lines: msg = str(e) - if "NULL byte" in msg: + if "NULL byte" in msg or "line contains NUL" in msg: msg = ( "NULL byte detected. This byte " "cannot be processed in Python's " diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 5d1a1fd938500..da97dbfa7a2b8 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1316,6 +1316,40 @@ def test_quantile_raises(): df.groupby("key").quantile() +def test_quantile_out_of_bounds_q_raises(): + # https://github.com/pandas-dev/pandas/issues/27470 + df = pd.DataFrame(dict(a=[0, 0, 0, 1, 1, 1], b=range(6))) + g = df.groupby([0, 0, 0, 1, 1, 1]) + with pytest.raises(ValueError, match="Got '50.0' instead"): + g.quantile(50) + + with pytest.raises(ValueError, match="Got '-1.0' instead"): + g.quantile(-1) + + +def test_quantile_missing_group_values_no_segfaults(): + # GH 28662 + data = np.array([1.0, np.nan, 1.0]) + df = pd.DataFrame(dict(key=data, val=range(3))) + + # Random segfaults; would have been guaranteed in loop + grp = df.groupby("key") + for _ in range(100): + grp.quantile() + + +def test_quantile_missing_group_values_correct_results(): + # GH 28662 + data = np.array([1.0, np.nan, 3.0, np.nan]) + df = pd.DataFrame(dict(key=data, val=range(4))) + + result = df.groupby("key").quantile() + expected = pd.DataFrame( + [1.0, 3.0], index=pd.Index([1.0, 3.0], name="key"), columns=["val"] + ) + tm.assert_frame_equal(result, expected) + + # pipe # -------------------------------- diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 4a54d43de667a..b94d5cd497ccf 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -1898,10 +1898,7 @@ def test_null_byte_char(all_parsers): out = parser.read_csv(StringIO(data), names=names) tm.assert_frame_equal(out, expected) else: - if compat.PY38: - msg = "line contains NUL" - else: - msg = "NULL byte detected" + msg = "NULL byte detected" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), names=names)
This includes pieces of #27826 except for the whatsnew note, which appeared in 0.25.1. Not sure if we want to move that here or keep as is, but test and implementation were included here
https://api.github.com/repos/pandas-dev/pandas/pulls/29313
2019-10-31T16:03:09Z
2019-10-31T18:32:02Z
2019-10-31T18:32:02Z
2020-01-16T00:33:38Z
Fix doc typo
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 63344af63470f..430daa4708001 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -119,7 +119,7 @@ def _convert_expression(expr): """ Convert an object to an expression. - Thus function converts an object to an expression (a unicode string) and + This function converts an object to an expression (a unicode string) and checks to make sure it isn't empty after conversion. This is used to convert operators to their string representation for recursive calls to :func:`~pandas.eval`.
https://api.github.com/repos/pandas-dev/pandas/pulls/29312
2019-10-31T14:44:44Z
2019-10-31T16:03:48Z
2019-10-31T16:03:48Z
2019-10-31T18:20:04Z
CLN: Consistent pandas.util.testing imports in remaining test suite
diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index 0af8ed0ebf8d5..3a8e263ac2a6d 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -2,7 +2,7 @@ import pandas as pd from pandas import api, compat -from pandas.util import testing as tm +import pandas.util.testing as tm class Base: diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index e2ff77715e301..24f325643479c 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -1,5 +1,5 @@ from pandas.api import types -from pandas.util import testing as tm +import pandas.util.testing as tm from .test_api import Base diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index c02d8ae4e7429..f9bb4981df7df 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -12,7 +12,6 @@ from pandas import isna from pandas.core.arrays.sparse import SparseArray, SparseDtype import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal @pytest.fixture(params=["integer", "block"]) @@ -386,7 +385,7 @@ def test_constructor_from_too_large_array(self): def test_constructor_from_sparse(self): res = SparseArray(self.zarr) assert res.fill_value == 0 - assert_almost_equal(res.sp_values, self.zarr.sp_values) + tm.assert_almost_equal(res.sp_values, self.zarr.sp_values) def test_constructor_copy(self): cp = SparseArray(self.arr, copy=True) @@ -586,7 +585,7 @@ def test_copy(self): assert arr2.sp_index is self.arr.sp_index def test_values_asarray(self): - assert_almost_equal(self.arr.to_dense(), self.arr_data) + tm.assert_almost_equal(self.arr.to_dense(), self.arr_data) @pytest.mark.parametrize( "data,shape,dtype", @@ -625,7 +624,7 @@ def test_dense_repr(self, vals, fill_value): def test_getitem(self): def _checkit(i): - assert_almost_equal(self.arr[i], self.arr.to_dense()[i]) + tm.assert_almost_equal(self.arr[i], self.arr.to_dense()[i]) for i in range(len(self.arr)): _checkit(i) @@ -703,7 +702,7 @@ def _check_op(op, first, second): op(first.to_dense(), second.to_dense()), fill_value=first.fill_value ) assert isinstance(res, SparseArray) - assert_almost_equal(res.to_dense(), exp.to_dense()) + tm.assert_almost_equal(res.to_dense(), exp.to_dense()) res2 = op(first, second.to_dense()) assert isinstance(res2, SparseArray) @@ -723,8 +722,8 @@ def _check_op(op, first, second): except ValueError: pass else: - assert_almost_equal(res4.fill_value, exp_fv) - assert_almost_equal(res4.to_dense(), exp) + tm.assert_almost_equal(res4.fill_value, exp_fv) + tm.assert_almost_equal(res4.to_dense(), exp) with np.errstate(all="ignore"): for first_arr, second_arr in [(arr1, arr2), (farr1, farr2)]: diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 4d40cd3a2d4ca..a075521b67561 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -34,14 +34,6 @@ _unary_math_ops, ) import pandas.util.testing as tm -from pandas.util.testing import ( - assert_frame_equal, - assert_numpy_array_equal, - assert_produces_warning, - assert_series_equal, - makeCustomDataframe as mkdf, - randbool, -) @pytest.fixture( @@ -205,14 +197,14 @@ def test_complex_cmp_ops(self, cmp1, cmp2): def test_simple_cmp_ops(self): bool_lhses = ( - DataFrame(randbool(size=(10, 5))), - Series(randbool((5,))), - randbool(), + DataFrame(tm.randbool(size=(10, 5))), + Series(tm.randbool((5,))), + tm.randbool(), ) bool_rhses = ( - DataFrame(randbool(size=(10, 5))), - Series(randbool((5,))), - randbool(), + DataFrame(tm.randbool(size=(10, 5))), + Series(tm.randbool((5,))), + tm.randbool(), ) for lhs, rhs, cmp_op in product(bool_lhses, bool_rhses, self.cmp_ops): self.check_simple_cmp_op(lhs, cmp_op, rhs) @@ -475,13 +467,13 @@ def test_frame_invert(self): else: expect = ~lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) # bool always works lhs = DataFrame(rand(5, 2) > 0.5) expect = ~lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) # object raises lhs = DataFrame({"b": ["a", 1, 2.0], "c": rand(3) > 0.5}) @@ -514,13 +506,13 @@ def test_series_invert(self): else: expect = ~lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) # bool lhs = Series(rand(5) > 0.5) expect = ~lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) # float # int @@ -542,13 +534,13 @@ def test_frame_negate(self): lhs = DataFrame(randn(5, 2)) expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) # int lhs = DataFrame(randint(5, size=(5, 2))) expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) # bool doesn't work with numexpr but works elsewhere lhs = DataFrame(rand(5, 2) > 0.5) @@ -558,7 +550,7 @@ def test_frame_negate(self): else: expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) def test_series_negate(self): expr = self.ex("-") @@ -567,13 +559,13 @@ def test_series_negate(self): lhs = Series(randn(5)) expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) # int lhs = Series(randint(5, size=5)) expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) # bool doesn't work with numexpr but works elsewhere lhs = Series(rand(5) > 0.5) @@ -583,7 +575,7 @@ def test_series_negate(self): else: expect = -lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) def test_frame_pos(self): expr = self.ex("+") @@ -592,19 +584,19 @@ def test_frame_pos(self): lhs = DataFrame(randn(5, 2)) expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) # int lhs = DataFrame(randint(5, size=(5, 2))) expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) # bool doesn't work with numexpr but works elsewhere lhs = DataFrame(rand(5, 2) > 0.5) expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_frame_equal(expect, result) + tm.assert_frame_equal(expect, result) def test_series_pos(self): expr = self.ex("+") @@ -613,19 +605,19 @@ def test_series_pos(self): lhs = Series(randn(5)) expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) # int lhs = Series(randint(5, size=5)) expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) # bool doesn't work with numexpr but works elsewhere lhs = Series(rand(5) > 0.5) expect = lhs result = pd.eval(expr, engine=self.engine, parser=self.parser) - assert_series_equal(expect, result) + tm.assert_series_equal(expect, result) def test_scalar_unary(self): with pytest.raises(TypeError): @@ -645,7 +637,7 @@ def test_scalar_unary(self): def test_unary_in_array(self): # GH 11235 - assert_numpy_array_equal( + tm.assert_numpy_array_equal( pd.eval( "[-True, True, ~True, +True," "-False, False, ~False, +False," @@ -847,18 +839,18 @@ class TestTypeCasting: # chain(*(np.sctypes[x] for x in ['uint', 'int', 'float'])) @pytest.mark.parametrize("dt", [np.float32, np.float64]) def test_binop_typecasting(self, engine, parser, op, dt): - df = mkdf(5, 3, data_gen_f=f, dtype=dt) + df = tm.makeCustomDataframe(5, 3, data_gen_f=f, dtype=dt) s = "df {} 3".format(op) res = pd.eval(s, engine=engine, parser=parser) assert df.values.dtype == dt assert res.values.dtype == dt - assert_frame_equal(res, eval(s)) + tm.assert_frame_equal(res, eval(s)) s = "3 {} df".format(op) res = pd.eval(s, engine=engine, parser=parser) assert df.values.dtype == dt assert res.values.dtype == dt - assert_frame_equal(res, eval(s)) + tm.assert_frame_equal(res, eval(s)) # ------------------------------------- @@ -882,19 +874,19 @@ class TestAlignment: def test_align_nested_unary_op(self, engine, parser): s = "df * ~2" - df = mkdf(5, 3, data_gen_f=f) + df = tm.makeCustomDataframe(5, 3, data_gen_f=f) res = pd.eval(s, engine=engine, parser=parser) - assert_frame_equal(res, df * ~2) + tm.assert_frame_equal(res, df * ~2) def test_basic_frame_alignment(self, engine, parser): args = product(self.lhs_index_types, self.index_types, self.index_types) with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) for lr_idx_type, rr_idx_type, c_idx_type in args: - df = mkdf( + df = tm.makeCustomDataframe( 10, 10, data_gen_f=f, r_idx_type=lr_idx_type, c_idx_type=c_idx_type ) - df2 = mkdf( + df2 = tm.makeCustomDataframe( 20, 10, data_gen_f=f, r_idx_type=rr_idx_type, c_idx_type=c_idx_type ) # only warns if not monotonic and not sortable @@ -903,20 +895,20 @@ def test_basic_frame_alignment(self, engine, parser): res = pd.eval("df + df2", engine=engine, parser=parser) else: res = pd.eval("df + df2", engine=engine, parser=parser) - assert_frame_equal(res, df + df2) + tm.assert_frame_equal(res, df + df2) def test_frame_comparison(self, engine, parser): args = product(self.lhs_index_types, repeat=2) for r_idx_type, c_idx_type in args: - df = mkdf( + df = tm.makeCustomDataframe( 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type ) res = pd.eval("df < 2", engine=engine, parser=parser) - assert_frame_equal(res, df < 2) + tm.assert_frame_equal(res, df < 2) df3 = DataFrame(randn(*df.shape), index=df.index, columns=df.columns) res = pd.eval("df < df3", engine=engine, parser=parser) - assert_frame_equal(res, df < df3) + tm.assert_frame_equal(res, df < df3) @pytest.mark.slow def test_medium_complex_frame_alignment(self, engine, parser): @@ -928,19 +920,25 @@ def test_medium_complex_frame_alignment(self, engine, parser): warnings.simplefilter("always", RuntimeWarning) for r1, c1, r2, c2 in args: - df = mkdf(3, 2, data_gen_f=f, r_idx_type=r1, c_idx_type=c1) - df2 = mkdf(4, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2) - df3 = mkdf(5, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2) + df = tm.makeCustomDataframe( + 3, 2, data_gen_f=f, r_idx_type=r1, c_idx_type=c1 + ) + df2 = tm.makeCustomDataframe( + 4, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 + ) + df3 = tm.makeCustomDataframe( + 5, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 + ) if should_warn(df.index, df2.index, df3.index): with tm.assert_produces_warning(RuntimeWarning): res = pd.eval("df + df2 + df3", engine=engine, parser=parser) else: res = pd.eval("df + df2 + df3", engine=engine, parser=parser) - assert_frame_equal(res, df + df2 + df3) + tm.assert_frame_equal(res, df + df2 + df3) def test_basic_frame_series_alignment(self, engine, parser): def testit(r_idx_type, c_idx_type, index_name): - df = mkdf( + df = tm.makeCustomDataframe( 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type ) index = getattr(df, index_name) @@ -956,7 +954,7 @@ def testit(r_idx_type, c_idx_type, index_name): expected = df.add(s) if engine == "numexpr" else df + s else: expected = df + s - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) args = product(self.lhs_index_types, self.index_types, ("index", "columns")) with warnings.catch_warnings(record=True): @@ -966,7 +964,9 @@ def testit(r_idx_type, c_idx_type, index_name): def test_basic_series_frame_alignment(self, engine, parser): def testit(r_idx_type, c_idx_type, index_name): - df = mkdf(10, 7, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type) + df = tm.makeCustomDataframe( + 10, 7, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type + ) index = getattr(df, index_name) s = Series(np.random.randn(5), index[:5]) if should_warn(s.index, df.index): @@ -979,7 +979,7 @@ def testit(r_idx_type, c_idx_type, index_name): expected = df.add(s) if engine == "numexpr" else s + df else: expected = s + df - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) # only test dt with dt, otherwise weird joins result args = product(["i", "u", "s"], ["i", "u", "s"], ("index", "columns")) @@ -1007,7 +1007,7 @@ def test_series_frame_commutativity(self, engine, parser): with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) for r_idx_type, c_idx_type, op, index_name in args: - df = mkdf( + df = tm.makeCustomDataframe( 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type ) index = getattr(df, index_name) @@ -1026,7 +1026,7 @@ def test_series_frame_commutativity(self, engine, parser): if r_idx_type != "dt" and c_idx_type != "dt": if engine == "numexpr": - assert_frame_equal(a, b) + tm.assert_frame_equal(a, b) @pytest.mark.slow def test_complex_series_frame_alignment(self, engine, parser): @@ -1045,8 +1045,12 @@ def test_complex_series_frame_alignment(self, engine, parser): index_name = random.choice(["index", "columns"]) obj_name = random.choice(["df", "df2"]) - df = mkdf(m1, n, data_gen_f=f, r_idx_type=r1, c_idx_type=c1) - df2 = mkdf(m2, n, data_gen_f=f, r_idx_type=r2, c_idx_type=c2) + df = tm.makeCustomDataframe( + m1, n, data_gen_f=f, r_idx_type=r1, c_idx_type=c1 + ) + df2 = tm.makeCustomDataframe( + m2, n, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 + ) index = getattr(locals().get(obj_name), index_name) s = Series(np.random.randn(n), index[:n]) @@ -1072,7 +1076,7 @@ def test_complex_series_frame_alignment(self, engine, parser): else: res = pd.eval("df2 + s + df", engine=engine, parser=parser) assert res.shape == expected.shape - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) def test_performance_warning_for_poor_alignment(self, engine, parser): df = DataFrame(randn(1000, 10)) @@ -1082,16 +1086,16 @@ def test_performance_warning_for_poor_alignment(self, engine, parser): else: seen = False - with assert_produces_warning(seen): + with tm.assert_produces_warning(seen): pd.eval("df + s", engine=engine, parser=parser) s = Series(randn(1000)) - with assert_produces_warning(False): + with tm.assert_produces_warning(False): pd.eval("df + s", engine=engine, parser=parser) df = DataFrame(randn(10, 10000)) s = Series(randn(10000)) - with assert_produces_warning(False): + with tm.assert_produces_warning(False): pd.eval("df + s", engine=engine, parser=parser) df = DataFrame(randn(10, 10)) @@ -1104,7 +1108,7 @@ def test_performance_warning_for_poor_alignment(self, engine, parser): else: wrn = False - with assert_produces_warning(wrn) as w: + with tm.assert_produces_warning(wrn) as w: pd.eval("df + s", engine=engine, parser=parser) if not is_python_engine: @@ -1199,7 +1203,7 @@ def test_constant(self): def test_single_variable(self): df = DataFrame(randn(10, 2)) df2 = self.eval("df", local_dict={"df": df}) - assert_frame_equal(df, df2) + tm.assert_frame_equal(df, df2) def test_truediv(self): s = np.array([1]) @@ -1237,7 +1241,7 @@ def test_lhs_expression_subscript(self): df = DataFrame(np.random.randn(5, 3)) result = self.eval("(df + 1)[df > 2]", local_dict={"df": df}) expected = (df + 1)[df > 2] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_attr_expression(self): df = DataFrame(np.random.randn(5, 3), columns=list("abc")) @@ -1250,7 +1254,7 @@ def test_attr_expression(self): exprs = expr1, expr2, expr3 expecs = expec1, expec2, expec3 for e, expec in zip(exprs, expecs): - assert_series_equal(expec, self.eval(e, local_dict={"df": df})) + tm.assert_series_equal(expec, self.eval(e, local_dict={"df": df})) def test_assignment_fails(self): df = DataFrame(np.random.randn(5, 3), columns=list("abc")) @@ -1284,14 +1288,14 @@ def test_assignment_column(self): expected["a"] = expected["a"] + expected["b"] df = orig_df.copy() df.eval("a = a + b", inplace=True) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # single assignment - new variable expected = orig_df.copy() expected["c"] = expected["a"] + expected["b"] df = orig_df.copy() df.eval("c = a + b", inplace=True) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # with a local name overlap def f(): @@ -1303,7 +1307,7 @@ def f(): df = f() expected = orig_df.copy() expected["a"] = 1 + expected["b"] - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) df = orig_df.copy() @@ -1312,7 +1316,7 @@ def f(): old_a = df.a.copy() df.eval("a = a + b", inplace=True) result = old_a + df.b - assert_series_equal(result, df.a, check_names=False) + tm.assert_series_equal(result, df.a, check_names=False) assert result.name is None f() @@ -1329,14 +1333,14 @@ def f(): self.eval("c = df.a + df.b", local_dict={"df": df}, target=df, inplace=True) expected = orig_df.copy() expected["c"] = expected["a"] + expected["b"] - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_column_in(self): # GH 11235 df = DataFrame({"a": [11], "b": [-32]}) result = df.eval("a in [11, -32]") expected = Series([True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def assignment_not_inplace(self): # see gh-9297 @@ -1362,7 +1366,7 @@ def test_multi_line_expression(self): d = c + b""", inplace=True, ) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) assert ans is None expected["a"] = expected["a"] - 1 @@ -1373,7 +1377,7 @@ def test_multi_line_expression(self): e = a + 2""", inplace=True, ) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) assert ans is None # multi-line not valid if not all assignments @@ -1398,7 +1402,7 @@ def test_multi_line_expression_not_inplace(self): d = c + b""", inplace=False, ) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) expected["a"] = expected["a"] - 1 expected["e"] = expected["a"] + 2 @@ -1408,7 +1412,7 @@ def test_multi_line_expression_not_inplace(self): e = a + 2""", inplace=False, ) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) def test_multi_line_expression_local_variable(self): # GH 15342 @@ -1425,7 +1429,7 @@ def test_multi_line_expression_local_variable(self): """, inplace=True, ) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) assert ans is None def test_multi_line_expression_callable_local_variable(self): @@ -1445,7 +1449,7 @@ def local_func(a, b): """, inplace=True, ) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) assert ans is None def test_multi_line_expression_callable_local_variable_with_kwargs(self): @@ -1465,7 +1469,7 @@ def local_func(a, b): """, inplace=True, ) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) assert ans is None def test_assignment_in_query(self): @@ -1474,7 +1478,7 @@ def test_assignment_in_query(self): df_orig = df.copy() with pytest.raises(ValueError): df.query("a = 1") - assert_frame_equal(df, df_orig) + tm.assert_frame_equal(df, df_orig) def test_query_inplace(self): # see gh-11149 @@ -1482,7 +1486,7 @@ def test_query_inplace(self): expected = df.copy() expected = expected[expected["a"] == 2] df.query("a == 2", inplace=True) - assert_frame_equal(expected, df) + tm.assert_frame_equal(expected, df) df = {} expected = {"a": 3} @@ -1522,26 +1526,26 @@ def test_inplace_no_assignment(self, target): self.eval(expression, target=target, inplace=True) def test_basic_period_index_boolean_expression(self): - df = mkdf(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i") + df = tm.makeCustomDataframe(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i") e = df < 2 r = self.eval("df < 2", local_dict={"df": df}) x = df < 2 - assert_frame_equal(r, e) - assert_frame_equal(x, e) + tm.assert_frame_equal(r, e) + tm.assert_frame_equal(x, e) def test_basic_period_index_subscript_expression(self): - df = mkdf(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i") + df = tm.makeCustomDataframe(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i") r = self.eval("df[df < 2 + 3]", local_dict={"df": df}) e = df[df < 2 + 3] - assert_frame_equal(r, e) + tm.assert_frame_equal(r, e) def test_nested_period_index_subscript_expression(self): - df = mkdf(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i") + df = tm.makeCustomDataframe(2, 2, data_gen_f=f, c_idx_type="p", r_idx_type="i") r = self.eval("df[df[df < 2] < 2] + df * 2", local_dict={"df": df}) e = df[df[df < 2] < 2] + df * 2 - assert_frame_equal(r, e) + tm.assert_frame_equal(r, e) def test_date_boolean(self): df = DataFrame(randn(5, 3)) @@ -1553,7 +1557,7 @@ def test_date_boolean(self): parser=self.parser, ) expec = df.dates1 < "20130101" - assert_series_equal(res, expec, check_names=False) + tm.assert_series_equal(res, expec, check_names=False) def test_simple_in_ops(self): if self.parser != "python": diff --git a/pandas/tests/dtypes/cast/test_construct_from_scalar.py b/pandas/tests/dtypes/cast/test_construct_from_scalar.py index 4ff3be5dfaa72..71f41fcf5b447 100644 --- a/pandas/tests/dtypes/cast/test_construct_from_scalar.py +++ b/pandas/tests/dtypes/cast/test_construct_from_scalar.py @@ -2,7 +2,7 @@ from pandas.core.dtypes.dtypes import CategoricalDtype from pandas import Categorical -from pandas.util import testing as tm +import pandas.util.testing as tm def test_cast_1d_array_like_from_scalar_categorical(): diff --git a/pandas/tests/dtypes/cast/test_construct_ndarray.py b/pandas/tests/dtypes/cast/test_construct_ndarray.py index da3789a87aa07..620e74f80d5fb 100644 --- a/pandas/tests/dtypes/cast/test_construct_ndarray.py +++ b/pandas/tests/dtypes/cast/test_construct_ndarray.py @@ -3,7 +3,7 @@ from pandas.core.dtypes.cast import construct_1d_ndarray_preserving_na -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/dtypes/cast/test_downcast.py b/pandas/tests/dtypes/cast/test_downcast.py index 9e2eca5259bc3..99afabfa42a04 100644 --- a/pandas/tests/dtypes/cast/test_downcast.py +++ b/pandas/tests/dtypes/cast/test_downcast.py @@ -6,7 +6,7 @@ from pandas.core.dtypes.cast import maybe_downcast_to_dtype from pandas import DatetimeIndex, Series, Timestamp -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py index 602b2f26eaa4a..bf11b81af6f90 100644 --- a/pandas/tests/dtypes/cast/test_infer_dtype.py +++ b/pandas/tests/dtypes/cast/test_infer_dtype.py @@ -11,7 +11,7 @@ from pandas.core.dtypes.common import is_dtype_equal from pandas import Categorical, Period, Series, Timedelta, Timestamp, date_range -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture(params=[True, False]) diff --git a/pandas/tests/dtypes/cast/test_upcast.py b/pandas/tests/dtypes/cast/test_upcast.py index f076bcd578001..b22ed0bcd0a11 100644 --- a/pandas/tests/dtypes/cast/test_upcast.py +++ b/pandas/tests/dtypes/cast/test_upcast.py @@ -4,7 +4,7 @@ from pandas.core.dtypes.cast import maybe_upcast_putmask from pandas import Series -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.mark.parametrize("result", [Series([10, 11, 12]), [10, 11, 12], (10, 11, 12)]) diff --git a/pandas/tests/dtypes/test_generic.py b/pandas/tests/dtypes/test_generic.py index 471fd06a29ae9..c17a8997a9b8f 100644 --- a/pandas/tests/dtypes/test_generic.py +++ b/pandas/tests/dtypes/test_generic.py @@ -5,7 +5,7 @@ from pandas.core.dtypes import generic as gt import pandas as pd -from pandas.util import testing as tm +import pandas.util.testing as tm class TestABCClasses: diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index aeec12b9ad14e..62fb118f719e3 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -51,7 +51,7 @@ Timestamp, isna, ) -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture(params=[True, False], ids=str) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 25b447e1df7d4..89474cf8fa953 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -23,7 +23,7 @@ import pandas as pd from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range -from pandas.util import testing as tm +import pandas.util.testing as tm now = pd.Timestamp.now() utcnow = pd.Timestamp.now("UTC") diff --git a/pandas/tests/frame/test_explode.py b/pandas/tests/frame/test_explode.py index c07de35f8bf34..545a4b5f9421e 100644 --- a/pandas/tests/frame/test_explode.py +++ b/pandas/tests/frame/test_explode.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas.util import testing as tm +import pandas.util.testing as tm def test_error(): diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py index ff9895cf14318..270a7c70a2e81 100644 --- a/pandas/tests/generic/test_frame.py +++ b/pandas/tests/generic/test_frame.py @@ -10,11 +10,6 @@ import pandas as pd from pandas import DataFrame, MultiIndex, Series, date_range import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) from .test_generic import Generic @@ -28,7 +23,7 @@ class TestDataFrame(Generic): _typ = DataFrame - _comparator = lambda self, x, y: assert_frame_equal(x, y) + _comparator = lambda self, x, y: tm.assert_frame_equal(x, y) def test_rename_mi(self): df = DataFrame( @@ -177,7 +172,7 @@ def test_set_attribute(self): df.y = 5 assert df.y == 5 - assert_series_equal(df["y"], Series([2, 4, 6], name="y")) + tm.assert_series_equal(df["y"], Series([2, 4, 6], name="y")) @pytest.mark.skipif( not _XARRAY_INSTALLED @@ -222,7 +217,7 @@ def test_to_xarray_index_types(self, index): assert result.dims["foo"] == 3 assert len(result.coords) == 1 assert len(result.data_vars) == 8 - assert_almost_equal(list(result.coords.keys()), ["foo"]) + tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, Dataset) # idempotency @@ -233,7 +228,7 @@ def test_to_xarray_index_types(self, index): expected["f"] = expected["f"].astype(object) expected["h"] = expected["h"].astype("datetime64[ns]") expected.columns.name = None - assert_frame_equal( + tm.assert_frame_equal( result.to_dataframe(), expected, check_index_type=False, @@ -270,7 +265,7 @@ def test_to_xarray(self): assert result.dims["two"] == 3 assert len(result.coords) == 2 assert len(result.data_vars) == 8 - assert_almost_equal(list(result.coords.keys()), ["one", "two"]) + tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) assert isinstance(result, Dataset) result = result.to_dataframe() @@ -278,7 +273,7 @@ def test_to_xarray(self): expected["f"] = expected["f"].astype(object) expected["h"] = expected["h"].astype("datetime64[ns]") expected.columns.name = None - assert_frame_equal(result, expected, check_index_type=False) + tm.assert_frame_equal(result, expected, check_index_type=False) def test_deepcopy_empty(self): # This test covers empty frame copying with non-empty column sets diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 7b9e50ebbf342..a7506f3d60b3c 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -8,7 +8,6 @@ import pandas as pd from pandas import DataFrame, MultiIndex, Series, date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal # ---------------------------------------------------------------------- # Generic types test cases @@ -606,7 +605,7 @@ def test_sample(sel): } ) sample1 = df.sample(n=1, weights="easyweights") - assert_frame_equal(sample1, df.iloc[5:6]) + tm.assert_frame_equal(sample1, df.iloc[5:6]) # Ensure proper error if string given as weight for Series or # DataFrame with axis = 1. @@ -635,19 +634,21 @@ def test_sample(sel): # Test axis argument df = pd.DataFrame({"col1": range(10), "col2": ["a"] * 10}) second_column_weight = [0, 1] - assert_frame_equal( + tm.assert_frame_equal( df.sample(n=1, axis=1, weights=second_column_weight), df[["col2"]] ) # Different axis arg types - assert_frame_equal( + tm.assert_frame_equal( df.sample(n=1, axis="columns", weights=second_column_weight), df[["col2"]] ) weight = [0] * 10 weight[5] = 0.5 - assert_frame_equal(df.sample(n=1, axis="rows", weights=weight), df.iloc[5:6]) - assert_frame_equal(df.sample(n=1, axis="index", weights=weight), df.iloc[5:6]) + tm.assert_frame_equal(df.sample(n=1, axis="rows", weights=weight), df.iloc[5:6]) + tm.assert_frame_equal( + df.sample(n=1, axis="index", weights=weight), df.iloc[5:6] + ) # Check out of range axis values with pytest.raises(ValueError): @@ -672,26 +673,26 @@ def test_sample(sel): {"col1": range(10, 20), "col2": range(20, 30), "colString": ["a"] * 10} ) sample1 = df.sample(n=1, axis=1, weights=easy_weight_list) - assert_frame_equal(sample1, df[["colString"]]) + tm.assert_frame_equal(sample1, df[["colString"]]) # Test default axes - assert_frame_equal( + tm.assert_frame_equal( df.sample(n=3, random_state=42), df.sample(n=3, axis=0, random_state=42) ) # Test that function aligns weights with frame df = DataFrame({"col1": [5, 6, 7], "col2": ["a", "b", "c"]}, index=[9, 5, 3]) s = Series([1, 0, 0], index=[3, 5, 9]) - assert_frame_equal(df.loc[[3]], df.sample(1, weights=s)) + tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=s)) # Weights have index values to be dropped because not in # sampled DataFrame s2 = Series([0.001, 0, 10000], index=[3, 5, 10]) - assert_frame_equal(df.loc[[3]], df.sample(1, weights=s2)) + tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=s2)) # Weights have empty values to be filed with zeros s3 = Series([0.01, 0], index=[3, 5]) - assert_frame_equal(df.loc[[3]], df.sample(1, weights=s3)) + tm.assert_frame_equal(df.loc[[3]], df.sample(1, weights=s3)) # No overlap in weight and sampled DataFrame indices s4 = Series([1, 0], index=[1, 2]) @@ -893,19 +894,19 @@ def test_pipe(self): f = lambda x, y: x ** y result = df.pipe(f, 2) expected = DataFrame({"A": [1, 4, 9]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.A.pipe(f, 2) - assert_series_equal(result, expected.A) + tm.assert_series_equal(result, expected.A) def test_pipe_tuple(self): df = DataFrame({"A": [1, 2, 3]}) f = lambda x, y: y result = df.pipe((f, "y"), 0) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.A.pipe((f, "y"), 0) - assert_series_equal(result, df.A) + tm.assert_series_equal(result, df.A) def test_pipe_tuple_error(self): df = DataFrame({"A": [1, 2, 3]}) diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py index 5c3c35832356e..ae452e6faef01 100644 --- a/pandas/tests/generic/test_series.py +++ b/pandas/tests/generic/test_series.py @@ -9,7 +9,6 @@ import pandas as pd from pandas import MultiIndex, Series, date_range import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal, assert_series_equal from .test_generic import Generic @@ -23,7 +22,7 @@ class TestSeries(Generic): _typ = Series - _comparator = lambda self, x, y: assert_series_equal(x, y) + _comparator = lambda self, x, y: tm.assert_series_equal(x, y) def setup_method(self): self.ts = tm.makeTimeSeries() # Was at top level in test_series @@ -213,11 +212,11 @@ def test_to_xarray_index_types(self, index): repr(result) assert len(result) == 6 assert len(result.coords) == 1 - assert_almost_equal(list(result.coords.keys()), ["foo"]) + tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) # idempotency - assert_series_equal( + tm.assert_series_equal( result.to_series(), s, check_index_type=False, check_categorical=True ) @@ -230,7 +229,7 @@ def test_to_xarray(self): result = s.to_xarray() assert len(result) == 0 assert len(result.coords) == 1 - assert_almost_equal(list(result.coords.keys()), ["foo"]) + tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) s = Series(range(6)) @@ -240,9 +239,9 @@ def test_to_xarray(self): ) result = s.to_xarray() assert len(result) == 2 - assert_almost_equal(list(result.coords.keys()), ["one", "two"]) + tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) assert isinstance(result, DataArray) - assert_series_equal(result.to_series(), s) + tm.assert_series_equal(result.to_series(), s) def test_valid_deprecated(self): # GH18800 diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py index 72e60c5099304..af98f9efe2af9 100644 --- a/pandas/tests/groupby/conftest.py +++ b/pandas/tests/groupby/conftest.py @@ -3,7 +3,7 @@ from pandas import DataFrame, MultiIndex from pandas.core.groupby.base import reduction_kernels -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index 1af4768b7381e..0e62569fffeb6 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -6,7 +6,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, bdate_range -from pandas.util import testing as tm +import pandas.util.testing as tm def test_apply_issues(): diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py index e407cfadac2fb..8f0df9051fc73 100644 --- a/pandas/tests/groupby/test_rank.py +++ b/pandas/tests/groupby/test_rank.py @@ -4,7 +4,7 @@ import pandas as pd from pandas import DataFrame, Series, concat from pandas.core.base import DataError -from pandas.util import testing as tm +import pandas.util.testing as tm def test_rank_apply(): diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py index f8bd8843ab7e3..363c5a9af0180 100644 --- a/pandas/tests/groupby/test_value_counts.py +++ b/pandas/tests/groupby/test_value_counts.py @@ -10,7 +10,7 @@ import pytest from pandas import DataFrame, MultiIndex, Series, date_range -from pandas.util import testing as tm +import pandas.util.testing as tm # our starting frame diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index 05d745ccc0e8e..58407d90a2cc8 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -14,7 +14,7 @@ reduction_kernels, transformation_kernels, ) -from pandas.util import testing as tm +import pandas.util.testing as tm AGG_FUNCTIONS = [ "sum", diff --git a/pandas/tests/indexes/datetimes/test_datetimelike.py b/pandas/tests/indexes/datetimes/test_datetimelike.py index 8fa87f55f404b..2ff6853b98929 100644 --- a/pandas/tests/indexes/datetimes/test_datetimelike.py +++ b/pandas/tests/indexes/datetimes/test_datetimelike.py @@ -2,7 +2,7 @@ import pytest from pandas import DatetimeIndex, date_range -from pandas.util import testing as tm +import pandas.util.testing as tm from ..datetimelike import DatetimeLike diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index 32e2a72fcef36..51aeb40744c3a 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -17,7 +17,7 @@ date_range, ) from pandas.core.indexing import IndexingError -from pandas.util import testing as tm +import pandas.util.testing as tm class TestSlicing: diff --git a/pandas/tests/indexes/period/test_asfreq.py b/pandas/tests/indexes/period/test_asfreq.py index 2a6e84da229e1..fd6013ab5ae08 100644 --- a/pandas/tests/indexes/period/test_asfreq.py +++ b/pandas/tests/indexes/period/test_asfreq.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import DataFrame, PeriodIndex, Series, period_range -from pandas.util import testing as tm +import pandas.util.testing as tm class TestPeriodIndex: diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index cf03e2c7847f0..c8f0d3b3fe553 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -7,7 +7,7 @@ import pandas as pd from pandas import DatetimeIndex, Period, PeriodIndex, Series, notna, period_range -from pandas.util import testing as tm +import pandas.util.testing as tm class TestGetItem: diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py index 00b9803980bc8..50a12baf352d9 100644 --- a/pandas/tests/indexes/period/test_partial_slicing.py +++ b/pandas/tests/indexes/period/test_partial_slicing.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import DataFrame, Period, Series, period_range -from pandas.util import testing as tm +import pandas.util.testing as tm class TestPeriodIndex: diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 42096f5000c62..d75bd7bb21827 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -17,7 +17,7 @@ offsets, period_range, ) -from pandas.util import testing as tm +import pandas.util.testing as tm from ..datetimelike import DatetimeLike diff --git a/pandas/tests/indexes/test_frozen.py b/pandas/tests/indexes/test_frozen.py index 57acc8ee72b70..712feb7b8ef61 100644 --- a/pandas/tests/indexes/test_frozen.py +++ b/pandas/tests/indexes/test_frozen.py @@ -5,7 +5,7 @@ from pandas.core.indexes.frozen import FrozenList, FrozenNDArray from pandas.tests.test_base import CheckImmutable, CheckStringMixin -from pandas.util import testing as tm +import pandas.util.testing as tm class TestFrozenList(CheckImmutable, CheckStringMixin): diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 645ad19ea4cc9..6626ccf4a29f8 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -11,7 +11,7 @@ _np_version_under1p17, ) from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/indexing/common.py b/pandas/tests/indexing/common.py index 812d84261eb46..fea34f795bd03 100644 --- a/pandas/tests/indexing/common.py +++ b/pandas/tests/indexing/common.py @@ -7,7 +7,7 @@ from pandas.core.dtypes.common import is_scalar from pandas import DataFrame, Float64Index, MultiIndex, Series, UInt64Index, date_range -from pandas.util import testing as tm +import pandas.util.testing as tm from pandas.io.formats.printing import pprint_thing diff --git a/pandas/tests/indexing/multiindex/conftest.py b/pandas/tests/indexing/multiindex/conftest.py index 23149944f3c38..e58e6ed0d5d83 100644 --- a/pandas/tests/indexing/multiindex/conftest.py +++ b/pandas/tests/indexing/multiindex/conftest.py @@ -2,7 +2,7 @@ import pytest from pandas import DataFrame, Index, MultiIndex -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture diff --git a/pandas/tests/indexing/multiindex/test_getitem.py b/pandas/tests/indexing/multiindex/test_getitem.py index 145bfe168390e..4f95e6bd28989 100644 --- a/pandas/tests/indexing/multiindex/test_getitem.py +++ b/pandas/tests/indexing/multiindex/test_getitem.py @@ -3,7 +3,7 @@ from pandas import DataFrame, Index, MultiIndex, Series from pandas.core.indexing import IndexingError -from pandas.util import testing as tm +import pandas.util.testing as tm # ---------------------------------------------------------------------------- # test indexing of Series with multi-level Index diff --git a/pandas/tests/indexing/multiindex/test_iloc.py b/pandas/tests/indexing/multiindex/test_iloc.py index 1335ee9dc2bdf..2c2e4d06f1ae3 100644 --- a/pandas/tests/indexing/multiindex/test_iloc.py +++ b/pandas/tests/indexing/multiindex/test_iloc.py @@ -2,7 +2,7 @@ import pytest from pandas import DataFrame, MultiIndex, Series -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture diff --git a/pandas/tests/indexing/multiindex/test_ix.py b/pandas/tests/indexing/multiindex/test_ix.py index 2e7a5a08a16f0..35f3137dac059 100644 --- a/pandas/tests/indexing/multiindex/test_ix.py +++ b/pandas/tests/indexing/multiindex/test_ix.py @@ -4,7 +4,7 @@ from pandas.errors import PerformanceWarning from pandas import DataFrame, MultiIndex -from pandas.util import testing as tm +import pandas.util.testing as tm class TestMultiIndex: diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 8b48c2bf7169f..9eeee897bfbb5 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -6,7 +6,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series from pandas.core.indexing import IndexingError -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py index ccaaa2ae02499..bf1e999b06860 100644 --- a/pandas/tests/indexing/multiindex/test_multiindex.py +++ b/pandas/tests/indexing/multiindex/test_multiindex.py @@ -6,7 +6,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series -from pandas.util import testing as tm +import pandas.util.testing as tm class TestMultiIndexBasic: diff --git a/pandas/tests/indexing/multiindex/test_partial.py b/pandas/tests/indexing/multiindex/test_partial.py index 692b57ff98f94..05ea949721b65 100644 --- a/pandas/tests/indexing/multiindex/test_partial.py +++ b/pandas/tests/indexing/multiindex/test_partial.py @@ -2,7 +2,7 @@ import pytest from pandas import DataFrame, MultiIndex -from pandas.util import testing as tm +import pandas.util.testing as tm class TestMultiIndexPartial: diff --git a/pandas/tests/indexing/multiindex/test_set_ops.py b/pandas/tests/indexing/multiindex/test_set_ops.py index 5d0bc61e9957c..66cb0d0d46380 100644 --- a/pandas/tests/indexing/multiindex/test_set_ops.py +++ b/pandas/tests/indexing/multiindex/test_set_ops.py @@ -1,7 +1,7 @@ from numpy.random import randn from pandas import DataFrame, MultiIndex, Series -from pandas.util import testing as tm +import pandas.util.testing as tm class TestMultiIndexSetOps: diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index c383c38958692..7fc95ba62a888 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -5,7 +5,7 @@ import pandas as pd from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, isna, notna import pandas.core.common as com -from pandas.util import testing as tm +import pandas.util.testing as tm class TestMultiIndexSetItem: diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index 692a86aa1a338..f1f11285696f9 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -9,7 +9,7 @@ from pandas import DataFrame, Index, MultiIndex, Series, Timestamp from pandas.core.indexing import _non_reducing_slice from pandas.tests.indexing.common import _mklbl -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.mark.filterwarnings("ignore:\\n.ix:FutureWarning") diff --git a/pandas/tests/indexing/multiindex/test_sorted.py b/pandas/tests/indexing/multiindex/test_sorted.py index 43ad66b7d1116..5b8300827609a 100644 --- a/pandas/tests/indexing/multiindex/test_sorted.py +++ b/pandas/tests/indexing/multiindex/test_sorted.py @@ -2,7 +2,7 @@ from numpy.random import randn from pandas import DataFrame, MultiIndex, Series -from pandas.util import testing as tm +import pandas.util.testing as tm class TestMultiIndexSorted: diff --git a/pandas/tests/indexing/multiindex/test_xs.py b/pandas/tests/indexing/multiindex/test_xs.py index 5e58b3ec155ed..99f343c2f4a7d 100644 --- a/pandas/tests/indexing/multiindex/test_xs.py +++ b/pandas/tests/indexing/multiindex/test_xs.py @@ -5,7 +5,7 @@ from pandas import DataFrame, Index, MultiIndex, Series, concat, date_range import pandas.core.common as com -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 702bf0b15dec9..bd106ba9c36f1 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -4,7 +4,7 @@ import pandas as pd from pandas import DataFrame, Series, Timestamp, date_range, option_context from pandas.core import common as com -from pandas.util import testing as tm +import pandas.util.testing as tm class TestCaching: diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index fb8f62d7a06c5..ab4a8fe89c6e3 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -5,7 +5,7 @@ import pandas as pd from pandas import DataFrame, Index, Series, Timestamp, date_range -from pandas.util import testing as tm +import pandas.util.testing as tm class TestDatetimeIndex: diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index c239c8383f1ba..7c1d8ddd14317 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -10,7 +10,7 @@ from pandas.api.types import is_scalar from pandas.core.indexing import IndexingError from pandas.tests.indexing.common import Base -from pandas.util import testing as tm +import pandas.util.testing as tm class TestiLoc(Base): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 5bf8780d76601..732914b3b8947 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -10,7 +10,7 @@ from pandas import DataFrame, Series, Timestamp, date_range from pandas.api.types import is_scalar from pandas.tests.indexing.common import Base -from pandas.util import testing as tm +import pandas.util.testing as tm class TestLoc(Base): diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index c4505231932c6..0fb71bfea76c0 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -11,7 +11,7 @@ import pandas as pd from pandas import DataFrame, Index, Series, date_range -from pandas.util import testing as tm +import pandas.util.testing as tm class TestPartialSetting: diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index 532b77d6519c1..b41b90cd9afd1 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -5,7 +5,7 @@ from pandas import DataFrame, Series, Timedelta, Timestamp, date_range from pandas.tests.indexing.common import Base -from pandas.util import testing as tm +import pandas.util.testing as tm class TestScalar(Base): diff --git a/pandas/tests/indexing/test_timedelta.py b/pandas/tests/indexing/test_timedelta.py index 7628aa53ef3cb..5c9865ddc7090 100644 --- a/pandas/tests/indexing/test_timedelta.py +++ b/pandas/tests/indexing/test_timedelta.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas.util import testing as tm +import pandas.util.testing as tm class TestTimedeltaIndexing: diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index ed1a321a3d7e6..16f14f35fdbae 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -25,12 +25,6 @@ from pandas.core.arrays import DatetimeArray, TimedeltaArray from pandas.core.internals import BlockManager, SingleBlockManager, make_block import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, - randn, -) # in 3.6.1 a c-api slicing function changed, see src/compat_helper.h PY361 = LooseVersion(sys.version) >= LooseVersion("3.6.1") @@ -261,8 +255,8 @@ def test_attrs(self): assert len(self.fblock) == len(self.fblock.values) def test_merge(self): - avals = randn(2, 10) - bvals = randn(2, 10) + avals = tm.randn(2, 10) + bvals = tm.randn(2, 10) ref_cols = Index(["e", "a", "b", "d", "f"]) @@ -390,7 +384,7 @@ def test_contains(self, mgr): def test_pickle(self, mgr): mgr2 = tm.round_trip_pickle(mgr) - assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) + tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) # share ref_items # assert mgr2.blocks[0].ref_items is mgr2.blocks[1].ref_items @@ -407,20 +401,20 @@ def test_non_unique_pickle(self): mgr = create_mgr("a,a,a:f8") mgr2 = tm.round_trip_pickle(mgr) - assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) + tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) mgr = create_mgr("a: f8; a: i8") mgr2 = tm.round_trip_pickle(mgr) - assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) + tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) def test_categorical_block_pickle(self): mgr = create_mgr("a: category") mgr2 = tm.round_trip_pickle(mgr) - assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) + tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) smgr = create_single_mgr("category") smgr2 = tm.round_trip_pickle(smgr) - assert_series_equal(Series(smgr), Series(smgr2)) + tm.assert_series_equal(Series(smgr), Series(smgr2)) def test_get(self): cols = Index(list("abc")) @@ -428,9 +422,9 @@ def test_get(self): block = make_block(values=values.copy(), placement=np.arange(3)) mgr = BlockManager(blocks=[block], axes=[cols, np.arange(3)]) - assert_almost_equal(mgr.get("a").internal_values(), values[0]) - assert_almost_equal(mgr.get("b").internal_values(), values[1]) - assert_almost_equal(mgr.get("c").internal_values(), values[2]) + tm.assert_almost_equal(mgr.get("a").internal_values(), values[0]) + tm.assert_almost_equal(mgr.get("b").internal_values(), values[1]) + tm.assert_almost_equal(mgr.get("c").internal_values(), values[2]) def test_set(self): mgr = create_mgr("a,b,c: int", item_shape=(3,)) @@ -456,10 +450,10 @@ def test_set_change_dtype(self, mgr): mgr2.set("baz", np.repeat("foo", N)) assert mgr2.get("baz").dtype == np.object_ - mgr2.set("quux", randn(N).astype(int)) + mgr2.set("quux", tm.randn(N).astype(int)) assert mgr2.get("quux").dtype == np.int_ - mgr2.set("quux", randn(N)) + mgr2.set("quux", tm.randn(N)) assert mgr2.get("quux").dtype == np.float_ def test_set_change_dtype_slice(self): # GH8850 @@ -469,10 +463,10 @@ def test_set_change_dtype_slice(self): # GH8850 blocks = df._to_dict_of_blocks() assert sorted(blocks.keys()) == ["float64", "int64"] - assert_frame_equal( + tm.assert_frame_equal( blocks["float64"], DataFrame([[1.0, 4.0], [4.0, 10.0]], columns=cols[:2]) ) - assert_frame_equal(blocks["int64"], DataFrame([[3], [6]], columns=cols[2:])) + tm.assert_frame_equal(blocks["int64"], DataFrame([[3], [6]], columns=cols[2:])) def test_copy(self, mgr): cp = mgr.copy(deep=False) @@ -688,11 +682,11 @@ def test_consolidate(self): pass def test_consolidate_ordering_issues(self, mgr): - mgr.set("f", randn(N)) - mgr.set("d", randn(N)) - mgr.set("b", randn(N)) - mgr.set("g", randn(N)) - mgr.set("h", randn(N)) + mgr.set("f", tm.randn(N)) + mgr.set("d", tm.randn(N)) + mgr.set("b", tm.randn(N)) + mgr.set("g", tm.randn(N)) + mgr.set("h", tm.randn(N)) # we have datetime/tz blocks in mgr cons = mgr.consolidate() @@ -715,16 +709,16 @@ def test_reindex_items(self): reindexed = mgr.reindex_axis(["g", "c", "a", "d"], axis=0) assert reindexed.nblocks == 2 tm.assert_index_equal(reindexed.items, pd.Index(["g", "c", "a", "d"])) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("g").internal_values(), reindexed.get("g").internal_values() ) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("c").internal_values(), reindexed.get("c").internal_values() ) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("a").internal_values(), reindexed.get("a").internal_values() ) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("d").internal_values(), reindexed.get("d").internal_values() ) @@ -740,13 +734,13 @@ def test_get_numeric_data(self): tm.assert_index_equal( numeric.items, pd.Index(["int", "float", "complex", "bool"]) ) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("float").internal_values(), numeric.get("float").internal_values() ) # Check sharing numeric.set("float", np.array([100.0, 200.0, 300.0])) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("float").internal_values(), np.array([100.0, 200.0, 300.0]) ) @@ -755,7 +749,7 @@ def test_get_numeric_data(self): numeric.items, pd.Index(["int", "float", "complex", "bool"]) ) numeric2.set("float", np.array([1000.0, 2000.0, 3000.0])) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("float").internal_values(), np.array([100.0, 200.0, 300.0]) ) @@ -769,7 +763,7 @@ def test_get_bool_data(self): bools = mgr.get_bool_data() tm.assert_index_equal(bools.items, pd.Index(["bool"])) - assert_almost_equal( + tm.assert_almost_equal( mgr.get("bool").internal_values(), bools.get("bool").internal_values() ) @@ -1268,7 +1262,7 @@ def test_binop_other(self, op, value, dtype): # asserts anything meaningful result = op(s, e.value).dtypes expected = op(s, value).dtypes - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( diff --git a/pandas/tests/io/formats/test_css.py b/pandas/tests/io/formats/test_css.py index 74e78b033bac9..a6ad5d5edbf5f 100644 --- a/pandas/tests/io/formats/test_css.py +++ b/pandas/tests/io/formats/test_css.py @@ -1,6 +1,6 @@ import pytest -from pandas.util import testing as tm +import pandas.util.testing as tm from pandas.io.formats.css import CSSResolver, CSSWarning diff --git a/pandas/tests/io/formats/test_eng_formatting.py b/pandas/tests/io/formats/test_eng_formatting.py index d2a2d0a6a9706..2edbff3766c9d 100644 --- a/pandas/tests/io/formats/test_eng_formatting.py +++ b/pandas/tests/io/formats/test_eng_formatting.py @@ -2,7 +2,7 @@ import pandas as pd from pandas import DataFrame -from pandas.util import testing as tm +import pandas.util.testing as tm import pandas.io.formats.format as fmt diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 095dfb7876154..80edbd828194d 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -6,7 +6,7 @@ import pandas as pd from pandas import DataFrame, compat -from pandas.util import testing as tm +import pandas.util.testing as tm class TestToCSV: diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index 6c4a226b7ebd2..a2a577a0753f7 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -7,7 +7,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, option_context -from pandas.util import testing as tm +import pandas.util.testing as tm import pandas.io.formats.format as fmt diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 9ffb54d23e37e..ea8688517bd93 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -5,7 +5,7 @@ import pandas as pd from pandas import DataFrame, Series -from pandas.util import testing as tm +import pandas.util.testing as tm class TestToLatex: diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 26bfefecc632d..debc797fe6e88 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -10,7 +10,7 @@ import pandas.util._test_decorators as td import pandas as pd -from pandas.util import testing as tm +import pandas.util.testing as tm from pandas.io.parquet import ( FastParquetImpl, diff --git a/pandas/tests/io/test_spss.py b/pandas/tests/io/test_spss.py index b7a62b7ba431b..ca84156d104fc 100644 --- a/pandas/tests/io/test_spss.py +++ b/pandas/tests/io/test_spss.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas.util import testing as tm +import pandas.util.testing as tm pyreadstat = pytest.importorskip("pyreadstat") diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 82d67d1db3510..86cb7fc57b225 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -15,7 +15,6 @@ import pandas as pd from pandas import DataFrame, Series import pandas.util.testing as tm -from pandas.util.testing import assert_is_valid_plot_return_object, ensure_clean """ @@ -540,7 +539,7 @@ def _check_plot_works(f, filterwarnings="always", **kwargs): kwargs.get("ax", fig.add_subplot(211)) ret = f(**kwargs) - assert_is_valid_plot_return_object(ret) + tm.assert_is_valid_plot_return_object(ret) if f is pd.plotting.bootstrap_plot: assert "ax" not in kwargs @@ -548,9 +547,9 @@ def _check_plot_works(f, filterwarnings="always", **kwargs): kwargs["ax"] = fig.add_subplot(212) ret = f(**kwargs) - assert_is_valid_plot_return_object(ret) + tm.assert_is_valid_plot_return_object(ret) - with ensure_clean(return_filelike=True) as path: + with tm.ensure_clean(return_filelike=True) as path: plt.savefig(path) finally: tm.close(fig) diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index be24f102851b7..973bda8292b2a 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -15,7 +15,6 @@ from pandas.core.resample import DatetimeIndex from pandas.tests.plotting.common import TestPlotBase import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal, ensure_clean from pandas.tseries.offsets import DateOffset @@ -628,7 +627,7 @@ def test_secondary_y(self): axes = fig.get_axes() line = ax.get_lines()[0] xp = Series(line.get_ydata(), line.get_xdata()) - assert_series_equal(ser, xp) + tm.assert_series_equal(ser, xp) assert ax.get_yaxis().get_ticks_position() == "right" assert not axes[0].get_yaxis().get_visible() self.plt.close(fig) @@ -658,7 +657,7 @@ def test_secondary_y_ts(self): axes = fig.get_axes() line = ax.get_lines()[0] xp = Series(line.get_ydata(), line.get_xdata()).to_timestamp() - assert_series_equal(ser, xp) + tm.assert_series_equal(ser, xp) assert ax.get_yaxis().get_ticks_position() == "right" assert not axes[0].get_yaxis().get_visible() self.plt.close(fig) @@ -1557,7 +1556,7 @@ def _check_plot_works(f, freq=None, series=None, *args, **kwargs): ret = f(*args, **kwargs) assert ret is not None # TODO: do something more intelligent - with ensure_clean(return_filelike=True) as path: + with tm.ensure_clean(return_filelike=True) as path: plt.savefig(path) # GH18439 @@ -1567,7 +1566,7 @@ def _check_plot_works(f, freq=None, series=None, *args, **kwargs): # https://github.com/pandas-dev/pandas/issues/24088 # https://github.com/statsmodels/statsmodels/issues/4772 if "statsmodels" not in sys.modules: - with ensure_clean(return_filelike=True) as path: + with tm.ensure_clean(return_filelike=True) as path: pickle.dump(fig, path) finally: plt.close(fig) diff --git a/pandas/tests/reshape/test_union_categoricals.py b/pandas/tests/reshape/test_union_categoricals.py index 188f08777668e..9b56c4df6d7de 100644 --- a/pandas/tests/reshape/test_union_categoricals.py +++ b/pandas/tests/reshape/test_union_categoricals.py @@ -5,7 +5,7 @@ import pandas as pd from pandas import Categorical, CategoricalIndex, Series -from pandas.util import testing as tm +import pandas.util.testing as tm class TestUnionCategoricals: diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 5eb69fb2952dc..79608f4fb3cde 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -23,7 +23,7 @@ ) from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.ops import roperator -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.mark.parametrize( diff --git a/pandas/tests/series/test_explode.py b/pandas/tests/series/test_explode.py index e4974bd0af145..6262da6bdfabf 100644 --- a/pandas/tests/series/test_explode.py +++ b/pandas/tests/series/test_explode.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas.util import testing as tm +import pandas.util.testing as tm def test_basic(): diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 738afaea4b532..9dd88fd5dd25b 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -28,7 +28,6 @@ import pandas.core.common as com from pandas.core.sorting import safe_sort import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal class TestFactorize: @@ -1588,7 +1587,7 @@ def _check(arr): arr[mask] = np.inf exp = rankdata(arr) exp[mask] = np.nan - assert_almost_equal(result, exp) + tm.assert_almost_equal(result, exp) _check(np.array([np.nan, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 3, np.nan])) _check(np.array([4.0, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 4.0, np.nan])) diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index b4d575682ffca..fb0511f8902f7 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -11,7 +11,7 @@ from pandas.compat import PY36 from pandas import DataFrame, Series -from pandas.util import testing as tm +import pandas.util.testing as tm def import_module(name): diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index 6edd3125331b9..1974f712b13ee 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -8,7 +8,6 @@ from pandas.core.api import DataFrame from pandas.core.computation import expressions as expr import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal _frame = DataFrame(randn(10000, 4), columns=list("ABCD"), dtype="float64") _frame2 = DataFrame(randn(100, 4), columns=list("ABCD"), dtype="float64") @@ -356,7 +355,7 @@ def test_bool_ops_warn_on_arithmetic(self, op_str, opname): def test_bool_ops_column_name_dtype(self, test_input, expected): # GH 22383 - .ne fails if columns containing column name 'dtype' result = test_input.loc[:, ["a", "dtype"]].ne(test_input.loc[:, ["a", "dtype"]]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "arith", ("add", "sub", "mul", "mod", "truediv", "floordiv") @@ -382,4 +381,4 @@ def test_frame_series_axis(self, axis, arith): expr.set_use_numexpr(True) result = op_func(other, axis=axis) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/test_join.py b/pandas/tests/test_join.py index 2de70ceb53647..8940a82b33777 100644 --- a/pandas/tests/test_join.py +++ b/pandas/tests/test_join.py @@ -5,7 +5,6 @@ from pandas import Categorical, DataFrame, Index, merge import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal, assert_frame_equal class TestIndexer: @@ -182,12 +181,12 @@ def test_inner_join_indexer(): index, ares, bres = _join.inner_join_indexer(a, b) index_exp = np.array([3, 5], dtype=np.int64) - assert_almost_equal(index, index_exp) + tm.assert_almost_equal(index, index_exp) aexp = np.array([2, 4], dtype=np.int64) bexp = np.array([1, 2], dtype=np.int64) - assert_almost_equal(ares, aexp) - assert_almost_equal(bres, bexp) + tm.assert_almost_equal(ares, aexp) + tm.assert_almost_equal(bres, bexp) a = np.array([5], dtype=np.int64) b = np.array([5], dtype=np.int64) @@ -205,12 +204,12 @@ def test_outer_join_indexer(): index, ares, bres = _join.outer_join_indexer(a, b) index_exp = np.array([0, 1, 2, 3, 4, 5, 7, 9], dtype=np.int64) - assert_almost_equal(index, index_exp) + tm.assert_almost_equal(index, index_exp) aexp = np.array([-1, 0, 1, 2, 3, 4, -1, -1], dtype=np.int64) bexp = np.array([0, -1, -1, 1, -1, 2, 3, 4], dtype=np.int64) - assert_almost_equal(ares, aexp) - assert_almost_equal(bres, bexp) + tm.assert_almost_equal(ares, aexp) + tm.assert_almost_equal(bres, bexp) a = np.array([5], dtype=np.int64) b = np.array([5], dtype=np.int64) @@ -227,12 +226,12 @@ def test_left_join_indexer(): index, ares, bres = _join.left_join_indexer(a, b) - assert_almost_equal(index, a) + tm.assert_almost_equal(index, a) aexp = np.array([0, 1, 2, 3, 4], dtype=np.int64) bexp = np.array([-1, -1, 1, -1, 2], dtype=np.int64) - assert_almost_equal(ares, aexp) - assert_almost_equal(bres, bexp) + tm.assert_almost_equal(ares, aexp) + tm.assert_almost_equal(bres, bexp) a = np.array([5], dtype=np.int64) b = np.array([5], dtype=np.int64) @@ -250,13 +249,13 @@ def test_left_join_indexer2(): res, lidx, ridx = _join.left_join_indexer(idx2.values, idx.values) exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) - assert_almost_equal(res, exp_res) + tm.assert_almost_equal(res, exp_res) exp_lidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.int64) - assert_almost_equal(lidx, exp_lidx) + tm.assert_almost_equal(lidx, exp_lidx) exp_ridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.int64) - assert_almost_equal(ridx, exp_ridx) + tm.assert_almost_equal(ridx, exp_ridx) def test_outer_join_indexer2(): @@ -266,13 +265,13 @@ def test_outer_join_indexer2(): res, lidx, ridx = _join.outer_join_indexer(idx2.values, idx.values) exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) - assert_almost_equal(res, exp_res) + tm.assert_almost_equal(res, exp_res) exp_lidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.int64) - assert_almost_equal(lidx, exp_lidx) + tm.assert_almost_equal(lidx, exp_lidx) exp_ridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.int64) - assert_almost_equal(ridx, exp_ridx) + tm.assert_almost_equal(ridx, exp_ridx) def test_inner_join_indexer2(): @@ -282,13 +281,13 @@ def test_inner_join_indexer2(): res, lidx, ridx = _join.inner_join_indexer(idx2.values, idx.values) exp_res = np.array([1, 1, 2, 5], dtype=np.int64) - assert_almost_equal(res, exp_res) + tm.assert_almost_equal(res, exp_res) exp_lidx = np.array([0, 0, 1, 2], dtype=np.int64) - assert_almost_equal(lidx, exp_lidx) + tm.assert_almost_equal(lidx, exp_lidx) exp_ridx = np.array([0, 1, 2, 3], dtype=np.int64) - assert_almost_equal(ridx, exp_ridx) + tm.assert_almost_equal(ridx, exp_ridx) def test_merge_join_categorical_multiindex(): @@ -315,7 +314,7 @@ def test_merge_join_categorical_multiindex(): ) result = a.join(b, on=["Cat1", "Int1"]) expected = expected.drop(["Cat", "Int"], axis=1) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) # Same test, but with ordered categorical a = { @@ -344,4 +343,4 @@ def test_merge_join_categorical_multiindex(): ) result = a.join(b, on=["Cat1", "Int1"]) expected = expected.drop(["Cat", "Int"], axis=1) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py index 9be35198a5592..32aeb7b186827 100644 --- a/pandas/tests/test_sorting.py +++ b/pandas/tests/test_sorting.py @@ -15,8 +15,7 @@ nargsort, safe_sort, ) -from pandas.util import testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm class TestSorting: @@ -98,8 +97,8 @@ def aggr(func): res = DataFrame(arr, columns=["jim", "joe"], index=mi) return res.sort_index() - assert_frame_equal(gr.mean(), aggr(np.mean)) - assert_frame_equal(gr.median(), aggr(np.median)) + tm.assert_frame_equal(gr.mean(), aggr(np.mean)) + tm.assert_frame_equal(gr.median(), aggr(np.median)) def test_lexsort_indexer(self): keys = [[np.nan] * 5 + list(range(100)) + [np.nan] * 5] @@ -205,22 +204,22 @@ def test_int64_overflow_issues(self): out = merge(left, right, how="outer") assert len(out) == len(left) - assert_series_equal(out["left"], -out["right"], check_names=False) + tm.assert_series_equal(out["left"], -out["right"], check_names=False) result = out.iloc[:, :-2].sum(axis=1) - assert_series_equal(out["left"], result, check_names=False) + tm.assert_series_equal(out["left"], result, check_names=False) assert result.name is None out.sort_values(out.columns.tolist(), inplace=True) out.index = np.arange(len(out)) for how in ["left", "right", "outer", "inner"]: - assert_frame_equal(out, merge(left, right, how=how, sort=True)) + tm.assert_frame_equal(out, merge(left, right, how=how, sort=True)) # check that left merge w/ sort=False maintains left frame order out = merge(left, right, how="left", sort=False) - assert_frame_equal(left, out[left.columns.tolist()]) + tm.assert_frame_equal(left, out[left.columns.tolist()]) out = merge(right, left, how="left", sort=False) - assert_frame_equal(right, out[right.columns.tolist()]) + tm.assert_frame_equal(right, out[right.columns.tolist()]) # one-2-many/none match n = 1 << 11 @@ -284,7 +283,7 @@ def align(df): def verify_order(df): kcols = list("ABCDEFG") - assert_frame_equal( + tm.assert_frame_equal( df[kcols].copy(), df[kcols].sort_values(kcols, kind="mergesort") ) @@ -309,7 +308,7 @@ def verify_order(df): verify_order(res) # as in GH9092 dtypes break with outer/right join - assert_frame_equal( + tm.assert_frame_equal( frame, align(res), check_dtype=how not in ("right", "outer") ) diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index cfaf123045b1f..f5d28ec82d1d4 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -10,14 +10,13 @@ from pandas import DataFrame, Index, MultiIndex, Series, concat, isna, notna import pandas.core.strings as strings import pandas.util.testing as tm -from pandas.util.testing import assert_index_equal, assert_series_equal def assert_series_or_index_equal(left, right): if isinstance(left, Series): - assert_series_equal(left, right) + tm.assert_series_equal(left, right) else: # Index - assert_index_equal(left, right) + tm.assert_index_equal(left, right) _any_string_method = [ @@ -363,7 +362,7 @@ def test_iter_single_element(self): pass assert not i - assert_series_equal(ds, s) + tm.assert_series_equal(ds, s) def test_iter_object_try_string(self): ds = Series([slice(None, randint(10), randint(10, 20)) for _ in range(4)]) @@ -1165,10 +1164,10 @@ def test_match(self): # na GH #6609 res = Series(["a", 0, np.nan]).str.match("a", na=False) exp = Series([True, False, False]) - assert_series_equal(exp, res) + tm.assert_series_equal(exp, res) res = Series(["a", 0, np.nan]).str.match("a") exp = Series([True, np.nan, np.nan]) - assert_series_equal(exp, res) + tm.assert_series_equal(exp, res) def test_extract_expand_None(self): values = Series(["fooBAD__barBAD", np.nan, "foo"]) @@ -1399,7 +1398,7 @@ def test_extract_expand_True(self): result_df = s_or_idx.str.extract(r"(?P<uno>A)\d", expand=True) assert isinstance(result_df, DataFrame) result_series = result_df["uno"] - assert_series_equal(result_series, Series(["A", "A"], name="uno")) + tm.assert_series_equal(result_series, Series(["A", "A"], name="uno")) def test_extract_series(self): # extract should give the same result whether or not the @@ -3087,15 +3086,15 @@ def test_strip_lstrip_rstrip_args(self): rs = values.str.strip("x") xp = Series(["ABC", " BNSD", "LDFJH "]) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) rs = values.str.lstrip("x") xp = Series(["ABCxx", " BNSD", "LDFJH xx"]) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) rs = values.str.rstrip("x") xp = Series(["xxABC", "xx BNSD", "LDFJH "]) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) def test_wrap(self): # test values are: two words less than width, two words equal to width, @@ -3132,14 +3131,14 @@ def test_wrap(self): ) rs = values.str.wrap(12, break_long_words=True) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) # test with pre and post whitespace (non-unicode), NaN, and non-ascii # Unicode values = Series([" pre ", np.nan, "\xac\u20ac\U00008000 abadcafe"]) xp = Series([" pre", np.nan, "\xac\u20ac\U00008000 ab\nadcafe"]) rs = values.str.wrap(6) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) def test_get(self): values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"]) @@ -3202,31 +3201,31 @@ def test_contains_moar(self): expected = Series( [False, False, False, True, True, False, np.nan, False, False, True] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.contains("a", case=False) expected = Series( [True, False, False, True, True, False, np.nan, True, False, True] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.contains("Aa") expected = Series( [False, False, False, True, False, False, np.nan, False, False, False] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.contains("ba") expected = Series( [False, False, False, True, False, False, np.nan, False, False, False] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.contains("ba", case=False) expected = Series( [False, False, False, True, True, False, np.nan, True, False, False] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_contains_nan(self): # PR #14171 @@ -3234,19 +3233,19 @@ def test_contains_nan(self): result = s.str.contains("foo", na=False) expected = Series([False, False, False], dtype=np.bool_) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.contains("foo", na=True) expected = Series([True, True, True], dtype=np.bool_) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.contains("foo", na="foo") expected = Series(["foo", "foo", "foo"], dtype=np.object_) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.contains("foo") expected = Series([np.nan, np.nan, np.nan], dtype=np.object_) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_replace_moar(self): # PR #1179 @@ -3256,7 +3255,7 @@ def test_replace_moar(self): expected = Series( ["YYY", "B", "C", "YYYaba", "Baca", "", np.nan, "CYYYBYYY", "dog", "cat"] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.replace("A", "YYY", case=False) expected = Series( @@ -3273,7 +3272,7 @@ def test_replace_moar(self): "cYYYt", ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str.replace("^.a|dog", "XX-XX ", case=False) expected = Series( @@ -3290,7 +3289,7 @@ def test_replace_moar(self): "XX-XX t", ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_string_slice_get_syntax(self): s = Series( @@ -3309,15 +3308,15 @@ def test_string_slice_get_syntax(self): result = s.str[0] expected = s.str.get(0) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str[:3] expected = s.str.slice(stop=3) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.str[2::-1] expected = s.str.slice(start=2, step=-1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_string_slice_out_of_bounds(self): s = Series([(1, 2), (1,), (3, 4, 5)]) @@ -3325,12 +3324,12 @@ def test_string_slice_out_of_bounds(self): result = s.str[1] expected = Series([2, np.nan, 4]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series(["foo", "b", "ba"]) result = s.str[1] expected = Series(["o", np.nan, "a"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_match_findall_flags(self): data = { diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py index bc1eee2a0aaf2..55f83e492e2cc 100644 --- a/pandas/tests/tools/test_numeric.py +++ b/pandas/tests/tools/test_numeric.py @@ -6,7 +6,7 @@ import pandas as pd from pandas import DataFrame, Index, Series, to_numeric -from pandas.util import testing as tm +import pandas.util.testing as tm @pytest.fixture(params=[None, "ignore", "raise", "coerce"]) diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py index 9ab58f8a51485..0bc30347b3fa9 100644 --- a/pandas/tests/tslibs/test_parsing.py +++ b/pandas/tests/tslibs/test_parsing.py @@ -11,7 +11,7 @@ from pandas._libs.tslibs.parsing import parse_time_string import pandas.util._test_decorators as td -from pandas.util import testing as tm +import pandas.util.testing as tm def test_parse_time_string():
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Fyi: When the remaining PRs of this are merged, I'll add another one to add the linting rule - then we can close the issue
https://api.github.com/repos/pandas-dev/pandas/pulls/29307
2019-10-31T09:05:02Z
2019-10-31T13:09:48Z
2019-10-31T13:09:48Z
2019-10-31T13:10:40Z
TST: Test DataFrame rename with ChainMap
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 017cbea7ec723..11d73fc37105e 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -1,3 +1,4 @@ +from collections import ChainMap from datetime import datetime, timedelta import inspect @@ -691,6 +692,24 @@ def test_rename(self, float_frame): tm.assert_index_equal(renamed.index, Index(["bar", "foo"], name="name")) assert renamed.index.name == renamer.index.name + @pytest.mark.parametrize( + "args,kwargs", + [ + ((ChainMap({"A": "a"}, {"B": "b"}),), dict(axis="columns")), + ((), dict(columns=ChainMap({"A": "a"}, {"B": "b"}))), + ], + ) + def test_rename_chainmap(self, args, kwargs): + # see gh-23859 + colAData = range(1, 11) + colBdata = np.random.randn(10) + + df = DataFrame({"A": colAData, "B": colBdata}) + result = df.rename(*args, **kwargs) + + expected = DataFrame({"a": colAData, "b": colBdata}) + tm.assert_frame_equal(result, expected) + def test_rename_axis_inplace(self, float_frame): # GH 15704 expected = float_frame.rename_axis("foo")
Closes https://github.com/pandas-dev/pandas/issues/23859
https://api.github.com/repos/pandas-dev/pandas/pulls/29306
2019-10-31T06:39:04Z
2019-10-31T08:06:04Z
2019-10-31T08:06:03Z
2019-10-31T08:07:43Z
CLN: tighten Exception catching in indexing.py
diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst index dd59a99b3df9e..409791c7530a2 100644 --- a/doc/source/reference/indexing.rst +++ b/doc/source/reference/indexing.rst @@ -93,7 +93,6 @@ Compatibility with MultiIndex :toctree: api/ Index.set_names - Index.is_lexsorted_for_tuple Index.droplevel Missing values diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 2e2c5281e6752..f9cecd662e545 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -256,6 +256,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Ability to read pickles containing :class:`Categorical` instances created with pre-0.16 version of pandas has been removed (:issue:`27538`) - Removed the previously deprecated ``reduce`` and ``broadcast`` arguments from :meth:`DataFrame.apply` (:issue:`18577`) - Removed the previously deprecated ``assert_raises_regex`` function in ``pandas.util.testing`` (:issue:`29174`) +- Removed :meth:`Index.is_lexsorted_for_tuple` (:issue:`29305`) - .. _whatsnew_1000.performance: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 187c7e2f3a7f7..301426d237d19 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1726,9 +1726,6 @@ def _is_strictly_monotonic_decreasing(self): """ return self.is_unique and self.is_monotonic_decreasing - def is_lexsorted_for_tuple(self, tup): - return True - @cache_readonly def is_unique(self): """ diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 44c786f003369..7db54f4305c2e 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -101,7 +101,6 @@ class IndexingError(Exception): class _NDFrameIndexer(_NDFrameIndexerBase): _valid_types = None # type: str - _exception = Exception axis = None def __call__(self, axis=None): @@ -881,14 +880,6 @@ def _handle_lowerdim_multi_index_axis0(self, tup: Tuple): # else IndexingError will be raised if len(tup) <= self.obj.index.nlevels and len(tup) > self.ndim: raise ek - except Exception as e1: - if isinstance(tup[0], (slice, Index)): - raise IndexingError("Handle elsewhere") - - # raise the error if we are not sorted - ax0 = self.obj._get_axis(0) - if not ax0.is_lexsorted_for_tuple(tup): - raise e1 return None @@ -1385,8 +1376,6 @@ def _convert_for_reindex(self, key, axis: int): class _LocationIndexer(_NDFrameIndexer): - _exception = Exception - def __getitem__(self, key): if type(key) is tuple: key = tuple(com.apply_if_callable(x, self.obj) for x in key) @@ -1417,10 +1406,7 @@ def _getbool_axis(self, key, axis: int): labels = self.obj._get_axis(axis) key = check_bool_indexer(labels, key) inds = key.nonzero()[0] - try: - return self.obj.take(inds, axis=axis) - except Exception as detail: - raise self._exception(detail) + return self.obj.take(inds, axis=axis) def _get_slice_axis(self, slice_obj: slice, axis: int): """ this is pretty simple as we just have to deal with labels """ @@ -1685,7 +1671,6 @@ class _LocIndexer(_LocationIndexer): "endpoints included! Can be slices of integers if the " "index is integers), listlike of labels, boolean" ) - _exception = KeyError @Appender(_NDFrameIndexer._validate_key.__doc__) def _validate_key(self, key, axis: int): @@ -1970,7 +1955,6 @@ class _iLocIndexer(_LocationIndexer): "integer, integer slice (START point is INCLUDED, END " "point is EXCLUDED), listlike of integers, boolean array" ) - _exception = IndexError _get_slice_axis = _NDFrameIndexer._get_slice_axis def _validate_key(self, key, axis: int):
get rid of is_lexsorted_for_tuple while we're at it
https://api.github.com/repos/pandas-dev/pandas/pulls/29305
2019-10-31T01:00:28Z
2019-11-03T20:46:23Z
2019-11-03T20:46:23Z
2019-11-03T21:42:27Z
CLN: Consistent pandas.util.testing imports in pandas/tests/frame - part 4
diff --git a/pandas/tests/frame/test_sort_values_level_as_str.py b/pandas/tests/frame/test_sort_values_level_as_str.py index 2bcc115bcd09c..b0287d9180859 100644 --- a/pandas/tests/frame/test_sort_values_level_as_str.py +++ b/pandas/tests/frame/test_sort_values_level_as_str.py @@ -4,8 +4,7 @@ from pandas.errors import PerformanceWarning from pandas import DataFrame -from pandas.util import testing as tm -from pandas.util.testing import assert_frame_equal +import pandas.util.testing as tm @pytest.fixture @@ -62,7 +61,7 @@ def test_sort_index_level_and_column_label(df_none, df_idx, sort_names, ascendin # Compute result sorting on mix on columns and index levels result = df_idx.sort_values(by=sort_names, ascending=ascending, axis=0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_sort_column_level_and_index_label(df_none, df_idx, sort_names, ascending): @@ -88,6 +87,6 @@ def test_sort_column_level_and_index_label(df_none, df_idx, sort_names, ascendin # Accessing multi-level columns that are not lexsorted raises a # performance warning with tm.assert_produces_warning(PerformanceWarning, check_stacklevel=False): - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) else: - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_sorting.py b/pandas/tests/frame/test_sorting.py index 2b4b20d318adf..9ea78b974fcbb 100644 --- a/pandas/tests/frame/test_sorting.py +++ b/pandas/tests/frame/test_sorting.py @@ -16,7 +16,6 @@ ) from pandas.api.types import CategoricalDtype import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal class TestDataFrameSorting: @@ -29,30 +28,30 @@ def test_sort_values(self): sorted_df = frame.sort_values(by="A") indexer = frame["A"].argsort().values expected = frame.loc[frame.index[indexer]] - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.sort_values(by="A", ascending=False) indexer = indexer[::-1] expected = frame.loc[frame.index[indexer]] - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.sort_values(by="A", ascending=False) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # GH4839 sorted_df = frame.sort_values(by=["A"], ascending=[False]) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # multiple bys sorted_df = frame.sort_values(by=["B", "C"]) expected = frame.loc[[2, 1, 3]] - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.sort_values(by=["B", "C"], ascending=False) - assert_frame_equal(sorted_df, expected[::-1]) + tm.assert_frame_equal(sorted_df, expected[::-1]) sorted_df = frame.sort_values(by=["B", "A"], ascending=[True, False]) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) msg = "No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>" with pytest.raises(ValueError, match=msg): @@ -61,22 +60,22 @@ def test_sort_values(self): # by row (axis=1): GH 10806 sorted_df = frame.sort_values(by=3, axis=1) expected = frame - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.sort_values(by=3, axis=1, ascending=False) expected = frame.reindex(columns=["C", "B", "A"]) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.sort_values(by=[1, 2], axis="columns") expected = frame.reindex(columns=["B", "A", "C"]) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=[True, False]) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.sort_values(by=[1, 3], axis=1, ascending=False) expected = frame.reindex(columns=["C", "B", "A"]) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) msg = r"Length of ascending \(5\) != length of by \(2\)" with pytest.raises(ValueError, match=msg): @@ -90,22 +89,22 @@ def test_sort_values_inplace(self): sorted_df = frame.copy() sorted_df.sort_values(by="A", inplace=True) expected = frame.sort_values(by="A") - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.copy() sorted_df.sort_values(by=1, axis=1, inplace=True) expected = frame.sort_values(by=1, axis=1) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.copy() sorted_df.sort_values(by="A", ascending=False, inplace=True) expected = frame.sort_values(by="A", ascending=False) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) sorted_df = frame.copy() sorted_df.sort_values(by=["A", "B"], ascending=False, inplace=True) expected = frame.sort_values(by=["A", "B"], ascending=False) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) def test_sort_nan(self): # GH3917 @@ -118,18 +117,18 @@ def test_sort_nan(self): index=[2, 0, 3, 1, 6, 4, 5], ) sorted_df = df.sort_values(["A"], na_position="first") - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) expected = DataFrame( {"A": [nan, 8, 6, 4, 2, 1, 1], "B": [5, 4, 5, 5, nan, 9, 2]}, index=[2, 5, 4, 6, 1, 0, 3], ) sorted_df = df.sort_values(["A"], na_position="first", ascending=False) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) expected = df.reindex(columns=["B", "A"]) sorted_df = df.sort_values(by=1, axis=1, na_position="first") - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # na_position='last', order expected = DataFrame( @@ -137,7 +136,7 @@ def test_sort_nan(self): index=[3, 0, 1, 6, 4, 5, 2], ) sorted_df = df.sort_values(["A", "B"]) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # na_position='first', order expected = DataFrame( @@ -145,7 +144,7 @@ def test_sort_nan(self): index=[2, 3, 0, 1, 6, 4, 5], ) sorted_df = df.sort_values(["A", "B"], na_position="first") - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # na_position='first', not order expected = DataFrame( @@ -153,7 +152,7 @@ def test_sort_nan(self): index=[2, 0, 3, 1, 6, 4, 5], ) sorted_df = df.sort_values(["A", "B"], ascending=[1, 0], na_position="first") - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # na_position='last', not order expected = DataFrame( @@ -161,7 +160,7 @@ def test_sort_nan(self): index=[5, 4, 6, 1, 3, 0, 2], ) sorted_df = df.sort_values(["A", "B"], ascending=[0, 1], na_position="last") - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # Test DataFrame with nan label df = DataFrame( @@ -175,7 +174,7 @@ def test_sort_nan(self): {"A": [1, 2, nan, 1, 6, 8, 4], "B": [9, nan, 5, 2, 5, 4, 5]}, index=[1, 2, 3, 4, 5, 6, nan], ) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=True, na_position='first' sorted_df = df.sort_index(na_position="first") @@ -183,7 +182,7 @@ def test_sort_nan(self): {"A": [4, 1, 2, nan, 1, 6, 8], "B": [5, 9, nan, 5, 2, 5, 4]}, index=[nan, 1, 2, 3, 4, 5, 6], ) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='last' sorted_df = df.sort_index(kind="quicksort", ascending=False) @@ -191,7 +190,7 @@ def test_sort_nan(self): {"A": [8, 6, 1, nan, 2, 1, 4], "B": [4, 5, 2, 5, nan, 9, 5]}, index=[6, 5, 4, 3, 2, 1, nan], ) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) # NaN label, ascending=False, na_position='first' sorted_df = df.sort_index( @@ -201,7 +200,7 @@ def test_sort_nan(self): {"A": [4, 8, 6, 1, nan, 2, 1], "B": [5, 4, 5, 2, 5, nan, 9]}, index=[nan, 6, 5, 4, 3, 2, 1], ) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) def test_stable_descending_sort(self): # GH #6399 @@ -210,7 +209,7 @@ def test_stable_descending_sort(self): columns=["sort_col", "order"], ) sorted_df = df.sort_values(by="sort_col", kind="mergesort", ascending=False) - assert_frame_equal(df, sorted_df) + tm.assert_frame_equal(df, sorted_df) def test_stable_descending_multicolumn_sort(self): nan = np.nan @@ -223,7 +222,7 @@ def test_stable_descending_multicolumn_sort(self): sorted_df = df.sort_values( ["A", "B"], ascending=[0, 1], na_position="first", kind="mergesort" ) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) expected = DataFrame( {"A": [nan, 8, 6, 4, 2, 1, 1], "B": [5, 4, 5, 5, nan, 9, 2]}, @@ -232,7 +231,7 @@ def test_stable_descending_multicolumn_sort(self): sorted_df = df.sort_values( ["A", "B"], ascending=[0, 0], na_position="first", kind="mergesort" ) - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) def test_sort_multi_index(self): # GH 25775, testing that sorting by index works with a multi-index. @@ -253,7 +252,7 @@ def test_stable_categorial(self): df = DataFrame({"x": pd.Categorical(np.repeat([1, 2, 3, 4], 5), ordered=True)}) expected = df.copy() sorted_df = df.sort_values("x", kind="mergesort") - assert_frame_equal(sorted_df, expected) + tm.assert_frame_equal(sorted_df, expected) def test_sort_datetimes(self): @@ -283,16 +282,16 @@ def test_sort_datetimes(self): df1 = df.sort_values(by="A") df2 = df.sort_values(by=["A"]) - assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df2) df1 = df.sort_values(by="B") df2 = df.sort_values(by=["B"]) - assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df2) df1 = df.sort_values(by="B") df2 = df.sort_values(by=["C", "B"]) - assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df2) def test_frame_column_inplace_sort_exception(self, float_frame): s = float_frame["A"] @@ -325,14 +324,14 @@ def test_sort_nat_values_in_int_column(self): # NaT is not a "na" for int64 columns, so na_position must not # influence the result: df_sorted = df.sort_values(["int", "float"], na_position="last") - assert_frame_equal(df_sorted, df_reversed) + tm.assert_frame_equal(df_sorted, df_reversed) df_sorted = df.sort_values(["int", "float"], na_position="first") - assert_frame_equal(df_sorted, df_reversed) + tm.assert_frame_equal(df_sorted, df_reversed) # reverse sorting order df_sorted = df.sort_values(["int", "float"], ascending=False) - assert_frame_equal(df_sorted, df) + tm.assert_frame_equal(df_sorted, df) # and now check if NaT is still considered as "na" for datetime64 # columns: @@ -348,14 +347,14 @@ def test_sort_nat_values_in_int_column(self): ) df_sorted = df.sort_values(["datetime", "float"], na_position="first") - assert_frame_equal(df_sorted, df_reversed) + tm.assert_frame_equal(df_sorted, df_reversed) df_sorted = df.sort_values(["datetime", "float"], na_position="last") - assert_frame_equal(df_sorted, df) + tm.assert_frame_equal(df_sorted, df) # Ascending should not affect the results. df_sorted = df.sort_values(["datetime", "float"], ascending=False) - assert_frame_equal(df_sorted, df) + tm.assert_frame_equal(df_sorted, df) def test_sort_nat(self): @@ -392,7 +391,7 @@ def test_sort_index_multicolumn(self): result = frame.sort_values(by=["A", "B"]) indexer = np.lexsort((frame["B"], frame["A"])) expected = frame.take(indexer) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # use .sort_values #9816 with tm.assert_produces_warning(FutureWarning): @@ -402,7 +401,7 @@ def test_sort_index_multicolumn(self): (frame["B"].rank(ascending=False), frame["A"].rank(ascending=False)) ) expected = frame.take(indexer) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # use .sort_values #9816 with tm.assert_produces_warning(FutureWarning): @@ -410,7 +409,7 @@ def test_sort_index_multicolumn(self): result = frame.sort_values(by=["B", "A"]) indexer = np.lexsort((frame["A"], frame["B"])) expected = frame.take(indexer) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_sort_index_inplace(self): frame = DataFrame( @@ -423,25 +422,25 @@ def test_sort_index_inplace(self): df = unordered.copy() df.sort_index(inplace=True) expected = frame - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) assert a_id != id(df["A"]) df = unordered.copy() df.sort_index(ascending=False, inplace=True) expected = frame[::-1] - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # axis=1 unordered = frame.loc[:, ["D", "B", "C", "A"]] df = unordered.copy() df.sort_index(axis=1, inplace=True) expected = frame - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) df = unordered.copy() df.sort_index(axis=1, ascending=False, inplace=True) expected = frame.iloc[:, ::-1] - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_sort_index_different_sortorder(self): A = np.arange(20).repeat(5) @@ -460,18 +459,18 @@ def test_sort_index_different_sortorder(self): ex_indexer = np.lexsort((df.B.max() - df.B, df.A)) expected = df.take(ex_indexer) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # test with multiindex, too idf = df.set_index(["A", "B"]) result = idf.sort_index(ascending=[1, 0]) expected = idf.take(ex_indexer) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # also, Series! result = idf["C"].sort_index(ascending=[1, 0]) - assert_series_equal(result, expected["C"]) + tm.assert_series_equal(result, expected["C"]) def test_sort_index_duplicates(self): @@ -524,7 +523,7 @@ def test_sort_index_duplicates(self): with tm.assert_produces_warning(FutureWarning): df.sort_index(by=("a", 1)) result = df.sort_values(by=("a", 1)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_sort_index_level(self): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) @@ -532,25 +531,25 @@ def test_sort_index_level(self): result = df.sort_index(level="A", sort_remaining=False) expected = df - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.sort_index(level=["A", "B"], sort_remaining=False) expected = df - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Error thrown by sort_index when # first index is sorted last (#26053) result = df.sort_index(level=["C", "B", "A"]) expected = df.iloc[[1, 0]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.sort_index(level=["B", "C", "A"]) expected = df.iloc[[1, 0]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.sort_index(level=["C", "A"]) expected = df.iloc[[1, 0]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_sort_index_categorical_index(self): @@ -563,11 +562,11 @@ def test_sort_index_categorical_index(self): result = df.sort_index() expected = df.iloc[[4, 0, 1, 5, 2, 3]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.sort_index(ascending=False) expected = df.iloc[[2, 3, 0, 1, 5, 4]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_sort_index(self): # GH13496 @@ -582,20 +581,20 @@ def test_sort_index(self): unordered = frame.loc[[3, 2, 4, 1]] result = unordered.sort_index(axis=0) expected = frame - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = unordered.sort_index(ascending=False) expected = frame[::-1] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis=1 : sort columns by column names unordered = frame.iloc[:, [2, 1, 3, 0]] result = unordered.sort_index(axis=1) - assert_frame_equal(result, frame) + tm.assert_frame_equal(result, frame) result = unordered.sort_index(axis=1, ascending=False) expected = frame.iloc[:, ::-1] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("level", ["A", 0]) # GH 21052 def test_sort_index_multiindex(self, level): @@ -612,7 +611,7 @@ def test_sort_index_multiindex(self, level): ) expected = pd.DataFrame([[5, 6], [3, 4], [1, 2]], index=expected_mi) result = df.sort_index(level=level) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # sort_remaining=False expected_mi = MultiIndex.from_tuples( @@ -620,7 +619,7 @@ def test_sort_index_multiindex(self, level): ) expected = pd.DataFrame([[5, 6], [1, 2], [3, 4]], index=expected_mi) result = df.sort_index(level=level, sort_remaining=False) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_sort_index_intervalindex(self): # this is a de-facto sort via unstack @@ -672,7 +671,7 @@ def test_sort_index_na_position_with_categories(self): index=na_indices + category_indices, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # sort ascending with na last result = df.sort_values( @@ -687,7 +686,7 @@ def test_sort_index_na_position_with_categories(self): index=category_indices + na_indices, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # sort descending with na first result = df.sort_values( @@ -704,7 +703,7 @@ def test_sort_index_na_position_with_categories(self): index=reversed_na_indices + reversed_category_indices, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # sort descending with na last result = df.sort_values( @@ -721,7 +720,7 @@ def test_sort_index_na_position_with_categories(self): index=reversed_category_indices + reversed_na_indices, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_sort_index_na_position_with_categories_raises(self): df = pd.DataFrame( diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 3355d6e746db2..cad1fd60ca2a9 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -18,11 +18,6 @@ to_datetime, ) import pandas.util.testing as tm -from pandas.util.testing import ( - assert_frame_equal, - assert_index_equal, - assert_series_equal, -) import pandas.tseries.offsets as offsets @@ -36,7 +31,7 @@ class TestDataFrameTimeSeriesMethods: def test_diff(self, datetime_frame): the_diff = datetime_frame.diff(1) - assert_series_equal( + tm.assert_series_equal( the_diff["A"], datetime_frame["A"] - datetime_frame["A"].shift(1) ) @@ -51,7 +46,7 @@ def test_diff(self, datetime_frame): # mixed numeric tf = datetime_frame.astype("float32") the_diff = tf.diff(1) - assert_series_equal(the_diff["A"], tf["A"] - tf["A"].shift(1)) + tm.assert_series_equal(the_diff["A"], tf["A"] - tf["A"].shift(1)) # issue 10907 df = pd.DataFrame({"y": pd.Series([2]), "z": pd.Series([3])}) @@ -60,7 +55,7 @@ def test_diff(self, datetime_frame): expected = pd.DataFrame( {"x": np.nan, "y": pd.Series(1), "z": pd.Series(1)} ).astype("float64") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("tz", [None, "UTC"]) def test_diff_datetime_axis0(self, tz): @@ -79,7 +74,7 @@ def test_diff_datetime_axis0(self, tz): 1: pd.TimedeltaIndex(["NaT", "1 days"]), } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("tz", [None, "UTC"]) def test_diff_datetime_axis1(self, tz): @@ -98,7 +93,7 @@ def test_diff_datetime_axis1(self, tz): 1: pd.TimedeltaIndex(["0 days", "0 days"]), } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) else: with pytest.raises(NotImplementedError): result = df.diff(axis=1) @@ -116,7 +111,7 @@ def test_diff_timedelta(self): exp = DataFrame( [[pd.NaT, np.nan], [pd.Timedelta("00:01:00"), 1]], columns=["time", "value"] ) - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) def test_diff_mixed_dtype(self): df = DataFrame(np.random.randn(5, 3)) @@ -128,34 +123,38 @@ def test_diff_mixed_dtype(self): def test_diff_neg_n(self, datetime_frame): rs = datetime_frame.diff(-1) xp = datetime_frame - datetime_frame.shift(-1) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_diff_float_n(self, datetime_frame): rs = datetime_frame.diff(1.0) xp = datetime_frame.diff(1) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_diff_axis(self): # GH 9727 df = DataFrame([[1.0, 2.0], [3.0, 4.0]]) - assert_frame_equal(df.diff(axis=1), DataFrame([[np.nan, 1.0], [np.nan, 1.0]])) - assert_frame_equal(df.diff(axis=0), DataFrame([[np.nan, np.nan], [2.0, 2.0]])) + tm.assert_frame_equal( + df.diff(axis=1), DataFrame([[np.nan, 1.0], [np.nan, 1.0]]) + ) + tm.assert_frame_equal( + df.diff(axis=0), DataFrame([[np.nan, np.nan], [2.0, 2.0]]) + ) def test_pct_change(self, datetime_frame): rs = datetime_frame.pct_change(fill_method=None) - assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1) + tm.assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1) rs = datetime_frame.pct_change(2) filled = datetime_frame.fillna(method="pad") - assert_frame_equal(rs, filled / filled.shift(2) - 1) + tm.assert_frame_equal(rs, filled / filled.shift(2) - 1) rs = datetime_frame.pct_change(fill_method="bfill", limit=1) filled = datetime_frame.fillna(method="bfill", limit=1) - assert_frame_equal(rs, filled / filled.shift(1) - 1) + tm.assert_frame_equal(rs, filled / filled.shift(1) - 1) rs = datetime_frame.pct_change(freq="5D") filled = datetime_frame.fillna(method="pad") - assert_frame_equal( + tm.assert_frame_equal( rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled) ) @@ -167,7 +166,7 @@ def test_pct_change_shift_over_nas(self): chg = df.pct_change() expected = Series([np.nan, 0.5, 0.0, 2.5 / 1.5 - 1, 0.2]) edf = DataFrame({"a": expected, "b": expected}) - assert_frame_equal(chg, edf) + tm.assert_frame_equal(chg, edf) @pytest.mark.parametrize( "freq, periods, fill_method, limit", @@ -190,12 +189,12 @@ def test_pct_change_periods_freq( rs_periods = datetime_frame.pct_change( periods, fill_method=fill_method, limit=limit ) - assert_frame_equal(rs_freq, rs_periods) + tm.assert_frame_equal(rs_freq, rs_periods) empty_ts = DataFrame(index=datetime_frame.index, columns=datetime_frame.columns) rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit) rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit) - assert_frame_equal(rs_freq, rs_periods) + tm.assert_frame_equal(rs_freq, rs_periods) def test_frame_ctor_datetime64_column(self): rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s") @@ -256,28 +255,28 @@ def test_shift(self, datetime_frame, int_frame): tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(5) - assert_series_equal(shiftedFrame["A"], shiftedSeries) + tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) shiftedFrame = datetime_frame.shift(-5) tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) shiftedSeries = datetime_frame["A"].shift(-5) - assert_series_equal(shiftedFrame["A"], shiftedSeries) + tm.assert_series_equal(shiftedFrame["A"], shiftedSeries) # shift by 0 unshifted = datetime_frame.shift(0) - assert_frame_equal(unshifted, datetime_frame) + tm.assert_frame_equal(unshifted, datetime_frame) # shift by DateOffset shiftedFrame = datetime_frame.shift(5, freq=offsets.BDay()) assert len(shiftedFrame) == len(datetime_frame) shiftedFrame2 = datetime_frame.shift(5, freq="B") - assert_frame_equal(shiftedFrame, shiftedFrame2) + tm.assert_frame_equal(shiftedFrame, shiftedFrame2) d = datetime_frame.index[0] shifted_d = d + offsets.BDay(5) - assert_series_equal( + tm.assert_series_equal( datetime_frame.xs(d), shiftedFrame.xs(shifted_d), check_names=False ) @@ -296,8 +295,8 @@ def test_shift(self, datetime_frame, int_frame): shifted2 = ps.shift(1, "B") shifted3 = ps.shift(1, offsets.BDay()) - assert_frame_equal(shifted2, shifted3) - assert_frame_equal(ps, shifted2.shift(-1, "B")) + tm.assert_frame_equal(shifted2, shifted3) + tm.assert_frame_equal(ps, shifted2.shift(-1, "B")) msg = "does not match PeriodIndex freq" with pytest.raises(ValueError, match=msg): @@ -312,7 +311,7 @@ def test_shift(self, datetime_frame, int_frame): axis=1, ) result = df.shift(1, axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # shift named axis df = DataFrame(np.random.rand(10, 5)) @@ -322,7 +321,7 @@ def test_shift(self, datetime_frame, int_frame): axis=1, ) result = df.shift(1, axis="columns") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_shift_bool(self): df = DataFrame({"high": [True, False], "low": [False, False]}) @@ -331,7 +330,7 @@ def test_shift_bool(self): np.array([[np.nan, np.nan], [True, False]], dtype=object), columns=["high", "low"], ) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_shift_categorical(self): # GH 9416 @@ -340,7 +339,7 @@ def test_shift_categorical(self): df = DataFrame({"one": s1, "two": s2}) rs = df.shift(1) xp = DataFrame({"one": s1.shift(1), "two": s2.shift(1)}) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_shift_fill_value(self): # GH #24128 @@ -351,20 +350,20 @@ def test_shift_fill_value(self): [0, 1, 2, 3, 4], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(1, fill_value=0) - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) exp = DataFrame( [0, 0, 1, 2, 3], index=date_range("1/1/2000", periods=5, freq="H") ) result = df.shift(2, fill_value=0) - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) def test_shift_empty(self): # Regression test for #8019 df = DataFrame({"foo": []}) rs = df.shift(-1) - assert_frame_equal(df, rs) + tm.assert_frame_equal(df, rs) def test_shift_duplicate_columns(self): # GH 9092; verify that position-based shifting works @@ -382,11 +381,11 @@ def test_shift_duplicate_columns(self): # sanity check the base case nulls = shifted[0].isna().sum() - assert_series_equal(nulls, Series(range(1, 6), dtype="int64")) + tm.assert_series_equal(nulls, Series(range(1, 6), dtype="int64")) # check all answers are the same - assert_frame_equal(shifted[0], shifted[1]) - assert_frame_equal(shifted[0], shifted[2]) + tm.assert_frame_equal(shifted[0], shifted[1]) + tm.assert_frame_equal(shifted[0], shifted[2]) def test_tshift(self, datetime_frame): # PeriodIndex @@ -394,13 +393,13 @@ def test_tshift(self, datetime_frame): shifted = ps.tshift(1) unshifted = shifted.tshift(-1) - assert_frame_equal(unshifted, ps) + tm.assert_frame_equal(unshifted, ps) shifted2 = ps.tshift(freq="B") - assert_frame_equal(shifted, shifted2) + tm.assert_frame_equal(shifted, shifted2) shifted3 = ps.tshift(freq=offsets.BDay()) - assert_frame_equal(shifted, shifted3) + tm.assert_frame_equal(shifted, shifted3) with pytest.raises(ValueError, match="does not match"): ps.tshift(freq="M") @@ -409,10 +408,10 @@ def test_tshift(self, datetime_frame): shifted = datetime_frame.tshift(1) unshifted = shifted.tshift(-1) - assert_frame_equal(datetime_frame, unshifted) + tm.assert_frame_equal(datetime_frame, unshifted) shifted2 = datetime_frame.tshift(freq=datetime_frame.index.freq) - assert_frame_equal(shifted, shifted2) + tm.assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( datetime_frame.values, @@ -421,8 +420,8 @@ def test_tshift(self, datetime_frame): ) shifted = inferred_ts.tshift(1) unshifted = shifted.tshift(-1) - assert_frame_equal(shifted, datetime_frame.tshift(1)) - assert_frame_equal(unshifted, inferred_ts) + tm.assert_frame_equal(shifted, datetime_frame.tshift(1)) + tm.assert_frame_equal(unshifted, inferred_ts) no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not given and was not set in the index" @@ -439,34 +438,34 @@ def test_truncate(self, datetime_frame): # neither specified truncated = ts.truncate() - assert_frame_equal(truncated, ts) + tm.assert_frame_equal(truncated, ts) # both specified expected = ts[1:3] truncated = ts.truncate(start, end) - assert_frame_equal(truncated, expected) + tm.assert_frame_equal(truncated, expected) truncated = ts.truncate(start_missing, end_missing) - assert_frame_equal(truncated, expected) + tm.assert_frame_equal(truncated, expected) # start specified expected = ts[1:] truncated = ts.truncate(before=start) - assert_frame_equal(truncated, expected) + tm.assert_frame_equal(truncated, expected) truncated = ts.truncate(before=start_missing) - assert_frame_equal(truncated, expected) + tm.assert_frame_equal(truncated, expected) # end specified expected = ts[:3] truncated = ts.truncate(after=end) - assert_frame_equal(truncated, expected) + tm.assert_frame_equal(truncated, expected) truncated = ts.truncate(after=end_missing) - assert_frame_equal(truncated, expected) + tm.assert_frame_equal(truncated, expected) msg = "Truncate: 2000-01-06 00:00:00 must be after 2000-02-04 00:00:00" with pytest.raises(ValueError, match=msg): @@ -553,11 +552,11 @@ def test_asfreq_fillvalue(self): actual_df = df.asfreq(freq="1S", fill_value=9.0) expected_df = df.asfreq(freq="1S").fillna(9.0) expected_df.loc["2016-01-01 00:00:08", "one"] = None - assert_frame_equal(expected_df, actual_df) + tm.assert_frame_equal(expected_df, actual_df) expected_series = ts.asfreq(freq="1S").fillna(9.0) actual_series = ts.asfreq(freq="1S", fill_value=9.0) - assert_series_equal(expected_series, actual_series) + tm.assert_series_equal(expected_series, actual_series) @pytest.mark.parametrize( "data,idx,expected_first,expected_last", @@ -621,14 +620,14 @@ def test_first_subset(self): result = ts.first("3M") expected = ts[:"3/31/2000"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = ts.first("21D") expected = ts[:21] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = ts[:0].first("3M") - assert_frame_equal(result, ts[:0]) + tm.assert_frame_equal(result, ts[:0]) def test_first_raises(self): # GH20725 @@ -647,14 +646,14 @@ def test_last_subset(self): result = ts.last("21D") expected = ts["2000-01-10":] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = ts.last("21D") expected = ts[-21:] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = ts[:0].last("3M") - assert_frame_equal(result, ts[:0]) + tm.assert_frame_equal(result, ts[:0]) def test_last_raises(self): # GH20725 @@ -672,19 +671,19 @@ def test_at_time(self): result = ts.at_time("9:30") expected = ts.at_time(time(9, 30)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = ts.loc[time(9, 30)] expected = ts.loc[(rng.hour == 9) & (rng.minute == 30)] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # midnight, everything rng = date_range("1/1/2000", "1/31/2000") ts = DataFrame(np.random.randn(len(rng), 3), index=rng) result = ts.at_time(time(0, 0)) - assert_frame_equal(result, ts) + tm.assert_frame_equal(result, ts) # time doesn't exist rng = date_range("1/1/2012", freq="23Min", periods=384) @@ -736,7 +735,7 @@ def test_at_time_axis(self, axis): expected = ts.loc[:, indices] result = ts.at_time("9:30", axis=axis) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_between_time(self, close_open_fixture): rng = date_range("1/1/2000", "1/5/2000", freq="5min") @@ -767,7 +766,7 @@ def test_between_time(self, close_open_fixture): result = ts.between_time("00:00", "01:00") expected = ts.between_time(stime, etime) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # across midnight rng = date_range("1/1/2000", "1/5/2000", freq="5min") @@ -890,7 +889,7 @@ def test_frame_to_period(self): pts = df.to_period() exp = df.copy() exp.index = pr - assert_frame_equal(pts, exp) + tm.assert_frame_equal(pts, exp) pts = df.to_period("M") tm.assert_index_equal(pts.index, exp.index.asfreq("M")) @@ -899,7 +898,7 @@ def test_frame_to_period(self): pts = df.to_period(axis=1) exp = df.copy() exp.columns = pr - assert_frame_equal(pts, exp) + tm.assert_frame_equal(pts, exp) pts = df.to_period("M", axis=1) tm.assert_index_equal(pts.columns, exp.columns.asfreq("M")) @@ -926,7 +925,7 @@ def test_tz_convert_and_localize(self, fn): df1 = DataFrame(np.ones(5), index=l0) df1 = getattr(df1, fn)("US/Pacific") - assert_index_equal(df1.index, l0_expected) + tm.assert_index_equal(df1.index, l0_expected) # MultiIndex # GH7846 @@ -934,14 +933,14 @@ def test_tz_convert_and_localize(self, fn): df3 = getattr(df2, fn)("US/Pacific", level=0) assert not df3.index.levels[0].equals(l0) - assert_index_equal(df3.index.levels[0], l0_expected) - assert_index_equal(df3.index.levels[1], l1) + tm.assert_index_equal(df3.index.levels[0], l0_expected) + tm.assert_index_equal(df3.index.levels[1], l1) assert not df3.index.levels[1].equals(l1_expected) df3 = getattr(df2, fn)("US/Pacific", level=1) - assert_index_equal(df3.index.levels[0], l0) + tm.assert_index_equal(df3.index.levels[0], l0) assert not df3.index.levels[0].equals(l0_expected) - assert_index_equal(df3.index.levels[1], l1_expected) + tm.assert_index_equal(df3.index.levels[1], l1_expected) assert not df3.index.levels[1].equals(l1) df4 = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0])) @@ -949,9 +948,9 @@ def test_tz_convert_and_localize(self, fn): # TODO: untested df5 = getattr(df4, fn)("US/Pacific", level=1) # noqa - assert_index_equal(df3.index.levels[0], l0) + tm.assert_index_equal(df3.index.levels[0], l0) assert not df3.index.levels[0].equals(l0_expected) - assert_index_equal(df3.index.levels[1], l1_expected) + tm.assert_index_equal(df3.index.levels[1], l1_expected) assert not df3.index.levels[1].equals(l1) # Bad Inputs diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index 67c748227a43d..ad058faff96e7 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -20,13 +20,6 @@ ) import pandas.core.common as com import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, - ensure_clean, - makeCustomDataframe as mkdf, -) from pandas.io.common import _get_handle @@ -52,7 +45,7 @@ def read_csv(self, path, **kwargs): def test_to_csv_from_csv1(self, float_frame, datetime_frame): - with ensure_clean("__tmp_to_csv_from_csv1__") as path: + with tm.ensure_clean("__tmp_to_csv_from_csv1__") as path: float_frame["A"][:5] = np.nan float_frame.to_csv(path) @@ -63,7 +56,7 @@ def test_to_csv_from_csv1(self, float_frame, datetime_frame): # test roundtrip datetime_frame.to_csv(path) recons = self.read_csv(path) - assert_frame_equal(datetime_frame, recons) + tm.assert_frame_equal(datetime_frame, recons) datetime_frame.to_csv(path, index_label="index") recons = self.read_csv(path, index_col=None) @@ -73,7 +66,7 @@ def test_to_csv_from_csv1(self, float_frame, datetime_frame): # no index datetime_frame.to_csv(path, index=False) recons = self.read_csv(path, index_col=None) - assert_almost_equal(datetime_frame.values, recons.values) + tm.assert_almost_equal(datetime_frame.values, recons.values) # corner case dm = DataFrame( @@ -85,11 +78,11 @@ def test_to_csv_from_csv1(self, float_frame, datetime_frame): dm.to_csv(path) recons = self.read_csv(path) - assert_frame_equal(dm, recons) + tm.assert_frame_equal(dm, recons) def test_to_csv_from_csv2(self, float_frame): - with ensure_clean("__tmp_to_csv_from_csv2__") as path: + with tm.ensure_clean("__tmp_to_csv_from_csv2__") as path: # duplicate index df = DataFrame( @@ -97,14 +90,14 @@ def test_to_csv_from_csv2(self, float_frame): ) df.to_csv(path) result = self.read_csv(path) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) midx = MultiIndex.from_tuples([("A", 1, 2), ("A", 1, 2), ("B", 1, 2)]) df = DataFrame(np.random.randn(3, 3), index=midx, columns=["x", "y", "z"]) df.to_csv(path) result = self.read_csv(path, index_col=[0, 1, 2], parse_dates=False) - assert_frame_equal(result, df, check_names=False) + tm.assert_frame_equal(result, df, check_names=False) # column aliases col_aliases = Index(["AA", "X", "Y", "Z"]) @@ -113,7 +106,7 @@ def test_to_csv_from_csv2(self, float_frame): rs = self.read_csv(path) xp = float_frame.copy() xp.columns = col_aliases - assert_frame_equal(xp, rs) + tm.assert_frame_equal(xp, rs) msg = "Writing 4 cols but got 2 aliases" with pytest.raises(ValueError, match=msg): @@ -121,7 +114,7 @@ def test_to_csv_from_csv2(self, float_frame): def test_to_csv_from_csv3(self): - with ensure_clean("__tmp_to_csv_from_csv3__") as path: + with tm.ensure_clean("__tmp_to_csv_from_csv3__") as path: df1 = DataFrame(np.random.randn(3, 1)) df2 = DataFrame(np.random.randn(3, 1)) @@ -131,11 +124,11 @@ def test_to_csv_from_csv3(self): rs = pd.read_csv(path, index_col=0) rs.columns = [int(label) for label in rs.columns] xp.columns = [int(label) for label in xp.columns] - assert_frame_equal(xp, rs) + tm.assert_frame_equal(xp, rs) def test_to_csv_from_csv4(self): - with ensure_clean("__tmp_to_csv_from_csv4__") as path: + with tm.ensure_clean("__tmp_to_csv_from_csv4__") as path: # GH 10833 (TimedeltaIndex formatting) dt = pd.Timedelta(seconds=1) df = pd.DataFrame( @@ -150,12 +143,12 @@ def test_to_csv_from_csv4(self): result.index = result.index.rename("dt_index") result["dt_data"] = pd.to_timedelta(result["dt_data"]) - assert_frame_equal(df, result, check_index_type=True) + tm.assert_frame_equal(df, result, check_index_type=True) def test_to_csv_from_csv5(self, timezone_frame): # tz, 8260 - with ensure_clean("__tmp_to_csv_from_csv5__") as path: + with tm.ensure_clean("__tmp_to_csv_from_csv5__") as path: timezone_frame.to_csv(path) result = pd.read_csv(path, index_col=0, parse_dates=["A"]) @@ -167,7 +160,7 @@ def test_to_csv_from_csv5(self, timezone_frame): ) result["B"] = converter("B") result["C"] = converter("C") - assert_frame_equal(result, timezone_frame) + tm.assert_frame_equal(result, timezone_frame) def test_to_csv_cols_reordering(self): # GH3454 @@ -176,21 +169,21 @@ def test_to_csv_cols_reordering(self): chunksize = 5 N = int(chunksize * 2.5) - df = mkdf(N, 3) + df = tm.makeCustomDataframe(N, 3) cs = df.columns cols = [cs[2], cs[0]] - with ensure_clean() as path: + with tm.ensure_clean() as path: df.to_csv(path, columns=cols, chunksize=chunksize) rs_c = pd.read_csv(path, index_col=0) - assert_frame_equal(df[cols], rs_c, check_names=False) + tm.assert_frame_equal(df[cols], rs_c, check_names=False) def test_to_csv_new_dupe_cols(self): import pandas as pd def _check_df(df, cols=None): - with ensure_clean() as path: + with tm.ensure_clean() as path: df.to_csv(path, columns=cols, chunksize=chunksize) rs_c = pd.read_csv(path, index_col=0) @@ -208,20 +201,20 @@ def _check_df(df, cols=None): obj_df = df[c] obj_rs = rs_c[c] if isinstance(obj_df, Series): - assert_series_equal(obj_df, obj_rs) + tm.assert_series_equal(obj_df, obj_rs) else: - assert_frame_equal(obj_df, obj_rs, check_names=False) + tm.assert_frame_equal(obj_df, obj_rs, check_names=False) # wrote in the same order else: rs_c.columns = df.columns - assert_frame_equal(df, rs_c, check_names=False) + tm.assert_frame_equal(df, rs_c, check_names=False) chunksize = 5 N = int(chunksize * 2.5) # dupe cols - df = mkdf(N, 3) + df = tm.makeCustomDataframe(N, 3) df.columns = ["a", "a", "b"] _check_df(df, None) @@ -252,12 +245,14 @@ def make_dtnat_arr(n, nnat=None): s2 = make_dtnat_arr(chunksize + 5, 0) # s3=make_dtnjat_arr(chunksize+5,0) - with ensure_clean("1.csv") as pth: + with tm.ensure_clean("1.csv") as pth: df = DataFrame(dict(a=s1, b=s2)) df.to_csv(pth, chunksize=chunksize) recons = self.read_csv(pth)._convert(datetime=True, coerce=True) - assert_frame_equal(df, recons, check_names=False, check_less_precise=True) + tm.assert_frame_equal( + df, recons, check_names=False, check_less_precise=True + ) @pytest.mark.slow def test_to_csv_moar(self): @@ -271,13 +266,13 @@ def _do_test( kwargs["index_col"] = list(range(rnlvl)) kwargs["header"] = list(range(cnlvl)) - with ensure_clean("__tmp_to_csv_moar__") as path: + with tm.ensure_clean("__tmp_to_csv_moar__") as path: df.to_csv(path, encoding="utf8", chunksize=chunksize) recons = self.read_csv(path, **kwargs) else: kwargs["header"] = 0 - with ensure_clean("__tmp_to_csv_moar__") as path: + with tm.ensure_clean("__tmp_to_csv_moar__") as path: df.to_csv(path, encoding="utf8", chunksize=chunksize) recons = self.read_csv(path, **kwargs) @@ -359,7 +354,9 @@ def _to_uni(x): recons.columns = np.array(recons.columns, dtype=c_dtype) df.columns = np.array(df.columns, dtype=c_dtype) - assert_frame_equal(df, recons, check_names=False, check_less_precise=True) + tm.assert_frame_equal( + df, recons, check_names=False, check_less_precise=True + ) N = 100 chunksize = 1000 @@ -382,7 +379,13 @@ def _to_uni(x): base, base + 1, ]: - _do_test(mkdf(nrows, ncols, r_idx_type="dt", c_idx_type="s"), "dt", "s") + _do_test( + tm.makeCustomDataframe( + nrows, ncols, r_idx_type="dt", c_idx_type="s" + ), + "dt", + "s", + ) for ncols in [4]: base = int((chunksize // ncols or 1) or 1) @@ -402,7 +405,13 @@ def _to_uni(x): base, base + 1, ]: - _do_test(mkdf(nrows, ncols, r_idx_type="dt", c_idx_type="s"), "dt", "s") + _do_test( + tm.makeCustomDataframe( + nrows, ncols, r_idx_type="dt", c_idx_type="s" + ), + "dt", + "s", + ) pass for r_idx_type, c_idx_type in [("i", "i"), ("s", "s"), ("u", "dt"), ("p", "p")]: @@ -425,7 +434,7 @@ def _to_uni(x): base + 1, ]: _do_test( - mkdf( + tm.makeCustomDataframe( nrows, ncols, r_idx_type=r_idx_type, c_idx_type=c_idx_type ), r_idx_type, @@ -450,10 +459,10 @@ def _to_uni(x): base, base + 1, ]: - _do_test(mkdf(nrows, ncols)) + _do_test(tm.makeCustomDataframe(nrows, ncols)) for nrows in [10, N - 2, N - 1, N, N + 1, N + 2]: - df = mkdf(nrows, 3) + df = tm.makeCustomDataframe(nrows, 3) cols = list(df.columns) cols[:2] = ["dupe", "dupe"] cols[-2:] = ["dupe", "dupe"] @@ -465,7 +474,9 @@ def _to_uni(x): _do_test(df, dupe_col=True) _do_test(DataFrame(index=np.arange(10))) - _do_test(mkdf(chunksize // 2 + 1, 2, r_idx_nlevels=2), rnlvl=2) + _do_test( + tm.makeCustomDataframe(chunksize // 2 + 1, 2, r_idx_nlevels=2), rnlvl=2 + ) for ncols in [2, 3, 4]: base = int(chunksize // ncols) for nrows in [ @@ -484,10 +495,12 @@ def _to_uni(x): base, base + 1, ]: - _do_test(mkdf(nrows, ncols, r_idx_nlevels=2), rnlvl=2) - _do_test(mkdf(nrows, ncols, c_idx_nlevels=2), cnlvl=2) + _do_test(tm.makeCustomDataframe(nrows, ncols, r_idx_nlevels=2), rnlvl=2) + _do_test(tm.makeCustomDataframe(nrows, ncols, c_idx_nlevels=2), cnlvl=2) _do_test( - mkdf(nrows, ncols, r_idx_nlevels=2, c_idx_nlevels=2), + tm.makeCustomDataframe( + nrows, ncols, r_idx_nlevels=2, c_idx_nlevels=2 + ), rnlvl=2, cnlvl=2, ) @@ -499,13 +512,13 @@ def test_to_csv_from_csv_w_some_infs(self, float_frame): f = lambda x: [np.inf, np.nan][np.random.rand() < 0.5] float_frame["H"] = float_frame.index.map(f) - with ensure_clean() as path: + with tm.ensure_clean() as path: float_frame.to_csv(path) recons = self.read_csv(path) # TODO to_csv drops column name - assert_frame_equal(float_frame, recons, check_names=False) - assert_frame_equal( + tm.assert_frame_equal(float_frame, recons, check_names=False) + tm.assert_frame_equal( np.isinf(float_frame), np.isinf(recons), check_names=False ) @@ -515,27 +528,27 @@ def test_to_csv_from_csv_w_all_infs(self, float_frame): float_frame["E"] = np.inf float_frame["F"] = -np.inf - with ensure_clean() as path: + with tm.ensure_clean() as path: float_frame.to_csv(path) recons = self.read_csv(path) # TODO to_csv drops column name - assert_frame_equal(float_frame, recons, check_names=False) - assert_frame_equal( + tm.assert_frame_equal(float_frame, recons, check_names=False) + tm.assert_frame_equal( np.isinf(float_frame), np.isinf(recons), check_names=False ) def test_to_csv_no_index(self): # GH 3624, after appending columns, to_csv fails - with ensure_clean("__tmp_to_csv_no_index__") as path: + with tm.ensure_clean("__tmp_to_csv_no_index__") as path: df = DataFrame({"c1": [1, 2, 3], "c2": [4, 5, 6]}) df.to_csv(path, index=False) result = read_csv(path) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) df["c3"] = Series([7, 8, 9], dtype="int64") df.to_csv(path, index=False) result = read_csv(path) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) def test_to_csv_with_mix_columns(self): # gh-11637: incorrect output when a mix of integer and string column @@ -550,17 +563,17 @@ def test_to_csv_headers(self): # causes to_csv to have different header semantics. from_df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) to_df = DataFrame([[1, 2], [3, 4]], columns=["X", "Y"]) - with ensure_clean("__tmp_to_csv_headers__") as path: + with tm.ensure_clean("__tmp_to_csv_headers__") as path: from_df.to_csv(path, header=["X", "Y"]) recons = self.read_csv(path) - assert_frame_equal(to_df, recons) + tm.assert_frame_equal(to_df, recons) from_df.to_csv(path, index=False, header=["X", "Y"]) recons = self.read_csv(path) recons.reset_index(inplace=True) - assert_frame_equal(to_df, recons) + tm.assert_frame_equal(to_df, recons) def test_to_csv_multiindex(self, float_frame, datetime_frame): @@ -570,7 +583,7 @@ def test_to_csv_multiindex(self, float_frame, datetime_frame): new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) frame.index = new_index - with ensure_clean("__tmp_to_csv_multiindex__") as path: + with tm.ensure_clean("__tmp_to_csv_multiindex__") as path: frame.to_csv(path, header=False) frame.to_csv(path, columns=["A", "B"]) @@ -581,7 +594,7 @@ def test_to_csv_multiindex(self, float_frame, datetime_frame): df = self.read_csv(path, index_col=[0, 1], parse_dates=False) # TODO to_csv drops column name - assert_frame_equal(frame, df, check_names=False) + tm.assert_frame_equal(frame, df, check_names=False) assert frame.index.names == df.index.names # needed if setUp becomes a class method @@ -597,7 +610,7 @@ def test_to_csv_multiindex(self, float_frame, datetime_frame): recons = self.read_csv(path, index_col=[0, 1]) # TODO to_csv drops column name - assert_frame_equal(tsframe, recons, check_names=False) + tm.assert_frame_equal(tsframe, recons, check_names=False) # do not load index tsframe.to_csv(path) @@ -607,12 +620,12 @@ def test_to_csv_multiindex(self, float_frame, datetime_frame): # no index tsframe.to_csv(path, index=False) recons = self.read_csv(path, index_col=None) - assert_almost_equal(recons.values, datetime_frame.values) + tm.assert_almost_equal(recons.values, datetime_frame.values) # needed if setUp becomes class method datetime_frame.index = old_index - with ensure_clean("__tmp_to_csv_multiindex__") as path: + with tm.ensure_clean("__tmp_to_csv_multiindex__") as path: # GH3571, GH1651, GH3141 def _make_frame(names=None): @@ -627,28 +640,28 @@ def _make_frame(names=None): ) # column & index are multi-index - df = mkdf(5, 3, r_idx_nlevels=2, c_idx_nlevels=4) + df = tm.makeCustomDataframe(5, 3, r_idx_nlevels=2, c_idx_nlevels=4) df.to_csv(path) result = read_csv(path, header=[0, 1, 2, 3], index_col=[0, 1]) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # column is mi - df = mkdf(5, 3, r_idx_nlevels=1, c_idx_nlevels=4) + df = tm.makeCustomDataframe(5, 3, r_idx_nlevels=1, c_idx_nlevels=4) df.to_csv(path) result = read_csv(path, header=[0, 1, 2, 3], index_col=0) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # dup column names? - df = mkdf(5, 3, r_idx_nlevels=3, c_idx_nlevels=4) + df = tm.makeCustomDataframe(5, 3, r_idx_nlevels=3, c_idx_nlevels=4) df.to_csv(path) result = read_csv(path, header=[0, 1, 2, 3], index_col=[0, 1, 2]) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # writing with no index df = _make_frame() df.to_csv(path, index=False) result = read_csv(path, header=[0, 1]) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # we lose the names here df = _make_frame(True) @@ -656,18 +669,18 @@ def _make_frame(names=None): result = read_csv(path, header=[0, 1]) assert com.all_none(*result.columns.names) result.columns.names = df.columns.names - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # whatsnew example df = _make_frame() df.to_csv(path) result = read_csv(path, header=[0, 1], index_col=[0]) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) df = _make_frame(True) df.to_csv(path) result = read_csv(path, header=[0, 1], index_col=[0]) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # invalid options df = _make_frame(True) @@ -683,7 +696,7 @@ def _make_frame(names=None): with pytest.raises(TypeError, match=msg): df.to_csv(path, columns=["foo", "bar"]) - with ensure_clean("__tmp_to_csv_multiindex__") as path: + with tm.ensure_clean("__tmp_to_csv_multiindex__") as path: # empty tsframe[:0].to_csv(path) recons = self.read_csv(path) @@ -698,7 +711,7 @@ def test_to_csv_interval_index(self): # GH 28210 df = DataFrame({"A": list("abc"), "B": range(3)}, index=pd.interval_range(0, 3)) - with ensure_clean("__tmp_to_csv_interval_index__.csv") as path: + with tm.ensure_clean("__tmp_to_csv_interval_index__.csv") as path: df.to_csv(path) result = self.read_csv(path, index_col=0) @@ -706,13 +719,13 @@ def test_to_csv_interval_index(self): expected = df.copy() expected.index = expected.index.astype(str) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_to_csv_float32_nanrep(self): df = DataFrame(np.random.randn(1, 4).astype(np.float32)) df[1] = np.nan - with ensure_clean("__tmp_to_csv_float32_nanrep__.csv") as path: + with tm.ensure_clean("__tmp_to_csv_float32_nanrep__.csv") as path: df.to_csv(path, na_rep=999) with open(path) as f: @@ -724,10 +737,10 @@ def test_to_csv_withcommas(self): # Commas inside fields should be correctly escaped when saving as CSV. df = DataFrame({"A": [1, 2, 3], "B": ["5,6", "7,8", "9,0"]}) - with ensure_clean("__tmp_to_csv_withcommas__.csv") as path: + with tm.ensure_clean("__tmp_to_csv_withcommas__.csv") as path: df.to_csv(path) df2 = self.read_csv(path) - assert_frame_equal(df2, df) + tm.assert_frame_equal(df2, df) def test_to_csv_mixed(self): def create_cols(name): @@ -766,12 +779,12 @@ def create_cols(name): for c in create_cols(n): dtypes[c] = dtype - with ensure_clean() as filename: + with tm.ensure_clean() as filename: df.to_csv(filename) rs = read_csv( filename, index_col=0, dtype=dtypes, parse_dates=create_cols("date") ) - assert_frame_equal(rs, df) + tm.assert_frame_equal(rs, df) def test_to_csv_dups_cols(self): @@ -781,11 +794,11 @@ def test_to_csv_dups_cols(self): dtype="float64", ) - with ensure_clean() as filename: + with tm.ensure_clean() as filename: df.to_csv(filename) # single dtype, fine result = read_csv(filename, index_col=0) result.columns = df.columns - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df_float = DataFrame(np.random.randn(1000, 3), dtype="float64") df_int = DataFrame(np.random.randn(1000, 3), dtype="int64") @@ -801,7 +814,7 @@ def test_to_csv_dups_cols(self): cols.extend([0, 1, 2]) df.columns = cols - with ensure_clean() as filename: + with tm.ensure_clean() as filename: df.to_csv(filename) result = read_csv(filename, index_col=0) @@ -810,22 +823,21 @@ def test_to_csv_dups_cols(self): result[i] = to_datetime(result[i]) result.columns = df.columns - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # GH3457 - from pandas.util.testing import makeCustomDataframe as mkdf N = 10 - df = mkdf(N, 3) + df = tm.makeCustomDataframe(N, 3) df.columns = ["a", "a", "b"] - with ensure_clean() as filename: + with tm.ensure_clean() as filename: df.to_csv(filename) # read_csv will rename the dups columns result = read_csv(filename, index_col=0) result = result.rename(columns={"a.1": "a"}) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_to_csv_chunking(self): @@ -835,44 +847,44 @@ def test_to_csv_chunking(self): aa["D"] = aa.A + 3.0 for chunksize in [10000, 50000, 100000]: - with ensure_clean() as filename: + with tm.ensure_clean() as filename: aa.to_csv(filename, chunksize=chunksize) rs = read_csv(filename, index_col=0) - assert_frame_equal(rs, aa) + tm.assert_frame_equal(rs, aa) @pytest.mark.slow def test_to_csv_wide_frame_formatting(self): # Issue #8621 df = DataFrame(np.random.randn(1, 100010), columns=None, index=None) - with ensure_clean() as filename: + with tm.ensure_clean() as filename: df.to_csv(filename, header=False, index=False) rs = read_csv(filename, header=None) - assert_frame_equal(rs, df) + tm.assert_frame_equal(rs, df) def test_to_csv_bug(self): f1 = StringIO("a,1.0\nb,2.0") df = self.read_csv(f1, header=None) newdf = DataFrame({"t": df[df.columns[0]]}) - with ensure_clean() as path: + with tm.ensure_clean() as path: newdf.to_csv(path) recons = read_csv(path, index_col=0) # don't check_names as t != 1 - assert_frame_equal(recons, newdf, check_names=False) + tm.assert_frame_equal(recons, newdf, check_names=False) def test_to_csv_unicode(self): df = DataFrame({"c/\u03c3": [1, 2, 3]}) - with ensure_clean() as path: + with tm.ensure_clean() as path: df.to_csv(path, encoding="UTF-8") df2 = read_csv(path, index_col=0, encoding="UTF-8") - assert_frame_equal(df, df2) + tm.assert_frame_equal(df, df2) df.to_csv(path, encoding="UTF-8", index=False) df2 = read_csv(path, index_col=None, encoding="UTF-8") - assert_frame_equal(df, df2) + tm.assert_frame_equal(df, df2) def test_to_csv_unicode_index_col(self): buf = StringIO("") @@ -886,7 +898,7 @@ def test_to_csv_unicode_index_col(self): buf.seek(0) df2 = read_csv(buf, index_col=0, encoding="UTF-8") - assert_frame_equal(df, df2) + tm.assert_frame_equal(df, df2) def test_to_csv_stringio(self, float_frame): buf = StringIO() @@ -894,7 +906,7 @@ def test_to_csv_stringio(self, float_frame): buf.seek(0) recons = read_csv(buf, index_col=0) # TODO to_csv drops column name - assert_frame_equal(recons, float_frame, check_names=False) + tm.assert_frame_equal(recons, float_frame, check_names=False) def test_to_csv_float_format(self): @@ -904,7 +916,7 @@ def test_to_csv_float_format(self): columns=["X", "Y", "Z"], ) - with ensure_clean() as filename: + with tm.ensure_clean() as filename: df.to_csv(filename, float_format="%.2f") @@ -914,7 +926,7 @@ def test_to_csv_float_format(self): index=["A", "B"], columns=["X", "Y", "Z"], ) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_to_csv_unicodewriter_quoting(self): df = DataFrame({"A": [1, 2, 3], "B": ["foo", "bar", "baz"]}) @@ -953,7 +965,7 @@ def test_to_csv_line_terminators(self): # see gh-20353 df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["one", "two", "three"]) - with ensure_clean() as path: + with tm.ensure_clean() as path: # case 1: CRLF as line terminator df.to_csv(path, line_terminator="\r\n") expected = b",A,B\r\none,1,4\r\ntwo,2,5\r\nthree,3,6\r\n" @@ -961,7 +973,7 @@ def test_to_csv_line_terminators(self): with open(path, mode="rb") as f: assert f.read() == expected - with ensure_clean() as path: + with tm.ensure_clean() as path: # case 2: LF as line terminator df.to_csv(path, line_terminator="\n") expected = b",A,B\none,1,4\ntwo,2,5\nthree,3,6\n" @@ -969,7 +981,7 @@ def test_to_csv_line_terminators(self): with open(path, mode="rb") as f: assert f.read() == expected - with ensure_clean() as path: + with tm.ensure_clean() as path: # case 3: The default line terminator(=os.linesep)(gh-21406) df.to_csv(path) os_linesep = os.linesep.encode("utf-8") @@ -1019,7 +1031,7 @@ def test_to_csv_path_is_none(self, float_frame): csv_str = float_frame.to_csv(path_or_buf=None) assert isinstance(csv_str, str) recons = pd.read_csv(StringIO(csv_str), index_col=0) - assert_frame_equal(float_frame, recons) + tm.assert_frame_equal(float_frame, recons) @pytest.mark.parametrize( "df,encoding", @@ -1043,14 +1055,14 @@ def test_to_csv_path_is_none(self, float_frame): ) def test_to_csv_compression(self, df, encoding, compression): - with ensure_clean() as filename: + with tm.ensure_clean() as filename: df.to_csv(filename, compression=compression, encoding=encoding) # test the round trip - to_csv -> read_csv result = read_csv( filename, compression=compression, index_col=0, encoding=encoding ) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # test the round trip using file handle - to_csv -> read_csv f, _handles = _get_handle( @@ -1065,7 +1077,7 @@ def test_to_csv_compression(self, df, encoding, compression): index_col=0, squeeze=True, ) - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) # explicitly make sure file is compressed with tm.decompress_file(filename, compression) as fh: @@ -1074,10 +1086,10 @@ def test_to_csv_compression(self, df, encoding, compression): assert col in text with tm.decompress_file(filename, compression) as fh: - assert_frame_equal(df, read_csv(fh, index_col=0, encoding=encoding)) + tm.assert_frame_equal(df, read_csv(fh, index_col=0, encoding=encoding)) def test_to_csv_date_format(self, datetime_frame): - with ensure_clean("__tmp_to_csv_date_format__") as path: + with tm.ensure_clean("__tmp_to_csv_date_format__") as path: dt_index = datetime_frame.index datetime_frame = DataFrame( {"A": dt_index, "B": dt_index.shift(1)}, index=dt_index @@ -1094,7 +1106,7 @@ def test_to_csv_date_format(self, datetime_frame): lambda x: int(x.strftime("%Y%m%d")) ) - assert_frame_equal(test, datetime_frame_int) + tm.assert_frame_equal(test, datetime_frame_int) datetime_frame.to_csv(path, date_format="%Y-%m-%d") @@ -1107,7 +1119,7 @@ def test_to_csv_date_format(self, datetime_frame): lambda x: x.strftime("%Y-%m-%d") ) - assert_frame_equal(test, datetime_frame_str) + tm.assert_frame_equal(test, datetime_frame_str) # Check that columns get converted datetime_frame_columns = datetime_frame.T @@ -1123,7 +1135,7 @@ def test_to_csv_date_format(self, datetime_frame): lambda x: x.strftime("%Y%m%d") ) - assert_frame_equal(test, datetime_frame_columns) + tm.assert_frame_equal(test, datetime_frame_columns) # test NaTs nat_index = to_datetime( @@ -1134,11 +1146,11 @@ def test_to_csv_date_format(self, datetime_frame): test = read_csv(path, parse_dates=[0, 1], index_col=0) - assert_frame_equal(test, nat_frame) + tm.assert_frame_equal(test, nat_frame) def test_to_csv_with_dst_transitions(self): - with ensure_clean("csv_date_format_with_dst") as path: + with tm.ensure_clean("csv_date_format_with_dst") as path: # make sure we are not failing on transitions times = pd.date_range( "2013-10-26 23:00", @@ -1158,12 +1170,12 @@ def test_to_csv_with_dst_transitions(self): result.index = to_datetime(result.index, utc=True).tz_convert( "Europe/London" ) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # GH11619 idx = pd.date_range("2015-01-01", "2015-12-31", freq="H", tz="Europe/Paris") df = DataFrame({"values": 1, "idx": idx}, index=idx) - with ensure_clean("csv_date_format_with_dst") as path: + with tm.ensure_clean("csv_date_format_with_dst") as path: df.to_csv(path, index=True) result = read_csv(path, index_col=0) result.index = to_datetime(result.index, utc=True).tz_convert( @@ -1172,15 +1184,15 @@ def test_to_csv_with_dst_transitions(self): result["idx"] = to_datetime(result["idx"], utc=True).astype( "datetime64[ns, Europe/Paris]" ) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # assert working df.astype(str) - with ensure_clean("csv_date_format_with_dst") as path: + with tm.ensure_clean("csv_date_format_with_dst") as path: df.to_pickle(path) result = pd.read_pickle(path) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_to_csv_quoting(self): df = DataFrame( @@ -1331,14 +1343,14 @@ def test_to_csv_single_level_multi_index(self): df = df.reindex(columns=[(1,), (3,)]) expected = ",1,3\n0,1,3\n" result = df.to_csv(line_terminator="\n") - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) def test_gz_lineend(self): # GH 25311 df = pd.DataFrame({"a": [1, 2]}) expected_rows = ["a", "1", "2"] expected = tm.convert_rows_list_to_csv_str(expected_rows) - with ensure_clean("__test_gz_lineend.csv.gz") as path: + with tm.ensure_clean("__test_gz_lineend.csv.gz") as path: df.to_csv(path, index=False) with tm.decompress_file(path, compression="gzip") as f: result = f.read().decode("utf-8")
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29303
2019-10-30T23:25:14Z
2019-10-31T08:08:12Z
2019-10-31T08:08:11Z
2019-10-31T08:11:23Z
CLN: Consistent pandas.util.testing imports in pandas/tests/frame - part 3
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index b9ae4fd4abd4c..04d27f4c12c59 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -9,11 +9,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, date_range from pandas.core.computation.check import _NUMEXPR_INSTALLED -from pandas.util.testing import ( - assert_frame_equal, - assert_series_equal, - makeCustomDataframe as mkdf, -) +import pandas.util.testing as tm PARSERS = "python", "pandas" ENGINES = "python", pytest.param("numexpr", marks=td.skip_if_no_ne) @@ -46,34 +42,34 @@ def test_query_default(self): # this should always work, whether _NUMEXPR_INSTALLED or not df = self.df result = df.query("A>0") - assert_frame_equal(result, self.expected1) + tm.assert_frame_equal(result, self.expected1) result = df.eval("A+1") - assert_series_equal(result, self.expected2, check_names=False) + tm.assert_series_equal(result, self.expected2, check_names=False) def test_query_None(self): df = self.df result = df.query("A>0", engine=None) - assert_frame_equal(result, self.expected1) + tm.assert_frame_equal(result, self.expected1) result = df.eval("A+1", engine=None) - assert_series_equal(result, self.expected2, check_names=False) + tm.assert_series_equal(result, self.expected2, check_names=False) def test_query_python(self): df = self.df result = df.query("A>0", engine="python") - assert_frame_equal(result, self.expected1) + tm.assert_frame_equal(result, self.expected1) result = df.eval("A+1", engine="python") - assert_series_equal(result, self.expected2, check_names=False) + tm.assert_series_equal(result, self.expected2, check_names=False) def test_query_numexpr(self): df = self.df if _NUMEXPR_INSTALLED: result = df.query("A>0", engine="numexpr") - assert_frame_equal(result, self.expected1) + tm.assert_frame_equal(result, self.expected1) result = df.eval("A+1", engine="numexpr") - assert_series_equal(result, self.expected2, check_names=False) + tm.assert_series_equal(result, self.expected2, check_names=False) else: with pytest.raises(ImportError): df.query("A>0", engine="numexpr") @@ -109,17 +105,17 @@ def test_ops(self): # ops as strings result = eval("m{op}df".format(op=op_str)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # these are commutative if op in ["+", "*"]: result = getattr(df, op)(m) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # these are not elif op in ["-", "/"]: result = getattr(df, rop)(m) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH7192: Note we need a large number of rows to ensure this # goes through the numexpr path @@ -127,7 +123,7 @@ def test_ops(self): df.iloc[0:5] = np.nan expected = 1 - np.isnan(df.iloc[0:25]) result = (1 - np.isnan(df)).iloc[0:25] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_query_non_str(self): # GH 11485 @@ -172,41 +168,41 @@ def test_query_with_named_multiindex(self, parser, engine): res1 = df.query('color == "red"', parser=parser, engine=engine) res2 = df.query('"red" == color', parser=parser, engine=engine) exp = df[ind == "red"] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # inequality res1 = df.query('color != "red"', parser=parser, engine=engine) res2 = df.query('"red" != color', parser=parser, engine=engine) exp = df[ind != "red"] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # list equality (really just set membership) res1 = df.query('color == ["red"]', parser=parser, engine=engine) res2 = df.query('["red"] == color', parser=parser, engine=engine) exp = df[ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) res1 = df.query('color != ["red"]', parser=parser, engine=engine) res2 = df.query('["red"] != color', parser=parser, engine=engine) exp = df[~ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # in/not in ops res1 = df.query('["red"] in color', parser=parser, engine=engine) res2 = df.query('"red" in color', parser=parser, engine=engine) exp = df[ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) res1 = df.query('["red"] not in color', parser=parser, engine=engine) res2 = df.query('"red" not in color', parser=parser, engine=engine) exp = df[~ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) def test_query_with_unnamed_multiindex(self, parser, engine): skip_if_no_pandas_parser(parser) @@ -219,82 +215,82 @@ def test_query_with_unnamed_multiindex(self, parser, engine): res1 = df.query('ilevel_0 == "red"', parser=parser, engine=engine) res2 = df.query('"red" == ilevel_0', parser=parser, engine=engine) exp = df[ind == "red"] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # inequality res1 = df.query('ilevel_0 != "red"', parser=parser, engine=engine) res2 = df.query('"red" != ilevel_0', parser=parser, engine=engine) exp = df[ind != "red"] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # list equality (really just set membership) res1 = df.query('ilevel_0 == ["red"]', parser=parser, engine=engine) res2 = df.query('["red"] == ilevel_0', parser=parser, engine=engine) exp = df[ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) res1 = df.query('ilevel_0 != ["red"]', parser=parser, engine=engine) res2 = df.query('["red"] != ilevel_0', parser=parser, engine=engine) exp = df[~ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # in/not in ops res1 = df.query('["red"] in ilevel_0', parser=parser, engine=engine) res2 = df.query('"red" in ilevel_0', parser=parser, engine=engine) exp = df[ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) res1 = df.query('["red"] not in ilevel_0', parser=parser, engine=engine) res2 = df.query('"red" not in ilevel_0', parser=parser, engine=engine) exp = df[~ind.isin(["red"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # ## LEVEL 1 ind = Series(df.index.get_level_values(1).values, index=index) res1 = df.query('ilevel_1 == "eggs"', parser=parser, engine=engine) res2 = df.query('"eggs" == ilevel_1', parser=parser, engine=engine) exp = df[ind == "eggs"] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # inequality res1 = df.query('ilevel_1 != "eggs"', parser=parser, engine=engine) res2 = df.query('"eggs" != ilevel_1', parser=parser, engine=engine) exp = df[ind != "eggs"] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # list equality (really just set membership) res1 = df.query('ilevel_1 == ["eggs"]', parser=parser, engine=engine) res2 = df.query('["eggs"] == ilevel_1', parser=parser, engine=engine) exp = df[ind.isin(["eggs"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) res1 = df.query('ilevel_1 != ["eggs"]', parser=parser, engine=engine) res2 = df.query('["eggs"] != ilevel_1', parser=parser, engine=engine) exp = df[~ind.isin(["eggs"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) # in/not in ops res1 = df.query('["eggs"] in ilevel_1', parser=parser, engine=engine) res2 = df.query('"eggs" in ilevel_1', parser=parser, engine=engine) exp = df[ind.isin(["eggs"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) res1 = df.query('["eggs"] not in ilevel_1', parser=parser, engine=engine) res2 = df.query('"eggs" not in ilevel_1', parser=parser, engine=engine) exp = df[~ind.isin(["eggs"])] - assert_frame_equal(res1, exp) - assert_frame_equal(res2, exp) + tm.assert_frame_equal(res1, exp) + tm.assert_frame_equal(res2, exp) def test_query_with_partially_named_multiindex(self, parser, engine): skip_if_no_pandas_parser(parser) @@ -308,27 +304,29 @@ def test_query_with_partially_named_multiindex(self, parser, engine): df.index.get_level_values("rating").values, index=index, name="rating" ) exp = df[ind == 1] - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) res = df.query("rating != 1", parser=parser, engine=engine) ind = Series( df.index.get_level_values("rating").values, index=index, name="rating" ) exp = df[ind != 1] - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) res = df.query('ilevel_0 == "red"', parser=parser, engine=engine) ind = Series(df.index.get_level_values(0).values, index=index) exp = df[ind == "red"] - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) res = df.query('ilevel_0 != "red"', parser=parser, engine=engine) ind = Series(df.index.get_level_values(0).values, index=index) exp = df[ind != "red"] - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) def test_query_multiindex_get_index_resolvers(self): - df = mkdf(10, 3, r_idx_nlevels=2, r_idx_names=["spam", "eggs"]) + df = tm.makeCustomDataframe( + 10, 3, r_idx_nlevels=2, r_idx_names=["spam", "eggs"] + ) resolvers = df._get_index_resolvers() def to_series(mi, level): @@ -349,7 +347,7 @@ def to_series(mi, level): if isinstance(v, Index): assert v.is_(expected[k]) elif isinstance(v, Series): - assert_series_equal(v, expected[k]) + tm.assert_series_equal(v, expected[k]) else: raise AssertionError("object must be a Series or Index") @@ -376,7 +374,7 @@ def test_date_query_with_attribute_access(self): "@df.dates1 < 20130101 < @df.dates3", engine=engine, parser=parser ) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_query_no_attribute_access(self): engine, parser = self.engine, self.parser @@ -386,7 +384,7 @@ def test_date_query_no_attribute_access(self): df["dates3"] = date_range("1/1/2014", periods=5) res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_query_with_NaT(self): engine, parser = self.engine, self.parser @@ -399,7 +397,7 @@ def test_date_query_with_NaT(self): df.loc[np.random.rand(n) > 0.5, "dates3"] = pd.NaT res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_index_query(self): engine, parser = self.engine, self.parser @@ -410,7 +408,7 @@ def test_date_index_query(self): df.set_index("dates1", inplace=True, drop=True) res = df.query("index < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.index < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_index_query_with_NaT(self): engine, parser = self.engine, self.parser @@ -422,7 +420,7 @@ def test_date_index_query_with_NaT(self): df.set_index("dates1", inplace=True, drop=True) res = df.query("index < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.index < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_index_query_with_NaT_duplicates(self): engine, parser = self.engine, self.parser @@ -435,7 +433,7 @@ def test_date_index_query_with_NaT_duplicates(self): df.set_index("dates1", inplace=True, drop=True) res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.index.to_series() < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_query_with_non_date(self): engine, parser = self.engine, self.parser @@ -449,7 +447,7 @@ def test_date_query_with_non_date(self): assert len(result) == 0 result = df.query("dates != nondate", parser=parser, engine=engine) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) for op in ["<", ">", "<=", ">="]: with pytest.raises(TypeError): @@ -474,11 +472,11 @@ def test_query_scope(self): a, b = 1, 2 # noqa res = df.query("a > b", engine=engine, parser=parser) expected = df[df.a > df.b] - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) res = df.query("@a > b", engine=engine, parser=parser) expected = df[a > df.b] - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) # no local variable c with pytest.raises(UndefinedVariableError): @@ -516,10 +514,10 @@ def test_query(self): engine, parser = self.engine, self.parser df = DataFrame(np.random.randn(10, 3), columns=["a", "b", "c"]) - assert_frame_equal( + tm.assert_frame_equal( df.query("a < b", engine=engine, parser=parser), df[df.a < df.b] ) - assert_frame_equal( + tm.assert_frame_equal( df.query("a + b > b * c", engine=engine, parser=parser), df[df.a + df.b > df.b * df.c], ) @@ -533,12 +531,12 @@ def test_query_index_with_name(self): ) res = df.query("(blob < 5) & (a < b)", engine=engine, parser=parser) expec = df[(df.index < 5) & (df.a < df.b)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) res = df.query("blob < b", engine=engine, parser=parser) expec = df[df.index < df.b] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_query_index_without_name(self): engine, parser = self.engine, self.parser @@ -551,12 +549,12 @@ def test_query_index_without_name(self): # "index" should refer to the index res = df.query("index < b", engine=engine, parser=parser) expec = df[df.index < df.b] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # test against a scalar res = df.query("index < 5", engine=engine, parser=parser) expec = df[df.index < 5] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_nested_scope(self): engine = self.engine @@ -569,20 +567,20 @@ def test_nested_scope(self): expected = df[(df > 0) & (df2 > 0)] result = df.query("(@df > 0) & (@df2 > 0)", engine=engine, parser=parser) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = pd.eval("df[df > 0 and df2 > 0]", engine=engine, parser=parser) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = pd.eval( "df[df > 0 and df2 > 0 and df[df > 0] > 0]", engine=engine, parser=parser ) expected = df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = pd.eval("df[(df>0) & (df2>0)]", engine=engine, parser=parser) expected = df.query("(@df>0) & (@df2>0)", engine=engine, parser=parser) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_nested_raises_on_local_self_reference(self): from pandas.core.computation.ops import UndefinedVariableError @@ -601,11 +599,11 @@ def test_local_syntax(self): b = 1 expect = df[df.a < b] result = df.query("a < @b", engine=engine, parser=parser) - assert_frame_equal(result, expect) + tm.assert_frame_equal(result, expect) expect = df[df.a < df.b] result = df.query("a < b", engine=engine, parser=parser) - assert_frame_equal(result, expect) + tm.assert_frame_equal(result, expect) def test_chained_cmp_and_in(self): skip_if_no_pandas_parser(self.parser) @@ -619,7 +617,7 @@ def test_chained_cmp_and_in(self): (df.a < df.b) & (df.b < df.c) & ~df.b.isin(df.a) & ~df.c.isin(df.b) ) # noqa expec = df[ind] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_local_variable_with_in(self): engine, parser = self.engine, self.parser @@ -630,12 +628,12 @@ def test_local_variable_with_in(self): expected = df.loc[(df.b - 1).isin(a)] result = df.query("b - 1 in a", engine=engine, parser=parser) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) b = Series(np.random.randint(10, size=15), name="b") expected = df.loc[(b - 1).isin(a)] result = df.query("@b - 1 in a", engine=engine, parser=parser) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_at_inside_string(self): engine, parser = self.engine, self.parser @@ -644,7 +642,7 @@ def test_at_inside_string(self): df = DataFrame({"a": ["a", "a", "b", "b", "@c", "@c"]}) result = df.query('a == "@c"', engine=engine, parser=parser) expected = df[df.a == "@c"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_query_undefined_local(self): from pandas.core.computation.ops import UndefinedVariableError @@ -666,22 +664,22 @@ def test_index_resolvers_come_after_columns_with_the_same_name(self): df.index.name = "index" result = df.query("index > 5", engine=self.engine, parser=self.parser) expected = df[df["index"] > 5] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame({"index": a, "b": np.random.randn(a.size)}) result = df.query("ilevel_0 > 5", engine=self.engine, parser=self.parser) expected = df.loc[df.index[df.index > 5]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame({"a": a, "b": np.random.randn(a.size)}) df.index.name = "a" result = df.query("a > 5", engine=self.engine, parser=self.parser) expected = df[df.a > 5] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.query("index > 5", engine=self.engine, parser=self.parser) expected = df.loc[df.index[df.index > 5]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_inf(self): n = 10 @@ -693,7 +691,7 @@ def test_inf(self): q = "a {op} inf".format(op=op) expected = df[f(df.a, np.inf)] result = df.query(q, engine=self.engine, parser=self.parser) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @td.skip_if_no_ne @@ -714,7 +712,7 @@ def test_date_query_no_attribute_access(self): "(dates1 < 20130101) & (20130101 < dates3)", engine=engine, parser=parser ) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_query_with_NaT(self): engine, parser = self.engine, self.parser @@ -729,7 +727,7 @@ def test_date_query_with_NaT(self): "(dates1 < 20130101) & (20130101 < dates3)", engine=engine, parser=parser ) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_index_query(self): engine, parser = self.engine, self.parser @@ -742,7 +740,7 @@ def test_date_index_query(self): "(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser ) expec = df[(df.index < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_index_query_with_NaT(self): engine, parser = self.engine, self.parser @@ -756,7 +754,7 @@ def test_date_index_query_with_NaT(self): "(index < 20130101) & (20130101 < dates3)", engine=engine, parser=parser ) expec = df[(df.index < "20130101") & ("20130101" < df.dates3)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_date_index_query_with_NaT_duplicates(self): engine, parser = self.engine, self.parser @@ -791,13 +789,13 @@ def test_nested_scope(self): expected = df[(df > 0) & (df2 > 0)] result = pd.eval("df[(df > 0) & (df2 > 0)]", engine=engine, parser=parser) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) expected = df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)] result = pd.eval( "df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)]", engine=engine, parser=parser ) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) class TestDataFrameQueryPythonPandas(TestDataFrameQueryNumExprPandas): @@ -816,7 +814,7 @@ def test_query_builtin(self): df.index.name = "sin" expected = df[df.index > 5] result = df.query("sin > 5", engine=engine, parser=parser) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) class TestDataFrameQueryPythonPython(TestDataFrameQueryNumExprPython): @@ -834,7 +832,7 @@ def test_query_builtin(self): df.index.name = "sin" expected = df[df.index > 5] result = df.query("sin > 5", engine=engine, parser=parser) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) class TestDataFrameQueryStrings: @@ -865,19 +863,19 @@ def test_str_query_method(self, parser, engine): ) else: res = df.query('"a" == strings', engine=engine, parser=parser) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) res = df.query('strings == "a"', engine=engine, parser=parser) - assert_frame_equal(res, expect) - assert_frame_equal(res, df[df.strings.isin(["a"])]) + tm.assert_frame_equal(res, expect) + tm.assert_frame_equal(res, df[df.strings.isin(["a"])]) expect = df[df.strings != "a"] res = df.query('strings != "a"', engine=engine, parser=parser) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) res = df.query('"a" != strings', engine=engine, parser=parser) - assert_frame_equal(res, expect) - assert_frame_equal(res, df[~df.strings.isin(["a"])]) + tm.assert_frame_equal(res, expect) + tm.assert_frame_equal(res, df[~df.strings.isin(["a"])]) def test_str_list_query_method(self, parser, engine): df = DataFrame(np.random.randn(10, 1), columns=["b"]) @@ -900,18 +898,18 @@ def test_str_list_query_method(self, parser, engine): df.query(ex, engine=engine, parser=parser) else: res = df.query('strings == ["a", "b"]', engine=engine, parser=parser) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) res = df.query('["a", "b"] == strings', engine=engine, parser=parser) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) expect = df[~df.strings.isin(["a", "b"])] res = df.query('strings != ["a", "b"]', engine=engine, parser=parser) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) res = df.query('["a", "b"] != strings', engine=engine, parser=parser) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) def test_query_with_string_columns(self, parser, engine): df = DataFrame( @@ -925,11 +923,11 @@ def test_query_with_string_columns(self, parser, engine): if parser == "pandas": res = df.query("a in b", parser=parser, engine=engine) expec = df[df.a.isin(df.b)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) res = df.query("a in b and c < d", parser=parser, engine=engine) expec = df[df.a.isin(df.b) & (df.c < df.d)] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) else: with pytest.raises(NotImplementedError): df.query("a in b", parser=parser, engine=engine) @@ -948,11 +946,11 @@ def test_object_array_eq_ne(self, parser, engine): ) res = df.query("a == b", parser=parser, engine=engine) exp = df[df.a == df.b] - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) res = df.query("a != b", parser=parser, engine=engine) exp = df[df.a != df.b] - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) def test_query_with_nested_strings(self, parser, engine): skip_if_no_pandas_parser(parser) @@ -975,14 +973,14 @@ def test_query_with_nested_strings(self, parser, engine): ) expected = df[df.event == '"page 1 load"'] res = df.query("""'"page 1 load"' in event""", parser=parser, engine=engine) - assert_frame_equal(expected, res) + tm.assert_frame_equal(expected, res) def test_query_with_nested_special_character(self, parser, engine): skip_if_no_pandas_parser(parser) df = DataFrame({"a": ["a", "b", "test & test"], "b": [1, 2, 3]}) res = df.query('a == "test & test"', parser=parser, engine=engine) expec = df[df.a == "test & test"] - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_query_lex_compare_strings(self, parser, engine): @@ -995,7 +993,7 @@ def test_query_lex_compare_strings(self, parser, engine): for op, func in ops.items(): res = df.query('X %s "d"' % op, engine=engine, parser=parser) expected = df[func(df.X, "d")] - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) def test_query_single_element_booleans(self, parser, engine): columns = "bid", "bidsize", "ask", "asksize" @@ -1003,7 +1001,7 @@ def test_query_single_element_booleans(self, parser, engine): df = DataFrame(data, columns=columns) res = df.query("bid & ask", engine=engine, parser=parser) expected = df[df.bid & df.ask] - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) def test_query_string_scalar_variable(self, parser, engine): skip_if_no_pandas_parser(parser) @@ -1016,7 +1014,7 @@ def test_query_string_scalar_variable(self, parser, engine): e = df[df.Symbol == "BUD US"] symb = "BUD US" # noqa r = df.query("Symbol == @symb", parser=parser, engine=engine) - assert_frame_equal(e, r) + tm.assert_frame_equal(e, r) class TestDataFrameEvalWithFrame: @@ -1029,12 +1027,12 @@ def teardown_method(self, method): def test_simple_expr(self, parser, engine): res = self.frame.eval("a + b", engine=engine, parser=parser) expect = self.frame.a + self.frame.b - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) def test_bool_arith_expr(self, parser, engine): res = self.frame.eval("a[a < 1] + b", engine=engine, parser=parser) expect = self.frame.a[self.frame.a < 1] + self.frame.b - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) @pytest.mark.parametrize("op", ["+", "-", "*", "/"]) def test_invalid_type_for_operator_raises(self, parser, engine, op): @@ -1061,39 +1059,39 @@ def df(self): def test_single_backtick_variable_query(self, df): res = df.query("1 < `B B`") expect = df[1 < df["B B"]] - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) def test_two_backtick_variables_query(self, df): res = df.query("1 < `B B` and 4 < `C C`") expect = df[(1 < df["B B"]) & (4 < df["C C"])] - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) def test_single_backtick_variable_expr(self, df): res = df.eval("A + `B B`") expect = df["A"] + df["B B"] - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) def test_two_backtick_variables_expr(self, df): res = df.eval("`B B` + `C C`") expect = df["B B"] + df["C C"] - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) def test_already_underscore_variable(self, df): res = df.eval("`C_C` + A") expect = df["C_C"] + df["A"] - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) def test_same_name_but_underscores(self, df): res = df.eval("C_C + `C C`") expect = df["C_C"] + df["C C"] - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) def test_mixed_underscores_and_spaces(self, df): res = df.eval("A + `D_D D`") expect = df["A"] + df["D_D D"] - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) def backtick_quote_name_with_no_spaces(self, df): res = df.eval("A + `C_C`") expect = df["A"] + df["C_C"] - assert_series_equal(res, expect) + tm.assert_series_equal(res, expect) diff --git a/pandas/tests/frame/test_rank.py b/pandas/tests/frame/test_rank.py index fd9c53c7d9f5b..be1a423c22aea 100644 --- a/pandas/tests/frame/test_rank.py +++ b/pandas/tests/frame/test_rank.py @@ -5,7 +5,6 @@ from pandas import DataFrame, Series import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal class TestRank: @@ -231,7 +230,7 @@ def test_rank_descending(self, method, dtype): res = df.rank(ascending=False) expected = (df.max() - df).rank() - assert_frame_equal(res, expected) + tm.assert_frame_equal(res, expected) if method == "first" and dtype == "O": return @@ -240,10 +239,10 @@ def test_rank_descending(self, method, dtype): if dtype != "O": res2 = df.rank(method=method, ascending=False, numeric_only=True) - assert_frame_equal(res2, expected) + tm.assert_frame_equal(res2, expected) res3 = df.rank(method=method, ascending=False, numeric_only=False) - assert_frame_equal(res3, expected) + tm.assert_frame_equal(res3, expected) @pytest.mark.parametrize("axis", [0, 1]) @pytest.mark.parametrize("dtype", [None, object]) @@ -258,7 +257,7 @@ def _check2d(df, expected, method="average", axis=0): exp_df = exp_df.T result = df.rank(method=method, axis=axis) - assert_frame_equal(result, exp_df) + tm.assert_frame_equal(result, exp_df) disabled = {(object, "first")} if (dtype, method) in disabled: diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index fdb450da53137..5eb2416d0dcd7 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -8,7 +8,7 @@ import pandas as pd from pandas import DataFrame, Index, Series, Timestamp, date_range -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm @pytest.fixture @@ -28,7 +28,7 @@ def test_replace_inplace(self, datetime_frame, float_string_frame): tsframe = datetime_frame.copy() tsframe.replace(np.nan, 0, inplace=True) - assert_frame_equal(tsframe, datetime_frame.fillna(0)) + tm.assert_frame_equal(tsframe, datetime_frame.fillna(0)) # mixed type mf = float_string_frame @@ -37,11 +37,11 @@ def test_replace_inplace(self, datetime_frame, float_string_frame): result = float_string_frame.replace(np.nan, 0) expected = float_string_frame.fillna(value=0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) tsframe = datetime_frame.copy() tsframe.replace([np.nan], [0], inplace=True) - assert_frame_equal(tsframe, datetime_frame.fillna(0)) + tm.assert_frame_equal(tsframe, datetime_frame.fillna(0)) def test_regex_replace_scalar(self, mix_ab): obj = {"a": list("ab.."), "b": list("efgh")} @@ -52,11 +52,11 @@ def test_regex_replace_scalar(self, mix_ab): # regex -> value # obj frame res = dfobj.replace(r"\s*\.\s*", np.nan, regex=True) - assert_frame_equal(dfobj, res.fillna(".")) + tm.assert_frame_equal(dfobj, res.fillna(".")) # mixed res = dfmix.replace(r"\s*\.\s*", np.nan, regex=True) - assert_frame_equal(dfmix, res.fillna(".")) + tm.assert_frame_equal(dfmix, res.fillna(".")) # regex -> regex # obj frame @@ -64,22 +64,22 @@ def test_regex_replace_scalar(self, mix_ab): objc = obj.copy() objc["a"] = ["a", "b", "...", "..."] expec = DataFrame(objc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # with mixed res = dfmix.replace(r"\s*(\.)\s*", r"\1\1\1", regex=True) mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # everything with compiled regexs as well res = dfobj.replace(re.compile(r"\s*\.\s*"), np.nan, regex=True) - assert_frame_equal(dfobj, res.fillna(".")) + tm.assert_frame_equal(dfobj, res.fillna(".")) # mixed res = dfmix.replace(re.compile(r"\s*\.\s*"), np.nan, regex=True) - assert_frame_equal(dfmix, res.fillna(".")) + tm.assert_frame_equal(dfmix, res.fillna(".")) # regex -> regex # obj frame @@ -87,26 +87,26 @@ def test_regex_replace_scalar(self, mix_ab): objc = obj.copy() objc["a"] = ["a", "b", "...", "..."] expec = DataFrame(objc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # with mixed res = dfmix.replace(re.compile(r"\s*(\.)\s*"), r"\1\1\1") mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) res = dfmix.replace(regex=re.compile(r"\s*(\.)\s*"), value=r"\1\1\1") mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) res = dfmix.replace(regex=r"\s*(\.)\s*", value=r"\1\1\1") mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_regex_replace_scalar_inplace(self, mix_ab): obj = {"a": list("ab.."), "b": list("efgh")} @@ -118,12 +118,12 @@ def test_regex_replace_scalar_inplace(self, mix_ab): # obj frame res = dfobj.copy() res.replace(r"\s*\.\s*", np.nan, regex=True, inplace=True) - assert_frame_equal(dfobj, res.fillna(".")) + tm.assert_frame_equal(dfobj, res.fillna(".")) # mixed res = dfmix.copy() res.replace(r"\s*\.\s*", np.nan, regex=True, inplace=True) - assert_frame_equal(dfmix, res.fillna(".")) + tm.assert_frame_equal(dfmix, res.fillna(".")) # regex -> regex # obj frame @@ -132,7 +132,7 @@ def test_regex_replace_scalar_inplace(self, mix_ab): objc = obj.copy() objc["a"] = ["a", "b", "...", "..."] expec = DataFrame(objc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # with mixed res = dfmix.copy() @@ -140,17 +140,17 @@ def test_regex_replace_scalar_inplace(self, mix_ab): mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # everything with compiled regexs as well res = dfobj.copy() res.replace(re.compile(r"\s*\.\s*"), np.nan, regex=True, inplace=True) - assert_frame_equal(dfobj, res.fillna(".")) + tm.assert_frame_equal(dfobj, res.fillna(".")) # mixed res = dfmix.copy() res.replace(re.compile(r"\s*\.\s*"), np.nan, regex=True, inplace=True) - assert_frame_equal(dfmix, res.fillna(".")) + tm.assert_frame_equal(dfmix, res.fillna(".")) # regex -> regex # obj frame @@ -159,7 +159,7 @@ def test_regex_replace_scalar_inplace(self, mix_ab): objc = obj.copy() objc["a"] = ["a", "b", "...", "..."] expec = DataFrame(objc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # with mixed res = dfmix.copy() @@ -167,16 +167,16 @@ def test_regex_replace_scalar_inplace(self, mix_ab): mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) res = dfobj.copy() res.replace(regex=r"\s*\.\s*", value=np.nan, inplace=True) - assert_frame_equal(dfobj, res.fillna(".")) + tm.assert_frame_equal(dfobj, res.fillna(".")) # mixed res = dfmix.copy() res.replace(regex=r"\s*\.\s*", value=np.nan, inplace=True) - assert_frame_equal(dfmix, res.fillna(".")) + tm.assert_frame_equal(dfmix, res.fillna(".")) # regex -> regex # obj frame @@ -185,7 +185,7 @@ def test_regex_replace_scalar_inplace(self, mix_ab): objc = obj.copy() objc["a"] = ["a", "b", "...", "..."] expec = DataFrame(objc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # with mixed res = dfmix.copy() @@ -193,17 +193,17 @@ def test_regex_replace_scalar_inplace(self, mix_ab): mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # everything with compiled regexs as well res = dfobj.copy() res.replace(regex=re.compile(r"\s*\.\s*"), value=np.nan, inplace=True) - assert_frame_equal(dfobj, res.fillna(".")) + tm.assert_frame_equal(dfobj, res.fillna(".")) # mixed res = dfmix.copy() res.replace(regex=re.compile(r"\s*\.\s*"), value=np.nan, inplace=True) - assert_frame_equal(dfmix, res.fillna(".")) + tm.assert_frame_equal(dfmix, res.fillna(".")) # regex -> regex # obj frame @@ -212,7 +212,7 @@ def test_regex_replace_scalar_inplace(self, mix_ab): objc = obj.copy() objc["a"] = ["a", "b", "...", "..."] expec = DataFrame(objc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # with mixed res = dfmix.copy() @@ -220,7 +220,7 @@ def test_regex_replace_scalar_inplace(self, mix_ab): mixc = mix_ab.copy() mixc["b"] = ["a", "b", "...", "..."] expec = DataFrame(mixc) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_regex_replace_list_obj(self): obj = {"a": list("ab.."), "b": list("efgh"), "c": list("helo")} @@ -238,7 +238,7 @@ def test_regex_replace_list_obj(self): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] to_replace_res = [r"\s*(\.)\s*", r"(e|f|g)"] @@ -251,7 +251,7 @@ def test_regex_replace_list_obj(self): "c": ["h", "e_crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN # or vN)] @@ -265,7 +265,7 @@ def test_regex_replace_list_obj(self): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) to_replace_res = [r"\s*(\.)\s*", r"e"] values = [r"\1\1", r"crap"] @@ -277,7 +277,7 @@ def test_regex_replace_list_obj(self): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_regex_replace_list_obj_inplace(self): # same as above with inplace=True @@ -298,7 +298,7 @@ def test_regex_replace_list_obj_inplace(self): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] to_replace_res = [r"\s*(\.)\s*", r"(e|f|g)"] @@ -312,7 +312,7 @@ def test_regex_replace_list_obj_inplace(self): "c": ["h", "e_crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN # or vN)] @@ -327,7 +327,7 @@ def test_regex_replace_list_obj_inplace(self): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) to_replace_res = [r"\s*(\.)\s*", r"e"] values = [r"\1\1", r"crap"] @@ -340,7 +340,7 @@ def test_regex_replace_list_obj_inplace(self): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_regex_replace_list_mixed(self, mix_ab): # mixed frame to make sure this doesn't break things @@ -360,14 +360,14 @@ def test_regex_replace_list_mixed(self, mix_ab): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] to_replace_res = [r"\s*(\.)\s*", r"(a|b)"] values = [r"\1\1", r"\1_crap"] res = dfmix.replace(to_replace_res, values, regex=True) expec = DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]}) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN # or vN)] @@ -375,13 +375,13 @@ def test_regex_replace_list_mixed(self, mix_ab): values = [r"\1\1", r"crap", r"\1_crap"] res = dfmix.replace(to_replace_res, values, regex=True) expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"] values = [r"\1\1", r"crap", r"\1_crap"] res = dfmix.replace(regex=to_replace_res, value=values) expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_regex_replace_list_mixed_inplace(self, mix_ab): dfmix = DataFrame(mix_ab) @@ -393,7 +393,7 @@ def test_regex_replace_list_mixed_inplace(self, mix_ab): res = dfmix.copy() res.replace(to_replace_res, values, inplace=True, regex=True) expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b", np.nan, np.nan]}) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [re1, re2, .., reN] to_replace_res = [r"\s*(\.)\s*", r"(a|b)"] @@ -401,7 +401,7 @@ def test_regex_replace_list_mixed_inplace(self, mix_ab): res = dfmix.copy() res.replace(to_replace_res, values, inplace=True, regex=True) expec = DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]}) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN # or vN)] @@ -410,14 +410,14 @@ def test_regex_replace_list_mixed_inplace(self, mix_ab): res = dfmix.copy() res.replace(to_replace_res, values, inplace=True, regex=True) expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"] values = [r"\1\1", r"crap", r"\1_crap"] res = dfmix.copy() res.replace(regex=to_replace_res, value=values, inplace=True) expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]}) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_regex_replace_dict_mixed(self, mix_abc): dfmix = DataFrame(mix_abc) @@ -434,8 +434,8 @@ def test_regex_replace_dict_mixed(self, mix_abc): expec = DataFrame( {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]} ) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) # list of dicts {re1: re11, re2: re12, ..., reN: re1N}, search the # whole frame @@ -445,8 +445,8 @@ def test_regex_replace_dict_mixed(self, mix_abc): expec = DataFrame( {"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]} ) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) res = dfmix.replace(regex={"b": r"\s*(\.)\s*"}, value={"b": r"\1ty"}) res2 = dfmix.copy() @@ -454,8 +454,8 @@ def test_regex_replace_dict_mixed(self, mix_abc): expec = DataFrame( {"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]} ) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) # scalar -> dict # to_replace regex, {value: value} @@ -465,8 +465,8 @@ def test_regex_replace_dict_mixed(self, mix_abc): res = dfmix.replace("a", {"b": np.nan}, regex=True) res2 = dfmix.copy() res2.replace("a", {"b": np.nan}, regex=True, inplace=True) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) res = dfmix.replace("a", {"b": np.nan}, regex=True) res2 = dfmix.copy() @@ -474,8 +474,8 @@ def test_regex_replace_dict_mixed(self, mix_abc): expec = DataFrame( {"a": mix_abc["a"], "b": [np.nan, "b", ".", "."], "c": mix_abc["c"]} ) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) def test_regex_replace_dict_nested(self, mix_abc): # nested dicts will not work until this is implemented for Series @@ -489,23 +489,23 @@ def test_regex_replace_dict_nested(self, mix_abc): expec = DataFrame( {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]} ) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) - assert_frame_equal(res3, expec) - assert_frame_equal(res4, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) + tm.assert_frame_equal(res4, expec) def test_regex_replace_dict_nested_non_first_character(self): # GH 25259 df = pd.DataFrame({"first": ["abc", "bca", "cab"]}) expected = pd.DataFrame({"first": [".bc", "bc.", "c.b"]}) result = df.replace({"a": "."}, regex=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_regex_replace_dict_nested_gh4115(self): df = pd.DataFrame({"Type": ["Q", "T", "Q", "Q", "T"], "tmp": 2}) expected = DataFrame({"Type": [0, 1, 0, 0, 1], "tmp": 2}) result = df.replace({"Type": {"Q": 0, "T": 1}}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_regex_replace_list_to_scalar(self, mix_abc): df = DataFrame(mix_abc) @@ -521,9 +521,9 @@ def test_regex_replace_list_to_scalar(self, mix_abc): res3 = df.copy() res2.replace([r"\s*\.\s*", "a|b"], np.nan, regex=True, inplace=True) res3.replace(regex=[r"\s*\.\s*", "a|b"], value=np.nan, inplace=True) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) - assert_frame_equal(res3, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) def test_regex_replace_str_to_numeric(self, mix_abc): # what happens when you try to replace a numeric value with a regex? @@ -534,9 +534,9 @@ def test_regex_replace_str_to_numeric(self, mix_abc): res3 = df.copy() res3.replace(regex=r"\s*\.\s*", value=0, inplace=True) expec = DataFrame({"a": mix_abc["a"], "b": ["a", "b", 0, 0], "c": mix_abc["c"]}) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) - assert_frame_equal(res3, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) def test_regex_replace_regex_list_to_numeric(self, mix_abc): df = DataFrame(mix_abc) @@ -548,9 +548,9 @@ def test_regex_replace_regex_list_to_numeric(self, mix_abc): expec = DataFrame( {"a": mix_abc["a"], "b": ["a", 0, 0, 0], "c": ["a", 0, np.nan, "d"]} ) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) - assert_frame_equal(res3, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) def test_regex_replace_series_of_regexes(self, mix_abc): df = DataFrame(mix_abc) @@ -564,15 +564,15 @@ def test_regex_replace_series_of_regexes(self, mix_abc): expec = DataFrame( {"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]} ) - assert_frame_equal(res, expec) - assert_frame_equal(res2, expec) - assert_frame_equal(res3, expec) + tm.assert_frame_equal(res, expec) + tm.assert_frame_equal(res2, expec) + tm.assert_frame_equal(res3, expec) def test_regex_replace_numeric_to_object_conversion(self, mix_abc): df = DataFrame(mix_abc) expec = DataFrame({"a": ["a", 1, 2, 3], "b": mix_abc["b"], "c": mix_abc["c"]}) res = df.replace(0, "a") - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) assert res.a.dtype == np.object_ @pytest.mark.parametrize("metachar", ["[]", "()", r"\d", r"\w", r"\s"]) @@ -580,15 +580,15 @@ 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) + tm.assert_frame_equal(result, expected) def test_replace(self, datetime_frame): datetime_frame["A"][:5] = np.nan datetime_frame["A"][-5:] = np.nan zero_filled = datetime_frame.replace(np.nan, -1e8) - assert_frame_equal(zero_filled, datetime_frame.fillna(-1e8)) - assert_frame_equal(zero_filled.replace(-1e8, np.nan), datetime_frame) + tm.assert_frame_equal(zero_filled, datetime_frame.fillna(-1e8)) + tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), datetime_frame) datetime_frame["A"][:5] = np.nan datetime_frame["A"][-5:] = np.nan @@ -596,7 +596,7 @@ def test_replace(self, datetime_frame): # empty df = DataFrame(index=["a", "b"]) - assert_frame_equal(df, df.replace(5, 7)) + tm.assert_frame_equal(df, df.replace(5, 7)) # GH 11698 # test for mixed data types. @@ -607,7 +607,7 @@ def test_replace(self, datetime_frame): expected_df = pd.DataFrame( [(np.nan, pd.to_datetime("20150101")), ("a", pd.to_datetime("20150102"))] ) - assert_frame_equal(df1, expected_df) + tm.assert_frame_equal(df1, expected_df) def test_replace_list(self): obj = {"a": list("ab.."), "b": list("efgh"), "c": list("helo")} @@ -625,7 +625,7 @@ def test_replace_list(self): "c": ["h", "crap", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) # list of [v1, v2, ..., vN] -> [v1, v2, .., vN] to_replace_res = [r".", r"f"] @@ -638,7 +638,7 @@ def test_replace_list(self): "c": ["h", "e", "l", "o"], } ) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_replace_with_empty_list(self): # GH 21977 @@ -646,7 +646,7 @@ def test_replace_with_empty_list(self): df = pd.DataFrame({"col": s}) expected = df result = df.replace([], np.nan) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH 19266 with pytest.raises(ValueError, match="cannot assign mismatch"): @@ -659,20 +659,20 @@ def test_replace_series_dict(self): df = DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}}) result = df.replace(0, {"zero": 0.5, "one": 1.0}) expected = DataFrame({"zero": {"a": 0.5, "b": 1}, "one": {"a": 2.0, "b": 1.0}}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.replace(0, df.mean()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # series to series/dict df = DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}}) s = Series({"zero": 0.0, "one": 2.0}) result = df.replace(s, {"zero": 0.5, "one": 1.0}) expected = DataFrame({"zero": {"a": 0.5, "b": 1}, "one": {"a": 1.0, "b": 0.0}}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.replace(s, df.mean()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_convert(self): # gh 3907 @@ -681,7 +681,7 @@ def test_replace_convert(self): rep = df.replace(m) expec = Series([np.int64] * 3) res = rep.dtypes - assert_series_equal(expec, res) + tm.assert_series_equal(expec, res) def test_replace_mixed(self, float_string_frame): mf = float_string_frame @@ -690,13 +690,13 @@ def test_replace_mixed(self, float_string_frame): result = float_string_frame.replace(np.nan, -18) expected = float_string_frame.fillna(value=-18) - assert_frame_equal(result, expected) - assert_frame_equal(result.replace(-18, np.nan), float_string_frame) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result.replace(-18, np.nan), float_string_frame) result = float_string_frame.replace(np.nan, -1e8) expected = float_string_frame.fillna(value=-1e8) - assert_frame_equal(result, expected) - assert_frame_equal(result.replace(-1e8, np.nan), float_string_frame) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result.replace(-1e8, np.nan), float_string_frame) # int block upcasting df = DataFrame( @@ -712,10 +712,10 @@ def test_replace_mixed(self, float_string_frame): } ) result = df.replace(0, 0.5) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df.replace(0, 0.5, inplace=True) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # int block splitting df = DataFrame( @@ -733,7 +733,7 @@ def test_replace_mixed(self, float_string_frame): } ) result = df.replace(0, 0.5) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # to object block upcasting df = DataFrame( @@ -749,7 +749,7 @@ def test_replace_mixed(self, float_string_frame): } ) result = df.replace(2, "foo") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( { @@ -758,7 +758,7 @@ def test_replace_mixed(self, float_string_frame): } ) result = df.replace([1, 2], ["foo", "bar"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # test case from df = DataFrame( @@ -769,28 +769,28 @@ def test_replace_mixed(self, float_string_frame): m = df.mean() expected.iloc[0, 0] = m[0] expected.iloc[1, 1] = m[1] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_simple_nested_dict(self): df = DataFrame({"col": range(1, 5)}) expected = DataFrame({"col": ["a", 2, 3, "b"]}) result = df.replace({"col": {1: "a", 4: "b"}}) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) # in this case, should be the same as the not nested version result = df.replace({1: "a", 4: "b"}) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_replace_simple_nested_dict_with_nonexistent_value(self): df = DataFrame({"col": range(1, 5)}) expected = DataFrame({"col": ["a", 2, 3, "b"]}) result = df.replace({-1: "-", 1: "a", 4: "b"}) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) result = df.replace({"col": {-1: "-", 1: "a", 4: "b"}}) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_replace_value_is_none(self, datetime_frame): orig_value = datetime_frame.iloc[0, 0] @@ -801,14 +801,14 @@ def test_replace_value_is_none(self, datetime_frame): result = datetime_frame.replace(to_replace={np.nan: 0}) expected = datetime_frame.T.replace(to_replace={np.nan: 0}).T - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = datetime_frame.replace(to_replace={np.nan: 0, 1: -1e8}) tsframe = datetime_frame.copy() tsframe.iloc[0, 0] = 0 tsframe.iloc[1, 0] = -1e8 expected = tsframe - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) datetime_frame.iloc[0, 0] = orig_value datetime_frame.iloc[1, 0] = orig2 @@ -820,8 +820,8 @@ def test_replace_for_new_dtypes(self, datetime_frame): tsframe["A"][-5:] = np.nan zero_filled = tsframe.replace(np.nan, -1e8) - assert_frame_equal(zero_filled, tsframe.fillna(-1e8)) - assert_frame_equal(zero_filled.replace(-1e8, np.nan), tsframe) + tm.assert_frame_equal(zero_filled, tsframe.fillna(-1e8)) + tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), tsframe) tsframe["A"][:5] = np.nan tsframe["A"][-5:] = np.nan @@ -831,7 +831,7 @@ def test_replace_for_new_dtypes(self, datetime_frame): b[b == -1e8] = np.nan tsframe["B"] = b result = tsframe.fillna(method="bfill") - assert_frame_equal(result, tsframe.fillna(method="bfill")) + tm.assert_frame_equal(result, tsframe.fillna(method="bfill")) @pytest.mark.parametrize( "frame, to_replace, value, expected", @@ -908,7 +908,7 @@ def test_replace_for_new_dtypes(self, datetime_frame): ) def test_replace_dtypes(self, frame, to_replace, value, expected): result = getattr(frame, "replace")(to_replace, value) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_input_formats_listlike(self): # both dicts @@ -919,13 +919,13 @@ def test_replace_input_formats_listlike(self): ) filled = df.replace(to_rep, values) expected = {k: v.replace(to_rep[k], values[k]) for k, v in df.items()} - assert_frame_equal(filled, DataFrame(expected)) + tm.assert_frame_equal(filled, DataFrame(expected)) result = df.replace([0, 2, 5], [5, 2, 0]) expected = DataFrame( {"A": [np.nan, 5, np.inf], "B": [5, 2, 0], "C": ["", "asdf", "fd"]} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # scalar to dict values = {"A": 0, "B": -1, "C": "missing"} @@ -934,7 +934,7 @@ def test_replace_input_formats_listlike(self): ) filled = df.replace(np.nan, values) expected = {k: v.replace(np.nan, values[k]) for k, v in df.items()} - assert_frame_equal(filled, DataFrame(expected)) + tm.assert_frame_equal(filled, DataFrame(expected)) # list to list to_rep = [np.nan, 0, ""] @@ -943,7 +943,7 @@ def test_replace_input_formats_listlike(self): expected = df.copy() for i in range(len(to_rep)): expected.replace(to_rep[i], values[i], inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) msg = r"Replacement lists must match in length\. Expecting 3 got 2" with pytest.raises(ValueError, match=msg): @@ -958,7 +958,7 @@ def test_replace_input_formats_scalar(self): to_rep = {"A": np.nan, "B": 0, "C": ""} filled = df.replace(to_rep, 0) expected = {k: v.replace(to_rep[k], 0) for k, v in df.items()} - assert_frame_equal(filled, DataFrame(expected)) + tm.assert_frame_equal(filled, DataFrame(expected)) msg = "value argument must be scalar, dict, or Series" with pytest.raises(TypeError, match=msg): @@ -970,7 +970,7 @@ def test_replace_input_formats_scalar(self): expected = df.copy() for i in range(len(to_rep)): expected.replace(to_rep[i], -1, inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_limit(self): pass @@ -994,7 +994,7 @@ def test_replace_dict_no_regex(self): } expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1}) result = answer.replace(weights) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_replace_series_no_regex(self): answer = Series( @@ -1017,7 +1017,7 @@ def test_replace_series_no_regex(self): ) expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1}) result = answer.replace(weights) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_replace_dict_tuple_list_ordering_remains_the_same(self): df = DataFrame(dict(A=[np.nan, 1])) @@ -1026,9 +1026,9 @@ def test_replace_dict_tuple_list_ordering_remains_the_same(self): res3 = df.replace(to_replace=[1, np.nan], value=[-1e8, 0]) expected = DataFrame({"A": [0, -1e8]}) - assert_frame_equal(res1, res2) - assert_frame_equal(res2, res3) - assert_frame_equal(res3, expected) + tm.assert_frame_equal(res1, res2) + tm.assert_frame_equal(res2, res3) + tm.assert_frame_equal(res3, expected) def test_replace_doesnt_replace_without_regex(self): raw = """fol T_opp T_Dir T_Enh @@ -1038,24 +1038,24 @@ def test_replace_doesnt_replace_without_regex(self): 3 3 0 bt 0""" df = pd.read_csv(StringIO(raw), sep=r"\s+") res = df.replace({r"\D": 1}) - assert_frame_equal(df, res) + tm.assert_frame_equal(df, res) def test_replace_bool_with_string(self): df = DataFrame({"a": [True, False], "b": list("ab")}) result = df.replace(True, "a") expected = DataFrame({"a": ["a", False], "b": df.b}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_pure_bool_with_string_no_op(self): df = DataFrame(np.random.rand(2, 2) > 0.5) result = df.replace("asdf", "fdsa") - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) def test_replace_bool_with_bool(self): df = DataFrame(np.random.rand(2, 2) > 0.5) result = df.replace(False, True) expected = DataFrame(np.ones((2, 2), dtype=bool)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_with_dict_with_bool_keys(self): df = DataFrame({0: [True, False], 1: [False, True]}) @@ -1066,7 +1066,7 @@ def test_replace_truthy(self): df = DataFrame({"a": [True, True]}) r = df.replace([np.inf, -np.inf], np.nan) e = df - assert_frame_equal(r, e) + tm.assert_frame_equal(r, e) def test_nested_dict_overlapping_keys_replace_int(self): # GH 27660 keep behaviour consistent for simple dictionary and @@ -1075,7 +1075,7 @@ def test_nested_dict_overlapping_keys_replace_int(self): result = df.replace({"a": dict(zip(range(1, 5), range(2, 6)))}) expected = df.replace(dict(zip(range(1, 5), range(2, 6)))) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_nested_dict_overlapping_keys_replace_str(self): # GH 27660 @@ -1085,18 +1085,18 @@ def test_nested_dict_overlapping_keys_replace_str(self): df = DataFrame({"a": astr}) result = df.replace(dict(zip(astr, bstr))) expected = df.replace({"a": dict(zip(astr, bstr))}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_swapping_bug(self): df = pd.DataFrame({"a": [True, False, True]}) res = df.replace({"a": {True: "Y", False: "N"}}) expect = pd.DataFrame({"a": ["Y", "N", "Y"]}) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) df = pd.DataFrame({"a": [0, 1, 0]}) res = df.replace({"a": {0: "Y", 1: "N"}}) expect = pd.DataFrame({"a": ["Y", "N", "Y"]}) - assert_frame_equal(res, expect) + tm.assert_frame_equal(res, expect) def test_replace_period(self): d = { @@ -1132,7 +1132,7 @@ def test_replace_period(self): {"fname": [d["fname"][k] for k in df.fname.values]}, dtype=object ) result = df.replace(d) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_datetime(self): d = { @@ -1162,7 +1162,7 @@ def test_replace_datetime(self): assert set(df.fname.values) == set(d["fname"].keys()) expected = DataFrame({"fname": [d["fname"][k] for k in df.fname.values]}) result = df.replace(d) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_datetimetz(self): @@ -1181,10 +1181,10 @@ def test_replace_datetimetz(self): "B": Series([0, 1, 2], dtype="float64"), } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.fillna(1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.replace(0, np.nan) expected = DataFrame( @@ -1193,7 +1193,7 @@ def test_replace_datetimetz(self): "B": [np.nan, np.nan, 2], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.replace( Timestamp("20130102", tz="US/Eastern"), @@ -1209,12 +1209,12 @@ def test_replace_datetimetz(self): "B": [0, np.nan, 2], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.iloc[1, 0] = np.nan result = result.replace({"A": pd.NaT}, Timestamp("20130104", tz="US/Eastern")) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # coerce to object result = df.copy() @@ -1230,7 +1230,7 @@ def test_replace_datetimetz(self): "B": [0, np.nan, 2], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.iloc[1, 0] = np.nan @@ -1245,16 +1245,16 @@ def test_replace_datetimetz(self): "B": [0, np.nan, 2], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_replace_with_empty_dictlike(self, mix_abc): # GH 15289 df = DataFrame(mix_abc) - assert_frame_equal(df, df.replace({})) - assert_frame_equal(df, df.replace(Series([]))) + tm.assert_frame_equal(df, df.replace({})) + tm.assert_frame_equal(df, df.replace(Series([]))) - assert_frame_equal(df, df.replace({"b": {}})) - assert_frame_equal(df, df.replace(Series({"b": {}}))) + tm.assert_frame_equal(df, df.replace({"b": {}})) + tm.assert_frame_equal(df, df.replace(Series({"b": {}}))) @pytest.mark.parametrize( "to_replace, method, expected", @@ -1294,4 +1294,4 @@ def test_replace_method(self, to_replace, method, expected): result = df.replace(to_replace=to_replace, value=None, method=method) expected = DataFrame(expected) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 5ce811712b989..5d2c115ce8eb5 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -7,7 +7,6 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Period, Series, Timedelta, date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal class TestDataFrameReshape: @@ -82,7 +81,7 @@ def test_pivot_index_none(self): ) expected.index.name, expected.columns.name = "index", "columns" - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # omit values result = frame.pivot(columns="columns") @@ -110,13 +109,13 @@ def test_stack_unstack(self, float_frame): unstacked = stacked.unstack() unstacked_df = stacked_df.unstack() - assert_frame_equal(unstacked, df) - assert_frame_equal(unstacked_df["bar"], df) + tm.assert_frame_equal(unstacked, df) + tm.assert_frame_equal(unstacked_df["bar"], df) unstacked_cols = stacked.unstack(0) unstacked_cols_df = stacked_df.unstack(0) - assert_frame_equal(unstacked_cols.T, df) - assert_frame_equal(unstacked_cols_df["bar"].T, df) + tm.assert_frame_equal(unstacked_cols.T, df) + tm.assert_frame_equal(unstacked_cols_df["bar"].T, df) def test_stack_mixed_level(self): # GH 18310 @@ -126,7 +125,7 @@ def test_stack_mixed_level(self): 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) + tm.assert_series_equal(result, expected) # MultiIndex columns: df = DataFrame(1, index=levels[0], columns=MultiIndex.from_product(levels[1:])) @@ -134,12 +133,12 @@ def test_stack_mixed_level(self): expected = DataFrame( 1, index=MultiIndex.from_product([levels[0], levels[2]]), columns=levels[1] ) - assert_frame_equal(result, expected) + tm.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) + tm.assert_frame_equal(result, expected) def test_unstack_fill(self): @@ -156,14 +155,14 @@ def test_unstack_fill(self): expected = DataFrame( {"a": [1, -1, 5], "b": [2, 4, -1]}, index=["x", "y", "z"], dtype=np.int16 ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # From a series with incorrect data type for fill_value result = data.unstack(fill_value=0.5) expected = DataFrame( {"a": [1, 0.5, 5], "b": [2, 4, 0.5]}, index=["x", "y", "z"], dtype=np.float ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH #13971: fill_value when unstacking multiple levels: df = DataFrame( @@ -173,20 +172,20 @@ def test_unstack_fill(self): key = ("w", "b", "j") expected = unstacked[key] result = pd.Series([0, 0, 2], index=unstacked.index, name=key) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) stacked = unstacked.stack(["x", "y"]) stacked.index = stacked.index.reorder_levels(df.index.names) # Workaround for GH #17886 (unnecessarily casts to float): stacked = stacked.astype(np.int64) result = stacked.loc[df.index] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # From a series s = df["w"] result = s.unstack(["x", "y"], fill_value=0) expected = unstacked["w"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_unstack_fill_frame(self): @@ -204,7 +203,7 @@ def test_unstack_fill_frame(self): expected.columns = MultiIndex.from_tuples( [("A", "a"), ("A", "b"), ("B", "a"), ("B", "b")] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # From a mixed type dataframe df["A"] = df["A"].astype(np.int16) @@ -213,7 +212,7 @@ def test_unstack_fill_frame(self): result = df.unstack(fill_value=-1) expected["A"] = expected["A"].astype(np.int16) expected["B"] = expected["B"].astype(np.float64) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # From a dataframe with incorrect data type for fill_value result = df.unstack(fill_value=0.5) @@ -223,7 +222,7 @@ def test_unstack_fill_frame(self): expected.columns = MultiIndex.from_tuples( [("A", "a"), ("A", "b"), ("B", "a"), ("B", "b")] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_datetime(self): @@ -239,14 +238,14 @@ def test_unstack_fill_frame_datetime(self): {"a": [dv[0], pd.NaT, dv[3]], "b": [dv[1], dv[2], pd.NaT]}, index=["x", "y", "z"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = data.unstack(fill_value=dv[0]) expected = DataFrame( {"a": [dv[0], dv[0], dv[3]], "b": [dv[1], dv[2], dv[0]]}, index=["x", "y", "z"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_timedelta(self): @@ -262,14 +261,14 @@ def test_unstack_fill_frame_timedelta(self): {"a": [td[0], pd.NaT, td[3]], "b": [td[1], td[2], pd.NaT]}, index=["x", "y", "z"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = data.unstack(fill_value=td[1]) expected = DataFrame( {"a": [td[0], td[1], td[3]], "b": [td[1], td[2], td[1]]}, index=["x", "y", "z"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_period(self): @@ -290,7 +289,7 @@ def test_unstack_fill_frame_period(self): {"a": [periods[0], None, periods[3]], "b": [periods[1], periods[2], None]}, index=["x", "y", "z"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = data.unstack(fill_value=periods[1]) expected = DataFrame( @@ -300,7 +299,7 @@ def test_unstack_fill_frame_period(self): }, index=["x", "y", "z"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_categorical(self): @@ -319,7 +318,7 @@ def test_unstack_fill_frame_categorical(self): }, index=list("xyz"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Fill with non-category results in a TypeError msg = r"'fill_value' \('d'\) is not in" @@ -335,7 +334,7 @@ def test_unstack_fill_frame_categorical(self): }, index=list("xyz"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_unstack_preserve_dtypes(self): # Checks fix for #11847 @@ -358,7 +357,7 @@ def test_unstack_preserve_dtypes(self): def unstack_and_compare(df, column_name): unstacked1 = df.unstack([column_name]) unstacked2 = df.unstack(column_name) - assert_frame_equal(unstacked1, unstacked2) + tm.assert_frame_equal(unstacked1, unstacked2) df1 = df.set_index(["state", "index"]) unstack_and_compare(df1, "index") @@ -383,13 +382,15 @@ def test_stack_ints(self): columns = MultiIndex.from_tuples(list(itertools.product(range(3), repeat=3))) df = DataFrame(np.random.randn(30, 27), columns=columns) - assert_frame_equal(df.stack(level=[1, 2]), df.stack(level=1).stack(level=1)) - assert_frame_equal(df.stack(level=[-2, -1]), df.stack(level=1).stack(level=1)) + tm.assert_frame_equal(df.stack(level=[1, 2]), df.stack(level=1).stack(level=1)) + tm.assert_frame_equal( + df.stack(level=[-2, -1]), df.stack(level=1).stack(level=1) + ) df_named = df.copy() df_named.columns.set_names(range(3), inplace=True) - assert_frame_equal( + tm.assert_frame_equal( df_named.stack(level=[1, 2]), df_named.stack(level=1).stack(level=1) ) @@ -413,10 +414,10 @@ def test_stack_mixed_levels(self): # the level numbers df2 = df.copy() df2.columns.names = ["exp", "animal", 1] - assert_frame_equal( + tm.assert_frame_equal( df2.stack(level=["animal", 1]), animal_hair_stacked, check_names=False ) - assert_frame_equal( + tm.assert_frame_equal( df2.stack(level=["exp", 1]), exp_hair_stacked, check_names=False ) @@ -433,7 +434,7 @@ def test_stack_mixed_levels(self): # strange error about lexsort depth df3 = df.copy() df3.columns.names = ["exp", "animal", 0] - assert_frame_equal( + tm.assert_frame_equal( df3.stack(level=["animal", 0]), animal_hair_stacked, check_names=False ) @@ -455,24 +456,28 @@ def test_stack_int_level_names(self): df2 = df.copy() df2.columns.names = [0, 1, 2] - assert_frame_equal( + tm.assert_frame_equal( df2.stack(level=[1, 2]), animal_hair_stacked, check_names=False ) - assert_frame_equal( + tm.assert_frame_equal( df2.stack(level=[0, 1]), exp_animal_stacked, check_names=False ) - assert_frame_equal(df2.stack(level=[0, 2]), exp_hair_stacked, check_names=False) + tm.assert_frame_equal( + df2.stack(level=[0, 2]), exp_hair_stacked, check_names=False + ) # Out-of-order int column names df3 = df.copy() df3.columns.names = [2, 0, 1] - assert_frame_equal( + tm.assert_frame_equal( df3.stack(level=[0, 1]), animal_hair_stacked, check_names=False ) - assert_frame_equal( + tm.assert_frame_equal( df3.stack(level=[2, 0]), exp_animal_stacked, check_names=False ) - assert_frame_equal(df3.stack(level=[2, 1]), exp_hair_stacked, check_names=False) + tm.assert_frame_equal( + df3.stack(level=[2, 1]), exp_hair_stacked, check_names=False + ) def test_unstack_bool(self): df = DataFrame( @@ -486,7 +491,7 @@ def test_unstack_bool(self): index=["a", "b"], columns=MultiIndex.from_arrays([["col", "col"], ["c", "l"]]), ) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_unstack_level_binding(self): # GH9856 @@ -512,7 +517,7 @@ def test_unstack_level_binding(self): columns=pd.Index(["a", "b"], name="third"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_unstack_to_series(self, float_frame): # check reversibility @@ -520,7 +525,7 @@ def test_unstack_to_series(self, float_frame): assert isinstance(data, Series) undo = data.unstack().T - assert_frame_equal(undo, float_frame) + tm.assert_frame_equal(undo, float_frame) # check NA handling data = DataFrame({"x": [1, 2, np.NaN], "y": [3.0, 4, np.NaN]}) @@ -533,13 +538,13 @@ def test_unstack_to_series(self, float_frame): ) expected = Series([1, 2, np.NaN, 3, 4, np.NaN], index=midx) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # check composability of unstack old_data = data.copy() for _ in range(4): data = data.unstack() - assert_frame_equal(old_data, data) + tm.assert_frame_equal(old_data, data) def test_unstack_dtypes(self): @@ -549,7 +554,7 @@ def test_unstack_dtypes(self): df = DataFrame(rows, columns=list("ABCD")) result = df.dtypes expected = Series([np.dtype("int64")] * 4, index=list("ABCD")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # single dtype df2 = df.set_index(["A", "B"]) @@ -561,7 +566,7 @@ def test_unstack_dtypes(self): [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B") ), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # mixed df2 = df.set_index(["A", "B"]) @@ -574,7 +579,7 @@ def test_unstack_dtypes(self): [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B") ), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df2["D"] = "foo" df3 = df2.unstack("B") result = df3.dtypes @@ -584,7 +589,7 @@ def test_unstack_dtypes(self): [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B") ), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH7405 for c, d in ( @@ -707,7 +712,7 @@ def verify(df): left = df.set_index(["jim", "joe"]).unstack()["jolie"] right = df.set_index(["joe", "jim"]).unstack()["jolie"].T - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) for idx in itertools.permutations(df.columns[:2]): mi = df.set_index(list(idx)) @@ -785,7 +790,7 @@ def verify(df): ) right = DataFrame(vals, columns=cols, index=idx) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) df = DataFrame({"A": list("aaaabbbb"), "B": list(range(4)) * 2, "C": range(8)}) df.iloc[2, 1] = np.NaN @@ -797,7 +802,7 @@ def verify(df): ) idx = Index([np.nan, 0, 1, 2, 3], name="B") right = DataFrame(vals, columns=cols, index=idx) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) df = pd.DataFrame( {"A": list("aaaabbbb"), "B": list(range(4)) * 2, "C": range(8)} @@ -811,7 +816,7 @@ def verify(df): ) idx = Index([np.nan, 0, 1, 2, 3], name="B") right = DataFrame(vals, columns=cols, index=idx) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) # GH7401 df = pd.DataFrame( @@ -834,7 +839,7 @@ def verify(df): ) right = DataFrame(vals, columns=cols, index=idx) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) # GH4862 vals = [ @@ -871,10 +876,10 @@ def verify(df): ) right = DataFrame(vals, columns=cols, index=idx) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) left = df.loc[17264:].copy().set_index(["s_id", "dosage", "agent"]) - assert_frame_equal(left.unstack(), right) + tm.assert_frame_equal(left.unstack(), right) # GH9497 - multiple unstack with nulls df = DataFrame( @@ -907,7 +912,7 @@ def test_stack_datetime_column_multiIndex(self): eidx = MultiIndex.from_product([(0, 1, 2, 3), ("B",)]) ecols = MultiIndex.from_tuples([(t, "A")]) expected = DataFrame([1, 2, 3, 4], index=eidx, columns=ecols) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_stack_partial_multiIndex(self): # GH 8844 @@ -925,18 +930,18 @@ def _test_stack_with_multiindex(multiindex): # as df.stack(level=level, dropna=True). expected = df.stack(level=level, dropna=True) if isinstance(expected, Series): - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) else: - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df.columns = MultiIndex.from_tuples( df.columns.to_numpy(), names=df.columns.names ) expected = df.stack(level=level, dropna=False) if isinstance(expected, Series): - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) else: - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) full_multiindex = MultiIndex.from_tuples( [("B", "x"), ("B", "z"), ("A", "y"), ("C", "x"), ("C", "u")], @@ -973,7 +978,7 @@ def _test_stack_with_multiindex(multiindex): columns=Index(["B", "C"], name="Upper"), dtype=df.dtypes[0], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("ordered", [False, True]) @pytest.mark.parametrize("labels", [list("yxz"), list("yxy")]) @@ -1075,14 +1080,14 @@ def test_unstack_fill_frame_object(): expected = pd.DataFrame( {"a": ["a", np.nan, "a"], "b": ["b", "c", np.nan]}, index=list("xyz") ) - assert_frame_equal(result, expected) + tm.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) + tm.assert_frame_equal(result, expected) def test_unstack_timezone_aware_values(): @@ -1106,7 +1111,7 @@ def test_unstack_timezone_aware_values(): names=[None, "b"], ), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_stack_timezone_aware_values(): @@ -1122,4 +1127,4 @@ def test_stack_timezone_aware_values(): levels=[["a", "b", "c"], ["A"]], codes=[[0, 1, 2], [0, 0, 0]] ), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected)
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29302
2019-10-30T23:25:10Z
2019-10-31T13:11:31Z
2019-10-31T13:11:30Z
2019-10-31T13:11:35Z
CLN: Consistent pandas.util.testing imports in pandas/tests/frame - part 2
diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 5f99d98c705cb..e215c90d2eb04 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -26,11 +26,6 @@ import pandas.core.common as com from pandas.core.indexing import IndexingError import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) from pandas.tseries.offsets import BDay @@ -73,10 +68,12 @@ def test_getitem_dupe_cols(self): def test_get(self, float_frame): b = float_frame.get("B") - assert_series_equal(b, float_frame["B"]) + tm.assert_series_equal(b, float_frame["B"]) assert float_frame.get("foo") is None - assert_series_equal(float_frame.get("foo", float_frame["B"]), float_frame["B"]) + tm.assert_series_equal( + float_frame.get("foo", float_frame["B"]), float_frame["B"] + ) @pytest.mark.parametrize( "df", @@ -95,7 +92,7 @@ def test_loc_iterable(self, float_frame, key_type): idx = key_type(["A", "B", "C"]) result = float_frame.loc[:, idx] expected = float_frame.loc[:, ["A", "B", "C"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "idx_type", @@ -135,7 +132,7 @@ def test_getitem_listlike(self, idx_type, levels, float_frame): expected = frame.loc[:, idx_check] expected.columns.names = frame.columns.names - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) idx = idx_type(keys + [missing]) with pytest.raises(KeyError, match="not in index"): @@ -170,8 +167,8 @@ def test_setitem_list(self, float_frame): data = float_frame[["A", "B"]] float_frame[["B", "A"]] = data - assert_series_equal(float_frame["B"], data["A"], check_names=False) - assert_series_equal(float_frame["A"], data["B"], check_names=False) + tm.assert_series_equal(float_frame["B"], data["A"], check_names=False) + tm.assert_series_equal(float_frame["A"], data["B"], check_names=False) msg = "Columns must be same length as key" with pytest.raises(ValueError, match=msg): @@ -186,18 +183,18 @@ def test_setitem_list(self, float_frame): result = df.loc[df.index[1], ["tt1", "tt2"]] expected = Series([1, 2], df.columns, dtype=np.int_, name=1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df["tt1"] = df["tt2"] = "0" df.loc[df.index[1], ["tt1", "tt2"]] = ["1", "2"] result = df.loc[df.index[1], ["tt1", "tt2"]] expected = Series(["1", "2"], df.columns, name=1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_setitem_list_not_dataframe(self, float_frame): data = np.random.randn(len(float_frame), 2) float_frame[["A", "B"]] = data - assert_almost_equal(float_frame[["A", "B"]].values, data) + tm.assert_almost_equal(float_frame[["A", "B"]].values, data) def test_setitem_list_of_tuples(self, float_frame): tuples = list(zip(float_frame["A"], float_frame["B"])) @@ -205,7 +202,7 @@ def test_setitem_list_of_tuples(self, float_frame): result = float_frame["tuples"] expected = Series(tuples, index=float_frame.index, name="tuples") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_setitem_mulit_index(self): # GH7655, test that assigning to a sub-frame of a frame @@ -221,15 +218,15 @@ def test_setitem_mulit_index(self): np.random.shuffle(i) df["jim"] = df["jolie"].loc[i, ::-1] - assert_frame_equal(df["jim"], df["jolie"]) + tm.assert_frame_equal(df["jim"], df["jolie"]) np.random.shuffle(j) df[("joe", "first")] = df[("jolie", "last")].loc[i, j] - assert_frame_equal(df[("joe", "first")], df[("jolie", "last")]) + tm.assert_frame_equal(df[("joe", "first")], df[("jolie", "last")]) np.random.shuffle(j) df[("joe", "last")] = df[("jolie", "first")].loc[i, j] - assert_frame_equal(df[("joe", "last")], df[("jolie", "first")]) + tm.assert_frame_equal(df[("joe", "last")], df[("jolie", "first")]) def test_setitem_callable(self): # GH 12533 @@ -266,7 +263,7 @@ def test_getitem_boolean( datetime_frame[indexer[:-1]] subframe_obj = datetime_frame[indexer_obj] - assert_frame_equal(subframe_obj, subframe) + tm.assert_frame_equal(subframe_obj, subframe) with pytest.raises(ValueError, match="Boolean array expected"): datetime_frame[datetime_frame] @@ -275,7 +272,7 @@ def test_getitem_boolean( indexer_obj = Series(indexer_obj, datetime_frame.index) subframe_obj = datetime_frame[indexer_obj] - assert_frame_equal(subframe_obj, subframe) + tm.assert_frame_equal(subframe_obj, subframe) # test that Series indexers reindex # we are producing a warning that since the passed boolean @@ -284,7 +281,7 @@ def test_getitem_boolean( with tm.assert_produces_warning(UserWarning, check_stacklevel=False): indexer_obj = indexer_obj.reindex(datetime_frame.index[::-1]) subframe_obj = datetime_frame[indexer_obj] - assert_frame_equal(subframe_obj, subframe) + tm.assert_frame_equal(subframe_obj, subframe) # test df[df > 0] for df in [ @@ -310,7 +307,7 @@ def test_getitem_boolean( bifw[c] = df[c] bifw = bifw.reindex(columns=df.columns) - assert_frame_equal(bif, bifw, check_dtype=False) + tm.assert_frame_equal(bif, bifw, check_dtype=False) for c in df.columns: if bif[c].dtype != bifw[c].dtype: assert bif[c].dtype == df[c].dtype @@ -334,7 +331,7 @@ def test_getitem_boolean_casting(self, datetime_frame): + [np.dtype("int64")] * 2, index=["A", "B", "C", "D", "E", "E1", "F", "F1"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # int block splitting df.loc[df.index[1:3], ["E1", "F1"]] = 0 @@ -348,7 +345,7 @@ def test_getitem_boolean_casting(self, datetime_frame): + [np.dtype("float64")], index=["A", "B", "C", "D", "E", "E1", "F", "F1"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # where dtype conversions # GH 3733 @@ -358,7 +355,7 @@ def test_getitem_boolean_casting(self, datetime_frame): mask = isna(df) expected = bools.astype(float).mask(mask) result = bools.mask(mask) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_getitem_boolean_list(self): df = DataFrame(np.arange(12).reshape(3, 4)) @@ -366,7 +363,7 @@ def test_getitem_boolean_list(self): def _checkit(lst): result = df[lst] expected = df.loc[df.index[lst]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) _checkit([True, False, True]) _checkit([True, True, True]) @@ -380,7 +377,7 @@ def test_getitem_boolean_iadd(self): df[df < 0] += 1 arr[arr < 0] += 1 - assert_almost_equal(df.values, arr) + tm.assert_almost_equal(df.values, arr) def test_boolean_index_empty_corner(self): # #2096 @@ -399,13 +396,13 @@ def test_getitem_ix_mixed_integer(self): result = df.iloc[:-1] expected = df.loc[df.index[:-1]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = df.ix[[1, 10]] expected = df.ix[Index([1, 10], dtype=object)] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # 11320 df = pd.DataFrame( @@ -419,26 +416,26 @@ def test_getitem_ix_mixed_integer(self): ) result = df[[1000]] expected = df.iloc[:, [3]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df[[-1000]] expected = df.iloc[:, [1]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_getitem_setitem_ix_negative_integers(self, float_frame): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = float_frame.ix[:, -1] - assert_series_equal(result, float_frame["D"]) + tm.assert_series_equal(result, float_frame["D"]) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = float_frame.ix[:, [-1]] - assert_frame_equal(result, float_frame[["D"]]) + tm.assert_frame_equal(result, float_frame[["D"]]) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = float_frame.ix[:, [-1, -2]] - assert_frame_equal(result, float_frame[["D", "C"]]) + tm.assert_frame_equal(result, float_frame[["D", "C"]]) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) @@ -467,12 +464,12 @@ def test_getitem_setitem_ix_negative_integers(self, float_frame): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_series_equal(a.ix[-1], a.ix[-2], check_names=False) + tm.assert_series_equal(a.ix[-1], a.ix[-2], check_names=False) assert a.ix[-1].name == "T" assert a.ix[-2].name == "S" def test_getattr(self, float_frame): - assert_series_equal(float_frame.A, float_frame["A"]) + tm.assert_series_equal(float_frame.A, float_frame["A"]) msg = "'DataFrame' object has no attribute 'NONEXISTENT_NAME'" with pytest.raises(AttributeError, match=msg): float_frame.NONEXISTENT_NAME @@ -535,11 +532,11 @@ def test_setitem(self, float_frame): df = DataFrame([[0, 0]]) df.iloc[0] = np.nan expected = DataFrame([[np.nan, np.nan]]) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) df = DataFrame([[0, 0]]) df.loc[0] = np.nan - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) @pytest.mark.parametrize("dtype", ["int32", "int64", "float32", "float64"]) def test_setitem_dtype(self, dtype, float_frame): @@ -550,7 +547,9 @@ def test_setitem_dtype(self, dtype, float_frame): def test_setitem_tuple(self, float_frame): float_frame["A", "B"] = float_frame["A"] - assert_series_equal(float_frame["A", "B"], float_frame["A"], check_names=False) + tm.assert_series_equal( + float_frame["A", "B"], float_frame["A"], check_names=False + ) def test_setitem_always_copy(self, float_frame): s = float_frame["A"].copy() @@ -565,32 +564,32 @@ def test_setitem_boolean(self, float_frame): df[df["A"] > 0] = 4 values[values[:, 0] > 0] = 4 - assert_almost_equal(df.values, values) + tm.assert_almost_equal(df.values, values) # test that column reindexing works series = df["A"] == 4 series = series.reindex(df.index[::-1]) df[series] = 1 values[values[:, 0] == 4] = 1 - assert_almost_equal(df.values, values) + tm.assert_almost_equal(df.values, values) df[df > 0] = 5 values[values > 0] = 5 - assert_almost_equal(df.values, values) + tm.assert_almost_equal(df.values, values) df[df == 5] = 0 values[values == 5] = 0 - assert_almost_equal(df.values, values) + tm.assert_almost_equal(df.values, values) # a df that needs alignment first df[df[:-1] < 0] = 2 np.putmask(values[:-1], values[:-1] < 0, 2) - assert_almost_equal(df.values, values) + tm.assert_almost_equal(df.values, values) # indexed with same shape but rows-reversed df df[df[::-1] == 2] = 3 values[values == 2] = 3 - assert_almost_equal(df.values, values) + tm.assert_almost_equal(df.values, values) msg = "Must pass DataFrame or 2-d ndarray with boolean values only" with pytest.raises(TypeError, match=msg): @@ -601,13 +600,13 @@ def test_setitem_boolean(self, float_frame): expected = df.copy() df[df > np.abs(df)] = np.nan expected.values[mask.values] = np.nan - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # set from DataFrame expected = df.copy() df[df > np.abs(df)] = df * 2 np.putmask(expected.values, mask.values, df.values * 2) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) @pytest.mark.parametrize( "mask_type", @@ -626,7 +625,7 @@ def test_setitem_boolean_mask(self, mask_type, float_frame): expected = df.copy() expected.values[np.array(mask)] = np.nan - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_setitem_cast(self, float_frame): float_frame["D"] = float_frame["D"].astype("i8") @@ -667,7 +666,7 @@ def test_setitem_cast(self, float_frame): [np.dtype("float64")] * 3 + [np.dtype("object")], index=["A", "B", "C", "event"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Test that data type is preserved . #5782 df = DataFrame({"one": np.arange(6, dtype=np.int8)}) @@ -683,7 +682,7 @@ def test_setitem_boolean_column(self, float_frame): float_frame.loc[mask, "B"] = 0 expected.values[mask.values, 1] = 0 - assert_frame_equal(float_frame, expected) + tm.assert_frame_equal(float_frame, expected) def test_frame_setitem_timestamp(self): # GH#2155 @@ -790,13 +789,13 @@ def test_setitem_clear_caches(self): def test_setitem_None(self, float_frame): # GH #766 float_frame[None] = float_frame["A"] - assert_series_equal( + tm.assert_series_equal( float_frame.iloc[:, -1], float_frame["A"], check_names=False ) - assert_series_equal( + tm.assert_series_equal( float_frame.loc[:, None], float_frame["A"], check_names=False ) - assert_series_equal(float_frame[None], float_frame["A"], check_names=False) + tm.assert_series_equal(float_frame[None], float_frame["A"], check_names=False) repr(float_frame) def test_setitem_empty(self): @@ -807,7 +806,7 @@ def test_setitem_empty(self): result = df.copy() result.loc[result.b.isna(), "a"] = result.a - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) @pytest.mark.parametrize("dtype", ["float", "int64"]) @pytest.mark.parametrize("kwargs", [dict(), dict(index=[1]), dict(columns=["A"])]) @@ -818,7 +817,7 @@ def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): df2 = df.copy() df[df > df2] = 47 - assert_frame_equal(df, df2) + tm.assert_frame_equal(df, df2) def test_setitem_with_empty_listlike(self): # GH #17101 @@ -833,14 +832,14 @@ def test_setitem_scalars_no_index(self): df = DataFrame() df["foo"] = 1 expected = DataFrame(columns=["foo"]).astype(np.int64) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_getitem_empty_frame_with_boolean(self): # Test for issue #11859 df = pd.DataFrame() df2 = df[df > 0] - assert_frame_equal(df, df2) + tm.assert_frame_equal(df, df2) def test_delitem_corner(self, float_frame): f = float_frame.copy() @@ -856,21 +855,21 @@ def test_getitem_fancy_2d(self, float_frame): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal(f.ix[:, ["B", "A"]], f.reindex(columns=["B", "A"])) + tm.assert_frame_equal(f.ix[:, ["B", "A"]], f.reindex(columns=["B", "A"])) subidx = float_frame.index[[5, 4, 1]] with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal( + tm.assert_frame_equal( f.ix[subidx, ["B", "A"]], f.reindex(index=subidx, columns=["B", "A"]) ) # slicing rows, etc. with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal(f.ix[5:10], f[5:10]) - assert_frame_equal(f.ix[5:10, :], f[5:10]) - assert_frame_equal( + tm.assert_frame_equal(f.ix[5:10], f[5:10]) + tm.assert_frame_equal(f.ix[5:10, :], f[5:10]) + tm.assert_frame_equal( f.ix[:5, ["A", "B"]], f.reindex(index=f.index[:5], columns=["A", "B"]) ) @@ -879,12 +878,12 @@ def test_getitem_fancy_2d(self, float_frame): simplefilter("ignore", FutureWarning) expected = f.ix[5:11] result = f.ix[f.index[5] : f.index[10]] - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) # slice columns with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal(f.ix[:, :2], f.reindex(columns=["A", "B"])) + tm.assert_frame_equal(f.ix[:, :2], f.reindex(columns=["A", "B"])) # get view with catch_warnings(record=True): @@ -892,7 +891,7 @@ def test_getitem_fancy_2d(self, float_frame): exp = f.copy() f.ix[5:10].values[:] = 5 exp.values[5:10] = 5 - assert_frame_equal(f, exp) + tm.assert_frame_equal(f, exp) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) @@ -938,8 +937,8 @@ def test_getitem_setitem_integer_slice_keyerrors(self): result2 = df.loc[3:11] expected = df.reindex([4, 6, 8, 10]) - assert_frame_equal(result, expected) - assert_frame_equal(result2, expected) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) # non-monotonic, raise KeyError df2 = df.iloc[list(range(5)) + list(range(5, 10))[::-1]] @@ -959,7 +958,7 @@ def test_setitem_fancy_2d(self, float_frame): frame.ix[:, ["B", "A"]] = 1 expected["B"] = 1.0 expected["A"] = 1.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) # case 2 frame = float_frame.copy() @@ -978,8 +977,8 @@ def test_setitem_fancy_2d(self, float_frame): expected["B"].ix[subidx] = values[:, 0] expected["A"].ix[subidx] = values[:, 1] - assert_frame_equal(frame, expected) - assert_frame_equal(frame2, expected) + tm.assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame2, expected) # case 3: slicing rows, etc. frame = float_frame.copy() @@ -989,7 +988,7 @@ def test_setitem_fancy_2d(self, float_frame): expected1 = float_frame.copy() frame.ix[5:10] = 1.0 expected1.values[5:10] = 1.0 - assert_frame_equal(frame, expected1) + tm.assert_frame_equal(frame, expected1) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) @@ -997,16 +996,16 @@ def test_setitem_fancy_2d(self, float_frame): arr = np.random.randn(5, len(frame.columns)) frame.ix[5:10] = arr expected2.values[5:10] = arr - assert_frame_equal(frame, expected2) + tm.assert_frame_equal(frame, expected2) # case 4 with catch_warnings(record=True): simplefilter("ignore", FutureWarning) frame = float_frame.copy() frame.ix[5:10, :] = 1.0 - assert_frame_equal(frame, expected1) + tm.assert_frame_equal(frame, expected1) frame.ix[5:10, :] = arr - assert_frame_equal(frame, expected2) + tm.assert_frame_equal(frame, expected2) # case 5 with catch_warnings(record=True): @@ -1020,12 +1019,12 @@ def test_setitem_fancy_2d(self, float_frame): frame.ix[:5, ["A", "B"]] = values expected["A"][:5] = values[:, 0] expected["B"][:5] = values[:, 1] - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) frame2.ix[:5, [0, 1]] = values - assert_frame_equal(frame2, expected) + tm.assert_frame_equal(frame2, expected) # case 6: slice rows with labels, inclusive! with catch_warnings(record=True): @@ -1035,7 +1034,7 @@ def test_setitem_fancy_2d(self, float_frame): frame.ix[frame.index[5] : frame.index[10]] = 5.0 expected.values[5:11] = 5 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) # case 7: slice columns with catch_warnings(record=True): @@ -1047,11 +1046,11 @@ def test_setitem_fancy_2d(self, float_frame): # slice indices frame.ix[:, 1:3] = 4.0 expected.values[:, 1:3] = 4.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) # slice with labels frame.ix[:, "B":"C"] = 4.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) # new corner case of boolean slicing / setting frame = DataFrame(zip([2, 3, 9, 6, 7], [np.nan] * 5), columns=["a", "b"]) @@ -1059,7 +1058,7 @@ def test_setitem_fancy_2d(self, float_frame): lst.extend([np.nan] * 4) expected = DataFrame(zip([100, 3, 9, 6, 7], lst), columns=["a", "b"]) frame[frame["a"] == 2] = 100 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) def test_fancy_getitem_slice_mixed(self, float_frame, float_string_frame): sliced = float_string_frame.iloc[:, -3:] @@ -1085,7 +1084,7 @@ def test_fancy_setitem_int_labels(self): exp = df.copy() tmp.ix[[0, 2, 4]] = 5 exp.values[:3] = 5 - assert_frame_equal(tmp, exp) + tm.assert_frame_equal(tmp, exp) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) @@ -1093,7 +1092,7 @@ def test_fancy_setitem_int_labels(self): exp = df.copy() tmp.ix[6] = 5 exp.values[3] = 5 - assert_frame_equal(tmp, exp) + tm.assert_frame_equal(tmp, exp) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) @@ -1104,7 +1103,7 @@ def test_fancy_setitem_int_labels(self): # tmp correctly sets the dtype # so match the exp way exp[2] = 5 - assert_frame_equal(tmp, exp) + tm.assert_frame_equal(tmp, exp) def test_fancy_getitem_int_labels(self): df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) @@ -1113,25 +1112,25 @@ def test_fancy_getitem_int_labels(self): simplefilter("ignore", FutureWarning) result = df.ix[[4, 2, 0], [2, 0]] expected = df.reindex(index=[4, 2, 0], columns=[2, 0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = df.ix[[4, 2, 0]] expected = df.reindex(index=[4, 2, 0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = df.ix[4] expected = df.xs(4) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = df.ix[:, 3] expected = df[3] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_fancy_index_int_labels_exceptions(self, float_frame): df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) @@ -1174,7 +1173,7 @@ def test_setitem_fancy_mixed_2d(self, float_string_frame): assert isna(float_string_frame.ix[5]).all() float_string_frame.ix[5] = float_string_frame.ix[6] - assert_series_equal( + tm.assert_series_equal( float_string_frame.ix[5], float_string_frame.ix[6], check_names=False ) @@ -1188,7 +1187,7 @@ def test_setitem_fancy_mixed_2d(self, float_string_frame): expected = DataFrame({1: [1.0, 5.0, 3.0], 2: [3, 10, 5]}) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_ix_align(self): b = Series(np.random.randn(10), name=0).sort_values() @@ -1198,27 +1197,27 @@ def test_ix_align(self): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) df.ix[:, 0] = b - assert_series_equal(df.ix[:, 0].reindex(b.index), b) + tm.assert_series_equal(df.ix[:, 0].reindex(b.index), b) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) dft = df_orig.T dft.ix[0, :] = b - assert_series_equal(dft.ix[0, :].reindex(b.index), b) + tm.assert_series_equal(dft.ix[0, :].reindex(b.index), b) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) df = df_orig.copy() df.ix[:5, 0] = b s = df.ix[:5, 0] - assert_series_equal(s, b.reindex(s.index)) + tm.assert_series_equal(s, b.reindex(s.index)) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) dft = df_orig.T dft.ix[0, :5] = b s = dft.ix[0, :5] - assert_series_equal(s, b.reindex(s.index)) + tm.assert_series_equal(s, b.reindex(s.index)) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) @@ -1226,14 +1225,14 @@ def test_ix_align(self): idx = [0, 1, 3, 5] df.ix[idx, 0] = b s = df.ix[idx, 0] - assert_series_equal(s, b.reindex(s.index)) + tm.assert_series_equal(s, b.reindex(s.index)) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) dft = df_orig.T dft.ix[0, idx] = b s = dft.ix[0, idx] - assert_series_equal(s, b.reindex(s.index)) + tm.assert_series_equal(s, b.reindex(s.index)) def test_ix_frame_align(self): b = DataFrame(np.random.randn(3, 4)) @@ -1244,7 +1243,7 @@ def test_ix_frame_align(self): simplefilter("ignore", FutureWarning) df.ix[:3] = b out = b.ix[:3] - assert_frame_equal(out, b) + tm.assert_frame_equal(out, b) b.sort_index(inplace=True) @@ -1253,14 +1252,14 @@ def test_ix_frame_align(self): df = df_orig.copy() df.ix[[0, 1, 2]] = b out = df.ix[[0, 1, 2]].reindex(b.index) - assert_frame_equal(out, b) + tm.assert_frame_equal(out, b) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) df = df_orig.copy() df.ix[:3] = b out = df.ix[:3] - assert_frame_equal(out, b.reindex(out.index)) + tm.assert_frame_equal(out, b.reindex(out.index)) def test_getitem_setitem_non_ix_labels(self): df = tm.makeTimeDataFrame() @@ -1270,8 +1269,8 @@ def test_getitem_setitem_non_ix_labels(self): result = df.loc[start:end] result2 = df[start:end] expected = df[5:11] - assert_frame_equal(result, expected) - assert_frame_equal(result2, expected) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) result = df.copy() result.loc[start:end] = 0 @@ -1279,20 +1278,20 @@ def test_getitem_setitem_non_ix_labels(self): result2[start:end] = 0 expected = df.copy() expected[5:11] = 0 - assert_frame_equal(result, expected) - assert_frame_equal(result2, expected) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) def test_ix_multi_take(self): df = DataFrame(np.random.randn(3, 2)) rs = df.loc[df.index == 0, :] xp = df.reindex([0]) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) """ #1321 df = DataFrame(np.random.randn(3, 2)) rs = df.loc[df.index==0, df.columns==1] xp = df.reindex([0], [1]) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) """ def test_ix_multi_take_nonint_index(self): @@ -1301,7 +1300,7 @@ def test_ix_multi_take_nonint_index(self): simplefilter("ignore", FutureWarning) rs = df.ix[[0], [0]] xp = df.reindex(["x"], columns=["a"]) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_ix_multi_take_multiindex(self): df = DataFrame( @@ -1313,7 +1312,7 @@ def test_ix_multi_take_multiindex(self): simplefilter("ignore", FutureWarning) rs = df.ix[[0], [0]] xp = df.reindex(["x"], columns=[("a", "1")]) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_ix_dup(self): idx = Index(["a", "a", "b", "c", "d", "d"]) @@ -1322,17 +1321,17 @@ def test_ix_dup(self): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) sub = df.ix[:"d"] - assert_frame_equal(sub, df) + tm.assert_frame_equal(sub, df) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) sub = df.ix["a":"c"] - assert_frame_equal(sub, df.ix[0:4]) + tm.assert_frame_equal(sub, df.ix[0:4]) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) sub = df.ix["b":"d"] - assert_frame_equal(sub, df.ix[2:]) + tm.assert_frame_equal(sub, df.ix[2:]) def test_getitem_fancy_1d(self, float_frame, float_string_frame): f = float_frame @@ -1371,7 +1370,7 @@ def test_getitem_fancy_1d(self, float_frame, float_string_frame): # single column with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_series_equal(f.ix[:, "A"], f["A"]) + tm.assert_series_equal(f.ix[:, "A"], f["A"]) # return view with catch_warnings(record=True): @@ -1406,13 +1405,13 @@ def test_setitem_fancy_1d(self, float_frame): expected["C"][2] = 1.0 expected["B"][2] = 2.0 expected["A"][2] = 3.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) frame2 = float_frame.copy() frame2.ix[2, [3, 2, 1]] = [1.0, 2.0, 3.0] - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) # case 2, set a section of a column frame = float_frame.copy() @@ -1423,13 +1422,13 @@ def test_setitem_fancy_1d(self, float_frame): vals = np.random.randn(5) expected.values[5:10, 2] = vals frame.ix[5:10, 2] = vals - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) frame2 = float_frame.copy() frame2.ix[5:10, "B"] = vals - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) # case 3: full xs frame = float_frame.copy() @@ -1439,13 +1438,13 @@ def test_setitem_fancy_1d(self, float_frame): simplefilter("ignore", FutureWarning) frame.ix[4] = 5.0 expected.values[4] = 5.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) frame.ix[frame.index[4]] = 6.0 expected.values[4] = 6.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) # single column frame = float_frame.copy() @@ -1455,7 +1454,7 @@ def test_setitem_fancy_1d(self, float_frame): simplefilter("ignore", FutureWarning) frame.ix[:, "A"] = 7.0 expected["A"] = 7.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) def test_getitem_fancy_scalar(self, float_frame): f = float_frame @@ -1481,7 +1480,7 @@ def test_setitem_fancy_scalar(self, float_frame): expected.values[i, j] = val ix[idx, col] = val - assert_frame_equal(f, expected) + tm.assert_frame_equal(f, expected) def test_getitem_fancy_boolean(self, float_frame): f = float_frame @@ -1489,22 +1488,22 @@ def test_getitem_fancy_boolean(self, float_frame): expected = f.reindex(columns=["B", "D"]) result = ix[:, [False, True, False, True]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = f.reindex(index=f.index[5:10], columns=["B", "D"]) result = ix[f.index[5:10], [False, True, False, True]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) boolvec = f.index > f.index[7] expected = f.reindex(index=f.index[boolvec]) result = ix[boolvec] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = ix[boolvec, :] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = ix[boolvec, f.columns[2:]] expected = f.reindex(index=f.index[boolvec], columns=["C", "D"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_setitem_fancy_boolean(self, float_frame): # from 2d, set with booleans @@ -1514,22 +1513,22 @@ def test_setitem_fancy_boolean(self, float_frame): mask = frame["A"] > 0 frame.loc[mask] = 0.0 expected.values[mask.values] = 0.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) frame = float_frame.copy() expected = float_frame.copy() frame.loc[mask, ["A", "B"]] = 0.0 expected.values[mask.values, :2] = 0.0 - assert_frame_equal(frame, expected) + tm.assert_frame_equal(frame, expected) def test_getitem_fancy_ints(self, float_frame): result = float_frame.iloc[[1, 4, 7]] expected = float_frame.loc[float_frame.index[[1, 4, 7]]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = float_frame.iloc[:, [2, 0, 1]] expected = float_frame.loc[:, float_frame.columns[[2, 0, 1]]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_getitem_setitem_fancy_exceptions(self, float_frame): ix = float_frame.iloc @@ -1545,13 +1544,13 @@ def test_getitem_setitem_boolean_misaligned(self, float_frame): result = float_frame.loc[mask] expected = float_frame.loc[mask[::-1]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) cp = float_frame.copy() expected = float_frame.copy() cp.loc[mask] = 0 expected.loc[mask] = 0 - assert_frame_equal(cp, expected) + tm.assert_frame_equal(cp, expected) def test_getitem_setitem_boolean_multi(self): df = DataFrame(np.random.randn(3, 2)) @@ -1561,12 +1560,12 @@ def test_getitem_setitem_boolean_multi(self): k2 = np.array([False, True]) result = df.loc[k1, k2] expected = df.loc[[0, 2], [1]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = df.copy() df.loc[np.array([True, False, True]), np.array([False, True])] = 5 expected.loc[[0, 2], [1]] = 5 - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_getitem_setitem_float_labels(self): index = Index([1.5, 2, 3, 4, 5]) @@ -1574,23 +1573,23 @@ def test_getitem_setitem_float_labels(self): result = df.loc[1.5:4] expected = df.reindex([1.5, 2, 3, 4]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert len(result) == 4 result = df.loc[4:5] expected = df.reindex([4, 5]) # reindex with int - assert_frame_equal(result, expected, check_index_type=False) + tm.assert_frame_equal(result, expected, check_index_type=False) assert len(result) == 2 result = df.loc[4:5] expected = df.reindex([4.0, 5.0]) # reindex with float - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert len(result) == 2 # loc_float changes this to work properly result = df.loc[1:2] expected = df.iloc[0:2] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df.loc[1:2] = 0 result = df[1:2] @@ -1611,7 +1610,7 @@ def test_getitem_setitem_float_labels(self): result = df.iloc[4:5] expected = df.reindex([5.0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert len(result) == 1 cp = df.copy() @@ -1633,22 +1632,22 @@ def test_getitem_setitem_float_labels(self): # float slicing result = df.loc[1.0:5] expected = df - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert len(result) == 5 result = df.loc[1.1:5] expected = df.reindex([2.5, 3.5, 4.5, 5.0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert len(result) == 4 result = df.loc[4.51:5] expected = df.reindex([5.0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert len(result) == 1 result = df.loc[1.0:5.0] expected = df.reindex([1.0, 2.5, 3.5, 4.5, 5.0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert len(result) == 5 cp = df.copy() @@ -1665,7 +1664,7 @@ def test_setitem_single_column_mixed(self): df["str"] = "qux" df.loc[df.index[::2], "str"] = np.nan expected = np.array([np.nan, "qux", np.nan, "qux", np.nan], dtype=object) - assert_almost_equal(df["str"].values, expected) + tm.assert_almost_equal(df["str"].values, expected) def test_setitem_single_column_mixed_datetime(self): df = DataFrame( @@ -1682,7 +1681,7 @@ def test_setitem_single_column_mixed_datetime(self): [np.dtype("float64")] * 3 + [np.dtype("datetime64[ns]")], index=["foo", "bar", "baz", "timestamp"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH#16674 iNaT is treated as an integer when given by the user df.loc["b", "timestamp"] = iNaT @@ -1731,14 +1730,14 @@ def test_setitem_mixed_datetime(self): ] ) df.loc[[4, 5], ["a", "b"]] = A - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_setitem_frame_float(self, float_frame): piece = float_frame.loc[float_frame.index[:2], ["A", "B"]] float_frame.loc[float_frame.index[-2] :, ["A", "B"]] = piece.values result = float_frame.loc[float_frame.index[-2:], ["A", "B"]].values expected = piece.values - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) def test_setitem_frame_mixed(self, float_string_frame): # GH 3216 @@ -1750,7 +1749,7 @@ def test_setitem_frame_mixed(self, float_string_frame): ) key = (slice(None, 2), ["A", "B"]) f.loc[key] = piece - assert_almost_equal(f.loc[f.index[0:2], ["A", "B"]].values, piece.values) + tm.assert_almost_equal(f.loc[f.index[0:2], ["A", "B"]].values, piece.values) # rows unaligned f = float_string_frame.copy() @@ -1761,7 +1760,9 @@ def test_setitem_frame_mixed(self, float_string_frame): ) key = (slice(None, 2), ["A", "B"]) f.loc[key] = piece - assert_almost_equal(f.loc[f.index[0:2:], ["A", "B"]].values, piece.values[0:2]) + tm.assert_almost_equal( + f.loc[f.index[0:2:], ["A", "B"]].values, piece.values[0:2] + ) # key is unaligned with values f = float_string_frame.copy() @@ -1770,14 +1771,14 @@ def test_setitem_frame_mixed(self, float_string_frame): key = (slice(-2, None), ["A", "B"]) f.loc[key] = piece piece["B"] = np.nan - assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values) + tm.assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values) # ndarray f = float_string_frame.copy() piece = float_string_frame.loc[f.index[:2], ["A", "B"]] key = (slice(-2, None), ["A", "B"]) f.loc[key] = piece.values - assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values) + tm.assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values) def test_setitem_frame_upcast(self): # needs upcasting @@ -1787,7 +1788,7 @@ def test_setitem_frame_upcast(self): expected = df.reindex(columns=["A", "B"]) expected += 0.5 expected["C"] = df["C"] - assert_frame_equal(df2, expected) + tm.assert_frame_equal(df2, expected) def test_setitem_frame_align(self, float_frame): piece = float_frame.loc[float_frame.index[:2], ["A", "B"]] @@ -1796,7 +1797,7 @@ def test_setitem_frame_align(self, float_frame): float_frame.loc[float_frame.index[-2:], ["A", "B"]] = piece result = float_frame.loc[float_frame.index[-2:], ["A", "B"]].values expected = piece.values - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) def test_getitem_setitem_ix_duplicates(self): # #1201 @@ -1804,15 +1805,15 @@ def test_getitem_setitem_ix_duplicates(self): result = df.loc["foo"] expected = df[:2] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.loc["bar"] expected = df.iloc[[2, 4]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.loc["baz"] expected = df.iloc[3] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_getitem_ix_boolean_duplicates_multiple(self): # #1201 @@ -1820,15 +1821,15 @@ def test_getitem_ix_boolean_duplicates_multiple(self): result = df.loc[["bar"]] exp = df.iloc[[2, 4]] - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) result = df.loc[df[1] > 0] exp = df[df[1] > 0] - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) result = df.loc[df[0] > 0] exp = df[df[0] > 0] - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) def test_getitem_setitem_ix_bool_keyerror(self): # #2199 @@ -1854,7 +1855,7 @@ def test_getitem_list_duplicates(self): assert result.columns.name == "foo" expected = df.iloc[:, 2:] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_get_value(self, float_frame): for idx in float_frame.index: @@ -2003,25 +2004,25 @@ def test_single_element_ix_dont_upcast(self, float_frame): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = df.ix[[0], "b"] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.loc[[0], "b"] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_iloc_row(self): df = DataFrame(np.random.randn(10, 4), index=range(0, 20, 2)) result = df.iloc[1] exp = df.loc[2] - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) result = df.iloc[2] exp = df.loc[4] - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) # slice result = df.iloc[slice(4, 8)] expected = df.loc[8:14] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # verify slice is view # setting it makes it raise/warn @@ -2030,12 +2031,12 @@ def test_iloc_row(self): exp_col = df[2].copy() exp_col[4:8] = 0.0 - assert_series_equal(df[2], exp_col) + tm.assert_series_equal(df[2], exp_col) # list of integers result = df.iloc[[1, 2, 4, 6]] expected = df.reindex(df.index[[1, 2, 4, 6]]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_iloc_col(self): @@ -2043,16 +2044,16 @@ def test_iloc_col(self): result = df.iloc[:, 1] exp = df.loc[:, 2] - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) result = df.iloc[:, 2] exp = df.loc[:, 4] - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) # slice result = df.iloc[:, slice(4, 8)] expected = df.loc[:, 8:14] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # verify slice is view # and that we are setting a copy @@ -2064,7 +2065,7 @@ def test_iloc_col(self): # list of integers result = df.iloc[:, [1, 2, 4, 6]] expected = df.reindex(columns=df.columns[[1, 2, 4, 6]]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_iloc_duplicates(self): @@ -2075,16 +2076,16 @@ def test_iloc_duplicates(self): simplefilter("ignore", FutureWarning) result2 = df.ix[0] assert isinstance(result, Series) - assert_almost_equal(result.values, df.values[0]) - assert_series_equal(result, result2) + tm.assert_almost_equal(result.values, df.values[0]) + tm.assert_series_equal(result, result2) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) result = df.T.iloc[:, 0] result2 = df.T.ix[:, 0] assert isinstance(result, Series) - assert_almost_equal(result.values, df.values[0]) - assert_series_equal(result, result2) + tm.assert_almost_equal(result.values, df.values[0]) + tm.assert_series_equal(result, result2) # multiindex df = DataFrame( @@ -2097,25 +2098,25 @@ def test_iloc_duplicates(self): simplefilter("ignore", FutureWarning) rs = df.iloc[0] xp = df.ix[0] - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) rs = df.iloc[:, 0] xp = df.T.ix[0] - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) rs = df.iloc[:, [0]] xp = df.ix[:, [0]] - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) # #2259 df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1, 1, 2]) result = df.iloc[:, [0]] expected = df.take([0], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_loc_duplicates(self): # gh-17105 @@ -2166,32 +2167,32 @@ def test_reindex_methods(self, method, expected_values): expected = pd.DataFrame({"x": expected_values}, index=target) actual = df.reindex(target, method=method) - assert_frame_equal(expected, actual) + tm.assert_frame_equal(expected, actual) actual = df.reindex_like(df, method=method, tolerance=0) - assert_frame_equal(df, actual) + tm.assert_frame_equal(df, actual) actual = df.reindex_like(df, method=method, tolerance=[0, 0, 0, 0]) - assert_frame_equal(df, actual) + tm.assert_frame_equal(df, actual) actual = df.reindex(target, method=method, tolerance=1) - assert_frame_equal(expected, actual) + tm.assert_frame_equal(expected, actual) actual = df.reindex(target, method=method, tolerance=[1, 1, 1, 1]) - assert_frame_equal(expected, actual) + tm.assert_frame_equal(expected, actual) e2 = expected[::-1] actual = df.reindex(target[::-1], method=method) - assert_frame_equal(e2, actual) + tm.assert_frame_equal(e2, actual) new_order = [3, 0, 2, 1] e2 = expected.iloc[new_order] actual = df.reindex(target[new_order], method=method) - assert_frame_equal(e2, actual) + tm.assert_frame_equal(e2, actual) switched_method = ( "pad" if method == "backfill" else "backfill" if method == "pad" else method ) actual = df[::-1].reindex(target, method=switched_method) - assert_frame_equal(expected, actual) + tm.assert_frame_equal(expected, actual) def test_reindex_methods_nearest_special(self): df = pd.DataFrame({"x": list(range(5))}) @@ -2199,11 +2200,11 @@ def test_reindex_methods_nearest_special(self): expected = pd.DataFrame({"x": [0, 1, 1, np.nan]}, index=target) actual = df.reindex(target, method="nearest", tolerance=0.2) - assert_frame_equal(expected, actual) + tm.assert_frame_equal(expected, actual) expected = pd.DataFrame({"x": [0, np.nan, 1, np.nan]}, index=target) actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1]) - assert_frame_equal(expected, actual) + tm.assert_frame_equal(expected, actual) def test_reindex_frame_add_nat(self): rng = date_range("1/1/2000 00:00:00", periods=10, freq="10s") @@ -2264,12 +2265,12 @@ def f(val): i = np.concatenate(list(map(f, idx))) left = df.set_index(icol).reindex(idx, level=level) right = df.iloc[i].set_index(icol) - assert_frame_equal(left, right, check_index_type=check_index_type) + tm.assert_frame_equal(left, right, check_index_type=check_index_type) def verify(df, level, idx, indexer, check_index_type=True): left = df.set_index(icol).reindex(idx, level=level) right = df.iloc[indexer].set_index(icol) - assert_frame_equal(left, right, check_index_type=check_index_type) + tm.assert_frame_equal(left, right, check_index_type=check_index_type) df = pd.DataFrame( { @@ -2353,45 +2354,45 @@ def test_getitem_ix_float_duplicates(self): np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list("abc") ) expect = df.iloc[1:] - assert_frame_equal(df.loc[0.2], expect) + tm.assert_frame_equal(df.loc[0.2], expect) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal(df.ix[0.2], expect) + tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[1:, 0] - assert_series_equal(df.loc[0.2, "a"], expect) + tm.assert_series_equal(df.loc[0.2, "a"], expect) df.index = [1, 0.2, 0.2] expect = df.iloc[1:] - assert_frame_equal(df.loc[0.2], expect) + tm.assert_frame_equal(df.loc[0.2], expect) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal(df.ix[0.2], expect) + tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[1:, 0] - assert_series_equal(df.loc[0.2, "a"], expect) + tm.assert_series_equal(df.loc[0.2, "a"], expect) df = pd.DataFrame( np.random.randn(4, 3), index=[1, 0.2, 0.2, 1], columns=list("abc") ) expect = df.iloc[1:-1] - assert_frame_equal(df.loc[0.2], expect) + tm.assert_frame_equal(df.loc[0.2], expect) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal(df.ix[0.2], expect) + tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[1:-1, 0] - assert_series_equal(df.loc[0.2, "a"], expect) + tm.assert_series_equal(df.loc[0.2, "a"], expect) df.index = [0.1, 0.2, 2, 0.2] expect = df.iloc[[1, -1]] - assert_frame_equal(df.loc[0.2], expect) + tm.assert_frame_equal(df.loc[0.2], expect) with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - assert_frame_equal(df.ix[0.2], expect) + tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[[1, -1], 0] - assert_series_equal(df.loc[0.2, "a"], expect) + tm.assert_series_equal(df.loc[0.2, "a"], expect) def test_getitem_sparse_column(self): # https://github.com/pandas-dev/pandas/issues/23559 @@ -2412,7 +2413,7 @@ def test_setitem_with_sparse_value(self): df = pd.DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]}) sp_array = pd.SparseArray([0, 0, 1]) df["new_column"] = sp_array - assert_series_equal( + tm.assert_series_equal( df["new_column"], pd.Series(sp_array, name="new_column"), check_names=False ) @@ -2421,7 +2422,7 @@ def test_setitem_with_unaligned_sparse_value(self): sp_series = pd.Series(pd.SparseArray([0, 0, 1]), index=[2, 1, 0]) df["new_column"] = sp_series exp = pd.Series(pd.SparseArray([1, 0, 0]), name="new_column") - assert_series_equal(df["new_column"], exp) + tm.assert_series_equal(df["new_column"], exp) def test_setitem_with_unaligned_tz_aware_datetime_column(self): # GH 12981 @@ -2432,11 +2433,11 @@ def test_setitem_with_unaligned_tz_aware_datetime_column(self): ) df = pd.DataFrame({"dates": column}) df["dates"] = column[[1, 0, 2]] - assert_series_equal(df["dates"], column) + tm.assert_series_equal(df["dates"], column) df = pd.DataFrame({"dates": column}) df.loc[[0, 1, 2], "dates"] = column[[1, 0, 2]] - assert_series_equal(df["dates"], column) + tm.assert_series_equal(df["dates"], column) def test_setitem_datetime_coercion(self): # gh-1048 @@ -2467,7 +2468,7 @@ def test_setitem_datetimelike_with_inference(self): [np.dtype("timedelta64[ns]")] * 6 + [np.dtype("datetime64[ns]")] * 2, index=list("ABCDEFGH"), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("idxer", ["var", ["var"]]) def test_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture): @@ -2490,15 +2491,15 @@ def test_at_time_between_time_datetimeindex(self): result = df.at_time(akey) expected = df.loc[akey] expected2 = df.iloc[ainds] - assert_frame_equal(result, expected) - assert_frame_equal(result, expected2) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected2) assert len(result) == 4 result = df.between_time(bkey.start, bkey.stop) expected = df.loc[bkey] expected2 = df.iloc[binds] - assert_frame_equal(result, expected) - assert_frame_equal(result, expected2) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected2) assert len(result) == 12 result = df.copy() @@ -2506,24 +2507,24 @@ def test_at_time_between_time_datetimeindex(self): result = result.loc[akey] expected = df.loc[akey].copy() expected.loc[:] = 0 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.loc[akey] = 0 result.loc[akey] = df.iloc[ainds] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.copy() result.loc[bkey] = 0 result = result.loc[bkey] expected = df.loc[bkey].copy() expected.loc[:] = 0 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.loc[bkey] = 0 result.loc[bkey] = df.iloc[binds] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_xs(self, float_frame, datetime_frame): idx = float_frame.index[5] @@ -2550,7 +2551,7 @@ def test_xs(self, float_frame, datetime_frame): # xs get column series = float_frame.xs("A", axis=1) expected = float_frame["A"] - assert_series_equal(series, expected) + tm.assert_series_equal(series, expected) # view is returned if possible series = float_frame.xs("A", axis=1) @@ -2574,14 +2575,14 @@ def test_xs_corner(self): df = DataFrame(index=["a", "b", "c"]) result = df.xs("a") expected = Series([], name="a", index=pd.Index([], dtype=object)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_xs_duplicates(self): df = DataFrame(np.random.randn(5, 2), index=["b", "b", "c", "b", "a"]) cross = df.xs("c") exp = df.iloc[2] - assert_series_equal(cross, exp) + tm.assert_series_equal(cross, exp) def test_xs_keep_level(self): df = DataFrame( @@ -2594,10 +2595,10 @@ def test_xs_keep_level(self): ).set_index(["year", "flavour", "day"]) result = df.xs("sat", level="day", drop_level=False) expected = df[:1] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.xs([2008, "sat"], level=["year", "day"], drop_level=False) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_xs_view(self): # in 0.14 this will return a view if possible a copy otherwise, but @@ -2644,7 +2645,7 @@ def test_boolean_indexing(self): ) df1[df1 > 2.0 * df2] = -1 - assert_frame_equal(df1, expected) + tm.assert_frame_equal(df1, expected) with pytest.raises(ValueError, match="Item wrong length"): df1[df1.index[:-1] > 2] = -1 @@ -2686,7 +2687,7 @@ def test_boolean_indexing_mixed(self): expected.loc[49, 1] = 1 expected.loc[50, 1] = 1 expected.loc[35, 4] = 1 - assert_frame_equal(df2, expected) + tm.assert_frame_equal(df2, expected) df["foo"] = "test" msg = "not supported between instances|unorderable types" @@ -2715,8 +2716,8 @@ def _check_get(df, cond, check_dtypes=True): rs2 = df.where(cond.values, other1) for k, v in rs.items(): exp = Series(np.where(cond[k], df[k], other1[k]), index=v.index) - assert_series_equal(v, exp, check_names=False) - assert_frame_equal(rs, rs2) + tm.assert_series_equal(v, exp, check_names=False) + tm.assert_frame_equal(rs, rs2) # dtypes if check_dtypes: @@ -2759,7 +2760,7 @@ def _check_get(df, cond, check_dtypes=True): # # expected = Series({ 'float32' : 1, 'float64' : 3 }) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # aligning def _check_align(df, cond, other, check_dtypes=True): @@ -2782,7 +2783,7 @@ def _check_align(df, cond, other, check_dtypes=True): # since we can't always have the correct numpy dtype # as numpy doesn't know how to downcast, don't check - assert_series_equal(result, expected, check_dtype=False) + tm.assert_series_equal(result, expected, check_dtype=False) # dtypes # can't check dtype when other is an ndarray @@ -2834,7 +2835,7 @@ def _check_set(df, cond, check_dtypes=True): expected = dfi.mask(~econd) dfi.where(cond, np.nan, inplace=True) - assert_frame_equal(dfi, expected) + tm.assert_frame_equal(dfi, expected) # dtypes (and confirm upcasts)x if check_dtypes: @@ -2869,7 +2870,7 @@ def _check_set(df, cond, check_dtypes=True): df = DataFrame({"a": range(3), "b": range(4, 7)}) result = df.where(df["a"] == 1) expected = df[df["a"] == 1].reindex(df.index) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("klass", [list, tuple, np.array]) def test_where_array_like(self, klass): @@ -2879,14 +2880,14 @@ def test_where_array_like(self, klass): expected = DataFrame({"a": [np.nan, 2, 3]}) result = df.where(klass(cond)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df["b"] = 2 expected["b"] = [2, np.nan, 2] cond = [[False, True], [True, False], [True, True]] result = df.where(klass(cond)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "cond", @@ -2974,11 +2975,11 @@ def test_where_bug(self): dtype="float64", ) result = df.where(df > 2, np.nan) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(result > 2, np.nan, inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_where_bug_mixed(self, sint_dtype): # see gh-2793 @@ -2995,11 +2996,11 @@ def test_where_bug_mixed(self, sint_dtype): ) result = df.where(df > 2, np.nan) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(result > 2, np.nan, inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_where_bug_transposition(self): # see gh-7506 @@ -3011,7 +3012,7 @@ def test_where_bug_transposition(self): expected[~do_not_replace] = b result = a.where(do_not_replace, b) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) a = DataFrame({0: [4, 6], 1: [1, 0]}) b = DataFrame({0: [np.nan, 3], 1: [3, np.nan]}) @@ -3021,7 +3022,7 @@ def test_where_bug_transposition(self): expected[~do_not_replace] = b result = a.where(do_not_replace, b) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_where_datetime(self): @@ -3043,7 +3044,7 @@ def test_where_datetime(self): expected = df.copy() expected.loc[[0, 1], "A"] = np.nan expected.loc[:, "C"] = np.nan - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_where_none(self): # GH 4667 @@ -3053,7 +3054,7 @@ def test_where_none(self): expected = DataFrame( {"series": Series([0, 1, 2, 3, 4, 5, 6, 7, np.nan, np.nan])} ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # GH 7656 df = DataFrame( @@ -3087,17 +3088,17 @@ def create(): df = create() expected = df.fillna(df.mean()) result = df.where(pd.notna(df), df.mean(), axis="columns") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df.where(pd.notna(df), df.mean(), inplace=True, axis="columns") - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) df = create().fillna(0) expected = df.apply(lambda x, y: x.where(x > 0, y), y=df[0]) result = df.where(df > 0, df[0], axis="index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.where(df > 0, df[0], axis="rows") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # frame df = create() @@ -3105,14 +3106,14 @@ def create(): result = df.where( pd.notna(df), DataFrame(1, index=df.index, columns=df.columns) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_where_complex(self): # GH 6345 expected = DataFrame([[1 + 1j, 2], [np.nan, 4 + 1j]], columns=["a", "b"]) df = DataFrame([[1 + 1j, 2], [5 + 1j, 4 + 1j]], columns=["a", "b"]) df[df.abs() >= 5] = np.nan - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_where_axis(self): # GH 9736 @@ -3122,19 +3123,19 @@ def test_where_axis(self): expected = DataFrame([[0, 0], [1, 1]], dtype="float64") result = df.where(mask, s, axis="index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, s, axis="index", inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame([[0, 1], [0, 1]], dtype="float64") result = df.where(mask, s, axis="columns") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, s, axis="columns", inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Upcast needed df = DataFrame([[1, 2], [3, 4]], dtype="int64") @@ -3143,15 +3144,15 @@ def test_where_axis(self): expected = DataFrame([[0, 0], [np.nan, np.nan]], dtype="float64") result = df.where(mask, s, axis="index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, s, axis="index", inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame([[0, np.nan], [0, np.nan]]) result = df.where(mask, s, axis="columns") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( { @@ -3161,7 +3162,7 @@ def test_where_axis(self): ) result = df.copy() result.where(mask, s, axis="columns", inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Multiple dtypes (=> multiple Blocks) df = pd.concat( @@ -3180,21 +3181,21 @@ def test_where_axis(self): expected = DataFrame(1.0, columns=df.columns, index=df.index) expected[2] = expected[2].astype("int64") expected[3] = expected[3].astype("int64") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, s1, axis="columns", inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.where(mask, s2, axis="index") expected = DataFrame(2.0, columns=df.columns, index=df.index) expected[2] = expected[2].astype("int64") expected[3] = expected[3].astype("int64") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, s2, axis="index", inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # DataFrame vs DataFrame d1 = df.copy().drop(1, axis=0) @@ -3202,30 +3203,30 @@ def test_where_axis(self): expected.loc[1, :] = np.nan result = df.where(mask, d1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.where(mask, d1, axis="index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, d1, inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, d1, inplace=True, axis="index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) d2 = df.copy().drop(1, axis=1) expected = df.copy() expected.loc[:, 1] = np.nan result = df.where(mask, d2) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.where(mask, d2, axis="columns") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, d2, inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result.where(mask, d2, inplace=True, axis="columns") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_where_callable(self): # GH 12533 @@ -3262,20 +3263,20 @@ def test_where_tz_values(self, tz_naive_fixture): columns=["date"], ) result = df1.where(mask, df2) - assert_frame_equal(exp, result) + tm.assert_frame_equal(exp, result) def test_mask(self): df = DataFrame(np.random.randn(5, 3)) cond = df > 0 rs = df.where(cond, np.nan) - assert_frame_equal(rs, df.mask(df <= 0)) - assert_frame_equal(rs, df.mask(~cond)) + tm.assert_frame_equal(rs, df.mask(df <= 0)) + tm.assert_frame_equal(rs, df.mask(~cond)) other = DataFrame(np.random.randn(5, 3)) rs = df.where(cond, other) - assert_frame_equal(rs, df.mask(df <= 0, other)) - assert_frame_equal(rs, df.mask(~cond, other)) + tm.assert_frame_equal(rs, df.mask(df <= 0, other)) + tm.assert_frame_equal(rs, df.mask(~cond, other)) # see gh-21891 df = DataFrame([1, 2]) @@ -3292,20 +3293,20 @@ def test_mask_inplace(self): rdf = df.copy() rdf.where(cond, inplace=True) - assert_frame_equal(rdf, df.where(cond)) - assert_frame_equal(rdf, df.mask(~cond)) + tm.assert_frame_equal(rdf, df.where(cond)) + tm.assert_frame_equal(rdf, df.mask(~cond)) rdf = df.copy() rdf.where(cond, -df, inplace=True) - assert_frame_equal(rdf, df.where(cond, -df)) - assert_frame_equal(rdf, df.mask(~cond, -df)) + tm.assert_frame_equal(rdf, df.where(cond, -df)) + tm.assert_frame_equal(rdf, df.mask(~cond, -df)) def test_mask_edge_case_1xN_frame(self): # GH4071 df = DataFrame([[1, 2]]) res = df.mask(DataFrame([[True, False]])) expec = DataFrame([[np.nan, 2]]) - assert_frame_equal(res, expec) + tm.assert_frame_equal(res, expec) def test_mask_callable(self): # GH 12533 @@ -3328,29 +3329,29 @@ def test_mask_callable(self): tm.assert_frame_equal(result, (df + 2).mask((df + 2) > 8, (df + 2) + 10)) def test_head_tail(self, float_frame): - assert_frame_equal(float_frame.head(), float_frame[:5]) - assert_frame_equal(float_frame.tail(), float_frame[-5:]) + tm.assert_frame_equal(float_frame.head(), float_frame[:5]) + tm.assert_frame_equal(float_frame.tail(), float_frame[-5:]) - assert_frame_equal(float_frame.head(0), float_frame[0:0]) - assert_frame_equal(float_frame.tail(0), float_frame[0:0]) + tm.assert_frame_equal(float_frame.head(0), float_frame[0:0]) + tm.assert_frame_equal(float_frame.tail(0), float_frame[0:0]) - assert_frame_equal(float_frame.head(-1), float_frame[:-1]) - assert_frame_equal(float_frame.tail(-1), float_frame[1:]) - assert_frame_equal(float_frame.head(1), float_frame[:1]) - assert_frame_equal(float_frame.tail(1), float_frame[-1:]) + tm.assert_frame_equal(float_frame.head(-1), float_frame[:-1]) + tm.assert_frame_equal(float_frame.tail(-1), float_frame[1:]) + tm.assert_frame_equal(float_frame.head(1), float_frame[:1]) + tm.assert_frame_equal(float_frame.tail(1), float_frame[-1:]) # with a float index df = float_frame.copy() df.index = np.arange(len(float_frame)) + 0.1 - assert_frame_equal(df.head(), df.iloc[:5]) - assert_frame_equal(df.tail(), df.iloc[-5:]) - assert_frame_equal(df.head(0), df[0:0]) - assert_frame_equal(df.tail(0), df[0:0]) - assert_frame_equal(df.head(-1), df.iloc[:-1]) - assert_frame_equal(df.tail(-1), df.iloc[1:]) + tm.assert_frame_equal(df.head(), df.iloc[:5]) + tm.assert_frame_equal(df.tail(), df.iloc[-5:]) + tm.assert_frame_equal(df.head(0), df[0:0]) + tm.assert_frame_equal(df.tail(0), df[0:0]) + tm.assert_frame_equal(df.head(-1), df.iloc[:-1]) + tm.assert_frame_equal(df.tail(-1), df.iloc[1:]) # test empty dataframe empty_df = DataFrame() - assert_frame_equal(empty_df.tail(), empty_df) - assert_frame_equal(empty_df.head(), empty_df) + tm.assert_frame_equal(empty_df.tail(), empty_df) + tm.assert_frame_equal(empty_df.head(), empty_df) def test_type_error_multiindex(self): # See gh-12218 @@ -3370,14 +3371,14 @@ def test_type_error_multiindex(self): expected = DataFrame([[1, 2], [3, 4]], columns=columns, index=index) result = dg.loc[:, (slice(None), 0)] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) name = ("x", 0) index = Index(range(2), name="i") expected = Series([1, 3], index=index, name=name) result = dg["x", 0] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interval_index(self): # GH 19977 @@ -3388,7 +3389,7 @@ def test_interval_index(self): expected = 1 result = df.loc[0.5, "A"] - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) index = pd.interval_range(start=0, periods=3, closed="both") df = pd.DataFrame( @@ -3398,7 +3399,7 @@ def test_interval_index(self): index_exp = pd.interval_range(start=0, periods=2, freq=1, closed="both") expected = pd.Series([1, 4], index=index_exp, name="A") result = df.loc[1, "A"] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) class TestDataFrameIndexingDatetimeWithTZ: @@ -3409,11 +3410,11 @@ def test_setitem(self, timezone_frame): # setitem df["C"] = idx - assert_series_equal(df["C"], Series(idx, name="C")) + tm.assert_series_equal(df["C"], Series(idx, name="C")) df["D"] = "foo" df["D"] = idx - assert_series_equal(df["D"], Series(idx, name="D")) + tm.assert_series_equal(df["D"], Series(idx, name="D")) del df["D"] # assert that A & C are not sharing the same base (e.g. they @@ -3428,8 +3429,8 @@ def test_setitem(self, timezone_frame): df2.iloc[1, 1] = pd.NaT df2.iloc[1, 2] = pd.NaT result = df2["B"] - assert_series_equal(notna(result), Series([True, False, True], name="B")) - assert_series_equal(df2.dtypes, df.dtypes) + tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) + tm.assert_series_equal(df2.dtypes, df.dtypes) def test_set_reset(self): @@ -3448,7 +3449,7 @@ def test_transpose(self, timezone_frame): result = timezone_frame.T expected = DataFrame(timezone_frame.values.T) expected.index = ["A", "B", "C"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_scalar_assignment(self): # issue #19843 @@ -3468,11 +3469,11 @@ def test_setitem(self, uint64_frame): # setitem df["C"] = idx - assert_series_equal(df["C"], Series(idx, name="C")) + tm.assert_series_equal(df["C"], Series(idx, name="C")) df["D"] = "foo" df["D"] = idx - assert_series_equal(df["D"], Series(idx, name="D")) + tm.assert_series_equal(df["D"], Series(idx, name="D")) del df["D"] # With NaN: because uint64 has no NaN element, @@ -3481,8 +3482,8 @@ def test_setitem(self, uint64_frame): df2.iloc[1, 1] = pd.NaT df2.iloc[1, 2] = pd.NaT result = df2["B"] - assert_series_equal(notna(result), Series([True, False, True], name="B")) - assert_series_equal( + tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) + tm.assert_series_equal( df2.dtypes, Series( [np.dtype("uint64"), np.dtype("O"), np.dtype("O")], @@ -3507,7 +3508,7 @@ def test_transpose(self, uint64_frame): result = uint64_frame.T expected = DataFrame(uint64_frame.values.T) expected.index = ["A", "B"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) class TestDataFrameIndexingCategorical: diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 1f4bbcb358378..24510ff9338ca 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -10,7 +10,6 @@ from pandas import Categorical, DataFrame, Series, Timestamp, date_range from pandas.tests.frame.common import _check_mixed_float import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal def _skip_if_no_pchip(): @@ -35,15 +34,15 @@ def test_dropEmptyRows(self, float_frame): smaller_frame = frame.dropna(how="all") # check that original was preserved - assert_series_equal(frame["foo"], original) + tm.assert_series_equal(frame["foo"], original) inplace_frame1.dropna(how="all", inplace=True) - assert_series_equal(smaller_frame["foo"], expected) - assert_series_equal(inplace_frame1["foo"], expected) + tm.assert_series_equal(smaller_frame["foo"], expected) + tm.assert_series_equal(inplace_frame1["foo"], expected) smaller_frame = frame.dropna(how="all", subset=["foo"]) inplace_frame2.dropna(how="all", subset=["foo"], inplace=True) - assert_series_equal(smaller_frame["foo"], expected) - assert_series_equal(inplace_frame2["foo"], expected) + tm.assert_series_equal(smaller_frame["foo"], expected) + tm.assert_series_equal(inplace_frame2["foo"], expected) def test_dropIncompleteRows(self, float_frame): N = len(float_frame.index) @@ -56,7 +55,7 @@ def test_dropIncompleteRows(self, float_frame): inp_frame1, inp_frame2 = frame.copy(), frame.copy() smaller_frame = frame.dropna() - assert_series_equal(frame["foo"], original) + tm.assert_series_equal(frame["foo"], original) inp_frame1.dropna(inplace=True) exp = Series(mat[5:], index=float_frame.index[5:], name="foo") @@ -64,7 +63,7 @@ def test_dropIncompleteRows(self, float_frame): tm.assert_series_equal(inp_frame1["foo"], exp) samesize_frame = frame.dropna(subset=["bar"]) - assert_series_equal(frame["foo"], original) + tm.assert_series_equal(frame["foo"], original) assert (frame["bar"] == 5).all() inp_frame2.dropna(subset=["bar"], inplace=True) tm.assert_index_equal(samesize_frame.index, float_frame.index) @@ -78,52 +77,52 @@ def test_dropna(self): expected = df.loc[:, [0, 1, 3]] inp = df.copy() inp.dropna(axis=1, inplace=True) - assert_frame_equal(dropped, expected) - assert_frame_equal(inp, expected) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) dropped = df.dropna(axis=0) expected = df.loc[list(range(2, 6))] inp = df.copy() inp.dropna(axis=0, inplace=True) - assert_frame_equal(dropped, expected) - assert_frame_equal(inp, expected) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) # threshold dropped = df.dropna(axis=1, thresh=5) expected = df.loc[:, [0, 1, 3]] inp = df.copy() inp.dropna(axis=1, thresh=5, inplace=True) - assert_frame_equal(dropped, expected) - assert_frame_equal(inp, expected) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) dropped = df.dropna(axis=0, thresh=4) expected = df.loc[range(2, 6)] inp = df.copy() inp.dropna(axis=0, thresh=4, inplace=True) - assert_frame_equal(dropped, expected) - assert_frame_equal(inp, expected) + tm.assert_frame_equal(dropped, expected) + tm.assert_frame_equal(inp, expected) dropped = df.dropna(axis=1, thresh=4) - assert_frame_equal(dropped, df) + tm.assert_frame_equal(dropped, df) dropped = df.dropna(axis=1, thresh=3) - assert_frame_equal(dropped, df) + tm.assert_frame_equal(dropped, df) # subset dropped = df.dropna(axis=0, subset=[0, 1, 3]) inp = df.copy() inp.dropna(axis=0, subset=[0, 1, 3], inplace=True) - assert_frame_equal(dropped, df) - assert_frame_equal(inp, df) + tm.assert_frame_equal(dropped, df) + tm.assert_frame_equal(inp, df) # all dropped = df.dropna(axis=1, how="all") - assert_frame_equal(dropped, df) + tm.assert_frame_equal(dropped, df) df[2] = np.nan dropped = df.dropna(axis=1, how="all") expected = df.loc[:, [0, 1, 3]] - assert_frame_equal(dropped, expected) + tm.assert_frame_equal(dropped, expected) # bad input msg = "No axis named 3 for object type <class 'pandas.core.frame.DataFrame'>" @@ -137,13 +136,13 @@ def test_drop_and_dropna_caching(self): df = pd.DataFrame({"A": original.values.copy()}) df2 = df.copy() df["A"].dropna() - assert_series_equal(df["A"], original) + tm.assert_series_equal(df["A"], original) df["A"].dropna(inplace=True) - assert_series_equal(df["A"], expected) + tm.assert_series_equal(df["A"], expected) df2["A"].drop([1]) - assert_series_equal(df2["A"], original) + tm.assert_series_equal(df2["A"], original) df2["A"].drop([1], inplace=True) - assert_series_equal(df2["A"], original.drop([1])) + tm.assert_series_equal(df2["A"], original.drop([1])) def test_dropna_corner(self, float_frame): # bad input @@ -175,14 +174,14 @@ def test_dropna_multiple_axes(self): result2 = df.dropna(how="all", axis=(0, 1)) expected = df.dropna(how="all").dropna(how="all", axis=1) - assert_frame_equal(result, expected) - assert_frame_equal(result2, expected) - assert_frame_equal(df, cp) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + tm.assert_frame_equal(df, cp) inp = df.copy() with tm.assert_produces_warning(FutureWarning): inp.dropna(how="all", axis=(0, 1), inplace=True) - assert_frame_equal(inp, expected) + tm.assert_frame_equal(inp, expected) def test_dropna_tz_aware_datetime(self): # GH13407 @@ -192,13 +191,13 @@ def test_dropna_tz_aware_datetime(self): df["Time"] = [dt1] result = df.dropna(axis=0) expected = DataFrame({"Time": [dt1]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Ex2 df = DataFrame({"Time": [dt1, None, np.nan, dt2]}) result = df.dropna(axis=0) expected = DataFrame([dt1, dt2], columns=["Time"], index=[0, 3]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dropna_categorical_interval_index(self): # GH 25087 @@ -268,10 +267,10 @@ def test_fillna_different_dtype(self): expected = DataFrame( [["a", "a", "foo", "a"], ["b", "b", "foo", "b"], ["c", "c", "foo", "c"]] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df.fillna({2: "foo"}, inplace=True) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_fillna_limit_and_value(self): # limit and value @@ -283,7 +282,7 @@ def test_fillna_limit_and_value(self): expected.iloc[2, 0] = 999 expected.iloc[3, 2] = 999 result = df.fillna(999, limit=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_fillna_datelike(self): # with datelike @@ -298,7 +297,7 @@ def test_fillna_datelike(self): expected = df.copy() expected["Date"] = expected["Date"].fillna(df.loc[df.index[0], "Date2"]) result = df.fillna(value={"Date": df["Date2"]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_fillna_tzaware(self): # with timezone @@ -312,7 +311,7 @@ def test_fillna_tzaware(self): ] } ) - assert_frame_equal(df.fillna(method="pad"), exp) + tm.assert_frame_equal(df.fillna(method="pad"), exp) df = pd.DataFrame({"A": [pd.NaT, pd.Timestamp("2012-11-11 00:00:00+01:00")]}) exp = pd.DataFrame( @@ -323,7 +322,7 @@ def test_fillna_tzaware(self): ] } ) - assert_frame_equal(df.fillna(method="bfill"), exp) + tm.assert_frame_equal(df.fillna(method="bfill"), exp) def test_fillna_tzaware_different_column(self): # with timezone in another column @@ -341,7 +340,7 @@ def test_fillna_tzaware_different_column(self): "B": [1.0, 2.0, 2.0, 2.0], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_na_actions_categorical(self): @@ -425,37 +424,37 @@ def test_fillna_downcast(self): df = pd.DataFrame({"a": [1.0, np.nan]}) result = df.fillna(0, downcast="infer") expected = pd.DataFrame({"a": [1, 0]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # infer int64 from float64 when fillna value is a dict df = pd.DataFrame({"a": [1.0, np.nan]}) result = df.fillna({"a": 0}, downcast="infer") expected = pd.DataFrame({"a": [1, 0]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_fillna_dtype_conversion(self): # make sure that fillna on an empty frame works df = DataFrame(index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) result = df.dtypes expected = Series([np.dtype("object")] * 5, index=[1, 2, 3, 4, 5]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.fillna(1) expected = DataFrame(1, index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # empty block df = DataFrame(index=range(3), columns=["A", "B"], dtype="float64") result = df.fillna("nan") expected = DataFrame("nan", index=range(3), columns=["A", "B"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # equiv of replace df = DataFrame(dict(A=[1, np.nan], B=[1.0, 2.0])) for v in ["", 1, np.nan, 1.0]: expected = df.replace(np.nan, v) result = df.fillna(v) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_fillna_datetime_columns(self): # GH 7095 @@ -505,7 +504,7 @@ def test_ffill(self, datetime_frame): datetime_frame["A"][:5] = np.nan datetime_frame["A"][-5:] = np.nan - assert_frame_equal( + tm.assert_frame_equal( datetime_frame.ffill(), datetime_frame.fillna(method="ffill") ) @@ -513,7 +512,7 @@ def test_bfill(self, datetime_frame): datetime_frame["A"][:5] = np.nan datetime_frame["A"][-5:] = np.nan - assert_frame_equal( + tm.assert_frame_equal( datetime_frame.bfill(), datetime_frame.fillna(method="bfill") ) @@ -611,7 +610,7 @@ def test_fillna_dict_series(self): expected = df.copy() expected["a"] = expected["a"].fillna(0) expected["b"] = expected["b"].fillna(5) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # it works result = df.fillna({"a": 0, "b": 5, "d": 7}) @@ -619,7 +618,7 @@ def test_fillna_dict_series(self): # Series treated same as dict result = df.fillna(df.max()) expected = df.fillna(df.max().to_dict()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # disable this for now with pytest.raises(NotImplementedError, match="column by column"): @@ -658,7 +657,7 @@ def test_fillna_dataframe(self): index=list("VWXYZ"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_fillna_columns(self): df = DataFrame(np.random.randn(10, 10)) @@ -666,12 +665,12 @@ def test_fillna_columns(self): result = df.fillna(method="ffill", axis=1) expected = df.T.fillna(method="pad").T - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df.insert(6, "foo", 5) result = df.fillna(method="ffill", axis=1) expected = df.astype(float).fillna(method="ffill", axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_fillna_invalid_method(self, float_frame): with pytest.raises(ValueError, match="ffil"): @@ -721,7 +720,7 @@ def test_fill_value_when_combine_const(self): exp = df.fillna(0).add(2) res = df.add(2, fill_value=0) - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) class TestDataFrameInterpolate: @@ -743,13 +742,13 @@ def test_interp_basic(self): } ) result = df.interpolate() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.set_index("C").interpolate() expected = df.set_index("C") expected.loc[3, "A"] = 3 expected.loc[5, "B"] = 9 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_interp_bad_method(self): df = DataFrame( @@ -775,11 +774,11 @@ def test_interp_combo(self): result = df["A"].interpolate() expected = Series([1.0, 2.0, 3.0, 4.0], name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df["A"].interpolate(downcast="infer") expected = Series([1, 2, 3, 4], name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interp_nan_idx(self): df = DataFrame({"A": [1, 2, np.nan, 4], "B": [np.nan, 2, 3, 4]}) @@ -798,33 +797,33 @@ def test_interp_various(self): expected.A.loc[3] = 2.66666667 expected.A.loc[13] = 5.76923076 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.interpolate(method="cubic") # GH #15662. expected.A.loc[3] = 2.81547781 expected.A.loc[13] = 5.52964175 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.interpolate(method="nearest") expected.A.loc[3] = 2 expected.A.loc[13] = 5 - assert_frame_equal(result, expected, check_dtype=False) + tm.assert_frame_equal(result, expected, check_dtype=False) result = df.interpolate(method="quadratic") expected.A.loc[3] = 2.82150771 expected.A.loc[13] = 6.12648668 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.interpolate(method="slinear") expected.A.loc[3] = 2.66666667 expected.A.loc[13] = 5.76923077 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.interpolate(method="zero") expected.A.loc[3] = 2.0 expected.A.loc[13] = 5 - assert_frame_equal(result, expected, check_dtype=False) + tm.assert_frame_equal(result, expected, check_dtype=False) @td.skip_if_no_scipy def test_interp_alt_scipy(self): @@ -835,15 +834,15 @@ def test_interp_alt_scipy(self): expected = df.copy() expected.loc[2, "A"] = 3 expected.loc[5, "A"] = 6 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.interpolate(method="barycentric", downcast="infer") - assert_frame_equal(result, expected.astype(np.int64)) + tm.assert_frame_equal(result, expected.astype(np.int64)) result = df.interpolate(method="krogh") expectedk = df.copy() expectedk["A"] = expected["A"] - assert_frame_equal(result, expectedk) + tm.assert_frame_equal(result, expectedk) _skip_if_no_pchip() @@ -851,7 +850,7 @@ def test_interp_alt_scipy(self): expected.loc[2, "A"] = 3 expected.loc[5, "A"] = 6.0 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_interp_rowwise(self): df = DataFrame( @@ -869,14 +868,14 @@ def test_interp_rowwise(self): expected.loc[0, 2] = 3 expected.loc[1, 3] = 3 expected[4] = expected[4].astype(np.float64) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.interpolate(axis=1, method="values") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.interpolate(axis=0) expected = df.interpolate() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "axis_name, axis_number", @@ -893,7 +892,7 @@ def test_interp_axis_names(self, axis_name, axis_number): df = DataFrame(data, dtype=np.float64) result = df.interpolate(axis=axis_name, method="linear") expected = df.interpolate(axis=axis_number, method="linear") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_rowwise_alt(self): df = DataFrame( @@ -914,11 +913,11 @@ def test_interp_leading_nans(self, check_scipy): result = df.interpolate() expected = df.copy() expected["B"].loc[3] = -3.75 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) if check_scipy: result = df.interpolate(method="polynomial", order=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_interp_raise_on_only_mixed(self): df = DataFrame( @@ -949,11 +948,11 @@ def test_interp_inplace(self): expected = DataFrame({"a": [1.0, 2.0, 3.0, 4.0]}) result = df.copy() result["a"].interpolate(inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.copy() result["a"].interpolate(inplace=True, downcast="infer") - assert_frame_equal(result, expected.astype("int64")) + tm.assert_frame_equal(result, expected.astype("int64")) def test_interp_inplace_row(self): # GH 10395 @@ -962,7 +961,7 @@ def test_interp_inplace_row(self): ) expected = result.interpolate(method="linear", axis=1, inplace=False) result.interpolate(method="linear", axis=1, inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_interp_ignore_all_good(self): # GH @@ -984,8 +983,8 @@ def test_interp_ignore_all_good(self): ) result = df.interpolate(downcast=None) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # all good result = df[["B", "D"]].interpolate(downcast=None) - assert_frame_equal(result, df[["B", "D"]]) + tm.assert_frame_equal(result, df[["B", "D"]]) diff --git a/pandas/tests/frame/test_mutate_columns.py b/pandas/tests/frame/test_mutate_columns.py index 7ad5abca82b29..7feb55f2fac09 100644 --- a/pandas/tests/frame/test_mutate_columns.py +++ b/pandas/tests/frame/test_mutate_columns.py @@ -7,7 +7,6 @@ from pandas import DataFrame, Index, MultiIndex, Series import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal # Column add, remove, delete. @@ -19,34 +18,34 @@ def test_assign(self): result = df.assign(C=df.B / df.A) expected = df.copy() expected["C"] = [4, 2.5, 2] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # lambda syntax result = df.assign(C=lambda x: x.B / x.A) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # original is unmodified - assert_frame_equal(df, original) + tm.assert_frame_equal(df, original) # Non-Series array-like result = df.assign(C=[4, 2.5, 2]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # original is unmodified - assert_frame_equal(df, original) + tm.assert_frame_equal(df, original) result = df.assign(B=df.B / df.A) expected = expected.drop("B", axis=1).rename(columns={"C": "B"}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # overwrite result = df.assign(A=df.A + df.B) expected = df.copy() expected["A"] = [5, 7, 9] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # lambda result = df.assign(A=lambda x: x.A + x.B) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_assign_multiple(self): df = DataFrame([[1, 4], [2, 5], [3, 6]], columns=["A", "B"]) @@ -54,7 +53,7 @@ def test_assign_multiple(self): expected = DataFrame( [[1, 4, 7, 1, 4], [2, 5, 8, 2, 5], [3, 6, 9, 3, 6]], columns=list("ABCDE") ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_assign_order(self): # GH 9818 @@ -65,12 +64,12 @@ def test_assign_order(self): expected = DataFrame([[1, 2, 3, -1], [3, 4, 7, -1]], columns=list("ABDC")) else: expected = DataFrame([[1, 2, -1, 3], [3, 4, -1, 7]], columns=list("ABCD")) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.assign(C=df.A - df.B, D=df.A + df.B) expected = DataFrame([[1, 2, -1, 3], [3, 4, -1, 7]], columns=list("ABCD")) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_assign_bad(self): df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) @@ -105,11 +104,11 @@ def test_assign_dependent(self): result = df.assign(C=df.A, D=lambda x: x["A"] + x["C"]) expected = DataFrame([[1, 3, 1, 2], [2, 4, 2, 4]], columns=list("ABCD")) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.assign(C=lambda df: df.A, D=lambda df: df["A"] + df["C"]) expected = DataFrame([[1, 3, 1, 2], [2, 4, 2, 4]], columns=list("ABCD")) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_insert_error_msmgs(self): @@ -140,7 +139,7 @@ def test_insert_benchmark(self): for i in range(K): df[i] = new_col expected = DataFrame(np.repeat(new_col, K).reshape(N, K), index=range(N)) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_insert(self): df = DataFrame( @@ -199,7 +198,7 @@ def test_insert(self): df["X"] = df.index df["X"] = ["x", "y", "z"] exp = DataFrame(data={"X": ["x", "y", "z"]}, index=["A", "B", "C"]) - assert_frame_equal(df, exp) + tm.assert_frame_equal(df, exp) def test_delitem(self, float_frame): del float_frame["A"] @@ -277,11 +276,11 @@ def test_insert_column_bug_4032(self): result = df.rename(columns={}) str(result) expected = DataFrame([[1, 1.1], [2, 2.2]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df.insert(0, "c", [1.3, 2.3]) result = df.rename(columns={}) str(result) expected = DataFrame([[1.3, 1, 1.1], [2.3, 2, 2.2]], columns=["c", "a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 430d9ad135c80..8fed695a483f5 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -4,14 +4,13 @@ import pandas as pd from pandas import DataFrame, MultiIndex, Series, date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal class TestDataFrameNonuniqueIndexes: def test_column_dups_operations(self): def check(result, expected=None): if expected is not None: - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result.dtypes str(result) @@ -116,7 +115,7 @@ def check(result, expected=None): [[4.0, 5.0, "bah", 3], [4.0, 5.0, "bah", 3], [4.0, 5.0, "bah", 3]], columns=["new_col", "new_col", "string", "foo2"], ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # dup across dtypes df = DataFrame( @@ -198,7 +197,7 @@ def check(result, expected=None): "QT_Close", ], ).set_index(["STK_ID", "RPT_Date"], drop=False) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # reindex is invalid! df = DataFrame( @@ -286,7 +285,7 @@ def test_column_dups2(self): expected = df.take([0, 1, 1], axis=1) df2 = df.take([2, 0, 1, 2, 1], axis=1) result = df2.drop("C", axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # dropna df = DataFrame( @@ -307,12 +306,12 @@ def test_column_dups2(self): df.columns = ["A", "A", "B", "C"] result = df.dropna(subset=["A", "C"], how="all") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_column_dups_indexing(self): def check(result, expected=None): if expected is not None: - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result.dtypes str(result) @@ -350,7 +349,7 @@ def check(result, expected=None): df2 = DataFrame([1, 2, 3], index=[1, 2, 3]) expected = DataFrame([0, 2, 0, 2, 2], index=[1, 1, 2, 2, 3]) result = df1.sub(df2) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # equality df1 = DataFrame([[1, 2], [2, np.nan], [3, 4], [4, 4]], columns=["A", "B"]) @@ -367,7 +366,7 @@ def check(result, expected=None): [[False, True], [True, False], [False, False], [True, False]], columns=["A", "A"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # mixed column selection # GH 5639 @@ -411,7 +410,7 @@ def test_column_dups_indexing2(self): ) result = df.B - df.A expected = Series(1, index=[2, 2, 3, 3, 4]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame( { @@ -422,7 +421,7 @@ def test_column_dups_indexing2(self): ) result = df.B - df.A expected = Series(pd.Timedelta("9 hours"), index=[2, 2, 3, 3, 4]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_columns_with_dups(self): # GH 3468 related @@ -432,20 +431,20 @@ def test_columns_with_dups(self): df.columns = ["a", "a.1"] str(df) expected = DataFrame([[1, 2]], columns=["a", "a.1"]) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) df = DataFrame([[1, 2, 3]], columns=["b", "a", "a"]) df.columns = ["b", "a", "a.1"] str(df) expected = DataFrame([[1, 2, 3]], columns=["b", "a", "a.1"]) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # with a dup index df = DataFrame([[1, 2]], columns=["a", "a"]) df.columns = ["b", "b"] str(df) expected = DataFrame([[1, 2]], columns=["b", "b"]) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # multi-dtype df = DataFrame( @@ -457,13 +456,13 @@ def test_columns_with_dups(self): expected = DataFrame( [[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("ABCDEFG") ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) df = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a", "a", "a"]) df.columns = ["a", "a.1", "a.2", "a.3"] str(df) expected = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a.1", "a.2", "a.3"]) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # dups across blocks df_float = DataFrame(np.random.randn(10, 3), dtype="float64") @@ -487,7 +486,7 @@ def test_columns_with_dups(self): rs = DataFrame(vals, columns=["A", "A", "B"]) xp = DataFrame(vals) xp.columns = ["A", "A", "B"] - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_values_duplicates(self): df = DataFrame( @@ -506,14 +505,14 @@ def test_set_value_by_index(self): expected = df.iloc[:, 2] df.iloc[:, 0] = 3 - assert_series_equal(df.iloc[:, 2], expected) + tm.assert_series_equal(df.iloc[:, 2], expected) df = DataFrame(np.arange(9).reshape(3, 3).T) df.columns = [2, float(2), str(2)] expected = df.iloc[:, 1] df.iloc[:, 0] = 3 - assert_series_equal(df.iloc[:, 1], expected) + tm.assert_series_equal(df.iloc[:, 1], expected) def test_insert_with_columns_dups(self): # GH 14291 @@ -524,4 +523,4 @@ def test_insert_with_columns_dups(self): exp = pd.DataFrame( [["a", "d", "g"], ["b", "e", "h"], ["c", "f", "i"]], columns=["A", "A", "A"] ) - assert_frame_equal(df, exp) + tm.assert_frame_equal(df, exp) diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index 73eddf91325ae..19d91241d6a6b 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -9,11 +9,6 @@ import pandas.core.common as com from pandas.tests.frame.common import _check_mixed_float import pandas.util.testing as tm -from pandas.util.testing import ( - assert_frame_equal, - assert_numpy_array_equal, - assert_series_equal, -) class TestDataFrameUnaryOperators: @@ -31,8 +26,8 @@ class TestDataFrameUnaryOperators: ], ) def test_neg_numeric(self, df, expected): - assert_frame_equal(-df, expected) - assert_series_equal(-df["a"], expected["a"]) + tm.assert_frame_equal(-df, expected) + tm.assert_series_equal(-df["a"], expected["a"]) @pytest.mark.parametrize( "df, expected", @@ -45,8 +40,8 @@ def test_neg_object(self, df, expected): # GH#21380 df = pd.DataFrame({"a": df}) expected = pd.DataFrame({"a": expected}) - assert_frame_equal(-df, expected) - assert_series_equal(-df["a"], expected["a"]) + tm.assert_frame_equal(-df, expected) + tm.assert_series_equal(-df["a"], expected["a"]) @pytest.mark.parametrize( "df", @@ -64,7 +59,7 @@ def test_neg_raises(self, df): def test_invert(self, float_frame): df = float_frame - assert_frame_equal(-(df < 0), ~(df < 0)) + tm.assert_frame_equal(-(df < 0), ~(df < 0)) @pytest.mark.parametrize( "df", @@ -76,8 +71,8 @@ def test_invert(self, float_frame): ) def test_pos_numeric(self, df): # GH#16073 - assert_frame_equal(+df, df) - assert_series_equal(+df["a"], df["a"]) + tm.assert_frame_equal(+df, df) + tm.assert_series_equal(+df["a"], df["a"]) @pytest.mark.parametrize( "df", @@ -93,8 +88,8 @@ def test_pos_numeric(self, df): ) def test_pos_object(self, df): # GH#21380 - assert_frame_equal(+df, df) - assert_series_equal(+df["a"], df["a"]) + tm.assert_frame_equal(+df, df) + tm.assert_series_equal(+df["a"], df["a"]) @pytest.mark.parametrize( "df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})] @@ -115,30 +110,30 @@ def test_logical_ops_empty_frame(self): df = DataFrame(index=[1]) result = df & df - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df | df - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df2 = DataFrame(index=[1, 2]) result = df & df2 - assert_frame_equal(result, df2) + tm.assert_frame_equal(result, df2) dfa = DataFrame(index=[1], columns=["A"]) result = dfa & dfa expected = DataFrame(False, index=[1], columns=["A"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_logical_ops_bool_frame(self): # GH#5808 df1a_bool = DataFrame(True, index=[1], columns=["A"]) result = df1a_bool & df1a_bool - assert_frame_equal(result, df1a_bool) + tm.assert_frame_equal(result, df1a_bool) result = df1a_bool | df1a_bool - assert_frame_equal(result, df1a_bool) + tm.assert_frame_equal(result, df1a_bool) def test_logical_ops_int_frame(self): # GH#5808 @@ -146,11 +141,11 @@ def test_logical_ops_int_frame(self): df1a_bool = DataFrame(True, index=[1], columns=["A"]) result = df1a_int | df1a_bool - assert_frame_equal(result, df1a_bool) + tm.assert_frame_equal(result, df1a_bool) # Check that this matches Series behavior res_ser = df1a_int["A"] | df1a_bool["A"] - assert_series_equal(res_ser, df1a_bool["A"]) + tm.assert_series_equal(res_ser, df1a_bool["A"]) def test_logical_ops_invalid(self): # GH#5808 @@ -172,13 +167,13 @@ def _check_bin_op(op): op(df1.values, df2.values), index=df1.index, columns=df1.columns ) assert result.values.dtype == np.bool_ - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def _check_unary_op(op): result = op(df1) expected = DataFrame(op(df1.values), index=df1.index, columns=df1.columns) assert result.values.dtype == np.bool_ - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df1 = { "a": {"a": True, "b": False, "c": False, "d": True, "e": True}, @@ -212,16 +207,16 @@ def test_logical_with_nas(self): # bool comparisons should return bool result = d["a"] | d["b"] expected = Series([False, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH4604, automatic casting here result = d["a"].fillna(False) | d["b"] expected = Series([True, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = d["a"].fillna(False, downcast=False) | d["b"] expected = Series([True, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) class TestDataFrameOperators: @@ -239,18 +234,18 @@ def test_operators_none_as_na(self, op): result = op(df, 3) expected = op(filled, 3).astype(object) expected[com.isna(expected)] = None - assert_frame_equal(result, expected) + tm.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) + tm.assert_frame_equal(result, expected) result = op(df, df.fillna(7)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = op(df.fillna(7), df) - assert_frame_equal(result, expected, check_dtype=False) + tm.assert_frame_equal(result, expected, check_dtype=False) @pytest.mark.parametrize("op,res", [("__eq__", False), ("__ne__", True)]) # TODO: not sure what's correct here. @@ -288,7 +283,7 @@ def test_binary_ops_align(self): expected = pd.concat( [opa(df.loc[idx[:, :, i], :], v) for i, v in x.items()] ).sort_index() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) x = Series([1.0, 10.0], ["two", "three"]) result = getattr(df, op)(x, level="second", axis=0) @@ -298,7 +293,7 @@ def test_binary_ops_align(self): .reindex_like(df) .sort_index() ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH9463 (alignment level of dataframe with series) @@ -324,11 +319,11 @@ def test_binary_ops_align(self): ) for res in [res1, res2]: - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) exp.columns.names = ["lvl0", "lvl1"] for res in [res3, res4, res5, res6]: - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) def test_dti_tz_convert_to_utc(self): base = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], tz="UTC") @@ -338,7 +333,7 @@ def test_dti_tz_convert_to_utc(self): df1 = DataFrame({"A": [1, 2]}, index=idx1) df2 = DataFrame({"A": [1, 1]}, index=idx2) exp = DataFrame({"A": [np.nan, 3, np.nan]}, index=base) - assert_frame_equal(df1 + df2, exp) + tm.assert_frame_equal(df1 + df2, exp) def test_combineFrame(self, float_frame, mixed_float_frame, mixed_int_frame): frame_copy = float_frame.reindex(float_frame.index[::2]) @@ -384,7 +379,7 @@ def test_combineFrame(self, float_frame, mixed_float_frame, mixed_int_frame): # out of order reverse = float_frame.reindex(columns=float_frame.columns[::-1]) - assert_frame_equal(reverse + float_frame, float_frame * 2) + tm.assert_frame_equal(reverse + float_frame, float_frame * 2) # mix vs float64, upcast added = float_frame + mixed_float_frame @@ -410,7 +405,7 @@ def test_combine_series( added = float_frame + series for key, s in added.items(): - assert_series_equal(s, float_frame[key] + series[key]) + tm.assert_series_equal(s, float_frame[key] + series[key]) larger_series = series.to_dict() larger_series["E"] = 1 @@ -418,7 +413,7 @@ def test_combine_series( larger_added = float_frame + larger_series for key, s in float_frame.items(): - assert_series_equal(larger_added[key], s + series[key]) + tm.assert_series_equal(larger_added[key], s + series[key]) assert "E" in larger_added assert np.isnan(larger_added["E"]).all() @@ -453,7 +448,7 @@ def test_combine_series( for key, col in datetime_frame.items(): result = col + ts - assert_series_equal(added[key], result, check_names=False) + tm.assert_series_equal(added[key], result, check_names=False) assert added[key].name == key if col.name == ts.name: assert result.name == "A" @@ -467,21 +462,21 @@ def test_combine_series( smaller_ts = ts[:-5] smaller_added2 = datetime_frame.add(smaller_ts, axis="index") - assert_frame_equal(smaller_added, smaller_added2) + tm.assert_frame_equal(smaller_added, smaller_added2) # length 0, result is all-nan result = datetime_frame.add(ts[:0], axis="index") expected = DataFrame( np.nan, index=datetime_frame.index, columns=datetime_frame.columns ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Frame is all-nan result = datetime_frame[:0].add(ts, axis="index") expected = DataFrame( np.nan, index=datetime_frame.index, columns=datetime_frame.columns ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # empty but with non-empty index frame = datetime_frame[:1].reindex(columns=[]) @@ -558,10 +553,10 @@ def test_boolean_comparison(self): # gt expected = DataFrame([[False, False], [False, True], [True, True]]) result = df > b - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.values > b - assert_numpy_array_equal(result, expected.values) + tm.assert_numpy_array_equal(result, expected.values) msg1d = "Unable to coerce to Series, length must be 2: given 3" msg2d = "Unable to coerce to DataFrame, shape must be" @@ -576,10 +571,10 @@ def test_boolean_comparison(self): # broadcasts like ndarray (GH#23000) result = df > b_r - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.values > b_r - assert_numpy_array_equal(result, expected.values) + tm.assert_numpy_array_equal(result, expected.values) with pytest.raises(ValueError, match=msg2d): df > b_c @@ -590,7 +585,7 @@ def test_boolean_comparison(self): # == expected = DataFrame([[False, False], [True, False], [False, False]]) result = df == b - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) with pytest.raises(ValueError, match=msg1d): result = df == lst @@ -600,10 +595,10 @@ def test_boolean_comparison(self): # broadcasts like ndarray (GH#23000) result = df == b_r - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.values == b_r - assert_numpy_array_equal(result, expected.values) + tm.assert_numpy_array_equal(result, expected.values) with pytest.raises(ValueError, match=msg2d): df == b_c @@ -639,8 +634,8 @@ def test_combine_generic(self, float_frame): float_frame.loc[float_frame.index[:-5], ["A", "B", "C"]].reindex_like(chunk) * 2 ) - assert_frame_equal(chunk, exp) - assert_frame_equal(chunk2, exp) + tm.assert_frame_equal(chunk, exp) + tm.assert_frame_equal(chunk2, exp) def test_inplace_ops_alignment(self): @@ -670,9 +665,9 @@ def test_inplace_ops_alignment(self): X[block1] += Z[block1] result4 = X.reindex(columns=subs) - assert_frame_equal(result1, result2) - assert_frame_equal(result1, result3) - assert_frame_equal(result1, result4) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) + tm.assert_frame_equal(result1, result4) # sub X = X_orig.copy() @@ -687,9 +682,9 @@ def test_inplace_ops_alignment(self): X[block1] -= Z[block1] result4 = X.reindex(columns=subs) - assert_frame_equal(result1, result2) - assert_frame_equal(result1, result3) - assert_frame_equal(result1, result4) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) + tm.assert_frame_equal(result1, result4) def test_inplace_ops_identity(self): @@ -702,16 +697,16 @@ def test_inplace_ops_identity(self): s = s_orig.copy() s2 = s s += 1 - assert_series_equal(s, s2) - assert_series_equal(s_orig + 1, s) + tm.assert_series_equal(s, s2) + tm.assert_series_equal(s_orig + 1, s) 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) + tm.assert_frame_equal(df, df2) + tm.assert_frame_equal(df_orig + 1, df) assert df is df2 assert df._data is df2._data @@ -719,14 +714,14 @@ def test_inplace_ops_identity(self): s = s_orig.copy() s2 = s s += 1.5 - assert_series_equal(s, s2) - assert_series_equal(s_orig + 1.5, s) + tm.assert_series_equal(s, s2) + tm.assert_series_equal(s_orig + 1.5, s) df = df_orig.copy() df2 = df df += 1.5 - assert_frame_equal(df, df2) - assert_frame_equal(df_orig + 1.5, df) + tm.assert_frame_equal(df, df2) + tm.assert_frame_equal(df_orig + 1.5, df) assert df is df2 assert df._data is df2._data @@ -737,16 +732,16 @@ def test_inplace_ops_identity(self): df2 = df df["A"] += 1 expected = DataFrame({"A": arr.copy() + 1, "B": "foo"}) - assert_frame_equal(df, expected) - assert_frame_equal(df2, expected) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(df2, expected) assert df._data is df2._data df = df_orig.copy() df2 = df df["A"] += 1.5 expected = DataFrame({"A": arr.copy() + 1.5, "B": "foo"}) - assert_frame_equal(df, expected) - assert_frame_equal(df2, expected) + tm.assert_frame_equal(df, expected) + tm.assert_frame_equal(df2, expected) assert df._data is df2._data @pytest.mark.parametrize( @@ -784,7 +779,7 @@ def test_inplace_ops_identity2(self, op): # no id change and value is correct getattr(df, iop)(operand) expected = getattr(df_copy, op)(operand) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) expected = id(df) assert id(df) == expected diff --git a/pandas/tests/frame/test_quantile.py b/pandas/tests/frame/test_quantile.py index e5e881dece34a..78953d43677fc 100644 --- a/pandas/tests/frame/test_quantile.py +++ b/pandas/tests/frame/test_quantile.py @@ -4,7 +4,6 @@ import pandas as pd from pandas import DataFrame, Series, Timestamp import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal class TestDataFrameQuantile: @@ -28,19 +27,19 @@ def test_quantile(self, datetime_frame): df = DataFrame({"col1": ["A", "A", "B", "B"], "col2": [1, 2, 3, 4]}) rs = df.quantile(0.5) xp = df.median().rename(0.5) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) # axis df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3]) result = df.quantile(0.5, axis=1) expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.quantile([0.5, 0.75], axis=1) expected = DataFrame( {1: [1.5, 1.75], 2: [2.5, 2.75], 3: [3.5, 3.75]}, index=[0.5, 0.75] ) - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) # We may want to break API in the future to change this # so that we exclude non-numeric along the same axis @@ -48,7 +47,7 @@ def test_quantile(self, datetime_frame): df = DataFrame([[1, 2, 3], ["a", "b", 4]]) result = df.quantile(0.5, axis=1) expected = Series([3.0, 4.0], index=[0, 1], name=0.5) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_quantile_axis_mixed(self): @@ -63,7 +62,7 @@ def test_quantile_axis_mixed(self): ) result = df.quantile(0.5, axis=1) expected = Series([1.5, 2.5, 3.5], name=0.5) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # must raise with pytest.raises(TypeError): @@ -77,18 +76,18 @@ def test_quantile_axis_parameter(self): result = df.quantile(0.5, axis=0) expected = Series([2.0, 3.0], index=["A", "B"], name=0.5) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = df.quantile(0.5, axis="index") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.quantile(0.5, axis=1) expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.quantile(0.5, axis="columns") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) msg = "No axis named -1 for object type <class 'pandas.core.frame.DataFrame'>" with pytest.raises(ValueError, match=msg): @@ -128,14 +127,14 @@ def test_quantile_interpolation(self): interpolation="nearest", ) expected = Series(exp, index=[1, 2, 3], name=0.5, dtype="float64") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # axis result = df.quantile([0.5, 0.75], axis=1, interpolation="lower") expected = DataFrame( {1: [1.0, 1.0], 2: [2.0, 2.0], 3: [3.0, 3.0]}, index=[0.5, 0.75] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # test degenerate case df = DataFrame({"x": [], "y": []}) @@ -152,7 +151,7 @@ def test_quantile_interpolation(self): index=[0.25, 0.5], columns=["a", "b", "c"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_quantile_interpolation_datetime(self, datetime_frame): # see gh-10174 @@ -183,7 +182,7 @@ def test_quantile_multi(self): index=[0.25, 0.5], columns=["a", "b", "c"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis = 1 result = df.quantile([0.25, 0.5], axis=1) @@ -196,7 +195,7 @@ def test_quantile_multi(self): expected = DataFrame( {"x": [np.nan, np.nan], "y": [np.nan, np.nan]}, index=[0.1, 0.9] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_quantile_datetime(self): df = DataFrame({"a": pd.to_datetime(["2010", "2011"]), "b": [0, 5]}) @@ -210,14 +209,14 @@ def test_quantile_datetime(self): expected = Series( [Timestamp("2010-07-02 12:00:00"), 2.5], index=["a", "b"], name=0.5 ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # datetime w/ multi result = df.quantile([0.5], numeric_only=False) expected = DataFrame( [[Timestamp("2010-07-02 12:00:00"), 2.5]], index=[0.5], columns=["a", "b"] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis = 1 df["c"] = pd.to_datetime(["2011", "2012"]) @@ -227,7 +226,7 @@ def test_quantile_datetime(self): index=[0, 1], name=0.5, ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df[["a", "c"]].quantile([0.5], axis=1, numeric_only=False) expected = DataFrame( @@ -235,7 +234,7 @@ def test_quantile_datetime(self): index=[0.5], columns=[0, 1], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # empty when numeric_only=True # FIXME (gives empty frame in 0.18.1, broken in 0.19.0)
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29301
2019-10-30T23:25:02Z
2019-10-31T08:01:49Z
2019-10-31T08:01:49Z
2019-10-31T08:01:55Z
CLN: Consistent pandas.util.testing imports in pandas/tests/frame - part1
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index d53a3d81ab5f8..50b1dec21c549 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -16,11 +16,6 @@ timedelta_range, ) import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) class SharedWithSparse: @@ -344,7 +339,7 @@ def test_values(self, float_frame, float_string_frame): # single block corner case arr = float_frame[["A", "B"]].values expected = float_frame.reindex(columns=["A", "B"]).values - assert_almost_equal(arr, expected) + tm.assert_almost_equal(arr, expected) def test_to_numpy(self): df = pd.DataFrame({"A": [1, 2], "B": [3, 4.5]}) @@ -401,11 +396,11 @@ def test_axis_aliases(self, float_frame): # reg name expected = f.sum(axis=0) result = f.sum(axis="index") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = f.sum(axis=1) result = f.sum(axis="columns") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_class_axis(self): # GH 18147 @@ -474,8 +469,8 @@ class TestDataFrameMisc(SharedWithSparse): klass = DataFrame # SharedWithSparse tests use generic, klass-agnostic assertion - _assert_frame_equal = staticmethod(assert_frame_equal) - _assert_series_equal = staticmethod(assert_series_equal) + _assert_frame_equal = staticmethod(tm.assert_frame_equal) + _assert_series_equal = staticmethod(tm.assert_series_equal) def test_values(self, float_frame): float_frame.values[:, 0] = 5.0 diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index 4b7439cd40023..16d17b04423b7 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -14,7 +14,6 @@ from pandas.conftest import _get_cython_table_params from pandas.core.apply import frame_apply import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal @pytest.fixture @@ -70,7 +69,7 @@ def test_apply_mixed_datetimelike(self): } ) result = df.apply(lambda x: x, axis=1) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_apply_empty(self, float_frame): # empty @@ -85,17 +84,17 @@ def test_apply_empty(self, float_frame): no_rows = float_frame[:0] result = no_rows.apply(lambda x: x.mean()) expected = Series(np.nan, index=float_frame.columns) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) no_cols = float_frame.loc[:, []] result = no_cols.apply(lambda x: x.mean(), axis=1) expected = Series(np.nan, index=float_frame.index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 2476 expected = DataFrame(index=["a"]) result = expected.apply(lambda x: x["a"], axis=1) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_apply_with_reduce_empty(self): # reduce with an empty DataFrame @@ -103,15 +102,15 @@ def test_apply_with_reduce_empty(self): x = [] result = empty_frame.apply(x.append, axis=1, result_type="expand") - assert_frame_equal(result, empty_frame) + tm.assert_frame_equal(result, empty_frame) result = empty_frame.apply(x.append, axis=1, result_type="reduce") - assert_series_equal(result, Series([], index=pd.Index([], dtype=object))) + tm.assert_series_equal(result, Series([], index=pd.Index([], dtype=object))) empty_with_cols = DataFrame(columns=["a", "b", "c"]) result = empty_with_cols.apply(x.append, axis=1, result_type="expand") - assert_frame_equal(result, empty_with_cols) + tm.assert_frame_equal(result, empty_with_cols) result = empty_with_cols.apply(x.append, axis=1, result_type="reduce") - assert_series_equal(result, Series([], index=pd.Index([], dtype=object))) + tm.assert_series_equal(result, Series([], index=pd.Index([], dtype=object))) # Ensure that x.append hasn't been called assert x == [] @@ -123,7 +122,7 @@ def test_apply_funcs_over_empty(self, func): result = df.apply(getattr(np, func)) expected = getattr(df, func)() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_nunique_empty(self): # GH 28213 @@ -131,21 +130,21 @@ def test_nunique_empty(self): result = df.nunique() expected = Series(0, index=df.columns) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.T.nunique() expected = Series([], index=pd.Index([])) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_standard_nonunique(self): df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=["a", "a", "c"]) result = df.apply(lambda s: s[0], axis=1) expected = Series([1, 4, 7], ["a", "a", "c"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.T.apply(lambda s: s[0], axis=0) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("func", ["sum", "mean", "min", "max", "std"]) @pytest.mark.parametrize( @@ -240,13 +239,13 @@ def test_apply_raw(self, float_frame): expected0 = float_frame.apply(lambda x: x.values.mean()) expected1 = float_frame.apply(lambda x: x.values.mean(), axis=1) - assert_series_equal(result0, expected0) - assert_series_equal(result1, expected1) + tm.assert_series_equal(result0, expected0) + tm.assert_series_equal(result1, expected1) # no reduction result = float_frame.apply(lambda x: x * 2, raw=True) expected = float_frame * 2 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_apply_axis1(self, float_frame): d = float_frame.index[0] @@ -258,7 +257,7 @@ def test_apply_ignore_failures(self, float_string_frame): float_string_frame, np.mean, 0, ignore_failures=True ).apply_standard() expected = float_string_frame._get_numeric_data().apply(np.mean) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_mixed_dtype_corner(self): df = DataFrame({"A": ["foo"], "B": [1.0]}) @@ -266,16 +265,16 @@ def test_apply_mixed_dtype_corner(self): # the result here is actually kind of ambiguous, should it be a Series # or a DataFrame? expected = Series(np.nan, index=pd.Index([], dtype="int64")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": ["foo"], "B": [1.0]}) result = df.apply(lambda x: x["A"], axis=1) expected = Series(["foo"], index=[0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.apply(lambda x: x["B"], axis=1) expected = Series([1.0], index=[0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_empty_infer_type(self): no_cols = DataFrame(index=["a", "b", "c"]) @@ -322,32 +321,32 @@ def subtract_and_divide(x, sub, divide=1): result = float_frame.apply(add_some, howmuch=2) expected = float_frame.apply(lambda x: x + 2) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = float_frame.apply(agg_and_add, howmuch=2) expected = float_frame.apply(lambda x: x.mean() + 2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = float_frame.apply(subtract_and_divide, args=(2,), divide=2) expected = float_frame.apply(lambda x: (x - 2.0) / 2.0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_apply_yield_list(self, float_frame): result = float_frame.apply(list) - assert_frame_equal(result, float_frame) + tm.assert_frame_equal(result, float_frame) def test_apply_reduce_Series(self, float_frame): float_frame.loc[::2, "A"] = np.nan expected = float_frame.mean(1) result = float_frame.apply(np.mean, axis=1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_reduce_rows_to_dict(self): # GH 25196 data = pd.DataFrame([[1, 2], [3, 4]]) expected = pd.Series([{0: 1, 1: 3}, {0: 2, 1: 4}]) result = data.apply(dict) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_differently_indexed(self): df = DataFrame(np.random.randn(20, 10)) @@ -356,13 +355,13 @@ def test_apply_differently_indexed(self): expected0 = DataFrame( {i: v.describe() for i, v in df.items()}, columns=df.columns ) - assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result0, expected0) result1 = df.apply(Series.describe, axis=1) expected1 = DataFrame( {i: v.describe() for i, v in df.T.items()}, columns=df.index ).T - assert_frame_equal(result1, expected1) + tm.assert_frame_equal(result1, expected1) def test_apply_modify_traceback(self): data = DataFrame( @@ -463,7 +462,7 @@ def f(r): columns=["a", "market", "position"], ) result = positions.apply(f, axis=1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_convert_objects(self): data = DataFrame( @@ -514,16 +513,16 @@ def test_apply_convert_objects(self): ) result = data.apply(lambda x: x, axis=1) - assert_frame_equal(result._convert(datetime=True), data) + tm.assert_frame_equal(result._convert(datetime=True), data) def test_apply_attach_name(self, float_frame): result = float_frame.apply(lambda x: x.name) expected = Series(float_frame.columns, index=float_frame.columns) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = float_frame.apply(lambda x: x.name, axis=1) expected = Series(float_frame.index, index=float_frame.index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # non-reductions result = float_frame.apply(lambda x: np.repeat(x.name, len(x))) @@ -532,14 +531,14 @@ def test_apply_attach_name(self, float_frame): index=float_frame.index, columns=float_frame.columns, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = float_frame.apply(lambda x: np.repeat(x.name, len(x)), axis=1) expected = Series( np.repeat(t[0], len(float_frame.columns)) for t in float_frame.itertuples() ) expected.index = float_frame.index - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_multi_index(self, float_frame): index = MultiIndex.from_arrays([["a", "a", "b"], ["c", "d", "d"]]) @@ -548,7 +547,7 @@ def test_apply_multi_index(self, float_frame): expected = DataFrame( [[1, 2], [3, 4], [5, 6]], index=index, columns=["min", "max"] ) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) def test_apply_dict(self): @@ -566,9 +565,9 @@ def test_apply_dict(self): reduce_false = df.apply(fn, result_type="expand") reduce_none = df.apply(fn) - assert_series_equal(reduce_true, dicts) - assert_frame_equal(reduce_false, df) - assert_series_equal(reduce_none, dicts) + tm.assert_series_equal(reduce_true, dicts) + tm.assert_frame_equal(reduce_false, df) + tm.assert_series_equal(reduce_none, dicts) def test_applymap(self, float_frame): applied = float_frame.applymap(lambda x: x * 2) @@ -672,17 +671,17 @@ def test_apply_non_numpy_dtype(self): {"dt": pd.date_range("2015-01-01", periods=3, tz="Europe/Brussels")} ) result = df.apply(lambda x: x) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.apply(lambda x: x + pd.Timedelta("1day")) expected = DataFrame( {"dt": pd.date_range("2015-01-02", periods=3, tz="Europe/Brussels")} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame({"dt": ["a", "b", "c", "a"]}, dtype="category") result = df.apply(lambda x: x) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_apply_dup_names_multi_agg(self): # GH 21063 @@ -713,19 +712,19 @@ def test_with_dictlike_columns(self): df = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1) expected = Series([{"s": 3} for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df["tm"] = [ pd.Timestamp("2017-05-01 00:00:00"), pd.Timestamp("2017-05-02 00:00:00"), ] result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # compose a series result = (df["a"] + df["b"]).apply(lambda x: {"s": x}) expected = Series([{"s": 3}, {"s": 3}]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 18775 df = DataFrame() @@ -736,7 +735,7 @@ def test_with_dictlike_columns(self): ) result = df.apply(lambda x: {}, axis=1) expected = Series([{}, {}, {}]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_with_dictlike_columns_with_infer(self): # GH 17602 @@ -745,7 +744,7 @@ def test_with_dictlike_columns_with_infer(self): lambda x: {"s": x["a"] + x["b"]}, axis=1, result_type="expand" ) expected = DataFrame({"s": [3, 3]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df["tm"] = [ pd.Timestamp("2017-05-01 00:00:00"), @@ -754,7 +753,7 @@ def test_with_dictlike_columns_with_infer(self): result = df.apply( lambda x: {"s": x["a"] + x["b"]}, axis=1, result_type="expand" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_with_listlike_columns(self): # GH 17348 @@ -768,11 +767,11 @@ def test_with_listlike_columns(self): result = df[["a", "b"]].apply(tuple, axis=1) expected = Series([t[1:] for t in df[["a", "b"]].itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df[["a", "ts"]].apply(tuple, axis=1) expected = Series([t[1:] for t in df[["a", "ts"]].itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 18919 df = DataFrame( @@ -782,7 +781,7 @@ def test_with_listlike_columns(self): result = df.apply(lambda row: [el for el in row["x"] if el in row["y"]], axis=1) expected = Series([[], ["q"]], index=df.index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_infer_output_shape_columns(self): # GH 18573 @@ -799,7 +798,7 @@ def test_infer_output_shape_columns(self): ) result = df.apply(lambda row: (row.number, row.string), axis=1) expected = Series([(t.number, t.string) for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_infer_output_shape_listlike_columns(self): # GH 16353 @@ -808,22 +807,22 @@ def test_infer_output_shape_listlike_columns(self): result = df.apply(lambda x: [1, 2, 3], axis=1) expected = Series([[1, 2, 3] for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.apply(lambda x: [1, 2], axis=1) expected = Series([[1, 2] for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 17970 df = DataFrame({"a": [1, 2, 3]}, index=list("abc")) result = df.apply(lambda row: np.ones(1), axis=1) expected = Series([np.ones(1) for t in df.itertuples()], index=df.index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.apply(lambda row: np.ones(2), axis=1) expected = Series([np.ones(2) for t in df.itertuples()], index=df.index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 17892 df = pd.DataFrame( @@ -845,7 +844,7 @@ def fun(x): result = df.apply(fun, axis=1) expected = Series([(1, 2) for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_consistent_coerce_for_shapes(self): # we want column names to NOT be propagated @@ -854,11 +853,11 @@ def test_consistent_coerce_for_shapes(self): result = df.apply(lambda x: [1, 2, 3], axis=1) expected = Series([[1, 2, 3] for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.apply(lambda x: [1, 2], axis=1) expected = Series([[1, 2] for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_consistent_names(self, int_frame_const_col): # if a Series is returned, we should use the resulting index names @@ -870,11 +869,11 @@ def test_consistent_names(self, int_frame_const_col): expected = int_frame_const_col.rename( columns={"A": "test", "B": "other", "C": "cols"} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.apply(lambda x: Series([1, 2], index=["test", "other"]), axis=1) expected = expected[["test", "other"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_result_type(self, int_frame_const_col): # result_type should be consistent no matter which @@ -884,36 +883,36 @@ def test_result_type(self, int_frame_const_col): result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="expand") expected = df.copy() expected.columns = [0, 1, 2] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.apply(lambda x: [1, 2], axis=1, result_type="expand") expected = df[["A", "B"]].copy() expected.columns = [0, 1] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # broadcast result result = df.apply(lambda x: [1, 2, 3], axis=1, result_type="broadcast") expected = df.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) columns = ["other", "col", "names"] result = df.apply( lambda x: Series([1, 2, 3], index=columns), axis=1, result_type="broadcast" ) expected = df.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # series result result = df.apply(lambda x: Series([1, 2, 3], index=x.index), axis=1) expected = df.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # series result with other index columns = ["other", "col", "names"] result = df.apply(lambda x: Series([1, 2, 3], index=columns), axis=1) expected = df.copy() expected.columns = columns - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("result_type", ["foo", 1]) def test_result_type_error(self, result_type, int_frame_const_col): @@ -934,11 +933,11 @@ def test_consistency_for_boxed(self, box, int_frame_const_col): result = df.apply(lambda x: box([1, 2]), axis=1) expected = Series([box([1, 2]) for t in df.itertuples()]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.apply(lambda x: box([1, 2]), axis=1, result_type="expand") expected = int_frame_const_col[["A", "B"]].rename(columns={"A": 0, "B": 1}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def zip_frames(frames, axis=1): @@ -972,13 +971,13 @@ def test_agg_transform(self, axis, float_frame): # ufunc result = float_frame.transform(np.sqrt, axis=axis) expected = f_sqrt.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = float_frame.apply(np.sqrt, axis=axis) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = float_frame.transform(np.sqrt, axis=axis) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # list-like result = float_frame.apply([np.sqrt], axis=axis) @@ -991,10 +990,10 @@ def test_agg_transform(self, axis, float_frame): expected.index = pd.MultiIndex.from_product( [float_frame.index, ["sqrt"]] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = float_frame.transform([np.sqrt], axis=axis) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # multiple items in list # these are in the order as if we are applying both @@ -1009,10 +1008,10 @@ def test_agg_transform(self, axis, float_frame): expected.index = pd.MultiIndex.from_product( [float_frame.index, ["absolute", "sqrt"]] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = float_frame.transform([np.abs, "sqrt"], axis=axis) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_transform_and_agg_err(self, axis, float_frame): # cannot both transform and agg @@ -1118,7 +1117,7 @@ def test_agg_reduce(self, axis, float_frame): expected = expected.T if axis in {0, "index"} else expected result = float_frame.agg(["mean", "max", "sum"], axis=axis) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # dict input with scalars func = OrderedDict([(name1, "mean"), (name2, "sum")]) @@ -1130,7 +1129,7 @@ def test_agg_reduce(self, axis, float_frame): ], index=[name1, name2], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # dict input with lists func = OrderedDict([(name1, ["mean"]), (name2, ["sum"])]) @@ -1146,7 +1145,7 @@ def test_agg_reduce(self, axis, float_frame): } ) expected = expected.T if axis in {1, "columns"} else expected - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # dict input with lists with multiple func = OrderedDict([(name1, ["mean", "sum"]), (name2, ["sum", "max"])]) @@ -1178,7 +1177,7 @@ def test_agg_reduce(self, axis, float_frame): ) ) expected = expected.T if axis in {1, "columns"} else expected - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_nuiscance_columns(self): @@ -1194,7 +1193,7 @@ def test_nuiscance_columns(self): result = df.agg("min") expected = Series([1, 1.0, "bar", pd.Timestamp("20130101")], index=df.columns) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.agg(["min"]) expected = DataFrame( @@ -1202,17 +1201,17 @@ def test_nuiscance_columns(self): index=["min"], columns=df.columns, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.agg("sum") expected = Series([6, 6.0, "foobarbaz"], index=["A", "B", "C"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.agg(["sum"]) expected = DataFrame( [[6, 6.0, "foobarbaz"]], index=["sum"], columns=["A", "B", "C"] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_non_callable_aggregates(self): @@ -1227,13 +1226,13 @@ def test_non_callable_aggregates(self): result = df.agg({"A": "count"}) expected = Series({"A": 2}) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Non-function aggregate result = df.agg({"A": "size"}) expected = Series({"A": 3}) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Mix function and non-function aggs result1 = df.agg(["count", "size"]) @@ -1248,14 +1247,14 @@ def test_non_callable_aggregates(self): } ) - assert_frame_equal(result1, result2, check_like=True) - assert_frame_equal(result2, expected, check_like=True) + tm.assert_frame_equal(result1, result2, check_like=True) + tm.assert_frame_equal(result2, expected, check_like=True) # Just functional string arg is same as calling df.arg() result = df.agg("count") expected = df.count() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Just a string attribute arg same as calling df.arg result = df.agg("size") diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 1ef10ea5857d0..16dfae847e0eb 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -9,7 +9,6 @@ import pandas as pd from pandas import Categorical, DataFrame, Index, MultiIndex, Series, date_range, isna import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal class TestDataFrameSelectReindex: @@ -73,10 +72,10 @@ def test_drop_col_still_multiindex(self): def test_drop(self): simple = DataFrame({"A": [1, 2, 3, 4], "B": [0, 1, 2, 3]}) - assert_frame_equal(simple.drop("A", axis=1), simple[["B"]]) - assert_frame_equal(simple.drop(["A", "B"], axis="columns"), simple[[]]) - assert_frame_equal(simple.drop([0, 1, 3], axis=0), simple.loc[[2], :]) - assert_frame_equal(simple.drop([0, 3], axis="index"), simple.loc[[1, 2], :]) + tm.assert_frame_equal(simple.drop("A", axis=1), simple[["B"]]) + tm.assert_frame_equal(simple.drop(["A", "B"], axis="columns"), simple[[]]) + tm.assert_frame_equal(simple.drop([0, 1, 3], axis=0), simple.loc[[2], :]) + tm.assert_frame_equal(simple.drop([0, 3], axis="index"), simple.loc[[1, 2], :]) with pytest.raises(KeyError, match=r"\[5\] not found in axis"): simple.drop(5) @@ -88,12 +87,12 @@ def test_drop(self): simple.drop(["A", "C"], 1) # errors = 'ignore' - assert_frame_equal(simple.drop(5, errors="ignore"), simple) - assert_frame_equal( + tm.assert_frame_equal(simple.drop(5, errors="ignore"), simple) + tm.assert_frame_equal( simple.drop([0, 5], errors="ignore"), simple.loc[[1, 2, 3], :] ) - assert_frame_equal(simple.drop("C", axis=1, errors="ignore"), simple) - assert_frame_equal( + tm.assert_frame_equal(simple.drop("C", axis=1, errors="ignore"), simple) + tm.assert_frame_equal( simple.drop(["A", "C"], axis=1, errors="ignore"), simple[["B"]] ) @@ -101,21 +100,21 @@ def test_drop(self): nu_df = DataFrame( list(zip(range(3), range(-3, 1), list("abc"))), columns=["a", "a", "b"] ) - assert_frame_equal(nu_df.drop("a", axis=1), nu_df[["b"]]) - assert_frame_equal(nu_df.drop("b", axis="columns"), nu_df["a"]) - assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398 + tm.assert_frame_equal(nu_df.drop("a", axis=1), nu_df[["b"]]) + tm.assert_frame_equal(nu_df.drop("b", axis="columns"), nu_df["a"]) + tm.assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398 nu_df = nu_df.set_index(pd.Index(["X", "Y", "X"])) nu_df.columns = list("abc") - assert_frame_equal(nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :]) - assert_frame_equal(nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :]) + tm.assert_frame_equal(nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :]) + tm.assert_frame_equal(nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :]) # inplace cache issue # GH 5628 df = pd.DataFrame(np.random.randn(10, 3), columns=list("abc")) expected = df[~(df.b > 0)] df.drop(labels=df[df.b > 0].index, inplace=True) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_drop_multiindex_not_lexsorted(self): # GH 11640 @@ -266,7 +265,7 @@ def test_reindex(self, float_frame): # copy with no axes result = float_frame.reindex() - assert_frame_equal(result, float_frame) + tm.assert_frame_equal(result, float_frame) assert result is not float_frame def test_reindex_nan(self): @@ -277,10 +276,10 @@ def test_reindex_nan(self): ) i, j = [np.nan, 5, 5, np.nan, 1, 2, np.nan], [1, 3, 3, 1, 2, 0, 1] - assert_frame_equal(df.reindex(i), df.iloc[j]) + tm.assert_frame_equal(df.reindex(i), df.iloc[j]) df.index = df.index.astype("object") - assert_frame_equal(df.reindex(i), df.iloc[j], check_index_type=False) + tm.assert_frame_equal(df.reindex(i), df.iloc[j], check_index_type=False) # GH10388 df = pd.DataFrame( @@ -296,7 +295,7 @@ def test_reindex_nan(self): left = df.set_index(["delta", "other", "date"]).reset_index() right = df.reindex(columns=["delta", "other", "date", "amount"]) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) def test_reindex_name_remains(self): s = Series(np.random.rand(10)) @@ -329,7 +328,7 @@ def test_reindex_int(self, int_frame): def test_reindex_like(self, float_frame): other = float_frame.reindex(index=float_frame.index[:10], columns=["C", "B"]) - assert_frame_equal(other, float_frame.reindex_like(other)) + tm.assert_frame_equal(other, float_frame.reindex_like(other)) def test_reindex_columns(self, float_frame): new_frame = float_frame.reindex(columns=["A", "B", "E"]) @@ -364,7 +363,7 @@ def test_reindex_columns_method(self): columns=range(6), dtype=float, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # method='ffill' result = df.reindex(columns=range(6), method="ffill") @@ -378,7 +377,7 @@ def test_reindex_columns_method(self): columns=range(6), dtype=float, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # method='bfill' result = df.reindex(columns=range(6), method="bfill") @@ -392,7 +391,7 @@ def test_reindex_columns_method(self): columns=range(6), dtype=float, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_axes(self): # GH 3317, reindexing by both axes loses freq of the index @@ -419,29 +418,29 @@ def test_reindex_fill_value(self): result = df.reindex(range(15), fill_value=0) expected = df.reindex(range(15)).fillna(0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis=1 result = df.reindex(columns=range(5), fill_value=0.0) expected = df.copy() expected[4] = 0.0 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.reindex(columns=range(5), fill_value=0) expected = df.copy() expected[4] = 0 - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.reindex(columns=range(5), fill_value="foo") expected = df.copy() expected[4] = "foo" - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # other dtypes df["foo"] = "foo" result = df.reindex(range(15), fill_value=0) expected = df.reindex(range(15)).fillna(0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_dups(self): @@ -453,7 +452,7 @@ def test_reindex_dups(self): result = df.copy() result.index = list(range(len(df))) expected = DataFrame(arr, index=list(range(len(df)))) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # reindex fails msg = "cannot reindex from a duplicate axis" @@ -467,13 +466,13 @@ def test_reindex_axis_style(self): {"A": [1, 2, np.nan], "B": [4, 5, np.nan]}, index=[0, 1, 3] ) result = df.reindex([0, 1, 3]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.reindex([0, 1, 3], axis=0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.reindex([0, 1, 3], axis="index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_positional_warns(self): # https://github.com/pandas-dev/pandas/issues/12392 @@ -482,7 +481,7 @@ def test_reindex_positional_warns(self): with tm.assert_produces_warning(FutureWarning): result = df.reindex([0, 1], ["A", "B", "C"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_axis_style_raises(self): # https://github.com/pandas-dev/pandas/issues/12392 @@ -524,7 +523,7 @@ def test_reindex_single_named_indexer(self): df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}) result = df.reindex([0, 1], columns=["A"]) expected = pd.DataFrame({"A": [1, 2]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_api_equivalence(self): # https://github.com/pandas-dev/pandas/issues/12392 @@ -699,8 +698,8 @@ def _check_align(self, a, b, axis, fill_axis, how, method, limit=None): ea = ea.fillna(axis=fill_axis, method=method, limit=limit) eb = eb.fillna(axis=fill_axis, method=method, limit=limit) - assert_frame_equal(aa, ea) - assert_frame_equal(ab, eb) + tm.assert_frame_equal(aa, ea) + tm.assert_frame_equal(ab, eb) @pytest.mark.parametrize("meth", ["pad", "bfill"]) @pytest.mark.parametrize("ax", [0, 1, None]) @@ -750,7 +749,7 @@ def test_align_int_fill_bug(self): result = df1 - df1.mean() expected = df2 - df2.mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_align_multiindex(self): # GH 10665 @@ -768,11 +767,11 @@ def test_align_multiindex(self): res2l, res2r = df2.align(df1, join="right") expl = df1 - assert_frame_equal(expl, res1l) - assert_frame_equal(expl, res2r) + tm.assert_frame_equal(expl, res1l) + tm.assert_frame_equal(expl, res2r) expr = pd.DataFrame([0, 0, 1, 1, np.nan, np.nan] * 2, index=midx) - assert_frame_equal(expr, res1r) - assert_frame_equal(expr, res2l) + tm.assert_frame_equal(expr, res1r) + tm.assert_frame_equal(expr, res2l) res1l, res1r = df1.align(df2, join="right") res2l, res2r = df2.align(df1, join="left") @@ -781,11 +780,11 @@ def test_align_multiindex(self): [range(2), range(2), range(2)], names=("a", "b", "c") ) expl = pd.DataFrame([0, 1, 2, 3, 6, 7, 8, 9], index=exp_idx) - assert_frame_equal(expl, res1l) - assert_frame_equal(expl, res2r) + tm.assert_frame_equal(expl, res1l) + tm.assert_frame_equal(expl, res2r) expr = pd.DataFrame([0, 0, 1, 1] * 2, index=exp_idx) - assert_frame_equal(expr, res1r) - assert_frame_equal(expr, res2l) + tm.assert_frame_equal(expr, res1r) + tm.assert_frame_equal(expr, res2l) def test_align_series_combinations(self): df = pd.DataFrame({"a": [1, 3, 5], "b": [1, 3, 5]}, index=list("ACE")) @@ -895,7 +894,7 @@ def test_filter_regex_search(self, float_frame): result = df.filter(regex="BB") exp = df[[x for x in df.columns if "BB" in x]] - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) @pytest.mark.parametrize( "name,expected", @@ -909,8 +908,8 @@ def test_filter_unicode(self, name, expected): # GH13101 df = DataFrame({"a": [1, 2], "あ": [3, 4]}) - assert_frame_equal(df.filter(like=name), expected) - assert_frame_equal(df.filter(regex=name), expected) + tm.assert_frame_equal(df.filter(like=name), expected) + tm.assert_frame_equal(df.filter(regex=name), expected) @pytest.mark.parametrize("name", ["a", "a"]) def test_filter_bytestring(self, name): @@ -918,17 +917,17 @@ def test_filter_bytestring(self, name): df = DataFrame({b"a": [1, 2], b"b": [3, 4]}) expected = DataFrame({b"a": [1, 2]}) - assert_frame_equal(df.filter(like=name), expected) - assert_frame_equal(df.filter(regex=name), expected) + tm.assert_frame_equal(df.filter(like=name), expected) + tm.assert_frame_equal(df.filter(regex=name), expected) def test_filter_corner(self): empty = DataFrame() result = empty.filter([]) - assert_frame_equal(result, empty) + tm.assert_frame_equal(result, empty) result = empty.filter(like="foo") - assert_frame_equal(result, empty) + tm.assert_frame_equal(result, empty) def test_take(self, float_frame): # homogeneous @@ -937,12 +936,12 @@ def test_take(self, float_frame): result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["D", "B", "C", "A"]] - assert_frame_equal(result, expected, check_names=False) + tm.assert_frame_equal(result, expected, check_names=False) # negative indices order = [2, 1, -1] @@ -950,15 +949,15 @@ def test_take(self, float_frame): result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.take(order, axis=0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["C", "B", "D"]] - assert_frame_equal(result, expected, check_names=False) + tm.assert_frame_equal(result, expected, check_names=False) # illegal indices msg = "indices are out-of-bounds" @@ -979,12 +978,12 @@ def test_take_mixed_type(self, float_string_frame): result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["foo", "B", "C", "A", "D"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # negative indices order = [4, 1, -2] @@ -992,12 +991,12 @@ def test_take_mixed_type(self, float_string_frame): result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["foo", "B", "D"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_take_mixed_numeric(self, mixed_float_frame, mixed_int_frame): # by dtype @@ -1006,12 +1005,12 @@ def test_take_mixed_numeric(self, mixed_float_frame, mixed_int_frame): result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis = 1 result = df.take(order, axis=1) expected = df.loc[:, ["B", "C", "A", "D"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_boolean(self): frame = DataFrame( @@ -1052,15 +1051,15 @@ def test_reindex_with_nans(self): result = df.reindex(index=[101.0, 102.0, 103.0]) expected = df.iloc[[1, 3, 4]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.reindex(index=[103.0]) expected = df.iloc[[4]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.reindex(index=[101.0]) expected = df.iloc[[1]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_multi(self): df = DataFrame(np.random.randn(3, 3)) @@ -1068,28 +1067,28 @@ def test_reindex_multi(self): result = df.reindex(index=range(4), columns=range(4)) expected = df.reindex(list(range(4))).reindex(columns=range(4)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame(np.random.randint(0, 10, (3, 3))) result = df.reindex(index=range(4), columns=range(4)) expected = df.reindex(list(range(4))).reindex(columns=range(4)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame(np.random.randint(0, 10, (3, 3))) result = df.reindex(index=range(2), columns=range(2)) expected = df.reindex(range(2)).reindex(columns=range(2)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame(np.random.randn(5, 3) + 1j, columns=["a", "b", "c"]) result = df.reindex(index=[0, 1], columns=["a", "b"]) expected = df.reindex([0, 1]).reindex(columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_reindex_multi_categorical_time(self): # https://github.com/pandas-dev/pandas/issues/21390 @@ -1104,7 +1103,7 @@ def test_reindex_multi_categorical_time(self): result = df2.reindex(midx) expected = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) data = [[1, 2, 3], [1, 2, 3]] @@ -1127,9 +1126,9 @@ def test_raise_on_drop_duplicate_index(self, actual): with pytest.raises(KeyError, match=msg): actual.T.drop("c", level=level, axis=1) expected_no_err = actual.drop("c", axis=0, level=level, errors="ignore") - assert_frame_equal(expected_no_err, actual) + tm.assert_frame_equal(expected_no_err, actual) expected_no_err = actual.T.drop("c", axis=1, level=level, errors="ignore") - assert_frame_equal(expected_no_err.T, actual) + tm.assert_frame_equal(expected_no_err.T, actual) @pytest.mark.parametrize("index", [[1, 2, 3], [1, 1, 2]]) @pytest.mark.parametrize("drop_labels", [[], [1], [2]]) diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 1b6ee91317996..b45c074f179a0 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -19,11 +19,6 @@ from pandas.core.internals import ObjectBlock from pandas.core.internals.blocks import IntBlock import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) # Segregated collection of methods that require the BlockManager internal data # structure @@ -50,11 +45,11 @@ def test_setitem_invalidates_datetime_index_freq(self): def test_cast_internals(self, float_frame): casted = DataFrame(float_frame._data, dtype=int) expected = DataFrame(float_frame._series, dtype=int) - assert_frame_equal(casted, expected) + tm.assert_frame_equal(casted, expected) casted = DataFrame(float_frame._data, dtype=np.int32) expected = DataFrame(float_frame._series, dtype=np.int32) - assert_frame_equal(casted, expected) + tm.assert_frame_equal(casted, expected) def test_consolidate(self, float_frame): float_frame["E"] = 7.0 @@ -101,7 +96,7 @@ def test_boolean_set_uncons(self, float_frame): expected[expected > 1] = 2 float_frame[float_frame > 1] = 2 - assert_almost_equal(expected, float_frame.values) + tm.assert_almost_equal(expected, float_frame.values) def test_values_numeric_cols(self, float_frame): float_frame["foo"] = "bar" @@ -155,66 +150,66 @@ def test_constructor_with_convert(self): df = DataFrame({"A": [2 ** 63 - 1]}) result = df["A"] expected = Series(np.asarray([2 ** 63 - 1], np.int64), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [2 ** 63]}) result = df["A"] expected = Series(np.asarray([2 ** 63], np.uint64), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [datetime(2005, 1, 1), True]}) result = df["A"] expected = Series( np.asarray([datetime(2005, 1, 1), True], np.object_), name="A" ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [None, 1]}) result = df["A"] expected = Series(np.asarray([np.nan, 1], np.float_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [1.0, 2]}) result = df["A"] expected = Series(np.asarray([1.0, 2], np.float_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [1.0 + 2.0j, 3]}) result = df["A"] expected = Series(np.asarray([1.0 + 2.0j, 3], np.complex_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [1.0 + 2.0j, 3.0]}) result = df["A"] expected = Series(np.asarray([1.0 + 2.0j, 3.0], np.complex_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [1.0 + 2.0j, True]}) result = df["A"] expected = Series(np.asarray([1.0 + 2.0j, True], np.object_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [1.0, None]}) result = df["A"] expected = Series(np.asarray([1.0, np.nan], np.float_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [1.0 + 2.0j, None]}) result = df["A"] expected = Series(np.asarray([1.0 + 2.0j, np.nan], np.complex_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [2.0, 1, True, None]}) result = df["A"] expected = Series(np.asarray([2.0, 1, True, None], np.object_), name="A") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame({"A": [2.0, 1, datetime(2006, 1, 1), None]}) result = df["A"] expected = Series( np.asarray([2.0, 1, datetime(2006, 1, 1), None], np.object_), name="A" ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_construction_with_mixed(self, float_string_frame): # test construction edge cases with mixed types @@ -245,7 +240,7 @@ def test_construction_with_mixed(self, float_string_frame): ], index=list("ABCD") + ["foo", "datetime", "timedelta"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_construction_with_conversions(self): @@ -256,7 +251,7 @@ def test_construction_with_conversions(self): expected = DataFrame( {"A": pd.timedelta_range("00:00:01", periods=3, freq="s")}, index=range(3) ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) expected = DataFrame( { @@ -276,7 +271,7 @@ def test_construction_with_conversions(self): # df['dt3'] = np.array(['2013-01-01 00:00:01','2013-01-01 # 00:00:02','2013-01-01 00:00:03'],dtype='datetime64[s]') - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_constructor_compound_dtypes(self): # GH 5191 @@ -308,7 +303,7 @@ def test_equals_different_blocks(self): assert df0._data.blocks[0].dtype != df1._data.blocks[0].dtype # do the real tests - assert_frame_equal(df0, df1) + tm.assert_frame_equal(df0, df1) assert df0.equals(df1) assert df1.equals(df0) @@ -359,7 +354,7 @@ def test_pickle(self, float_string_frame, timezone_frame): empty_frame = DataFrame() unpickled = tm.round_trip_pickle(float_string_frame) - assert_frame_equal(float_string_frame, unpickled) + tm.assert_frame_equal(float_string_frame, unpickled) # buglet float_string_frame._data.ndim @@ -370,7 +365,7 @@ def test_pickle(self, float_string_frame, timezone_frame): # tz frame unpickled = tm.round_trip_pickle(timezone_frame) - assert_frame_equal(timezone_frame, unpickled) + tm.assert_frame_equal(timezone_frame, unpickled) def test_consolidate_datetime64(self): # numpy vstack bug @@ -429,7 +424,7 @@ def test_get_numeric_data(self): ], index=["a", "b", "c", "f"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame( { @@ -446,22 +441,22 @@ def test_get_numeric_data(self): result = df._get_numeric_data() expected = df.loc[:, ["a", "b", "d", "e", "f"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) only_obj = df.loc[:, ["c", "g"]] result = only_obj._get_numeric_data() expected = df.loc[:, []] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame.from_dict({"a": [1, 2], "b": ["foo", "bar"], "c": [np.pi, np.e]}) result = df._get_numeric_data() expected = DataFrame.from_dict({"a": [1, 2], "c": [np.pi, np.e]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = result.copy() result = df._get_numeric_data() expected = df - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_get_numeric_data_extension_dtype(self): # GH 22290 @@ -475,13 +470,13 @@ def test_get_numeric_data_extension_dtype(self): ) result = df._get_numeric_data() expected = df.loc[:, ["A", "C"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_convert_objects(self, float_string_frame): oops = float_string_frame.T.T converted = oops._convert(datetime=True) - assert_frame_equal(converted, float_string_frame) + tm.assert_frame_equal(converted, float_string_frame) assert converted["A"].dtype == np.float64 # force numeric conversion @@ -517,12 +512,12 @@ def test_convert_objects(self, float_string_frame): df = DataFrame(dict(s=Series([1, "na", 3, 4]))) result = df._convert(datetime=True, numeric=True) expected = DataFrame(dict(s=Series([1, np.nan, 3, 4]))) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_convert_objects_no_conversion(self): mixed1 = DataFrame({"a": [1, 2, 3], "b": [4.0, 5, 6], "c": ["x", "y", "z"]}) mixed2 = mixed1._convert(datetime=True) - assert_frame_equal(mixed1, mixed2) + tm.assert_frame_equal(mixed1, mixed2) def test_infer_objects(self): # GH 11221 @@ -636,4 +631,4 @@ def test_add_column_with_pandas_array(self): ) assert type(df["c"]._data.blocks[0]) == ObjectBlock assert type(df2["c"]._data.blocks[0]) == ObjectBlock - assert_frame_equal(df, df2) + tm.assert_frame_equal(df, df2) diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py index e38d214eadeb6..e3f37e1ef3186 100644 --- a/pandas/tests/frame/test_combine_concat.py +++ b/pandas/tests/frame/test_combine_concat.py @@ -6,7 +6,6 @@ import pandas as pd from pandas import DataFrame, Index, Series, Timestamp, date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal class TestDataFrameConcatCommon: @@ -20,7 +19,7 @@ def test_concat_multiple_frames_dtypes(self): [np.dtype("float64")] * 2 + [np.dtype("float32")] * 2, index=["foo", "bar", 0, 1], ) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) @pytest.mark.parametrize( "data", @@ -56,15 +55,15 @@ def test_concat_multiple_tzs(self): results = pd.concat([df1, df2]).reset_index(drop=True) expected = DataFrame(dict(time=[ts1, ts2]), dtype=object) - assert_frame_equal(results, expected) + tm.assert_frame_equal(results, expected) results = pd.concat([df1, df3]).reset_index(drop=True) expected = DataFrame(dict(time=[ts1, ts3]), dtype=object) - assert_frame_equal(results, expected) + tm.assert_frame_equal(results, expected) results = pd.concat([df2, df3]).reset_index(drop=True) expected = DataFrame(dict(time=[ts2, ts3])) - assert_frame_equal(results, expected) + tm.assert_frame_equal(results, expected) @pytest.mark.parametrize( "t1", @@ -91,7 +90,7 @@ def test_concat_tz_NaT(self, t1): result = pd.concat([df1, df2]) expected = DataFrame([[ts1, ts2], [ts3, pd.NaT]], index=[0, 0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_tz_not_aligned(self): # GH 22796 @@ -102,7 +101,7 @@ def test_concat_tz_not_aligned(self): expected = pd.DataFrame( {"A": list(ts) + list(ts), "B": [pd.NaT, pd.NaT] + list(ts)} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_tuple_keys(self): # GH 14438 @@ -127,7 +126,7 @@ def test_concat_tuple_keys(self): }, } ) - assert_frame_equal(results, expected) + tm.assert_frame_equal(results, expected) def test_append_series_dict(self): df = DataFrame(np.random.randn(5, 4), columns=["foo", "bar", "baz", "qux"]) @@ -146,24 +145,24 @@ def test_append_series_dict(self): expected = df.append( DataFrame({0: series[::-1]}, index=df.columns).T, ignore_index=True ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # dict result = df.append(series.to_dict(), ignore_index=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.append(series[::-1][:3], ignore_index=True) expected = df.append( DataFrame({0: series[::-1][:3]}).T, ignore_index=True, sort=True ) - assert_frame_equal(result, expected.loc[:, result.columns]) + tm.assert_frame_equal(result, expected.loc[:, result.columns]) # can append when name set row = df.loc[4] row.name = 5 result = df.append(row) expected = df.append(df[-1:], ignore_index=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_append_list_of_series_dicts(self): df = DataFrame(np.random.randn(5, 4), columns=["foo", "bar", "baz", "qux"]) @@ -172,7 +171,7 @@ def test_append_list_of_series_dicts(self): result = df.append(dicts, ignore_index=True) expected = df.append(df, ignore_index=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # different columns dicts = [ @@ -181,7 +180,7 @@ def test_append_list_of_series_dicts(self): ] result = df.append(dicts, ignore_index=True, sort=True) expected = df.append(DataFrame(dicts), ignore_index=True, sort=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_append_missing_cols(self): # GH22252 @@ -195,7 +194,7 @@ def test_append_missing_cols(self): result = df.append(dicts, ignore_index=True, sort=True) expected = df.append(DataFrame(dicts), ignore_index=True, sort=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_append_empty_dataframe(self): @@ -204,28 +203,28 @@ def test_append_empty_dataframe(self): df2 = DataFrame() result = df1.append(df2) expected = df1.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Non-empty df append empty df df1 = DataFrame(np.random.randn(5, 2)) df2 = DataFrame() result = df1.append(df2) expected = df1.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Empty df with columns append empty df df1 = DataFrame(columns=["bar", "foo"]) df2 = DataFrame() result = df1.append(df2) expected = df1.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Non-Empty df with columns append empty df df1 = DataFrame(np.random.randn(5, 2), columns=["bar", "foo"]) df2 = DataFrame() result = df1.append(df2) expected = df1.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_append_dtypes(self): @@ -237,13 +236,13 @@ def test_append_dtypes(self): df2 = DataFrame() result = df1.append(df2) expected = df1.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df1 = DataFrame({"bar": Timestamp("20130101")}, index=range(1)) df2 = DataFrame({"bar": "foo"}, index=range(1, 2)) result = df1.append(df2) expected = DataFrame({"bar": [Timestamp("20130101"), "foo"]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df1 = DataFrame({"bar": Timestamp("20130101")}, index=range(1)) df2 = DataFrame({"bar": np.nan}, index=range(1, 2)) @@ -251,7 +250,7 @@ def test_append_dtypes(self): expected = DataFrame( {"bar": Series([Timestamp("20130101"), np.nan], dtype="M8[ns]")} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df1 = DataFrame({"bar": Timestamp("20130101")}, index=range(1)) df2 = DataFrame({"bar": np.nan}, index=range(1, 2), dtype=object) @@ -259,7 +258,7 @@ def test_append_dtypes(self): expected = DataFrame( {"bar": Series([Timestamp("20130101"), np.nan], dtype="M8[ns]")} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df1 = DataFrame({"bar": np.nan}, index=range(1)) df2 = DataFrame({"bar": Timestamp("20130101")}, index=range(1, 2)) @@ -267,13 +266,13 @@ def test_append_dtypes(self): expected = DataFrame( {"bar": Series([np.nan, Timestamp("20130101")], dtype="M8[ns]")} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df1 = DataFrame({"bar": Timestamp("20130101")}, index=range(1)) df2 = DataFrame({"bar": 1}, index=range(1, 2), dtype=object) result = df1.append(df2) expected = DataFrame({"bar": Series([Timestamp("20130101"), 1])}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_update(self): df = DataFrame( @@ -287,7 +286,7 @@ def test_update(self): expected = DataFrame( [[1.5, np.nan, 3], [3.6, 2, 3], [1.5, np.nan, 3], [1.5, np.nan, 7.0]] ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_update_dtypes(self): @@ -304,7 +303,7 @@ def test_update_dtypes(self): [[45.0, 45.0, False, True], [4.0, 5.0, True, False]], columns=["A", "B", "bool1", "bool2"], ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_update_nooverwrite(self): df = DataFrame( @@ -318,7 +317,7 @@ def test_update_nooverwrite(self): expected = DataFrame( [[1.5, np.nan, 3], [1.5, 2, 3], [1.5, np.nan, 3], [1.5, np.nan, 3.0]] ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_update_filtered(self): df = DataFrame( @@ -332,7 +331,7 @@ def test_update_filtered(self): expected = DataFrame( [[1.5, np.nan, 3], [1.5, np.nan, 3], [1.5, np.nan, 3], [1.5, np.nan, 7.0]] ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) @pytest.mark.parametrize( "bad_kwarg, exception, msg", @@ -372,7 +371,7 @@ def test_update_from_non_df(self): expected = DataFrame(d) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) d = {"a": [1, 2, 3, 4], "b": [5, 6, 7, 8]} df = DataFrame(d) @@ -382,14 +381,14 @@ def test_update_from_non_df(self): expected = DataFrame(d) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) def test_update_datetime_tz(self): # GH 25807 result = DataFrame([pd.Timestamp("2019", tz="UTC")]) result.update(result) expected = DataFrame([pd.Timestamp("2019", tz="UTC")]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_join_str_datetime(self): str_dates = ["20120209", "20120222"] @@ -440,8 +439,8 @@ def test_join_multiindex_leftright(self): ) # these must be the same results (but columns are flipped) - assert_frame_equal(df1.join(df2, how="left"), exp) - assert_frame_equal(df2.join(df1, how="right"), exp[["value2", "value1"]]) + tm.assert_frame_equal(df1.join(df2, how="left"), exp) + tm.assert_frame_equal(df2.join(df1, how="right"), exp[["value2", "value1"]]) exp_idx = pd.MultiIndex.from_product( [["a", "b"], ["x", "y", "z"]], names=["first", "second"] @@ -459,8 +458,8 @@ def test_join_multiindex_leftright(self): columns=["value1", "value2"], ) - assert_frame_equal(df1.join(df2, how="right"), exp) - assert_frame_equal(df2.join(df1, how="left"), exp[["value2", "value1"]]) + tm.assert_frame_equal(df1.join(df2, how="right"), exp) + tm.assert_frame_equal(df2.join(df1, how="left"), exp[["value2", "value1"]]) def test_concat_named_keys(self): # GH 14252 @@ -471,20 +470,20 @@ def test_concat_named_keys(self): {"foo": [1, 2, 1, 2], "bar": [0.1, 0.2, 0.1, 0.2]}, index=pd.MultiIndex.from_product((["a", "b"], [0, 1]), names=["baz", None]), ) - assert_frame_equal(concatted_named_from_keys, expected_named) + tm.assert_frame_equal(concatted_named_from_keys, expected_named) index_no_name = Index(["a", "b"], name=None) concatted_named_from_names = pd.concat( [df, df], keys=index_no_name, names=["baz"] ) - assert_frame_equal(concatted_named_from_names, expected_named) + tm.assert_frame_equal(concatted_named_from_names, expected_named) concatted_unnamed = pd.concat([df, df], keys=index_no_name) expected_unnamed = pd.DataFrame( {"foo": [1, 2, 1, 2], "bar": [0.1, 0.2, 0.1, 0.2]}, index=pd.MultiIndex.from_product((["a", "b"], [0, 1]), names=[None, None]), ) - assert_frame_equal(concatted_unnamed, expected_unnamed) + tm.assert_frame_equal(concatted_unnamed, expected_unnamed) def test_concat_axis_parameter(self): # GH 14369 @@ -495,13 +494,13 @@ def test_concat_axis_parameter(self): expected_index = pd.DataFrame({"A": [0.1, 0.2, 0.3, 0.4]}, index=[0, 1, 0, 1]) concatted_index = pd.concat([df1, df2], axis="index") - assert_frame_equal(concatted_index, expected_index) + tm.assert_frame_equal(concatted_index, expected_index) concatted_row = pd.concat([df1, df2], axis="rows") - assert_frame_equal(concatted_row, expected_index) + tm.assert_frame_equal(concatted_row, expected_index) concatted_0 = pd.concat([df1, df2], axis=0) - assert_frame_equal(concatted_0, expected_index) + tm.assert_frame_equal(concatted_0, expected_index) # Columns/1 DataFrame expected_columns = pd.DataFrame( @@ -509,10 +508,10 @@ def test_concat_axis_parameter(self): ) concatted_columns = pd.concat([df1, df2], axis="columns") - assert_frame_equal(concatted_columns, expected_columns) + tm.assert_frame_equal(concatted_columns, expected_columns) concatted_1 = pd.concat([df1, df2], axis=1) - assert_frame_equal(concatted_1, expected_columns) + tm.assert_frame_equal(concatted_1, expected_columns) series1 = pd.Series([0.1, 0.2]) series2 = pd.Series([0.3, 0.4]) @@ -521,13 +520,13 @@ def test_concat_axis_parameter(self): expected_index_series = pd.Series([0.1, 0.2, 0.3, 0.4], index=[0, 1, 0, 1]) concatted_index_series = pd.concat([series1, series2], axis="index") - assert_series_equal(concatted_index_series, expected_index_series) + tm.assert_series_equal(concatted_index_series, expected_index_series) concatted_row_series = pd.concat([series1, series2], axis="rows") - assert_series_equal(concatted_row_series, expected_index_series) + tm.assert_series_equal(concatted_row_series, expected_index_series) concatted_0_series = pd.concat([series1, series2], axis=0) - assert_series_equal(concatted_0_series, expected_index_series) + tm.assert_series_equal(concatted_0_series, expected_index_series) # Columns/1 Series expected_columns_series = pd.DataFrame( @@ -535,10 +534,10 @@ def test_concat_axis_parameter(self): ) concatted_columns_series = pd.concat([series1, series2], axis="columns") - assert_frame_equal(concatted_columns_series, expected_columns_series) + tm.assert_frame_equal(concatted_columns_series, expected_columns_series) concatted_1_series = pd.concat([series1, series2], axis=1) - assert_frame_equal(concatted_1_series, expected_columns_series) + tm.assert_frame_equal(concatted_1_series, expected_columns_series) # Testing ValueError with pytest.raises(ValueError, match="No axis named"): @@ -599,9 +598,9 @@ def test_combine_first(self, float_frame): combined = head.combine_first(tail) reordered_frame = float_frame.reindex(combined.index) - assert_frame_equal(combined, reordered_frame) + tm.assert_frame_equal(combined, reordered_frame) assert tm.equalContents(combined.columns, float_frame.columns) - assert_series_equal(combined["A"], reordered_frame["A"]) + tm.assert_series_equal(combined["A"], reordered_frame["A"]) # same index fcopy = float_frame.copy() @@ -615,9 +614,9 @@ def test_combine_first(self, float_frame): combined = fcopy.combine_first(fcopy2) assert (combined["A"] == 1).all() - assert_series_equal(combined["B"], fcopy["B"]) - assert_series_equal(combined["C"], fcopy2["C"]) - assert_series_equal(combined["D"], fcopy["D"]) + tm.assert_series_equal(combined["B"], fcopy["B"]) + tm.assert_series_equal(combined["C"], fcopy2["C"]) + tm.assert_series_equal(combined["D"], fcopy["D"]) # overlap head, tail = reordered_frame[:10].copy(), reordered_frame @@ -635,15 +634,15 @@ def test_combine_first(self, float_frame): f = float_frame[:10] g = float_frame[10:] combined = f.combine_first(g) - assert_series_equal(combined["A"].reindex(f.index), f["A"]) - assert_series_equal(combined["A"].reindex(g.index), g["A"]) + tm.assert_series_equal(combined["A"].reindex(f.index), f["A"]) + tm.assert_series_equal(combined["A"].reindex(g.index), g["A"]) # corner cases comb = float_frame.combine_first(DataFrame()) - assert_frame_equal(comb, float_frame) + tm.assert_frame_equal(comb, float_frame) comb = DataFrame().combine_first(float_frame) - assert_frame_equal(comb, float_frame) + tm.assert_frame_equal(comb, float_frame) comb = float_frame.combine_first(DataFrame(index=["faz", "boo"])) assert "faz" in comb.index @@ -680,12 +679,12 @@ def test_combine_first_mixed_bug(self): other = DataFrame([[45, 45]], index=[0], columns=["A", "B"]) result = df.combine_first(other) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df.loc[0, "A"] = np.nan result = df.combine_first(other) df.loc[0, "A"] = 45 - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # doc example df1 = DataFrame( @@ -701,7 +700,7 @@ def test_combine_first_mixed_bug(self): result = df1.combine_first(df2) expected = DataFrame({"A": [1, 2, 3, 5, 3, 7.0], "B": [np.nan, 2, 3, 4, 6, 8]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH3552, return object dtype with bools df1 = DataFrame( @@ -711,7 +710,7 @@ def test_combine_first_mixed_bug(self): result = df1.combine_first(df2)[2] expected = Series([True, True, False], name=2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 3593, converting datetime64[ns] incorrectly df0 = DataFrame( @@ -719,10 +718,10 @@ def test_combine_first_mixed_bug(self): ) df1 = DataFrame({"a": [None, None, None]}) df2 = df1.combine_first(df0) - assert_frame_equal(df2, df0) + tm.assert_frame_equal(df2, df0) df2 = df0.combine_first(df1) - assert_frame_equal(df2, df0) + tm.assert_frame_equal(df2, df0) df0 = DataFrame( {"a": [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)]} @@ -731,10 +730,10 @@ def test_combine_first_mixed_bug(self): df2 = df1.combine_first(df0) result = df0.copy() result.iloc[0, :] = df1.iloc[0, :] - assert_frame_equal(df2, result) + tm.assert_frame_equal(df2, result) df2 = df0.combine_first(df1) - assert_frame_equal(df2, df0) + tm.assert_frame_equal(df2, df0) def test_combine_first_align_nan(self): # GH 7509 (not fixed) diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 00be13b1c0e72..68844aeeb081e 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -20,11 +20,6 @@ ) from pandas.core.arrays import integer_array import pandas.util.testing as tm -from pandas.util.testing import ( - assert_frame_equal, - assert_series_equal, - makeCustomDataframe as mkdf, -) def _check_cast(df, v): @@ -53,35 +48,37 @@ def test_concat_empty_dataframe_dtypes(self): def test_empty_frame_dtypes_ftypes(self): empty_df = pd.DataFrame() - assert_series_equal(empty_df.dtypes, pd.Series(dtype=np.object)) + tm.assert_series_equal(empty_df.dtypes, pd.Series(dtype=np.object)) # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): - assert_series_equal(empty_df.ftypes, pd.Series(dtype=np.object)) + tm.assert_series_equal(empty_df.ftypes, pd.Series(dtype=np.object)) nocols_df = pd.DataFrame(index=[1, 2, 3]) - assert_series_equal(nocols_df.dtypes, pd.Series(dtype=np.object)) + tm.assert_series_equal(nocols_df.dtypes, pd.Series(dtype=np.object)) # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): - assert_series_equal(nocols_df.ftypes, pd.Series(dtype=np.object)) + tm.assert_series_equal(nocols_df.ftypes, pd.Series(dtype=np.object)) norows_df = pd.DataFrame(columns=list("abc")) - assert_series_equal(norows_df.dtypes, pd.Series(np.object, index=list("abc"))) + tm.assert_series_equal( + norows_df.dtypes, pd.Series(np.object, index=list("abc")) + ) # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): - assert_series_equal( + tm.assert_series_equal( norows_df.ftypes, pd.Series("object:dense", index=list("abc")) ) norows_int_df = pd.DataFrame(columns=list("abc")).astype(np.int32) - assert_series_equal( + tm.assert_series_equal( norows_int_df.dtypes, pd.Series(np.dtype("int32"), index=list("abc")) ) # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): - assert_series_equal( + tm.assert_series_equal( norows_int_df.ftypes, pd.Series("int32:dense", index=list("abc")) ) @@ -93,18 +90,18 @@ def test_empty_frame_dtypes_ftypes(self): ex_ftypes = pd.Series( odict([("a", "int64:dense"), ("b", "bool:dense"), ("c", "float64:dense")]) ) - assert_series_equal(df.dtypes, ex_dtypes) + tm.assert_series_equal(df.dtypes, ex_dtypes) # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): - assert_series_equal(df.ftypes, ex_ftypes) + tm.assert_series_equal(df.ftypes, ex_ftypes) # same but for empty slice of df - assert_series_equal(df[:0].dtypes, ex_dtypes) + tm.assert_series_equal(df[:0].dtypes, ex_dtypes) # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): - assert_series_equal(df[:0].ftypes, ex_ftypes) + tm.assert_series_equal(df[:0].ftypes, ex_ftypes) def test_datetime_with_tz_dtypes(self): tzframe = DataFrame( @@ -126,18 +123,20 @@ def test_datetime_with_tz_dtypes(self): ["A", "B", "C"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_dtypes_are_correct_after_column_slice(self): # GH6525 df = pd.DataFrame(index=range(5), columns=list("abc"), dtype=np.float_) odict = OrderedDict - assert_series_equal( + tm.assert_series_equal( df.dtypes, pd.Series(odict([("a", np.float_), ("b", np.float_), ("c", np.float_)])), ) - assert_series_equal(df.iloc[:, 2:].dtypes, pd.Series(odict([("c", np.float_)]))) - assert_series_equal( + tm.assert_series_equal( + df.iloc[:, 2:].dtypes, pd.Series(odict([("c", np.float_)])) + ) + tm.assert_series_equal( df.dtypes, pd.Series(odict([("a", np.float_), ("b", np.float_), ("c", np.float_)])), ) @@ -161,27 +160,27 @@ def test_select_dtypes_include_using_list_like(self): ri = df.select_dtypes(include=[np.number]) ei = df[["b", "c", "d", "k"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include=[np.number], exclude=["timedelta"]) ei = df[["b", "c", "d"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include=[np.number, "category"], exclude=["timedelta"]) ei = df[["b", "c", "d", "f"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include=["datetime"]) ei = df[["g"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include=["datetime64"]) ei = df[["g"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include=["datetimetz"]) ei = df[["h", "i"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) with pytest.raises(NotImplementedError, match=r"^$"): df.select_dtypes(include=["period"]) @@ -198,7 +197,7 @@ def test_select_dtypes_exclude_using_list_like(self): ) re = df.select_dtypes(exclude=[np.number]) ee = df[["a", "e"]] - assert_frame_equal(re, ee) + tm.assert_frame_equal(re, ee) def test_select_dtypes_exclude_include_using_list_like(self): df = DataFrame( @@ -215,13 +214,13 @@ def test_select_dtypes_exclude_include_using_list_like(self): include = np.bool_, "integer" r = df.select_dtypes(include=include, exclude=exclude) e = df[["b", "c", "e"]] - assert_frame_equal(r, e) + tm.assert_frame_equal(r, e) exclude = ("datetime",) include = "bool", "int64", "int32" r = df.select_dtypes(include=include, exclude=exclude) e = df[["b", "e"]] - assert_frame_equal(r, e) + tm.assert_frame_equal(r, e) def test_select_dtypes_include_using_scalars(self): df = DataFrame( @@ -242,19 +241,19 @@ def test_select_dtypes_include_using_scalars(self): ri = df.select_dtypes(include=np.number) ei = df[["b", "c", "d", "k"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include="datetime") ei = df[["g"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include="datetime64") ei = df[["g"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include="category") ei = df[["f"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) with pytest.raises(NotImplementedError, match=r"^$"): df.select_dtypes(include="period") @@ -278,11 +277,11 @@ def test_select_dtypes_exclude_using_scalars(self): ri = df.select_dtypes(exclude=np.number) ei = df[["a", "e", "f", "g", "h", "i", "j"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(exclude="category") ei = df[["a", "b", "c", "d", "e", "g", "h", "i", "j", "k"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) with pytest.raises(NotImplementedError, match=r"^$"): df.select_dtypes(exclude="period") @@ -306,7 +305,7 @@ def test_select_dtypes_include_exclude_using_scalars(self): ri = df.select_dtypes(include=np.number, exclude="floating") ei = df[["b", "c", "k"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) def test_select_dtypes_include_exclude_mixed_scalars_lists(self): df = DataFrame( @@ -327,11 +326,11 @@ def test_select_dtypes_include_exclude_mixed_scalars_lists(self): ri = df.select_dtypes(include=np.number, exclude=["floating", "timedelta"]) ei = df[["b", "c"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) ri = df.select_dtypes(include=[np.number, "category"], exclude="floating") ei = df[["b", "c", "f", "k"]] - assert_frame_equal(ri, ei) + tm.assert_frame_equal(ri, ei) def test_select_dtypes_duplicate_columns(self): # GH20839 @@ -355,7 +354,7 @@ def test_select_dtypes_duplicate_columns(self): ) result = df.select_dtypes(include=[np.number], exclude=["floating"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_select_dtypes_not_an_attr_but_still_valid_dtype(self): df = DataFrame( @@ -372,11 +371,11 @@ def test_select_dtypes_not_an_attr_but_still_valid_dtype(self): assert not hasattr(np, "u8") r = df.select_dtypes(include=["i8", "O"], exclude=["timedelta"]) e = df[["a", "b"]] - assert_frame_equal(r, e) + tm.assert_frame_equal(r, e) r = df.select_dtypes(include=["i8", "O", "timedelta64[ns]"]) e = df[["a", "b", "g"]] - assert_frame_equal(r, e) + tm.assert_frame_equal(r, e) def test_select_dtypes_empty(self): df = DataFrame({"a": list("abc"), "b": list(range(1, 4))}) @@ -413,7 +412,7 @@ def test_select_dtypes_datetime_with_tz(self): df3 = pd.concat([df2.A.to_frame(), df2.B.to_frame()], axis=1) result = df3.select_dtypes(include=["datetime64[ns]"]) expected = df3.reindex(columns=[]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype", [str, "str", np.string_, "S1", "unicode", np.unicode_, "U1"] @@ -456,10 +455,10 @@ def test_select_dtypes_bad_arg_raises(self): def test_select_dtypes_typecodes(self): # GH 11990 - df = mkdf(30, 3, data_gen_f=lambda x, y: np.random.random()) + df = tm.makeCustomDataframe(30, 3, data_gen_f=lambda x, y: np.random.random()) expected = df FLOAT_TYPES = list(np.typecodes["AllFloat"]) - assert_frame_equal(df.select_dtypes(FLOAT_TYPES), expected) + tm.assert_frame_equal(df.select_dtypes(FLOAT_TYPES), expected) def test_dtypes_gh8722(self, float_string_frame): float_string_frame["bool"] = float_string_frame["A"] > 0 @@ -467,13 +466,13 @@ def test_dtypes_gh8722(self, float_string_frame): expected = Series( {k: v.dtype for k, v in float_string_frame.items()}, index=result.index ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # compat, GH 8722 with option_context("use_inf_as_na", True): df = DataFrame([[1]]) result = df.dtypes - assert_series_equal(result, Series({0: np.dtype("int64")})) + tm.assert_series_equal(result, Series({0: np.dtype("int64")})) def test_ftypes(self, mixed_float_frame): frame = mixed_float_frame @@ -489,7 +488,7 @@ def test_ftypes(self, mixed_float_frame): # GH 26705 - Assert .ftypes is deprecated with tm.assert_produces_warning(FutureWarning): result = frame.ftypes.sort_values() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_astype_float(self, float_frame): casted = float_frame.astype(int) @@ -498,7 +497,7 @@ def test_astype_float(self, float_frame): index=float_frame.index, columns=float_frame.columns, ) - assert_frame_equal(casted, expected) + tm.assert_frame_equal(casted, expected) casted = float_frame.astype(np.int32) expected = DataFrame( @@ -506,7 +505,7 @@ def test_astype_float(self, float_frame): index=float_frame.index, columns=float_frame.columns, ) - assert_frame_equal(casted, expected) + tm.assert_frame_equal(casted, expected) float_frame["foo"] = "5" casted = float_frame.astype(int) @@ -515,7 +514,7 @@ def test_astype_float(self, float_frame): index=float_frame.index, columns=float_frame.columns, ) - assert_frame_equal(casted, expected) + tm.assert_frame_equal(casted, expected) def test_astype_mixed_float(self, mixed_float_frame): # mixed casting @@ -557,7 +556,7 @@ def test_astype_with_exclude_string(self, float_frame): casted = df.astype(int, errors="ignore") expected["string"] = "foo" - assert_frame_equal(casted, expected) + tm.assert_frame_equal(casted, expected) df = float_frame.copy() expected = float_frame.astype(np.int32) @@ -565,7 +564,7 @@ def test_astype_with_exclude_string(self, float_frame): casted = df.astype(np.int32, errors="ignore") expected["string"] = "foo" - assert_frame_equal(casted, expected) + tm.assert_frame_equal(casted, expected) def test_astype_with_view_float(self, float_frame): @@ -624,21 +623,21 @@ def test_astype_str(self): } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_astype_str_float(self): # see gh-11302 result = DataFrame([np.NaN]).astype(str) expected = DataFrame(["nan"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = DataFrame([1.12345678901234567890]).astype(str) # < 1.14 truncates # >= 1.14 preserves the full repr val = "1.12345678901" if _np_version_under1p14 else "1.1234567890123457" expected = DataFrame([val]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype_class", [dict, Series]) def test_astype_dict_like(self, dtype_class): @@ -661,8 +660,8 @@ def test_astype_dict_like(self, dtype_class): "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float32"), } ) - assert_frame_equal(result, expected) - assert_frame_equal(df, original) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, original) dt2 = dtype_class({"b": np.float32, "c": "float32", "d": np.float64}) result = df.astype(dt2) @@ -674,13 +673,13 @@ def test_astype_dict_like(self, dtype_class): "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float64"), } ) - assert_frame_equal(result, expected) - assert_frame_equal(df, original) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(df, original) # change all columns dt3 = dtype_class({"a": str, "b": str, "c": str, "d": str}) - assert_frame_equal(df.astype(dt3), df.astype(str)) - assert_frame_equal(df, original) + tm.assert_frame_equal(df.astype(dt3), df.astype(str)) + tm.assert_frame_equal(df, original) # error should be raised when using something other than column labels # in the keys of the dtype dict @@ -691,22 +690,22 @@ def test_astype_dict_like(self, dtype_class): df.astype(dt4) with pytest.raises(KeyError, match=msg): df.astype(dt5) - assert_frame_equal(df, original) + tm.assert_frame_equal(df, original) # if the dtypes provided are the same as the original dtypes, the # resulting DataFrame should be the same as the original DataFrame dt6 = dtype_class({col: df[col].dtype for col in df.columns}) equiv = df.astype(dt6) - assert_frame_equal(df, equiv) - assert_frame_equal(df, original) + tm.assert_frame_equal(df, equiv) + tm.assert_frame_equal(df, original) # GH 16717 # if dtypes provided is empty, the resulting DataFrame # should be the same as the original DataFrame dt7 = dtype_class({}) result = df.astype(dt7) - assert_frame_equal(df, equiv) - assert_frame_equal(df, original) + tm.assert_frame_equal(df, equiv) + tm.assert_frame_equal(df, original) def test_astype_duplicate_col(self): a1 = Series([1, 2, 3, 4, 5], name="a") @@ -719,11 +718,11 @@ def test_astype_duplicate_col(self): b_str = Series(["0.1", "0.2", "0.4", "0.6", "0.8"], dtype=str, name="b") a2_str = Series(["0", "1", "2", "3", "4"], dtype="str", name="a") expected = concat([a1_str, b_str, a2_str], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.astype({"a": "str"}) expected = concat([a1_str, b, a2_str], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype", @@ -814,7 +813,7 @@ def test_astype_extension_dtypes_duplicate_col(self, dtype): result = df.astype(dtype) expected = concat([a1.astype(dtype), a2.astype(dtype)], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype", [{100: "float64", 200: "uint64"}, "category", "float64"] @@ -926,7 +925,7 @@ def test_timedeltas(self): expected = Series( [np.dtype("datetime64[ns]"), np.dtype("timedelta64[ns]")], index=list("AB") ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df["C"] = df["A"] + df["B"] result = df.dtypes @@ -938,7 +937,7 @@ def test_timedeltas(self): ], index=list("ABC"), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # mixed int types df["D"] = 1 @@ -952,7 +951,7 @@ def test_timedeltas(self): ], index=list("ABCD"), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_arg_for_errors_in_astype(self): # issue #14878 @@ -1001,13 +1000,13 @@ def test_constructor_list_str(self, input_vals, string_dtype): result = DataFrame({"A": input_vals}, dtype=string_dtype) expected = DataFrame({"A": input_vals}).astype({"A": string_dtype}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_constructor_list_str_na(self, string_dtype): result = DataFrame({"A": [1.0, 2.0, None]}, dtype=string_dtype) expected = DataFrame({"A": ["1.0", "2.0", None]}, dtype=object) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "data, expected", @@ -1146,7 +1145,7 @@ def test_astype(self, timezone_frame): dtype=object, ) result = timezone_frame.astype(object) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = timezone_frame.astype("datetime64[ns]") expected = DataFrame( @@ -1166,7 +1165,7 @@ def test_astype(self, timezone_frame): ) expected.iloc[1, 1] = pd.NaT expected.iloc[1, 2] = pd.NaT - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_astype_str(self, timezone_frame): # str formatting
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29300
2019-10-30T23:24:58Z
2019-10-31T07:59:32Z
2019-10-31T07:59:32Z
2019-10-31T07:59:35Z
CLN: Consistent pandas.util.testing imports in pandas/tests/io
diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 79fc87a62ad08..e9b4a5d4e430d 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -1,7 +1,7 @@ import pytest from pandas import DataFrame -from pandas.util.testing import ensure_clean +import pandas.util.testing as tm from pandas.io.excel import ExcelWriter, _OpenpyxlWriter @@ -65,7 +65,7 @@ def test_write_cells_merge_styled(ext): ) ] - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: writer = _OpenpyxlWriter(path) writer.write_cells(initial_cells, sheet_name=sheet_name) writer.write_cells(merge_cells, sheet_name=sheet_name) @@ -83,7 +83,7 @@ def test_write_cells_merge_styled(ext): def test_write_append_mode(ext, mode, expected): df = DataFrame([1], columns=["baz"]) - with ensure_clean(ext) as f: + with tm.ensure_clean(ext) as f: wb = openpyxl.Workbook() wb.worksheets[0].title = "foo" wb.worksheets[0]["A1"].value = "foo" diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index 8862f85ae9ab4..41363bf13ed4e 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -2,7 +2,7 @@ import pytest from pandas import DataFrame -from pandas.util.testing import ensure_clean +import pandas.util.testing as tm from pandas.io.excel import ExcelWriter from pandas.io.formats.excel import ExcelFormatter @@ -70,7 +70,7 @@ def custom_converter(css): # Prepare spreadsheets df = DataFrame(np.random.randn(11, 3)) - with ensure_clean(".xlsx" if engine != "xlwt" else ".xls") as path: + with tm.ensure_clean(".xlsx" if engine != "xlwt" else ".xls") as path: writer = ExcelWriter(path, engine=engine) df.to_excel(writer, sheet_name="frame") df.style.to_excel(writer, sheet_name="unstyled") diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 793f11c62f9f5..1bc4ad3e7867a 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -12,7 +12,6 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, get_option, set_option import pandas.util.testing as tm -from pandas.util.testing import ensure_clean, makeCustomDataframe as mkdf from pandas.io.excel import ( ExcelFile, @@ -29,7 +28,7 @@ def path(ext): """ Fixture to open file for use in each test case. """ - with ensure_clean(ext) as file_path: + with tm.ensure_clean(ext) as file_path: yield file_path @@ -64,7 +63,7 @@ def test_read_one_empty_col_no_header(self, ext, header, expected): filename = "no_header" df = pd.DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: df.to_excel(path, filename, index=False, header=False) result = pd.read_excel(path, filename, usecols=[0], header=header) @@ -80,7 +79,7 @@ def test_read_one_empty_col_with_header(self, ext, header, expected): filename = "with_header" df = pd.DataFrame([["", 1, 100], ["", 2, 200], ["", 3, 300], ["", 4, 400]]) - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: df.to_excel(path, "with_header", index=False, header=True) result = pd.read_excel(path, filename, usecols=[0], header=header) @@ -93,7 +92,7 @@ def test_set_column_names_in_parameter(self, ext): # keyword argument names refdf = pd.DataFrame([[1, "foo"], [2, "bar"], [3, "baz"]], columns=["a", "b"]) - with ensure_clean(ext) as pth: + with tm.ensure_clean(ext) as pth: with ExcelWriter(pth) as writer: refdf.to_excel(writer, "Data_no_head", header=False, index=False) refdf.to_excel(writer, "Data_with_head", index=False) @@ -127,7 +126,7 @@ def tdf(col_sheet_name): dfs = [tdf(s) for s in sheets] dfs = dict(zip(sheets, dfs)) - with ensure_clean(ext) as pth: + with tm.ensure_clean(ext) as pth: with ExcelWriter(pth) as ew: for sheetname, df in dfs.items(): df.to_excel(ew, sheetname) @@ -140,7 +139,7 @@ def tdf(col_sheet_name): @td.skip_if_no("xlsxwriter") def test_read_excel_multiindex_empty_level(self, ext): # see gh-12453 - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: df = DataFrame( { ("One", "x"): {0: 1}, @@ -194,7 +193,7 @@ def test_excel_multindex_roundtrip( self, ext, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels ): # see gh-4679 - with ensure_clean(ext) as pth: + with tm.ensure_clean(ext) as pth: if c_idx_levels == 1 and c_idx_names: pytest.skip( "Column index name cannot be serialized unless it's a MultiIndex" @@ -204,7 +203,9 @@ def test_excel_multindex_roundtrip( # unnamed levels, not Nones. check_names = r_idx_names or r_idx_levels <= 1 - df = mkdf(5, 5, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels) + df = tm.makeCustomDataframe( + 5, 5, c_idx_names, r_idx_names, c_idx_levels, r_idx_levels + ) df.to_excel(pth) act = pd.read_excel( @@ -243,7 +244,7 @@ def test_read_excel_parse_dates(self, ext): df2 = df.copy() df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y") - with ensure_clean(ext) as pth: + with tm.ensure_clean(ext) as pth: df2.to_excel(pth) res = pd.read_excel(pth, index_col=0) @@ -581,7 +582,7 @@ def test_excel_date_datetime_format(self, engine, ext, path): columns=["X", "Y"], ) - with ensure_clean(ext) as filename2: + with tm.ensure_clean(ext) as filename2: writer1 = ExcelWriter(path) writer2 = ExcelWriter( filename2, @@ -778,13 +779,13 @@ def test_to_excel_output_encoding(self, ext): columns=["X\u0193", "Y", "Z"], ) - with ensure_clean("__tmp_to_excel_float_format__." + ext) as filename: + with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename: df.to_excel(filename, sheet_name="TestSheet", encoding="utf8") result = pd.read_excel(filename, "TestSheet", encoding="utf8", index_col=0) tm.assert_frame_equal(result, df) def test_to_excel_unicode_filename(self, ext, path): - with ensure_clean("\u0192u." + ext) as filename: + with tm.ensure_clean("\u0192u." + ext) as filename: try: f = open(filename, "wb") except UnicodeEncodeError: @@ -932,12 +933,10 @@ def roundtrip(data, header=True, parser_hdr=0, index=True): nrows = 5 ncols = 3 - from pandas.util.testing import makeCustomDataframe as mkdf - # ensure limited functionality in 0.10 # override of gh-2370 until sorted out in 0.11 - df = mkdf( + df = tm.makeCustomDataframe( nrows, ncols, r_idx_nlevels=r_idx_nlevels, c_idx_nlevels=c_idx_nlevels ) @@ -1216,7 +1215,7 @@ class TestExcelWriterEngineTests: ], ) def test_ExcelWriter_dispatch(self, klass, ext): - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: writer = ExcelWriter(path) if ext == ".xlsx" and td.safe_import("xlsxwriter"): # xlsxwriter has preference over openpyxl if both installed diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index c4d99c827318d..fc36be9e1b738 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -2,7 +2,6 @@ import pandas as pd import pandas.util.testing as tm -from pandas.util.testing import ensure_clean from pandas.io.excel import ExcelFile @@ -22,7 +21,7 @@ def test_read_xlrd_book(read_ext, frame): engine = "xlrd" sheet_name = "SheetA" - with ensure_clean(read_ext) as pth: + with tm.ensure_clean(read_ext) as pth: df.to_excel(pth, sheet_name) book = xlrd.open_workbook(pth) diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index 63e41c59ecb89..deb72cc230669 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -3,7 +3,7 @@ import pytest from pandas import DataFrame -from pandas.util.testing import ensure_clean +import pandas.util.testing as tm from pandas.io.excel import ExcelWriter @@ -20,7 +20,7 @@ def test_column_format(ext): warnings.simplefilter("ignore") openpyxl = pytest.importorskip("openpyxl") - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: frame = DataFrame({"A": [123456, 123456], "B": [123456, 123456]}) writer = ExcelWriter(path) @@ -59,6 +59,6 @@ def test_column_format(ext): def test_write_append_mode_raises(ext): msg = "Append mode is not supported with xlsxwriter!" - with ensure_clean(ext) as f: + with tm.ensure_clean(ext) as f: with pytest.raises(ValueError, match=msg): ExcelWriter(f, engine="xlsxwriter", mode="a") diff --git a/pandas/tests/io/excel/test_xlwt.py b/pandas/tests/io/excel/test_xlwt.py index 51f94a2f01b84..c6af78c2704d8 100644 --- a/pandas/tests/io/excel/test_xlwt.py +++ b/pandas/tests/io/excel/test_xlwt.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import DataFrame, MultiIndex -from pandas.util.testing import ensure_clean +import pandas.util.testing as tm from pandas.io.excel import ExcelWriter, _XlwtWriter @@ -19,7 +19,7 @@ def test_excel_raise_error_on_multiindex_columns_and_no_index(ext): ) df = DataFrame(np.random.randn(10, 3), columns=cols) with pytest.raises(NotImplementedError): - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: df.to_excel(path, index=False) @@ -28,7 +28,7 @@ def test_excel_multiindex_columns_and_index_true(ext): [("site", ""), ("2014", "height"), ("2014", "weight")] ) df = pd.DataFrame(np.random.randn(10, 3), columns=cols) - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: df.to_excel(path, index=True) @@ -38,7 +38,7 @@ def test_excel_multiindex_index(ext): [("site", ""), ("2014", "height"), ("2014", "weight")] ) df = DataFrame(np.random.randn(3, 10), index=cols) - with ensure_clean(ext) as path: + with tm.ensure_clean(ext) as path: df.to_excel(path, index=False) @@ -62,6 +62,6 @@ def test_to_excel_styleconverter(ext): def test_write_append_mode_raises(ext): msg = "Append mode is not supported with xlwt!" - with ensure_clean(ext) as f: + with tm.ensure_clean(ext) as f: with pytest.raises(ValueError, match=msg): ExcelWriter(f, engine="xlwt", mode="a") diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index 56be84bccc51a..adbb9dfbd2ddf 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -4,7 +4,6 @@ import pandas as pd import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal def test_compression_roundtrip(compression): @@ -16,12 +15,12 @@ def test_compression_roundtrip(compression): with tm.ensure_clean() as path: df.to_json(path, compression=compression) - assert_frame_equal(df, pd.read_json(path, compression=compression)) + tm.assert_frame_equal(df, pd.read_json(path, compression=compression)) # explicitly ensure file was compressed. with tm.decompress_file(path, compression) as fh: result = fh.read().decode("utf8") - assert_frame_equal(df, pd.read_json(result)) + tm.assert_frame_equal(df, pd.read_json(result)) def test_read_zipped_json(datapath): @@ -31,7 +30,7 @@ def test_read_zipped_json(datapath): compressed_path = datapath("io", "json", "data", "tsframe_v012.json.zip") compressed_df = pd.read_json(compressed_path, compression="zip") - assert_frame_equal(uncompressed_df, compressed_df) + tm.assert_frame_equal(uncompressed_df, compressed_df) @td.skip_if_not_us_locale @@ -46,7 +45,7 @@ def test_with_s3_url(compression, s3_resource): s3_resource.Bucket("pandas-test").put_object(Key="test-1", Body=f) roundtripped_df = pd.read_json("s3://pandas-test/test-1", compression=compression) - assert_frame_equal(df, roundtripped_df) + tm.assert_frame_equal(df, roundtripped_df) def test_lines_with_compression(compression): @@ -55,7 +54,7 @@ def test_lines_with_compression(compression): df = pd.read_json('{"a": [1, 2, 3], "b": [4, 5, 6]}') df.to_json(path, orient="records", lines=True, compression=compression) roundtripped_df = pd.read_json(path, lines=True, compression=compression) - assert_frame_equal(df, roundtripped_df) + tm.assert_frame_equal(df, roundtripped_df) def test_chunksize_with_compression(compression): @@ -66,7 +65,7 @@ def test_chunksize_with_compression(compression): res = pd.read_json(path, lines=True, chunksize=1, compression=compression) roundtripped_df = pd.concat(res) - assert_frame_equal(df, roundtripped_df) + tm.assert_frame_equal(df, roundtripped_df) def test_write_unsupported_compression_type(): diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 8e28740c70bad..eaa46c4e9dc9b 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -13,12 +13,6 @@ import pandas as pd from pandas import DataFrame, DatetimeIndex, Series, Timestamp, read_json import pandas.util.testing as tm -from pandas.util.testing import ( - assert_frame_equal, - assert_series_equal, - ensure_clean, - network, -) _seriesd = tm.getSeriesData() _tsd = tm.getTimeSeriesData() @@ -42,7 +36,7 @@ def assert_json_roundtrip_equal(result, expected, orient): expected = expected.reset_index(drop=True) if orient == "values": expected.columns = range(len(expected.columns)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) class TestPandasContainer: @@ -142,7 +136,7 @@ def test_frame_non_unique_columns(self, orient, data): elif orient == "split": expected = df - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("orient", ["index", "columns", "records"]) def test_frame_non_unique_columns_raises(self, orient): @@ -425,7 +419,7 @@ def test_frame_to_json_except(self): def test_frame_empty(self): df = DataFrame(columns=["jim", "joe"]) assert not df._is_mixed_type - assert_frame_equal( + tm.assert_frame_equal( read_json(df.to_json(), dtype=dict(df.dtypes)), df, check_index_type=False ) # GH 7445 @@ -438,7 +432,7 @@ def test_frame_empty_mixedtype(self): df = DataFrame(columns=["jim", "joe"]) df["joe"] = df["joe"].astype("i8") assert df._is_mixed_type - assert_frame_equal( + tm.assert_frame_equal( read_json(df.to_json(), dtype=dict(df.dtypes)), df, check_index_type=False ) @@ -460,17 +454,17 @@ def test_frame_mixedtype_orient(self): # GH10289 for orient in ["split", "index", "columns"]: inp = df.to_json(orient=orient) left = read_json(inp, orient=orient, convert_axes=False) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) right.index = np.arange(len(df)) inp = df.to_json(orient="records") left = read_json(inp, orient="records", convert_axes=False) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) right.columns = np.arange(df.shape[1]) inp = df.to_json(orient="values") left = read_json(inp, orient="values", convert_axes=False) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) def test_v12_compat(self): df = DataFrame( @@ -491,12 +485,12 @@ def test_v12_compat(self): v12_json = os.path.join(self.dirpath, "tsframe_v012.json") df_unser = pd.read_json(v12_json) - assert_frame_equal(df, df_unser) + tm.assert_frame_equal(df, df_unser) df_iso = df.drop(["modified"], axis=1) v12_iso_json = os.path.join(self.dirpath, "tsframe_iso_v012.json") df_unser_iso = pd.read_json(v12_iso_json) - assert_frame_equal(df_iso, df_unser_iso) + tm.assert_frame_equal(df_iso, df_unser_iso) def test_blocks_compat_GH9037(self): index = pd.date_range("20000101", periods=10, freq="H") @@ -582,7 +576,7 @@ def test_blocks_compat_GH9037(self): df_mixed.columns = df_mixed.columns.astype("unicode") df_roundtrip = pd.read_json(df_mixed.to_json(orient="split"), orient="split") - assert_frame_equal( + tm.assert_frame_equal( df_mixed, df_roundtrip, check_index_type=True, @@ -643,7 +637,7 @@ def test_series_non_unique_index(self): with pytest.raises(ValueError, match=msg): s.to_json(orient="index") - assert_series_equal( + tm.assert_series_equal( s, read_json(s.to_json(orient="split"), orient="split", typ="series") ) unser = read_json(s.to_json(orient="records"), orient="records", typ="series") @@ -736,14 +730,14 @@ def test_series_to_json_except(self): def test_series_from_json_precise_float(self): s = Series([4.56, 4.56, 4.56]) result = read_json(s.to_json(), typ="series", precise_float=True) - assert_series_equal(result, s, check_index_type=False) + tm.assert_series_equal(result, s, check_index_type=False) def test_series_with_dtype(self): # GH 21986 s = Series([4.56, 4.56, 4.56]) result = read_json(s.to_json(), typ="series", dtype=np.int64) expected = Series([4] * 3) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "dtype,expected", @@ -756,32 +750,34 @@ def test_series_with_dtype_datetime(self, dtype, expected): s = Series(["2000-01-01"], dtype="datetime64[ns]") data = s.to_json() result = pd.read_json(data, typ="series", dtype=dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_frame_from_json_precise_float(self): df = DataFrame([[4.56, 4.56, 4.56], [4.56, 4.56, 4.56]]) result = read_json(df.to_json(), precise_float=True) - assert_frame_equal(result, df, check_index_type=False, check_column_type=False) + tm.assert_frame_equal( + result, df, check_index_type=False, check_column_type=False + ) def test_typ(self): s = Series(range(6), index=["a", "b", "c", "d", "e", "f"], dtype="int64") result = read_json(s.to_json(), typ=None) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) def test_reconstruction_index(self): df = DataFrame([[1, 2, 3], [4, 5, 6]]) result = read_json(df.to_json()) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=["A", "B", "C"]) result = read_json(df.to_json()) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_path(self): - with ensure_clean("test.json") as path: + with tm.ensure_clean("test.json") as path: for df in [ self.frame, self.frame2, @@ -797,12 +793,12 @@ def test_axis_dates(self): # frame json = self.tsframe.to_json() result = read_json(json) - assert_frame_equal(result, self.tsframe) + tm.assert_frame_equal(result, self.tsframe) # series json = self.ts.to_json() result = read_json(json, typ="series") - assert_series_equal(result, self.ts, check_names=False) + tm.assert_series_equal(result, self.ts, check_names=False) assert result.name is None def test_convert_dates(self): @@ -813,7 +809,7 @@ def test_convert_dates(self): json = df.to_json() result = read_json(json) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df["foo"] = 1.0 json = df.to_json(date_unit="ns") @@ -822,13 +818,13 @@ def test_convert_dates(self): expected = df.copy() expected["date"] = expected["date"].values.view("i8") expected["foo"] = expected["foo"].astype("int64") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # series ts = Series(Timestamp("20130101"), index=self.ts.index) json = ts.to_json() result = read_json(json, typ="series") - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) @pytest.mark.parametrize( "infer_word", @@ -851,7 +847,7 @@ def test_convert_dates_infer(self, infer_word): [[1, Timestamp("2002-11-08")], [2, pd.NaT]], columns=["id", infer_word] ) result = read_json(dumps(data))[["id", infer_word]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "date,date_unit", @@ -877,7 +873,7 @@ def test_date_format_frame(self, date, date_unit): expected = df.copy() # expected.index = expected.index.tz_localize("UTC") expected["date"] = expected["date"].dt.tz_localize("UTC") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_date_format_frame_raises(self): df = self.tsframe.copy() @@ -907,7 +903,7 @@ def test_date_format_series(self, date, date_unit): expected = ts.copy() # expected.index = expected.index.tz_localize("UTC") expected = expected.dt.tz_localize("UTC") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_date_format_series_raises(self): ts = Series(Timestamp("20130101 20:43:42.123"), index=self.ts.index) @@ -928,11 +924,11 @@ def test_date_unit(self, unit): # force date unit result = read_json(json, date_unit=unit) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # detect date unit result = read_json(json, date_unit=None) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_weird_nested_json(self): # this used to core dump the parser @@ -965,7 +961,7 @@ def test_doc_example(self): json = dfj2.to_json() result = read_json(json, dtype={"ints": np.int64, "bools": np.bool_}) - assert_frame_equal(result, result) + tm.assert_frame_equal(result, result) def test_misc_example(self): @@ -979,13 +975,13 @@ def test_misc_example(self): \\[left\\]: Index\\(\\['a', 'b'\\], dtype='object'\\) \\[right\\]: RangeIndex\\(start=0, stop=2, step=1\\)""" with pytest.raises(AssertionError, match=error_msg): - assert_frame_equal(result, expected, check_index_type=False) + tm.assert_frame_equal(result, expected, check_index_type=False) result = read_json('[{"a": 1, "b": 2}, {"b":2, "a" :1}]') expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) - @network + @tm.network @pytest.mark.single def test_round_trip_exception_(self): # GH 3867 @@ -993,9 +989,9 @@ def test_round_trip_exception_(self): df = pd.read_csv(csv) s = df.to_json() result = pd.read_json(s) - assert_frame_equal(result.reindex(index=df.index, columns=df.columns), df) + tm.assert_frame_equal(result.reindex(index=df.index, columns=df.columns), df) - @network + @tm.network @pytest.mark.single @pytest.mark.parametrize( "field,dtype", @@ -1017,16 +1013,16 @@ def test_timedelta(self): assert s.dtype == "timedelta64[ns]" result = pd.read_json(s.to_json(), typ="series").apply(converter) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) s = Series([timedelta(23), timedelta(seconds=5)], index=pd.Index([0, 1])) assert s.dtype == "timedelta64[ns]" result = pd.read_json(s.to_json(), typ="series").apply(converter) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) frame = DataFrame([timedelta(23), timedelta(seconds=5)]) assert frame[0].dtype == "timedelta64[ns]" - assert_frame_equal(frame, pd.read_json(frame.to_json()).apply(converter)) + tm.assert_frame_equal(frame, pd.read_json(frame.to_json()).apply(converter)) frame = DataFrame( { @@ -1039,7 +1035,7 @@ def test_timedelta(self): result = pd.read_json(frame.to_json(date_unit="ns")) result["a"] = pd.to_timedelta(result.a, unit="ns") result["c"] = pd.to_datetime(result.c) - assert_frame_equal(frame, result) + tm.assert_frame_equal(frame, result) def test_mixed_timedelta_datetime(self): frame = DataFrame( @@ -1050,14 +1046,14 @@ def test_mixed_timedelta_datetime(self): {"a": [pd.Timedelta(frame.a[0]).value, pd.Timestamp(frame.a[1]).value]} ) result = pd.read_json(frame.to_json(date_unit="ns"), dtype={"a": "int64"}) - assert_frame_equal(result, expected, check_index_type=False) + tm.assert_frame_equal(result, expected, check_index_type=False) def test_default_handler(self): value = object() frame = DataFrame({"a": [7, value]}) expected = DataFrame({"a": [7, str(value)]}) result = pd.read_json(frame.to_json(default_handler=str)) - assert_frame_equal(expected, result, check_index_type=False) + tm.assert_frame_equal(expected, result, check_index_type=False) def test_default_handler_indirect(self): from pandas.io.json import dumps @@ -1199,7 +1195,7 @@ def test_read_inline_jsonl(self): # GH9180 result = read_json('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n', lines=True) expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @td.skip_if_not_us_locale def test_read_s3_jsonl(self, s3_resource): @@ -1207,16 +1203,16 @@ def test_read_s3_jsonl(self, s3_resource): result = read_json("s3n://pandas-test/items.jsonl", lines=True) expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_local_jsonl(self): # GH17200 - with ensure_clean("tmp_items.json") as path: + with tm.ensure_clean("tmp_items.json") as path: with open(path, "w") as infile: infile.write('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n') result = read_json(path, lines=True) expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_jsonl_unicode_chars(self): # GH15132: non-ascii unicode characters @@ -1227,13 +1223,13 @@ def test_read_jsonl_unicode_chars(self): json = StringIO(json) result = read_json(json, lines=True) expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # simulate string json = '{"a": "foo”", "b": "bar"}\n{"a": "foo", "b": "bar"}\n' result = read_json(json, lines=True) expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_json_large_numbers(self): # GH18842 @@ -1241,13 +1237,13 @@ def test_read_json_large_numbers(self): json = StringIO(json) result = read_json(json, typ="series") expected = Series(1.404366e21, index=["articleId"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) json = '{"0": {"articleId": "1404366058080022500245"}}' json = StringIO(json) result = read_json(json) expected = DataFrame(1.404366e21, index=["articleId"], columns=[0]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_to_jsonl(self): # GH9180 @@ -1260,14 +1256,14 @@ def test_to_jsonl(self): result = df.to_json(orient="records", lines=True) expected = '{"a":"foo}","b":"bar"}\n{"a":"foo\\"","b":"bar"}' assert result == expected - assert_frame_equal(pd.read_json(result, lines=True), df) + tm.assert_frame_equal(pd.read_json(result, lines=True), df) # GH15096: escaped characters in columns and data df = DataFrame([["foo\\", "bar"], ['foo"', "bar"]], columns=["a\\", "b"]) result = df.to_json(orient="records", lines=True) expected = '{"a\\\\":"foo\\\\","b":"bar"}\n' '{"a\\\\":"foo\\"","b":"bar"}' assert result == expected - assert_frame_equal(pd.read_json(result, lines=True), df) + tm.assert_frame_equal(pd.read_json(result, lines=True), df) # TODO: there is a near-identical test for pytables; can we share? def test_latin_encoding(self): @@ -1297,10 +1293,10 @@ def test_latin_encoding(self): examples.append(Series(val, dtype=dtype)) def roundtrip(s, encoding="latin-1"): - with ensure_clean("test.json") as path: + with tm.ensure_clean("test.json") as path: s.to_json(path, encoding=encoding) retr = read_json(path, encoding=encoding) - assert_series_equal(s, retr, check_categorical=False) + tm.assert_series_equal(s, retr, check_categorical=False) for s in examples: roundtrip(s) @@ -1324,14 +1320,14 @@ def test_from_json_to_json_table_index_and_columns(self, index, columns): expected = DataFrame([[1, 2], [3, 4]], index=index, columns=columns) dfjson = expected.to_json(orient="table") result = pd.read_json(dfjson, orient="table") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_from_json_to_json_table_dtypes(self): # GH21345 expected = pd.DataFrame({"a": [1, 2], "b": [3.0, 4.0], "c": ["5", "6"]}) dfjson = expected.to_json(orient="table") result = pd.read_json(dfjson, orient="table") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", [True, {"b": int, "c": int}]) def test_read_json_table_dtype_raises(self, dtype): @@ -1435,7 +1431,7 @@ def test_index_false_from_json_to_json(self, orient, index): expected = DataFrame({"a": [1, 2], "b": [3, 4]}) dfjson = expected.to_json(orient=orient, index=index) result = read_json(dfjson, orient=orient) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_timezone_information(self): # GH 25546 @@ -1443,7 +1439,7 @@ def test_read_timezone_information(self): '{"2019-01-01T11:00:00.000Z":88}', typ="series", orient="index" ) expected = Series([88], index=DatetimeIndex(["2019-01-01 11:00:00"], tz="UTC")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "date_format,key", [("epoch", 86400000), ("iso", "P1DT0H0M0S")] diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py index 821bf0287c6f1..05f97a1769205 100644 --- a/pandas/tests/io/json/test_readlines.py +++ b/pandas/tests/io/json/test_readlines.py @@ -5,7 +5,6 @@ import pandas as pd from pandas import DataFrame, read_json import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal, ensure_clean from pandas.io.json._json import JsonReader @@ -20,7 +19,7 @@ def test_read_jsonl(): # GH9180 result = read_json('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n', lines=True) expected = DataFrame([[1, 2], [1, 2]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_jsonl_unicode_chars(): @@ -32,13 +31,13 @@ def test_read_jsonl_unicode_chars(): json = StringIO(json) result = read_json(json, lines=True) expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # simulate string json = '{"a": "foo”", "b": "bar"}\n{"a": "foo", "b": "bar"}\n' result = read_json(json, lines=True) expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_to_jsonl(): @@ -52,14 +51,14 @@ def test_to_jsonl(): result = df.to_json(orient="records", lines=True) expected = '{"a":"foo}","b":"bar"}\n{"a":"foo\\"","b":"bar"}' assert result == expected - assert_frame_equal(read_json(result, lines=True), df) + tm.assert_frame_equal(read_json(result, lines=True), df) # GH15096: escaped characters in columns and data df = DataFrame([["foo\\", "bar"], ['foo"', "bar"]], columns=["a\\", "b"]) result = df.to_json(orient="records", lines=True) expected = '{"a\\\\":"foo\\\\","b":"bar"}\n' '{"a\\\\":"foo\\"","b":"bar"}' assert result == expected - assert_frame_equal(read_json(result, lines=True), df) + tm.assert_frame_equal(read_json(result, lines=True), df) @pytest.mark.parametrize("chunksize", [1, 1.0]) @@ -72,7 +71,7 @@ def test_readjson_chunks(lines_json_df, chunksize): reader = read_json(StringIO(lines_json_df), lines=True, chunksize=chunksize) chunked = pd.concat(reader) - assert_frame_equal(chunked, unchunked) + tm.assert_frame_equal(chunked, unchunked) def test_readjson_chunksize_requires_lines(lines_json_df): @@ -91,7 +90,7 @@ def test_readjson_chunks_series(): strio = StringIO(s.to_json(lines=True, orient="records")) chunked = pd.concat(pd.read_json(strio, lines=True, typ="Series", chunksize=1)) - assert_series_equal(chunked, unchunked) + tm.assert_series_equal(chunked, unchunked) def test_readjson_each_chunk(lines_json_df): @@ -103,17 +102,17 @@ def test_readjson_each_chunk(lines_json_df): def test_readjson_chunks_from_file(): - with ensure_clean("test.json") as path: + with tm.ensure_clean("test.json") as path: df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) df.to_json(path, lines=True, orient="records") chunked = pd.concat(pd.read_json(path, lines=True, chunksize=1)) unchunked = pd.read_json(path, lines=True) - assert_frame_equal(unchunked, chunked) + tm.assert_frame_equal(unchunked, chunked) @pytest.mark.parametrize("chunksize", [None, 1]) def test_readjson_chunks_closes(chunksize): - with ensure_clean("test.json") as path: + with tm.ensure_clean("test.json") as path: df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) df.to_json(path, lines=True, orient="records") reader = JsonReader( diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index 9afeaf75f4da3..75a5b7cd53ddb 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -13,7 +13,6 @@ from pandas import DataFrame import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal from pandas.io.parsers import TextFileReader, read_csv @@ -323,19 +322,19 @@ def test_empty_field_eof(self): for _ in range(100): df = read_csv(StringIO("a,b\nc\n"), skiprows=0, names=["a"], engine="c") - assert_frame_equal(df, a) + tm.assert_frame_equal(df, a) df = read_csv( StringIO("1,1,1,1,0\n" * 2 + "\n" * 2), names=list("abcd"), engine="c" ) - assert_frame_equal(df, b) + tm.assert_frame_equal(df, b) df = read_csv( StringIO("0,1,2,3,4\n5,6\n7,8,9,10,11\n12,13,14"), names=list("abcd"), engine="c", ) - assert_frame_equal(df, c) + tm.assert_frame_equal(df, c) def test_empty_csv_input(self): # GH14867 diff --git a/pandas/tests/io/pytables/test_compat.py b/pandas/tests/io/pytables/test_compat.py index fe8d8c56a4e82..1e320e12a4a53 100644 --- a/pandas/tests/io/pytables/test_compat.py +++ b/pandas/tests/io/pytables/test_compat.py @@ -2,7 +2,7 @@ import pandas as pd from pandas.tests.io.pytables.common import ensure_clean_path -from pandas.util.testing import assert_frame_equal +import pandas.util.testing as tm tables = pytest.importorskip("tables") @@ -52,25 +52,25 @@ def test_read_complete(self, pytables_hdf5_file): path, objname, df = pytables_hdf5_file result = pd.read_hdf(path, key=objname) expected = df - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_with_start(self, pytables_hdf5_file): path, objname, df = pytables_hdf5_file # This is a regression test for pandas-dev/pandas/issues/11188 result = pd.read_hdf(path, key=objname, start=1) expected = df[1:].reset_index(drop=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_with_stop(self, pytables_hdf5_file): path, objname, df = pytables_hdf5_file # This is a regression test for pandas-dev/pandas/issues/11188 result = pd.read_hdf(path, key=objname, stop=1) expected = df[:1].reset_index(drop=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_with_startstop(self, pytables_hdf5_file): path, objname, df = pytables_hdf5_file # This is a regression test for pandas-dev/pandas/issues/11188 result = pd.read_hdf(path, key=objname, start=1, stop=2) expected = df[1:2].reset_index(drop=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py index e48cfb724ef1d..91ee1061a5ef1 100644 --- a/pandas/tests/io/pytables/test_complex.py +++ b/pandas/tests/io/pytables/test_complex.py @@ -9,7 +9,6 @@ from pandas import DataFrame, Series from pandas.tests.io.pytables.common import ensure_clean_path, ensure_clean_store import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal from pandas.io.pytables import read_hdf @@ -26,7 +25,7 @@ def test_complex_fixed(setup_path): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df") reread = read_hdf(path, "df") - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) df = DataFrame( np.random.rand(4, 5).astype(np.complex128), @@ -36,7 +35,7 @@ def test_complex_fixed(setup_path): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df") reread = read_hdf(path, "df") - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) def test_complex_table(setup_path): @@ -49,7 +48,7 @@ def test_complex_table(setup_path): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df", format="table") reread = read_hdf(path, "df") - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) df = DataFrame( np.random.rand(4, 5).astype(np.complex128), @@ -60,7 +59,7 @@ def test_complex_table(setup_path): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df", format="table", mode="w") reread = read_hdf(path, "df") - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) @td.xfail_non_writeable @@ -84,7 +83,7 @@ def test_complex_mixed_fixed(setup_path): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df") reread = read_hdf(path, "df") - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) def test_complex_mixed_table(setup_path): @@ -108,12 +107,12 @@ def test_complex_mixed_table(setup_path): with ensure_clean_store(setup_path) as store: store.append("df", df, data_columns=["A", "B"]) result = store.select("df", where="A>2") - assert_frame_equal(df.loc[df.A > 2], result) + tm.assert_frame_equal(df.loc[df.A > 2], result) with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df", format="table") reread = read_hdf(path, "df") - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) def test_complex_across_dimensions_fixed(setup_path): @@ -183,4 +182,4 @@ def test_complex_append(setup_path): store.append("df", df, data_columns=["b"]) store.append("df", df) result = store.select("df") - assert_frame_equal(pd.concat([df, df], 0), result) + tm.assert_frame_equal(pd.concat([df, df], 0), result) diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 956438f1afdf4..f9d525399bde3 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -42,7 +42,6 @@ tables, ) import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal from pandas.io.pytables import ( ClosedFileError, @@ -99,19 +98,19 @@ def roundtrip(key, obj, **kwargs): return read_hdf(path, key) o = tm.makeTimeSeries() - assert_series_equal(o, roundtrip("series", o)) + tm.assert_series_equal(o, roundtrip("series", o)) o = tm.makeStringSeries() - assert_series_equal(o, roundtrip("string_series", o)) + tm.assert_series_equal(o, roundtrip("string_series", o)) o = tm.makeDataFrame() - assert_frame_equal(o, roundtrip("frame", o)) + tm.assert_frame_equal(o, roundtrip("frame", o)) # table df = DataFrame(dict(A=range(5), B=range(5))) df.to_hdf(path, "table", append=True) result = read_hdf(path, "table", where=["index>2"]) - assert_frame_equal(df[df.index > 2], result) + tm.assert_frame_equal(df[df.index > 2], result) finally: safe_remove(path) @@ -127,7 +126,7 @@ def test_long_strings(self, setup_path): store.append("df", df, data_columns=["a"]) result = store.select("df") - assert_frame_equal(df, result) + tm.assert_frame_equal(df, result) def test_api(self, setup_path): @@ -138,39 +137,39 @@ def test_api(self, setup_path): df = tm.makeDataFrame() df.iloc[:10].to_hdf(path, "df", append=True, format="table") df.iloc[10:].to_hdf(path, "df", append=True, format="table") - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) # append to False df.iloc[:10].to_hdf(path, "df", append=False, format="table") df.iloc[10:].to_hdf(path, "df", append=True, format="table") - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) with ensure_clean_path(setup_path) as path: df = tm.makeDataFrame() df.iloc[:10].to_hdf(path, "df", append=True) df.iloc[10:].to_hdf(path, "df", append=True, format="table") - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) # append to False df.iloc[:10].to_hdf(path, "df", append=False, format="table") df.iloc[10:].to_hdf(path, "df", append=True) - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) with ensure_clean_path(setup_path) as path: df = tm.makeDataFrame() df.to_hdf(path, "df", append=False, format="fixed") - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) df.to_hdf(path, "df", append=False, format="f") - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) df.to_hdf(path, "df", append=False) - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) df.to_hdf(path, "df") - assert_frame_equal(read_hdf(path, "df"), df) + tm.assert_frame_equal(read_hdf(path, "df"), df) with ensure_clean_store(setup_path) as store: @@ -180,24 +179,24 @@ def test_api(self, setup_path): _maybe_remove(store, "df") store.append("df", df.iloc[:10], append=True, format="table") store.append("df", df.iloc[10:], append=True, format="table") - assert_frame_equal(store.select("df"), df) + tm.assert_frame_equal(store.select("df"), df) # append to False _maybe_remove(store, "df") store.append("df", df.iloc[:10], append=False, format="table") store.append("df", df.iloc[10:], append=True, format="table") - assert_frame_equal(store.select("df"), df) + tm.assert_frame_equal(store.select("df"), df) # formats _maybe_remove(store, "df") store.append("df", df.iloc[:10], append=False, format="table") store.append("df", df.iloc[10:], append=True, format="table") - assert_frame_equal(store.select("df"), df) + tm.assert_frame_equal(store.select("df"), df) _maybe_remove(store, "df") store.append("df", df.iloc[:10], append=False, format="table") store.append("df", df.iloc[10:], append=True, format=None) - assert_frame_equal(store.select("df"), df) + tm.assert_frame_equal(store.select("df"), df) with ensure_clean_path(setup_path) as path: # Invalid. @@ -432,7 +431,7 @@ def check(mode): read_hdf(path, "df", mode=mode) else: result = read_hdf(path, "df", mode=mode) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def check_default_mode(): @@ -440,7 +439,7 @@ def check_default_mode(): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df", mode="w") result = read_hdf(path, "df") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) check("r") check("r+") @@ -962,7 +961,7 @@ def check(format, index): _maybe_remove(store, "df") store.put("df", df, format=format) - assert_frame_equal(df, store["df"]) + tm.assert_frame_equal(df, store["df"]) for index in [ tm.makeFloatIndex, @@ -1032,9 +1031,11 @@ def test_latin_encoding(self, setup_path, dtype, val): if is_categorical_dtype(s_nan): assert is_categorical_dtype(retr) - assert_series_equal(s_nan, retr, check_dtype=False, check_categorical=False) + tm.assert_series_equal( + s_nan, retr, check_dtype=False, check_categorical=False + ) else: - assert_series_equal(s_nan, retr) + tm.assert_series_equal(s_nan, retr) # FIXME: don't leave commented-out # fails: @@ -1861,14 +1862,14 @@ def check(obj, comparator): # repeated append of 0/non-zero frames df = DataFrame(np.random.rand(10, 3), columns=list("ABC")) store.append("df", df) - assert_frame_equal(store.select("df"), df) + tm.assert_frame_equal(store.select("df"), df) store.append("df", df_empty) - assert_frame_equal(store.select("df"), df) + tm.assert_frame_equal(store.select("df"), df) # store df = DataFrame(columns=list("ABC")) store.put("df2", df) - assert_frame_equal(store.select("df2"), df) + tm.assert_frame_equal(store.select("df2"), df) def test_append_raise(self, setup_path): @@ -1929,11 +1930,11 @@ def test_table_values_dtypes_roundtrip(self, setup_path): with ensure_clean_store(setup_path) as store: df1 = DataFrame({"a": [1, 2, 3]}, dtype="f8") store.append("df_f8", df1) - assert_series_equal(df1.dtypes, store["df_f8"].dtypes) + tm.assert_series_equal(df1.dtypes, store["df_f8"].dtypes) df2 = DataFrame({"a": [1, 2, 3]}, dtype="i8") store.append("df_i8", df2) - assert_series_equal(df2.dtypes, store["df_i8"].dtypes) + tm.assert_series_equal(df2.dtypes, store["df_i8"].dtypes) # incompatible dtype with pytest.raises(ValueError): @@ -1943,7 +1944,7 @@ def test_table_values_dtypes_roundtrip(self, setup_path): # actually create them thought) df1 = DataFrame(np.array([[1], [2], [3]], dtype="f4"), columns=["A"]) store.append("df_f4", df1) - assert_series_equal(df1.dtypes, store["df_f4"].dtypes) + tm.assert_series_equal(df1.dtypes, store["df_f4"].dtypes) assert df1.dtypes[0] == "float32" # check with mixed dtypes @@ -2057,11 +2058,11 @@ def test_calendar_roundtrip_issue(self, setup_path): store.put("fixed", s) result = store.select("fixed") - assert_series_equal(result, s) + tm.assert_series_equal(result, s) store.append("table", s) result = store.select("table") - assert_series_equal(result, s) + tm.assert_series_equal(result, s) def test_roundtrip_tz_aware_index(self, setup_path): # GH 17618 @@ -2096,32 +2097,32 @@ def test_append_with_timedelta(self, setup_path): _maybe_remove(store, "df") store.append("df", df, data_columns=True) result = store.select("df") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = store.select("df", where="C<100000") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = store.select("df", where="C<pd.Timedelta('-3D')") - assert_frame_equal(result, df.iloc[3:]) + tm.assert_frame_equal(result, df.iloc[3:]) result = store.select("df", "C<'-3D'") - assert_frame_equal(result, df.iloc[3:]) + tm.assert_frame_equal(result, df.iloc[3:]) # a bit hacky here as we don't really deal with the NaT properly result = store.select("df", "C<'-500000s'") result = result.dropna(subset=["C"]) - assert_frame_equal(result, df.iloc[6:]) + tm.assert_frame_equal(result, df.iloc[6:]) result = store.select("df", "C<'-3.5D'") result = result.iloc[1:] - assert_frame_equal(result, df.iloc[4:]) + tm.assert_frame_equal(result, df.iloc[4:]) # fixed _maybe_remove(store, "df2") store.put("df2", df) result = store.select("df2") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_remove(self, setup_path): @@ -2228,16 +2229,16 @@ def test_same_name_scoping(self, setup_path): import datetime # noqa result = store.select("df", "index>datetime.datetime(2013,1,5)") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) from datetime import datetime # noqa # technically an error, but allow it result = store.select("df", "index>datetime.datetime(2013,1,5)") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = store.select("df", "index>datetime(2013,1,5)") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_series(self, setup_path): @@ -2459,7 +2460,7 @@ def test_store_index_name_numpy_str(self, table_format, setup_path): df.to_hdf(path, "df", format=table_format) df2 = read_hdf(path, "df") - assert_frame_equal(df, df2, check_names=True) + tm.assert_frame_equal(df, df2, check_names=True) assert type(df2.index.name) == str assert type(df2.columns.name) == str @@ -2534,15 +2535,15 @@ def test_select_with_dups(self, setup_path): result = store.select("df") expected = df - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) result = store.select("df", columns=df.columns) expected = df - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) result = store.select("df", columns=["A"]) expected = df.loc[:, ["A"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # dups across dtypes df = concat( @@ -2561,19 +2562,19 @@ def test_select_with_dups(self, setup_path): result = store.select("df") expected = df - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) result = store.select("df", columns=df.columns) expected = df - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) expected = df.loc[:, ["A"]] result = store.select("df", columns=["A"]) - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) expected = df.loc[:, ["B", "A"]] result = store.select("df", columns=["B", "A"]) - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) # duplicates on both index and columns with ensure_clean_store(setup_path) as store: @@ -2583,7 +2584,7 @@ def test_select_with_dups(self, setup_path): expected = df.loc[:, ["B", "A"]] expected = concat([expected, expected]) result = store.select("df", columns=["B", "A"]) - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) def test_overwrite_node(self, setup_path): @@ -3269,40 +3270,40 @@ def test_frame_select_complex2(self, setup_path): l = selection.index.tolist() # noqa store = HDFStore(hh) result = store.select("df", where="l1=l") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) store.close() result = read_hdf(hh, "df", where="l1=l") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # index index = selection.index # noqa result = read_hdf(hh, "df", where="l1=index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = read_hdf(hh, "df", where="l1=selection.index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = read_hdf(hh, "df", where="l1=selection.index.tolist()") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = read_hdf(hh, "df", where="l1=list(selection.index)") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # scope with index store = HDFStore(hh) result = store.select("df", where="l1=index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = store.select("df", where="l1=selection.index") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = store.select("df", where="l1=selection.index.tolist()") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = store.select("df", where="l1=list(selection.index)") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) store.close() @@ -3337,11 +3338,11 @@ def test_string_select(self, setup_path): result = store.select("df", "x=none") expected = df[df.x == "none"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = store.select("df", "x!=none") expected = df[df.x != "none"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df2 = df.copy() df2.loc[df2.x == "", "x"] = np.nan @@ -3349,7 +3350,7 @@ def test_string_select(self, setup_path): store.append("df2", df2, data_columns=["x"]) result = store.select("df2", "x!=none") expected = df2[isna(df2.x)] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # int ==/!= df["int"] = 1 @@ -3359,11 +3360,11 @@ def test_string_select(self, setup_path): result = store.select("df3", "int=2") expected = df[df.int == 2] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = store.select("df3", "int!=2") expected = df[df.int != 2] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_read_column(self, setup_path): @@ -3700,7 +3701,7 @@ def test_nan_selection_bug_4858(self, setup_path): # write w/o the index on that particular column store.append("df", df, data_columns=True, index=["cols"]) result = store.select("df", where="values>2.0") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_start_stop_table(self, setup_path): @@ -3816,7 +3817,7 @@ def test_contiguous_mixed_data_table(self, start, stop, setup_path): store.append("test_dataset", df) result = store.select("test_dataset", start=start, stop=stop) - assert_frame_equal(df[start:stop], result) + tm.assert_frame_equal(df[start:stop], result) def test_path_pathlib_hdfstore(self, setup_path): df = tm.makeDataFrame() @@ -4044,7 +4045,7 @@ def test_legacy_table_fixed_format_read_py2(self, datapath, setup_path): columns=["A", "B", "C", "D"], index=pd.Index(["ABC"], name="INDEX_NAME"), ) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_legacy_table_read_py2(self, datapath, setup_path): # issue: 24925 @@ -4055,7 +4056,7 @@ def test_legacy_table_read_py2(self, datapath, setup_path): result = store.select("table") expected = pd.DataFrame({"a": ["a", "b"], "b": [2, 3]}) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_copy(self, setup_path): @@ -4152,7 +4153,7 @@ def test_tseries_indices_frame(self, setup_path): store["a"] = df result = store["a"] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) assert result.index.freq == df.index.freq tm.assert_class_equal(result.index, df.index, obj="dataframe index") @@ -4161,7 +4162,7 @@ def test_tseries_indices_frame(self, setup_path): store["a"] = df result = store["a"] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) assert result.index.freq == df.index.freq tm.assert_class_equal(result.index, df.index, obj="dataframe index") @@ -4442,7 +4443,7 @@ def test_preserve_timedeltaindex_type(self, setup_path): with ensure_clean_store(setup_path) as store: store["df"] = df - assert_frame_equal(store["df"], df) + tm.assert_frame_equal(store["df"], df) def test_columns_multiindex_modified(self, setup_path): # BUG: 7212 @@ -4569,7 +4570,7 @@ def test_read_nokey(self, setup_path): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df", mode="a") reread = read_hdf(path) - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) df.to_hdf(path, "df2", mode="a") with pytest.raises(ValueError): @@ -4582,7 +4583,7 @@ def test_read_nokey_table(self, setup_path): with ensure_clean_path(setup_path) as path: df.to_hdf(path, "df", mode="a", format="table") reread = read_hdf(path) - assert_frame_equal(df, reread) + tm.assert_frame_equal(df, reread) df.to_hdf(path, "df2", mode="a", format="table") with pytest.raises(ValueError): @@ -4739,7 +4740,7 @@ def test_read_py2_hdf_file_in_py3(self, datapath): mode="r", ) as store: result = store["p"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("where", ["", (), (None,), [], [None]]) def test_select_empty_where(self, where): @@ -4754,7 +4755,7 @@ def test_select_empty_where(self, where): with pd.HDFStore(path) as store: store.put("df", df, "t") result = pd.read_hdf(store, "df", where=where) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) @pytest.mark.parametrize( "idx", diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index ba1df24224831..1acb0ac6e06d2 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -13,7 +13,6 @@ ensure_clean_store, ) import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, set_timezone def _compare_with_tz(a, b): @@ -57,7 +56,7 @@ def test_append_with_timezones_dateutil(setup_path): store.append("df_tz", df, data_columns=["A"]) result = store["df_tz"] _compare_with_tz(result, df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # select with tz aware expected = df[df.A >= df.A[3]] @@ -76,7 +75,7 @@ def test_append_with_timezones_dateutil(setup_path): store.append("df_tz", df) result = store["df_tz"] _compare_with_tz(result, df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df = DataFrame( dict( @@ -93,7 +92,7 @@ def test_append_with_timezones_dateutil(setup_path): store.append("df_tz", df, data_columns=["A", "B"]) result = store["df_tz"] _compare_with_tz(result, df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # can't append with diff timezone df = DataFrame( @@ -124,12 +123,12 @@ def test_append_with_timezones_dateutil(setup_path): _maybe_remove(store, "df") store.put("df", df) result = store.select("df") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) _maybe_remove(store, "df") store.append("df", df) result = store.select("df") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_append_with_timezones_pytz(setup_path): @@ -152,7 +151,7 @@ def test_append_with_timezones_pytz(setup_path): store.append("df_tz", df, data_columns=["A"]) result = store["df_tz"] _compare_with_tz(result, df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # select with tz aware _compare_with_tz(store.select("df_tz", where="A>=df.A[3]"), df[df.A >= df.A[3]]) @@ -169,7 +168,7 @@ def test_append_with_timezones_pytz(setup_path): store.append("df_tz", df) result = store["df_tz"] _compare_with_tz(result, df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df = DataFrame( dict( @@ -186,7 +185,7 @@ def test_append_with_timezones_pytz(setup_path): store.append("df_tz", df, data_columns=["A", "B"]) result = store["df_tz"] _compare_with_tz(result, df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # can't append with diff timezone df = DataFrame( @@ -215,12 +214,12 @@ def test_append_with_timezones_pytz(setup_path): _maybe_remove(store, "df") store.put("df", df) result = store.select("df") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) _maybe_remove(store, "df") store.append("df", df) result = store.select("df") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_tseries_select_index_column(setup_path): @@ -264,7 +263,7 @@ def test_timezones_fixed(setup_path): df = DataFrame(np.random.randn(len(rng), 4), index=rng) store["df"] = df result = store["df"] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # as data # GH11411 @@ -280,7 +279,7 @@ def test_timezones_fixed(setup_path): ) store["df"] = df result = store["df"] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_fixed_offset_tz(setup_path): @@ -307,20 +306,20 @@ def test_store_timezone(setup_path): df = DataFrame([1, 2, 3], index=[today, today, today]) store["obj1"] = df result = store["obj1"] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) # with tz setting with ensure_clean_store(setup_path) as store: - with set_timezone("EST5EDT"): + with tm.set_timezone("EST5EDT"): today = datetime.date(2013, 9, 10) df = DataFrame([1, 2, 3], index=[today, today, today]) store["obj1"] = df - with set_timezone("CST6CDT"): + with tm.set_timezone("CST6CDT"): result = store["obj1"] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_legacy_datetimetz_object(datapath, setup_path): @@ -336,7 +335,7 @@ def test_legacy_datetimetz_object(datapath, setup_path): datapath("io", "data", "legacy_hdf", "datetimetz_object.h5"), mode="r" ) as store: result = store["df"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dst_transitions(setup_path): @@ -355,7 +354,7 @@ def test_dst_transitions(setup_path): df = DataFrame({"A": range(len(i)), "B": i}, index=i) store.append("df", df) result = store.select("df") - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_read_with_where_tz_aware_index(setup_path): @@ -370,7 +369,7 @@ def test_read_with_where_tz_aware_index(setup_path): with pd.HDFStore(path) as store: store.append(key, expected, format="table", append=True) result = pd.read_hdf(path, key, where="DATE > 20151130") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_py2_created_with_datetimez(datapath, setup_path): @@ -384,4 +383,4 @@ def test_py2_created_with_datetimez(datapath, setup_path): datapath("io", "data", "legacy_hdf", "gh26443.h5"), mode="r" ) as store: result = store["key"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index fccd52f9916b8..33e6d3b05100e 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -6,8 +6,7 @@ import pandas as pd from pandas import DataFrame, get_option, read_clipboard -from pandas.util import testing as tm -from pandas.util.testing import makeCustomDataframe as mkdf +import pandas.util.testing as tm from pandas.io.clipboard import clipboard_get, clipboard_set from pandas.io.clipboard.exceptions import PyperclipException @@ -54,12 +53,12 @@ def df(request): {"a": ["\U0001f44d\U0001f44d", "\U0001f44d\U0001f44d"], "b": ["abc", "def"]} ) elif data_type == "string": - return mkdf( + return tm.makeCustomDataframe( 5, 3, c_idx_type="s", r_idx_type="i", c_idx_names=[None], r_idx_names=[None] ) elif data_type == "long": max_rows = get_option("display.max_rows") - return mkdf( + return tm.makeCustomDataframe( max_rows + 1, 3, data_gen_f=lambda *args: randint(2), @@ -72,7 +71,7 @@ def df(request): return pd.DataFrame({"en": "in English".split(), "es": "en español".split()}) elif data_type == "colwidth": _cw = get_option("display.max_colwidth") + 1 - return mkdf( + return tm.makeCustomDataframe( 5, 3, data_gen_f=lambda *args: "x" * _cw, @@ -86,7 +85,7 @@ def df(request): {"a": np.arange(1.0, 6.0) + 0.01, "b": np.arange(1, 6), "c": list("abcde")} ) elif data_type == "float": - return mkdf( + return tm.makeCustomDataframe( 5, 3, data_gen_f=lambda r, c: float(r) + 0.01, @@ -96,7 +95,7 @@ def df(request): r_idx_names=[None], ) elif data_type == "int": - return mkdf( + return tm.makeCustomDataframe( 5, 3, data_gen_f=lambda *args: randint(2), diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index ea69245924b0c..0f68a6534dad1 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -6,7 +6,6 @@ import pandas as pd import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, ensure_clean from pandas.io.feather_format import read_feather, to_feather # noqa: E402 isort:skip @@ -25,7 +24,7 @@ def check_error_on_write(self, df, exc): # on writing with pytest.raises(exc): - with ensure_clean() as path: + with tm.ensure_clean() as path: to_feather(df, path) def check_round_trip(self, df, expected=None, **kwargs): @@ -33,11 +32,11 @@ def check_round_trip(self, df, expected=None, **kwargs): if expected is None: expected = df - with ensure_clean() as path: + with tm.ensure_clean() as path: to_feather(df, path) result = read_feather(path, **kwargs) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_error(self): diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py index 8313b85d75ca7..85ac56c8193a6 100644 --- a/pandas/tests/io/test_gcs.py +++ b/pandas/tests/io/test_gcs.py @@ -6,7 +6,7 @@ from pandas import DataFrame, date_range, read_csv from pandas.util import _test_decorators as td -from pandas.util.testing import assert_frame_equal +import pandas.util.testing as tm from pandas.io.common import is_gcs_url @@ -35,7 +35,7 @@ def open(*args): monkeypatch.setattr("gcsfs.GCSFileSystem", MockGCSFileSystem) df2 = read_csv("gs://test/test.csv", parse_dates=["dt"]) - assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df2) @td.skip_if_no("gcsfs") @@ -58,7 +58,7 @@ def open(*args): df1.to_csv("gs://test/test.csv", index=True) df2 = read_csv(StringIO(s.getvalue()), parse_dates=["dt"], index_col=0) - assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df2) @td.skip_if_no("fastparquet") @@ -105,7 +105,7 @@ def mock_get_filepath_or_buffer(*args, **kwargs): ) df2 = read_csv("gs://test/test.csv", parse_dates=["dt"]) - assert_frame_equal(df1, df2) + tm.assert_frame_equal(df1, df2) @td.skip_if_installed("gcsfs") diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index f35707de189dc..3d855a12d5481 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -16,7 +16,6 @@ from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv import pandas.util.testing as tm -from pandas.util.testing import makeCustomDataframe as mkdf, network from pandas.io.common import file_path_to_url import pandas.io.html @@ -108,7 +107,7 @@ def set_defaults(self, flavor, request): def test_to_html_compat(self): df = ( - mkdf( + tm.makeCustomDataframe( 4, 3, data_gen_f=lambda *args: rand(), @@ -122,7 +121,7 @@ def test_to_html_compat(self): res = self.read_html(out, attrs={"class": "dataframe"}, index_col=0)[0] tm.assert_frame_equal(res, df) - @network + @tm.network def test_banklist_url(self): url = "http://www.fdic.gov/bank/individual/failed/banklist.html" df1 = self.read_html( @@ -132,7 +131,7 @@ def test_banklist_url(self): assert_framelist_equal(df1, df2) - @network + @tm.network def test_spam_url(self): url = ( "https://raw.githubusercontent.com/pandas-dev/pandas/master/" @@ -275,12 +274,12 @@ def test_file_like(self): assert_framelist_equal(df1, df2) - @network + @tm.network def test_bad_url_protocol(self): with pytest.raises(URLError): self.read_html("git://github.com", match=".*Water.*") - @network + @tm.network @pytest.mark.slow def test_invalid_url(self): try: @@ -361,13 +360,13 @@ def test_negative_skiprows(self): with pytest.raises(ValueError, match=msg): self.read_html(self.spam_data, "Water", skiprows=-1) - @network + @tm.network def test_multiple_matches(self): url = "https://docs.python.org/2/" dfs = self.read_html(url, match="Python") assert len(dfs) > 1 - @network + @tm.network def test_python_docs_table(self): url = "https://docs.python.org/2/" dfs = self.read_html(url, match="Python") diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index 0bafbab069dd4..f8005273319e0 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -26,13 +26,6 @@ period_range, ) import pandas.util.testing as tm -from pandas.util.testing import ( - assert_categorical_equal, - assert_frame_equal, - assert_index_equal, - assert_series_equal, - ensure_clean, -) from pandas.io.packers import read_msgpack, to_msgpack @@ -76,11 +69,11 @@ def check_arbitrary(a, b): for a_, b_ in zip(a, b): check_arbitrary(a_, b_) elif isinstance(a, DataFrame): - assert_frame_equal(a, b) + tm.assert_frame_equal(a, b) elif isinstance(a, Series): - assert_series_equal(a, b) + tm.assert_series_equal(a, b) elif isinstance(a, Index): - assert_index_equal(a, b) + tm.assert_index_equal(a, b) elif isinstance(a, Categorical): # Temp, # Categorical.categories is changed from str to bytes in PY3 @@ -107,7 +100,7 @@ def teardown_method(self, method): pass def encode_decode(self, x, compress=None, **kwargs): - with ensure_clean(self.path) as p: + with tm.ensure_clean(self.path) as p: to_msgpack(p, x, compress=compress, **kwargs) return read_msgpack(p, **kwargs) @@ -133,7 +126,7 @@ def test_string_io(self): result = read_msgpack(s) tm.assert_frame_equal(result, df) - with ensure_clean(self.path) as p: + with tm.ensure_clean(self.path) as p: s = df.to_msgpack() with open(p, "wb") as fh: @@ -462,7 +455,7 @@ def test_basic(self): for n in range(10): for s, i in self.d.items(): i_rec = self.encode_decode(i) - assert_series_equal(i, i_rec) + tm.assert_series_equal(i, i_rec) @pytest.mark.filterwarnings("ignore:.*msgpack:FutureWarning") @@ -486,7 +479,7 @@ def test_basic(self): for n in range(10): for s, i in self.d.items(): i_rec = self.encode_decode(i) - assert_categorical_equal(i, i_rec) + tm.assert_categorical_equal(i, i_rec) @pytest.mark.filterwarnings("ignore:msgpack:FutureWarning") @@ -516,13 +509,13 @@ def test_basic_frame(self): for s, i in self.frame.items(): i_rec = self.encode_decode(i) - assert_frame_equal(i, i_rec) + tm.assert_frame_equal(i, i_rec) def test_multi(self): i_rec = self.encode_decode(self.frame) for k in self.frame.keys(): - assert_frame_equal(self.frame[k], i_rec[k]) + tm.assert_frame_equal(self.frame[k], i_rec[k]) packed_items = tuple( [self.frame["float"], self.frame["float"].A, self.frame["float"].B, None] @@ -550,7 +543,7 @@ def test_iterator(self): None, ] - with ensure_clean(self.path) as path: + with tm.ensure_clean(self.path) as path: to_msgpack(path, *packed_items) for i, packed in enumerate(read_msgpack(path, iterator=True)): check_arbitrary(packed, packed_items[i]) @@ -561,11 +554,11 @@ def tests_datetimeindex_freq_issue(self): # inferring freq on the datetimeindex df = DataFrame([1, 2, 3], index=date_range("1/1/2013", "1/3/2013")) result = self.encode_decode(df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) df = DataFrame([1, 2], index=date_range("1/1/2013", "1/2/2013")) result = self.encode_decode(df) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_dataframe_duplicate_column_names(self): @@ -580,9 +573,9 @@ def test_dataframe_duplicate_column_names(self): result_2 = self.encode_decode(expected_2) result_3 = self.encode_decode(expected_3) - assert_frame_equal(result_1, expected_1) - assert_frame_equal(result_2, expected_2) - assert_frame_equal(result_3, expected_3) + tm.assert_frame_equal(result_1, expected_1) + tm.assert_frame_equal(result_2, expected_2) + tm.assert_frame_equal(result_3, expected_3) @pytest.mark.filterwarnings("ignore:.*msgpack:FutureWarning") @@ -617,14 +610,14 @@ def setup_method(self, method): def test_plain(self): i_rec = self.encode_decode(self.frame) for k in self.frame.keys(): - assert_frame_equal(self.frame[k], i_rec[k]) + tm.assert_frame_equal(self.frame[k], i_rec[k]) def _test_compression(self, compress): i_rec = self.encode_decode(self.frame, compress=compress) for k in self.frame.keys(): value = i_rec[k] expected = self.frame[k] - assert_frame_equal(value, expected) + tm.assert_frame_equal(value, expected) # make sure that we can write to the new frames for block in value._data.blocks: assert block.values.flags.writeable @@ -676,7 +669,7 @@ def decompress(ob): value = i_rec[k] expected = self.frame[k] - assert_frame_equal(value, expected) + tm.assert_frame_equal(value, expected) # make sure that we can write to the new frames even though # we needed to copy the data for block in value._data.blocks: @@ -773,7 +766,7 @@ def test_readonly_axis_blosc_to_sql(self): df.to_sql("test", eng, if_exists="append") result = pandas.read_sql_table("test", eng, index_col="index") result.index.names = [None] - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_readonly_axis_zlib_to_sql(self): # GH11880 @@ -787,7 +780,7 @@ def test_readonly_axis_zlib_to_sql(self): df.to_sql("test", eng, if_exists="append") result = pandas.read_sql_table("test", eng, index_col="index") result.index.names = [None] - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) @pytest.mark.filterwarnings("ignore:.*msgpack:FutureWarning") @@ -814,7 +807,7 @@ def test_utf(self): for encoding in self.utf_encodings: for frame in self.frame.values(): result = self.encode_decode(frame, encoding=encoding) - assert_frame_equal(result, frame) + tm.assert_frame_equal(result, frame) def test_default_encoding(self): for frame in self.frame.values(): @@ -822,7 +815,7 @@ def test_default_encoding(self): expected = frame.to_msgpack(encoding="utf8") assert result == expected result = self.encode_decode(frame) - assert_frame_equal(result, frame) + tm.assert_frame_equal(result, frame) files = glob.glob(
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29299
2019-10-30T23:23:16Z
2019-10-31T08:00:59Z
2019-10-31T08:00:59Z
2019-10-31T08:01:36Z
CLN: unnecessary exception catching
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index f505c0479e944..287a7bb0a7dea 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -170,10 +170,6 @@ cdef class Reducer: PyArray_SETITEM(result, PyArray_ITER_DATA(it), res) chunk.data = chunk.data + self.increment PyArray_ITER_NEXT(it) - except Exception as err: - if hasattr(err, 'args'): - err.args = err.args + (i,) - raise finally: # so we don't free the wrong memory chunk.data = dummy_buf diff --git a/pandas/core/apply.py b/pandas/core/apply.py index f402154dc91ca..d0093e5b697e1 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -13,8 +13,6 @@ ) from pandas.core.dtypes.generic import ABCSeries -from pandas.io.formats.printing import pprint_thing - def frame_apply( obj, @@ -293,20 +291,9 @@ def apply_series_generator(self): res_index = res_index.take(successes) else: - try: - for i, v in enumerate(series_gen): - results[i] = self.f(v) - keys.append(v.name) - except Exception as err: - if hasattr(err, "args"): - - # make sure i is defined - if i is not None: - k = res_index[i] - err.args = err.args + ( - "occurred at index %s" % pprint_thing(k), - ) - raise + for i, v in enumerate(series_gen): + results[i] = self.f(v) + keys.append(v.name) self.results = results self.res_index = res_index diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index f4c3ac970a3ca..606fd4ed4c360 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -262,8 +262,6 @@ def aggregate(self, func=None, *args, **kwargs): try: return self._python_agg_general(func, *args, **kwargs) - except (AssertionError, TypeError): - raise except (ValueError, KeyError, AttributeError, IndexError): # TODO: IndexError can be removed here following GH#29106 # TODO: AttributeError is caused by _index_data hijinx in @@ -1465,8 +1463,6 @@ def _transform_item_by_item(self, obj, wrapper): for i, col in enumerate(obj): try: output[col] = self[col].transform(wrapper) - except AssertionError: - raise except TypeError: # e.g. trying to call nanmean with string values pass diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 13cb0f9aed303..0e36726ac5f97 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -361,8 +361,6 @@ def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs): result = grouped._aggregate_item_by_item(how, *args, **kwargs) else: result = grouped.aggregate(how, *args, **kwargs) - except AssertionError: - raise except DataError: # we have a non-reducing function; try to evaluate result = grouped.apply(how, *args, **kwargs) diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index 4b7439cd40023..b6330178a23f9 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -424,12 +424,9 @@ def transform2(row): row["D"] = 7 return row - try: + msg = "'float' object has no attribute 'startswith'" + with pytest.raises(AttributeError, match=msg): data.apply(transform, axis=1) - except AttributeError as e: - assert len(e.args) == 2 - assert e.args[1] == "occurred at index 4" - assert e.args[0] == "'float' object has no attribute 'startswith'" def test_apply_bug(self):
adding an index to the exception is a nice thought, but ultimately adds more complication than information. The `except AssertionError`s were needed back when the lines below were `except Exception`, but those have been made more specific, so these are no longer needed
https://api.github.com/repos/pandas-dev/pandas/pulls/29298
2019-10-30T22:54:05Z
2019-11-07T20:48:25Z
2019-11-07T20:48:25Z
2019-11-07T21:01:34Z
0.25.3 whatsnew
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index fe80cc8bb959a..05c7f72882088 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -24,6 +24,7 @@ Version 0.25 .. toctree:: :maxdepth: 2 + v0.25.3 v0.25.2 v0.25.1 v0.25.0 diff --git a/doc/source/whatsnew/v0.25.3.rst b/doc/source/whatsnew/v0.25.3.rst new file mode 100644 index 0000000000000..f73a3f956f42e --- /dev/null +++ b/doc/source/whatsnew/v0.25.3.rst @@ -0,0 +1,22 @@ +.. _whatsnew_0253: + +What's new in 0.25.3 (October 31, 2019) +--------------------------------------- + +These are the changes in pandas 0.25.3. See :ref:`release` for a full changelog +including other versions of pandas. + +.. _whatsnew_0253.bug_fixes: + +Bug fixes +~~~~~~~~~ + +Groupby/resample/rolling +^^^^^^^^^^^^^^^^^^^^^^^^ + +- Bug in :meth:`DataFrameGroupBy.quantile` where NA values in the grouping could cause segfaults or incorrect results (:issue:`28882`) + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v0.25.2..HEAD diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index a9218650d4fe7..fa1669b1f3343 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -411,7 +411,6 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.groupby` not offering selection by column name when ``axis=1`` (:issue:`27614`) - Bug in :meth:`DataFrameGroupby.agg` not able to use lambda function with named aggregation (:issue:`27519`) - Bug in :meth:`DataFrame.groupby` losing column name information when grouping by a categorical column (:issue:`28787`) -- Bug in :meth:`DataFrameGroupBy.quantile` where NA values in the grouping could cause segfaults or incorrect results (:issue:`28882`) Reshaping ^^^^^^^^^
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29296
2019-10-30T18:42:05Z
2019-10-31T01:02:01Z
2019-10-31T01:02:01Z
2019-10-31T01:02:04Z
Fix SS06 formatting errors
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f2606ce1b0d61..40efc4c65476a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -310,10 +310,12 @@ class DataFrame(NDFrame): """ - Two-dimensional size-mutable, potentially heterogeneous tabular data - structure with labeled axes (rows and columns). Arithmetic operations - align on both row and column labels. Can be thought of as a dict-like - container for Series objects. The primary pandas data structure. + Two-dimensional, size-mutable, potentially heterogeneous tabular data. + + Data structure also contains labeled axes (rows and columns). + Arithmetic operations align on both row and column labels. Can be + thought of as a dict-like container for Series objects. The primary + pandas data structure. Parameters ---------- @@ -4798,8 +4800,9 @@ def dropna(self, axis=0, how="any", thresh=None, subset=None, inplace=False): def drop_duplicates(self, subset=None, keep="first", inplace=False): """ - Return DataFrame with duplicate rows removed, optionally only - considering certain columns. Indexes, including time indexes + Return DataFrame with duplicate rows removed. + + Considering certain columns is optional. Indexes, including time indexes are ignored. Parameters @@ -4834,8 +4837,9 @@ def drop_duplicates(self, subset=None, keep="first", inplace=False): def duplicated(self, subset=None, keep="first"): """ - Return boolean Series denoting duplicate rows, optionally only - considering certain columns. + Return boolean Series denoting duplicate rows. + + Considering certain columns is optional. Parameters ---------- @@ -7536,9 +7540,12 @@ def cov(self, min_periods=None): def corrwith(self, other, axis=0, drop=False, method="pearson"): """ - Compute pairwise correlation between rows or columns of DataFrame - with rows or columns of Series or DataFrame. DataFrames are first - aligned along both axes before computing the correlations. + Compute pairwise correlation. + + Pairwise correlation is computed between rows or columns of + DataFrame with rows or columns of Series or DataFrame. DataFrames + are first aligned along both axes before computing the + correlations. Parameters ---------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index e15332a5277b9..f88c26c7bc782 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5156,8 +5156,9 @@ def pipe(self, func, *args, **kwargs): _shared_docs[ "transform" ] = """ - Call ``func`` on self producing a %(klass)s with transformed values - and that has the same axis length as self. + Call ``func`` on self producing a %(klass)s with transformed values. + + Produced %(klass)s will have same axis length as self. Parameters ---------- @@ -8741,8 +8742,9 @@ def ranker(data): _shared_docs[ "align" ] = """ - Align two objects on their axes with the - specified join method for each axis Index. + Align two objects on their axes with the specified join method. + + Join method is specified for each axis Index. Parameters ---------- @@ -9965,9 +9967,11 @@ def abs(self): def describe(self, percentiles=None, include=None, exclude=None): """ - Generate descriptive statistics that summarize the central tendency, - dispersion and shape of a dataset's distribution, excluding - ``NaN`` values. + Generate descriptive statistics. + + Descriptive statistics include those that summarize the central + tendency, dispersion and shape of a + dataset's distribution, excluding ``NaN`` values. Analyzes both numeric and object series, as well as ``DataFrame`` column sets of mixed data types. The output @@ -10649,7 +10653,7 @@ def compound(self, axis=None, skipna=None, level=None): name, name2, axis_descr, - "Return unbiased skew over requested axis\nNormalized by N-1.", + "Return unbiased skew over requested axis.\n\nNormalized by N-1.", nanops.nanskew, ) cls.kurt = _make_stat_function( @@ -10658,8 +10662,9 @@ def compound(self, axis=None, skipna=None, level=None): name, name2, axis_descr, - "Return unbiased kurtosis over requested axis using Fisher's " - "definition of\nkurtosis (kurtosis of normal == 0.0). Normalized " + "Return unbiased kurtosis over requested axis.\n\n" + "Kurtosis obtained using Fisher's definition of\n" + "kurtosis (kurtosis of normal == 0.0). Normalized " "by N-1.", nanops.nankurt, )
More SS06 (Summary should fit in a single line) errors fixed (#29254): The following docstrings were examined and fixed: ``` pandas.DataFrame pandas.DataFrame.transform pandas.DataFrame.corrwith pandas.DataFrame.describe pandas.DataFrame.kurt pandas.DataFrame.kurtosis pandas.DataFrame.skew pandas.DataFrame.align pandas.DataFrame.drop_duplicates pandas.DataFrame.duplicated ``` Validated with python scripts/validate_docstrings.py Also referencing issue: #27977
https://api.github.com/repos/pandas-dev/pandas/pulls/29295
2019-10-30T16:48:32Z
2019-10-31T17:04:09Z
2019-10-31T17:04:09Z
2020-02-28T19:57:10Z
troubleshoot CI
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index c82486532530f..058d65b9464ae 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -2929,7 +2929,7 @@ def _next_iter_line(self, row_num): if self.warn_bad_lines or self.error_bad_lines: msg = str(e) - if "NULL byte" in msg: + if "NULL byte" in msg or "line contains NUL" in msg: msg = ( "NULL byte detected. This byte " "cannot be processed in Python's " diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 3d657418e43cd..6e6c31bc5b972 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -1915,10 +1915,7 @@ def test_null_byte_char(all_parsers): out = parser.read_csv(StringIO(data), names=names) tm.assert_frame_equal(out, expected) else: - if compat.PY38: - msg = "line contains NUL" - else: - msg = "NULL byte detected" + msg = "NULL byte detected" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), names=names)
https://api.github.com/repos/pandas-dev/pandas/pulls/29294
2019-10-30T15:38:02Z
2019-10-30T18:38:20Z
2019-10-30T18:38:20Z
2019-10-30T18:47:28Z
Implement safe_ea_cast to avoid catching Exception
diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index 868118bac6a7b..03d998707c26b 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -2,6 +2,7 @@ ExtensionArray, ExtensionOpsMixin, ExtensionScalarOpsMixin, + try_cast_to_ea, ) from .categorical import Categorical # noqa: F401 from .datetimes import DatetimeArray # noqa: F401 diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 08901df963f20..7333254831838 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -32,6 +32,29 @@ _extension_array_shared_docs = dict() # type: Dict[str, str] +def try_cast_to_ea(cls_or_instance, obj, dtype=None): + """ + Call to `_from_sequence` that returns the object unchanged on Exception. + + Parameters + ---------- + cls_or_instance : ExtensionArray subclass or instance + obj : arraylike + Values to pass to cls._from_sequence + dtype : ExtensionDtype, optional + + Returns + ------- + ExtensionArray or obj + """ + try: + result = cls_or_instance._from_sequence(obj, dtype=dtype) + except Exception: + # We can't predict what downstream EA constructors may raise + result = obj + return result + + class ExtensionArray: """ Abstract base class for custom 1-D array types. @@ -1156,9 +1179,9 @@ def _maybe_convert(arr): # https://github.com/pandas-dev/pandas/issues/22850 # We catch all regular exceptions here, and fall back # to an ndarray. - try: - res = self._from_sequence(arr) - except Exception: + res = try_cast_to_ea(self, arr) + if not isinstance(res, type(self)): + # exception raised in _from_sequence; ensure we have ndarray res = np.asarray(arr) else: res = np.asarray(arr) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c50870563df28..4f37bfc52c162 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -56,7 +56,7 @@ from pandas.io.formats import console -from .base import ExtensionArray, _extension_array_shared_docs +from .base import ExtensionArray, _extension_array_shared_docs, try_cast_to_ea _take_msg = textwrap.dedent( """\ @@ -2613,10 +2613,10 @@ def _get_codes_for_values(values, categories): # Support inferring the correct extension dtype from an array of # scalar objects. e.g. # Categorical(array[Period, Period], categories=PeriodIndex(...)) - try: - values = categories.dtype.construct_array_type()._from_sequence(values) - except Exception: - # but that may fail for any reason, so fall back to object + cls = categories.dtype.construct_array_type() + values = try_cast_to_ea(cls, values) + if not isinstance(values, cls): + # exception raised in _from_sequence values = ensure_object(values) categories = ensure_object(categories) else: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index e53e7ffdbf72f..404da096d8535 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -43,7 +43,7 @@ class providing the base-class of operations. from pandas.core import nanops import pandas.core.algorithms as algorithms -from pandas.core.arrays import Categorical +from pandas.core.arrays import Categorical, try_cast_to_ea from pandas.core.base import DataError, PandasObject, SelectionMixin import pandas.core.common as com from pandas.core.construction import extract_array @@ -819,14 +819,8 @@ def _try_cast(self, result, obj, numeric_only=False): # if the type is compatible with the calling EA. # return the same type (Series) as our caller - try: - result = obj._values._from_sequence(result, dtype=dtype) - except Exception: - # https://github.com/pandas-dev/pandas/issues/22850 - # pandas has no control over what 3rd-party ExtensionArrays - # do in _values_from_sequence. We still want ops to work - # though, so we catch any regular Exception. - pass + cls = dtype.construct_array_type() + result = try_cast_to_ea(cls, result, dtype=dtype) elif numeric_only and is_numeric_dtype(dtype) or not numeric_only: result = maybe_downcast_to_dtype(result, dtype) diff --git a/pandas/core/series.py b/pandas/core/series.py index 3e9d3d5c04559..1a0db520f6a6a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -55,7 +55,7 @@ import pandas as pd from pandas.core import algorithms, base, generic, nanops, ops from pandas.core.accessor import CachedAccessor -from pandas.core.arrays import ExtensionArray +from pandas.core.arrays import ExtensionArray, try_cast_to_ea from pandas.core.arrays.categorical import Categorical, CategoricalAccessor from pandas.core.arrays.sparse import SparseAccessor import pandas.core.common as com @@ -2849,14 +2849,7 @@ def combine(self, other, func, fill_value=None): elif is_extension_array_dtype(self.values): # The function can return something of any type, so check # if the type is compatible with the calling EA. - try: - new_values = self._values._from_sequence(new_values) - except Exception: - # https://github.com/pandas-dev/pandas/issues/22850 - # pandas has no control over what 3rd-party ExtensionArrays - # do in _values_from_sequence. We still want ops to work - # though, so we catch any regular Exception. - pass + new_values = try_cast_to_ea(self._values, new_values) return self._constructor(new_values, index=new_index, name=new_name) def combine_first(self, other):
instead of having `except Exception` in many places, we have it in one place, with one helpful comment
https://api.github.com/repos/pandas-dev/pandas/pulls/29293
2019-10-30T15:33:56Z
2019-11-02T15:30:11Z
2019-11-02T15:30:11Z
2019-11-02T15:32:27Z
REF/BENCH: tslibs-specific parts of asvs
diff --git a/asv_bench/benchmarks/offset.py b/asv_bench/benchmarks/offset.py index d822646e712ae..a960f43f46acd 100644 --- a/asv_bench/benchmarks/offset.py +++ b/asv_bench/benchmarks/offset.py @@ -1,8 +1,5 @@ -from datetime import datetime import warnings -import numpy as np - import pandas as pd try: @@ -54,24 +51,6 @@ def time_apply_index(self, offset): offset.apply_index(self.rng) -class OnOffset: - - params = offsets - param_names = ["offset"] - - def setup(self, offset): - self.dates = [ - datetime(2016, m, d) - for m in [10, 11, 12] - for d in [1, 2, 3, 28, 29, 30, 31] - if not (m == 11 and d == 31) - ] - - def time_on_offset(self, offset): - for date in self.dates: - offset.onOffset(date) - - class OffsetSeriesArithmetic: params = offsets @@ -99,31 +78,3 @@ def setup(self, offset): def time_add_offset(self, offset): with warnings.catch_warnings(record=True): self.data + offset - - -class OffestDatetimeArithmetic: - - params = offsets - param_names = ["offset"] - - def setup(self, offset): - self.date = datetime(2011, 1, 1) - self.dt64 = np.datetime64("2011-01-01 09:00Z") - - def time_apply(self, offset): - offset.apply(self.date) - - def time_apply_np_dt64(self, offset): - offset.apply(self.dt64) - - def time_add(self, offset): - self.date + offset - - def time_add_10(self, offset): - self.date + (10 * offset) - - def time_subtract(self, offset): - self.date - offset - - def time_subtract_10(self, offset): - self.date - (10 * offset) diff --git a/asv_bench/benchmarks/period.py b/asv_bench/benchmarks/period.py index 7303240a25f29..b52aa2e55af35 100644 --- a/asv_bench/benchmarks/period.py +++ b/asv_bench/benchmarks/period.py @@ -1,71 +1,12 @@ +""" +Period benchmarks with non-tslibs dependencies. See +benchmarks.tslibs.period for benchmarks that rely only on tslibs. +""" from pandas import DataFrame, Period, PeriodIndex, Series, date_range, period_range from pandas.tseries.frequencies import to_offset -class PeriodProperties: - - params = ( - ["M", "min"], - [ - "year", - "month", - "day", - "hour", - "minute", - "second", - "is_leap_year", - "quarter", - "qyear", - "week", - "daysinmonth", - "dayofweek", - "dayofyear", - "start_time", - "end_time", - ], - ) - param_names = ["freq", "attr"] - - def setup(self, freq, attr): - self.per = Period("2012-06-01", freq=freq) - - def time_property(self, freq, attr): - getattr(self.per, attr) - - -class PeriodUnaryMethods: - - params = ["M", "min"] - param_names = ["freq"] - - def setup(self, freq): - self.per = Period("2012-06-01", freq=freq) - - def time_to_timestamp(self, freq): - self.per.to_timestamp() - - def time_now(self, freq): - self.per.now(freq) - - def time_asfreq(self, freq): - self.per.asfreq("A") - - -class PeriodConstructor: - params = [["D"], [True, False]] - param_names = ["freq", "is_offset"] - - def setup(self, freq, is_offset): - if is_offset: - self.freq = to_offset(freq) - else: - self.freq = freq - - def time_period_constructor(self, freq, is_offset): - Period("2012-06-01", freq=freq) - - class PeriodIndexConstructor: params = [["D"], [True, False]] diff --git a/asv_bench/benchmarks/timedelta.py b/asv_bench/benchmarks/timedelta.py index 36a9db529f98f..828134b80aa3d 100644 --- a/asv_bench/benchmarks/timedelta.py +++ b/asv_bench/benchmarks/timedelta.py @@ -1,49 +1,11 @@ -import datetime +""" +Timedelta benchmarks with non-tslibs dependencies. See +benchmarks.tslibs.timedelta for benchmarks that rely only on tslibs. +""" import numpy as np -from pandas import ( - DataFrame, - Series, - Timedelta, - Timestamp, - timedelta_range, - to_timedelta, -) - - -class TimedeltaConstructor: - def time_from_int(self): - Timedelta(123456789) - - def time_from_unit(self): - Timedelta(1, unit="d") - - def time_from_components(self): - Timedelta( - days=1, - hours=2, - minutes=3, - seconds=4, - milliseconds=5, - microseconds=6, - nanoseconds=7, - ) - - def time_from_datetime_timedelta(self): - Timedelta(datetime.timedelta(days=1, seconds=1)) - - def time_from_np_timedelta(self): - Timedelta(np.timedelta64(1, "ms")) - - def time_from_string(self): - Timedelta("1 days") - - def time_from_iso_format(self): - Timedelta("P4DT12H30M5S") - - def time_from_missing(self): - Timedelta("nat") +from pandas import DataFrame, Series, Timestamp, timedelta_range, to_timedelta class ToTimedelta: @@ -88,24 +50,6 @@ def time_add_td_ts(self): self.td + self.ts -class TimedeltaProperties: - def setup_cache(self): - td = Timedelta(days=365, minutes=35, seconds=25, milliseconds=35) - return td - - def time_timedelta_days(self, td): - td.days - - def time_timedelta_seconds(self, td): - td.seconds - - def time_timedelta_microseconds(self, td): - td.microseconds - - def time_timedelta_nanoseconds(self, td): - td.nanoseconds - - class DatetimeAccessor: def setup_cache(self): N = 100000 diff --git a/asv_bench/benchmarks/tslibs/__init__.py b/asv_bench/benchmarks/tslibs/__init__.py new file mode 100644 index 0000000000000..815cf55b291cd --- /dev/null +++ b/asv_bench/benchmarks/tslibs/__init__.py @@ -0,0 +1,7 @@ +""" +Benchmarks in this directory should depend only on tslibs, tseries.offsets, +and to_offset. + +i.e. any code changes that do not touch those files should not need to +run these benchmarks. +""" diff --git a/asv_bench/benchmarks/tslibs/offsets.py b/asv_bench/benchmarks/tslibs/offsets.py new file mode 100644 index 0000000000000..d6379b922641c --- /dev/null +++ b/asv_bench/benchmarks/tslibs/offsets.py @@ -0,0 +1,90 @@ +""" +offsets benchmarks that rely only on tslibs. See benchmarks.offset for +offsets benchmarks that rely on other parts of pandas. +""" +from datetime import datetime + +import numpy as np + +from pandas import offsets + +try: + import pandas.tseries.holiday # noqa +except ImportError: + pass + +hcal = pandas.tseries.holiday.USFederalHolidayCalendar() +# These offsets currently raise a NotImplimentedError with .apply_index() +non_apply = [ + offsets.Day(), + offsets.BYearEnd(), + offsets.BYearBegin(), + offsets.BQuarterEnd(), + offsets.BQuarterBegin(), + offsets.BMonthEnd(), + offsets.BMonthBegin(), + offsets.CustomBusinessDay(), + offsets.CustomBusinessDay(calendar=hcal), + offsets.CustomBusinessMonthBegin(calendar=hcal), + offsets.CustomBusinessMonthEnd(calendar=hcal), + offsets.CustomBusinessMonthEnd(calendar=hcal), +] +other_offsets = [ + offsets.YearEnd(), + offsets.YearBegin(), + offsets.QuarterEnd(), + offsets.QuarterBegin(), + offsets.MonthEnd(), + offsets.MonthBegin(), + offsets.DateOffset(months=2, days=2), + offsets.BusinessDay(), + offsets.SemiMonthEnd(), + offsets.SemiMonthBegin(), +] +offset_objs = non_apply + other_offsets + + +class OnOffset: + + params = offset_objs + param_names = ["offset"] + + def setup(self, offset): + self.dates = [ + datetime(2016, m, d) + for m in [10, 11, 12] + for d in [1, 2, 3, 28, 29, 30, 31] + if not (m == 11 and d == 31) + ] + + def time_on_offset(self, offset): + for date in self.dates: + offset.onOffset(date) + + +class OffestDatetimeArithmetic: + + params = offset_objs + param_names = ["offset"] + + def setup(self, offset): + self.date = datetime(2011, 1, 1) + self.dt64 = np.datetime64("2011-01-01 09:00Z") + + def time_apply(self, offset): + offset.apply(self.date) + + def time_apply_np_dt64(self, offset): + offset.apply(self.dt64) + + def time_add(self, offset): + self.date + offset + + def time_add_10(self, offset): + self.date + (10 * offset) + + def time_subtract(self, offset): + self.date - offset + + def time_subtract_10(self, offset): + self.date - (10 * offset) diff --git a/asv_bench/benchmarks/tslibs/period.py b/asv_bench/benchmarks/tslibs/period.py new file mode 100644 index 0000000000000..9156c4aa90ea0 --- /dev/null +++ b/asv_bench/benchmarks/tslibs/period.py @@ -0,0 +1,70 @@ +""" +Period benchmarks that rely only on tslibs. See benchmarks.period for +Period benchmarks that rely on other parts fo pandas. +""" +from pandas import Period + +from pandas.tseries.frequencies import to_offset + + +class PeriodProperties: + + params = ( + ["M", "min"], + [ + "year", + "month", + "day", + "hour", + "minute", + "second", + "is_leap_year", + "quarter", + "qyear", + "week", + "daysinmonth", + "dayofweek", + "dayofyear", + "start_time", + "end_time", + ], + ) + param_names = ["freq", "attr"] + + def setup(self, freq, attr): + self.per = Period("2012-06-01", freq=freq) + + def time_property(self, freq, attr): + getattr(self.per, attr) + + +class PeriodUnaryMethods: + + params = ["M", "min"] + param_names = ["freq"] + + def setup(self, freq): + self.per = Period("2012-06-01", freq=freq) + + def time_to_timestamp(self, freq): + self.per.to_timestamp() + + def time_now(self, freq): + self.per.now(freq) + + def time_asfreq(self, freq): + self.per.asfreq("A") + + +class PeriodConstructor: + params = [["D"], [True, False]] + param_names = ["freq", "is_offset"] + + def setup(self, freq, is_offset): + if is_offset: + self.freq = to_offset(freq) + else: + self.freq = freq + + def time_period_constructor(self, freq, is_offset): + Period("2012-06-01", freq=freq) diff --git a/asv_bench/benchmarks/tslibs/timedelta.py b/asv_bench/benchmarks/tslibs/timedelta.py new file mode 100644 index 0000000000000..8a16ddc189483 --- /dev/null +++ b/asv_bench/benchmarks/tslibs/timedelta.py @@ -0,0 +1,61 @@ +""" +Timedelta benchmarks that rely only on tslibs. See benchmarks.timedeltas for +Timedelta benchmarks that rely on other parts fo pandas. +""" +import datetime + +import numpy as np + +from pandas import Timedelta + + +class TimedeltaConstructor: + def time_from_int(self): + Timedelta(123456789) + + def time_from_unit(self): + Timedelta(1, unit="d") + + def time_from_components(self): + Timedelta( + days=1, + hours=2, + minutes=3, + seconds=4, + milliseconds=5, + microseconds=6, + nanoseconds=7, + ) + + def time_from_datetime_timedelta(self): + Timedelta(datetime.timedelta(days=1, seconds=1)) + + def time_from_np_timedelta(self): + Timedelta(np.timedelta64(1, "ms")) + + def time_from_string(self): + Timedelta("1 days") + + def time_from_iso_format(self): + Timedelta("P4DT12H30M5S") + + def time_from_missing(self): + Timedelta("nat") + + +class TimedeltaProperties: + def setup_cache(self): + td = Timedelta(days=365, minutes=35, seconds=25, milliseconds=35) + return td + + def time_timedelta_days(self, td): + td.days + + def time_timedelta_seconds(self, td): + td.seconds + + def time_timedelta_microseconds(self, td): + td.microseconds + + def time_timedelta_nanoseconds(self, td): + td.nanoseconds diff --git a/asv_bench/benchmarks/timestamp.py b/asv_bench/benchmarks/tslibs/timestamp.py similarity index 100% rename from asv_bench/benchmarks/timestamp.py rename to asv_bench/benchmarks/tslibs/timestamp.py
Motivation: asv runs take way too long. One way to get around that is to make it easier to identify\* which benchmarks to run for a given PR. To that extent, if we can identify benchmarks that don't rely on anything outside of tslibs\**, then a PR that doesn't touch that code can skip those benchmarks. We can do the same thing for other low-dependency modules like _libs.algos. \* Ideally in an automated way, but I'm not there yet. \*\* Here and elsewhere, "tslibs" informally includes tseries.offsets and parts of tseries.frequences (until we can get all of that into the tslibs directory) @TomAugspurger will moving benchmarks cause asv to start new time series, or will it successfully link up the new location to the old?
https://api.github.com/repos/pandas-dev/pandas/pulls/29292
2019-10-30T14:56:55Z
2019-10-31T17:45:05Z
2019-10-31T17:45:04Z
2019-11-01T03:49:58Z
CLN: Consistent pandas.util.testing imports in pandas/tests/indexing
diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index 005a9a24dc597..6c81a00cb8f34 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -15,8 +15,7 @@ Timestamp, ) from pandas.api.types import CategoricalDtype as CDT -from pandas.util import testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm class TestCategoricalIndex: @@ -52,7 +51,7 @@ def test_loc_scalar(self): expected = DataFrame( {"A": [0, 1, 5], "B": (Series(list("aaa")).astype(CDT(list("cab"))))} ).set_index("B") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = self.df.copy() df.loc["a"] = 20 @@ -62,7 +61,7 @@ def test_loc_scalar(self): "B": (Series(list("aabbca")).astype(CDT(list("cab")))), } ).set_index("B") - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) # value not in the categories with pytest.raises(KeyError, match=r"^'d'$"): @@ -329,12 +328,12 @@ def test_loc_listlike(self): # list of labels result = self.df.loc[["c", "a"]] expected = self.df.iloc[[4, 0, 1, 5]] - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = self.df2.loc[["a", "b", "e"]] 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) + tm.assert_frame_equal(result, expected, check_index_type=True) # element in the categories but not in the values with pytest.raises(KeyError, match=r"^'e'$"): @@ -346,13 +345,13 @@ def test_loc_listlike(self): result = df.loc[["a", "b", "e"]] 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) + tm.assert_frame_equal(result, expected) df = self.df2.copy() result = df.loc[["a", "b", "e"]] 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) + tm.assert_frame_equal(result, expected, check_index_type=True) # not all labels in the categories with pytest.raises( @@ -474,7 +473,7 @@ def test_getitem_with_listlike(self): ) dummies = pd.get_dummies(cats) result = dummies[[c for c in dummies.columns]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_setitem_listlike(self): @@ -500,18 +499,18 @@ def test_ix_categorical_index(self): cdf.columns = CategoricalIndex(df.columns) expect = Series(df.loc["A", :], index=cdf.columns, name="A") - assert_series_equal(cdf.loc["A", :], expect) + tm.assert_series_equal(cdf.loc["A", :], expect) expect = Series(df.loc[:, "X"], index=cdf.index, name="X") - assert_series_equal(cdf.loc[:, "X"], expect) + tm.assert_series_equal(cdf.loc[:, "X"], expect) 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) + tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect) 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) + tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect) # non-unique df = DataFrame(np.random.randn(3, 3), index=list("ABA"), columns=list("XYX")) @@ -521,25 +520,25 @@ def test_ix_categorical_index(self): 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) + tm.assert_frame_equal(cdf.loc["A", :], expect) 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) + tm.assert_frame_equal(cdf.loc[:, "X"], expect) expect = DataFrame( df.loc[["A", "B"], :], columns=cdf.columns, index=CategoricalIndex(list("AAB")), ) - assert_frame_equal(cdf.loc[["A", "B"], :], expect) + tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect) expect = DataFrame( df.loc[:, ["X", "Y"]], index=cdf.index, columns=CategoricalIndex(list("XXY")), ) - assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect) + tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect) def test_read_only_source(self): # GH 10043 @@ -550,15 +549,15 @@ def test_read_only_source(self): ro_array.setflags(write=False) ro_df = DataFrame(ro_array) - assert_frame_equal(rw_df.iloc[[1, 2, 3]], ro_df.iloc[[1, 2, 3]]) - assert_frame_equal(rw_df.iloc[[1]], ro_df.iloc[[1]]) - assert_series_equal(rw_df.iloc[1], ro_df.iloc[1]) - assert_frame_equal(rw_df.iloc[1:3], ro_df.iloc[1:3]) + tm.assert_frame_equal(rw_df.iloc[[1, 2, 3]], ro_df.iloc[[1, 2, 3]]) + tm.assert_frame_equal(rw_df.iloc[[1]], ro_df.iloc[[1]]) + tm.assert_series_equal(rw_df.iloc[1], ro_df.iloc[1]) + tm.assert_frame_equal(rw_df.iloc[1:3], ro_df.iloc[1:3]) - assert_frame_equal(rw_df.loc[[1, 2, 3]], ro_df.loc[[1, 2, 3]]) - assert_frame_equal(rw_df.loc[[1]], ro_df.loc[[1]]) - assert_series_equal(rw_df.loc[1], ro_df.loc[1]) - assert_frame_equal(rw_df.loc[1:3], ro_df.loc[1:3]) + tm.assert_frame_equal(rw_df.loc[[1, 2, 3]], ro_df.loc[[1, 2, 3]]) + tm.assert_frame_equal(rw_df.loc[[1]], ro_df.loc[[1]]) + tm.assert_series_equal(rw_df.loc[1], ro_df.loc[1]) + tm.assert_frame_equal(rw_df.loc[1:3], ro_df.loc[1:3]) def test_reindexing(self): df = DataFrame( @@ -574,19 +573,19 @@ def test_reindexing(self): expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index( "B" ) - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(["a", "b"]) expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(["e"]) expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(["d"]) expected = DataFrame({"A": [np.nan], "B": Series(["d"])}).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) # since we are actually reindexing with a Categorical # then return a Categorical @@ -596,40 +595,40 @@ def test_reindexing(self): expected = DataFrame( {"A": [0, np.nan], "B": Series(list("ae")).astype(CDT(cats))} ).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(Categorical(["a"], categories=cats)) expected = DataFrame( {"A": [0], "B": Series(list("a")).astype(CDT(cats))} ).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(["a", "b", "e"]) expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index( "B" ) - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(["a", "b"]) expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(["e"]) expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) # give back the type of categorical that we received result = df.reindex(Categorical(["a", "e"], categories=cats, ordered=True)) expected = DataFrame( {"A": [0, np.nan], "B": Series(list("ae")).astype(CDT(cats, ordered=True))} ).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) result = df.reindex(Categorical(["a", "d"], categories=["a", "d"])) expected = DataFrame( {"A": [0, np.nan], "B": Series(list("ad")).astype(CDT(["a", "d"]))} ).set_index("B") - assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected, check_index_type=True) # passed duplicate indexers are not allowed msg = "cannot reindex from a duplicate axis" @@ -661,7 +660,7 @@ def test_loc_slice(self): # result = df.loc[1:5] # expected = df.iloc[[1,2,3,4]] - # assert_frame_equal(result, expected) + # tm.assert_frame_equal(result, expected) def test_loc_and_at_with_categorical_index(self): # GH 20629 @@ -681,19 +680,19 @@ def test_boolean_selection(self): result = df3[df3.index == "a"] expected = df3.iloc[[]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df4[df4.index == "a"] expected = df4.iloc[[]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df3[df3.index == 1] expected = df3.iloc[[0, 1, 3]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df4[df4.index == 1] expected = df4.iloc[[0, 1, 3]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # since we have an ordered categorical @@ -703,11 +702,11 @@ def test_boolean_selection(self): # name='B') result = df3[df3.index < 2] expected = df3.iloc[[4]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df3[df3.index > 1] expected = df3.iloc[[]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # unordered # cannot be compared diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 56a78081bc624..eadaeaba63a26 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -3,7 +3,6 @@ from pandas import DataFrame, Float64Index, Index, Int64Index, RangeIndex, Series import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal, assert_series_equal class TestFloatIndexers: @@ -21,7 +20,7 @@ def check(self, result, original, indexer, getitem): else: expected = original.iloc[indexer] - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) def test_scalar_error(self): @@ -504,7 +503,7 @@ def test_integer_positional_indexing(self): result = s[2:4] expected = s.iloc[2:4] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) for idxr in [lambda x: x, lambda x: x.iloc]: @@ -642,8 +641,8 @@ def test_floating_misc(self): result1 = s[1.0:3.0] result2 = s.loc[1.0:3.0] result3 = s.loc[1.0:3.0] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) # exact indexing when found result1 = s[5.0] @@ -674,58 +673,58 @@ def test_floating_misc(self): # fancy tests expected = Series([2, 0], index=Float64Index([5.0, 0.0])) for fancy_idx in [[5.0, 0.0], np.array([5.0, 0.0])]: # float - assert_series_equal(s[fancy_idx], expected) - assert_series_equal(s.loc[fancy_idx], expected) - assert_series_equal(s.loc[fancy_idx], expected) + tm.assert_series_equal(s[fancy_idx], expected) + tm.assert_series_equal(s.loc[fancy_idx], expected) + tm.assert_series_equal(s.loc[fancy_idx], expected) expected = Series([2, 0], index=Index([5, 0], dtype="int64")) for fancy_idx in [[5, 0], np.array([5, 0])]: # int - assert_series_equal(s[fancy_idx], expected) - assert_series_equal(s.loc[fancy_idx], expected) - assert_series_equal(s.loc[fancy_idx], expected) + tm.assert_series_equal(s[fancy_idx], expected) + tm.assert_series_equal(s.loc[fancy_idx], expected) + tm.assert_series_equal(s.loc[fancy_idx], expected) # all should return the same as we are slicing 'the same' result1 = s.loc[2:5] result2 = s.loc[2.0:5.0] result3 = s.loc[2.0:5] result4 = s.loc[2.1:5] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) - assert_series_equal(result1, result4) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result1, result4) # previously this did fallback indexing result1 = s[2:5] result2 = s[2.0:5.0] result3 = s[2.0:5] result4 = s[2.1:5] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) - assert_series_equal(result1, result4) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result1, result4) result1 = s.loc[2:5] result2 = s.loc[2.0:5.0] result3 = s.loc[2.0:5] result4 = s.loc[2.1:5] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) - assert_series_equal(result1, result4) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result1, result4) # combined test result1 = s.loc[2:5] result2 = s.loc[2:5] result3 = s[2:5] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) # list selection result1 = s[[0.0, 5, 10]] result2 = s.loc[[0.0, 5, 10]] result3 = s.loc[[0.0, 5, 10]] result4 = s.iloc[[0, 2, 4]] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) - assert_series_equal(result1, result4) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result1, result4) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result1 = s[[1.6, 5, 10]] @@ -733,9 +732,9 @@ def test_floating_misc(self): result2 = s.loc[[1.6, 5, 10]] with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result3 = s.loc[[1.6, 5, 10]] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) - assert_series_equal(result1, Series([np.nan, 2, 4], index=[1.6, 5, 10])) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result1, Series([np.nan, 2, 4], index=[1.6, 5, 10])) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result1 = s[[0, 1, 2]] @@ -743,21 +742,21 @@ def test_floating_misc(self): result2 = s.loc[[0, 1, 2]] with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result3 = s.loc[[0, 1, 2]] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) - assert_series_equal(result1, Series([0.0, np.nan, np.nan], index=[0, 1, 2])) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result1, Series([0.0, np.nan, np.nan], index=[0, 1, 2])) result1 = s.loc[[2.5, 5]] result2 = s.loc[[2.5, 5]] - assert_series_equal(result1, result2) - assert_series_equal(result1, Series([1, 2], index=[2.5, 5.0])) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, Series([1, 2], index=[2.5, 5.0])) result1 = s[[2.5]] result2 = s.loc[[2.5]] result3 = s.loc[[2.5]] - assert_series_equal(result1, result2) - assert_series_equal(result1, result3) - assert_series_equal(result1, Series([1], index=[2.5])) + tm.assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result1, Series([1], index=[2.5])) def test_floating_tuples(self): # see gh-13509 diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 31120c2c023cc..c239c8383f1ba 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -766,9 +766,8 @@ def test_iloc_non_unique_indexing(self): tm.assert_frame_equal(result, expected, check_index_type=False) def test_iloc_empty_list_indexer_is_ok(self): - from pandas.util.testing import makeCustomDataframe as mkdf - df = mkdf(5, 2) + df = tm.makeCustomDataframe(5, 2) # vertical empty tm.assert_frame_equal( df.iloc[:, []], diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index d478fbfa1686d..d611dc5497cca 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -264,9 +264,8 @@ def test_setitem_dtype_upcast(self): def test_dups_fancy_indexing(self): # GH 3455 - from pandas.util.testing import makeCustomDataframe as mkdf - df = mkdf(10, 3) + df = tm.makeCustomDataframe(10, 3) df.columns = ["a", "a", "b"] result = df[["b", "a"]].columns expected = Index(["b", "a", "a"]) diff --git a/pandas/tests/indexing/test_ix.py b/pandas/tests/indexing/test_ix.py index 6029db8ed66f6..a46cd65162f4e 100644 --- a/pandas/tests/indexing/test_ix.py +++ b/pandas/tests/indexing/test_ix.py @@ -9,7 +9,7 @@ import pandas as pd from pandas import DataFrame, Series, option_context -from pandas.util import testing as tm +import pandas.util.testing as tm def test_ix_deprecation(): @@ -313,9 +313,8 @@ def test_ix_setitem_out_of_bounds_axis_1(self): def test_ix_empty_list_indexer_is_ok(self): with catch_warnings(record=True): - from pandas.util.testing import makeCustomDataframe as mkdf - df = mkdf(5, 2) + df = tm.makeCustomDataframe(5, 2) # vertical empty tm.assert_frame_equal( df.ix[:, []], diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 5e517d556a095..5bf8780d76601 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1013,9 +1013,8 @@ def test_loc_name(self): assert result == "index_name" def test_loc_empty_list_indexer_is_ok(self): - from pandas.util.testing import makeCustomDataframe as mkdf - df = mkdf(5, 2) + df = tm.makeCustomDataframe(5, 2) # vertical empty tm.assert_frame_equal( df.loc[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29291
2019-10-30T14:31:30Z
2019-10-31T07:56:20Z
2019-10-31T07:56:20Z
2019-10-31T07:56:24Z
CLN: Consistent pandas.util.testing imports in pandas/tests/indexes
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index d6055b2b39280..1776538a15fc2 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -7,7 +7,6 @@ import pandas as pd from pandas import DataFrame, DatetimeIndex, Index, Timestamp, date_range, offsets import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal randn = np.random.randn @@ -262,7 +261,7 @@ def test_isin(self): result = index.isin(list(index)) assert result.all() - assert_almost_equal( + tm.assert_almost_equal( index.isin([index[2], 5]), np.array([False, False, True, False]) ) diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index b6f25d45f136a..4e5d624eba844 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -31,8 +31,7 @@ ) from pandas.core.arrays import DatetimeArray from pandas.core.tools import datetimes as tools -from pandas.util import testing as tm -from pandas.util.testing import assert_series_equal +import pandas.util.testing as tm class TestTimeConversionFormats: @@ -55,7 +54,7 @@ def test_to_datetime_format(self, cache): expected = expecteds[i] if isinstance(expected, Series): - assert_series_equal(result, Series(expected)) + tm.assert_series_equal(result, Series(expected)) elif isinstance(expected, Timestamp): assert result == expected else: @@ -67,10 +66,10 @@ def test_to_datetime_format_YYYYMMDD(self, cache): expected = Series([Timestamp(x) for x in s.apply(str)]) result = to_datetime(s, format="%Y%m%d", cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = to_datetime(s.apply(str), format="%Y%m%d", cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # with NaT expected = Series( @@ -80,13 +79,13 @@ def test_to_datetime_format_YYYYMMDD(self, cache): s[2] = np.nan result = to_datetime(s, format="%Y%m%d", cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # string with NaT s = s.apply(str) s[2] = "nat" result = to_datetime(s, format="%Y%m%d", cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # coercion # GH 7930 @@ -131,7 +130,7 @@ def test_to_datetime_format_YYYYMMDD_overflow(self, input_s, expected): # GH 25512 # format='%Y%m%d', errors='coerce' result = pd.to_datetime(input_s, format="%Y%m%d", errors="coerce") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_integer(self, cache): @@ -140,13 +139,13 @@ def test_to_datetime_format_integer(self, cache): expected = Series([Timestamp(x) for x in s.apply(str)]) result = to_datetime(s, format="%Y", cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([200001, 200105, 200206]) expected = Series([Timestamp(x[:4] + "-" + x[4:]) for x in s.apply(str)]) result = to_datetime(s, format="%Y%m", cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "int_date, expected", @@ -216,7 +215,7 @@ def test_to_datetime_with_non_exact(self, cache): expected = to_datetime( s.str.extract(r"(\d+\w+\d+)", expand=False), format="%d%b%y", cache=cache ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_parse_nanoseconds_with_formula(self, cache): @@ -1204,11 +1203,11 @@ def test_dataframe(self, cache): expected = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:0:00")] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # dict-like result = to_datetime(df[["year", "month", "day"]].to_dict(), cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # dict but with constructable df2 = df[["year", "month", "day"]].to_dict() @@ -1217,7 +1216,7 @@ def test_dataframe(self, cache): expected2 = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160205 00:0:00")] ) - assert_series_equal(result, expected2) + tm.assert_series_equal(result, expected2) # unit mappings units = [ @@ -1244,7 +1243,7 @@ def test_dataframe(self, cache): expected = Series( [Timestamp("20150204 06:58:10"), Timestamp("20160305 07:59:11")] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) d = { "year": "year", @@ -1265,11 +1264,11 @@ def test_dataframe(self, cache): Timestamp("20160305 07:59:11.001002003"), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # coerce back to int result = to_datetime(df.astype(str), cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # passing coerce df2 = DataFrame({"year": [2015, 2016], "month": [2, 20], "day": [4, 5]}) @@ -1282,7 +1281,7 @@ def test_dataframe(self, cache): to_datetime(df2, cache=cache) result = to_datetime(df2, errors="coerce", cache=cache) expected = Series([Timestamp("20150204 00:00:00"), NaT]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # extra columns msg = "extra keys have been passed to the datetime assemblage: " r"\[foo\]" @@ -1330,7 +1329,7 @@ def test_dataframe_dtypes(self, cache): expected = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:00:00")] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # mixed dtypes df["month"] = df["month"].astype("int8") @@ -1339,7 +1338,7 @@ def test_dataframe_dtypes(self, cache): expected = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:00:00")] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # float df = DataFrame({"year": [2000, 2001], "month": [1.5, 1], "day": [1, 1]}) @@ -1434,7 +1433,7 @@ def test_to_datetime_with_apply(self, cache): td = Series(["May 04", "Jun 02", "Dec 11"], index=[1, 2, 3]) expected = pd.to_datetime(td, format="%b %y", cache=cache) result = td.apply(pd.to_datetime, format="%b %y", cache=cache) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) td = pd.Series(["May 04", "Jun 02", ""], index=[1, 2, 3]) msg = r"time data '' does not match format '%b %y' \(match\)" @@ -1447,7 +1446,7 @@ def test_to_datetime_with_apply(self, cache): result = td.apply( lambda x: pd.to_datetime(x, format="%b %y", errors="coerce", cache=cache) ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_types(self, cache): @@ -1584,10 +1583,10 @@ def test_string_na_nat_conversion(self, cache): else: expected[i] = to_datetime(x, cache=cache) - assert_series_equal(result, expected, check_names=False) + tm.assert_series_equal(result, expected, check_names=False) assert result.name == "foo" - assert_series_equal(dresult, expected, check_names=False) + tm.assert_series_equal(dresult, expected, check_names=False) assert dresult.name == "foo" @pytest.mark.parametrize( @@ -2158,20 +2157,20 @@ def test_to_basic(self, julian_dates): expected = Series( pd.to_datetime(julian_dates - pd.Timestamp(0).to_julian_date(), unit="D") ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = Series(pd.to_datetime([0, 1, 2], unit="D", origin="unix")) expected = Series( [Timestamp("1970-01-01"), Timestamp("1970-01-02"), Timestamp("1970-01-03")] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # default result = Series(pd.to_datetime([0, 1, 2], unit="D")) expected = Series( [Timestamp("1970-01-01"), Timestamp("1970-01-02"), Timestamp("1970-01-03")] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_julian_round_trip(self): result = pd.to_datetime(2456658, origin="julian", unit="D") @@ -2204,7 +2203,7 @@ def test_epoch(self, units, epochs, epoch_1960, units_from_epochs): ) result = Series(pd.to_datetime(units_from_epochs, unit=units, origin=epochs)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "origin, exc", diff --git a/pandas/tests/indexes/multi/test_astype.py b/pandas/tests/indexes/multi/test_astype.py index f320a89c471bf..93fdeb10b849a 100644 --- a/pandas/tests/indexes/multi/test_astype.py +++ b/pandas/tests/indexes/multi/test_astype.py @@ -3,14 +3,14 @@ from pandas.core.dtypes.dtypes import CategoricalDtype -from pandas.util.testing import assert_copy +import pandas.util.testing as tm def test_astype(idx): expected = idx.copy() actual = idx.astype("O") - assert_copy(actual.levels, expected.levels) - assert_copy(actual.codes, expected.codes) + tm.assert_copy(actual.levels, expected.levels) + tm.assert_copy(actual.codes, expected.codes) assert actual.names == list(expected.names) with pytest.raises(TypeError, match="^Setting.*dtype.*object"): diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index ec2e8aa6564a8..9ef2a77205acc 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -14,7 +14,6 @@ ) from pandas.core.indexes.base import InvalidIndexError import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal def test_slice_locs_partial(idx): @@ -145,32 +144,32 @@ def test_get_indexer(): idx2 = index[[1, 3, 5]] r1 = idx1.get_indexer(idx2) - assert_almost_equal(r1, np.array([1, 3, -1], dtype=np.intp)) + tm.assert_almost_equal(r1, np.array([1, 3, -1], dtype=np.intp)) r1 = idx2.get_indexer(idx1, method="pad") e1 = np.array([-1, 0, 0, 1, 1], dtype=np.intp) - assert_almost_equal(r1, e1) + tm.assert_almost_equal(r1, e1) r2 = idx2.get_indexer(idx1[::-1], method="pad") - assert_almost_equal(r2, e1[::-1]) + tm.assert_almost_equal(r2, e1[::-1]) rffill1 = idx2.get_indexer(idx1, method="ffill") - assert_almost_equal(r1, rffill1) + tm.assert_almost_equal(r1, rffill1) r1 = idx2.get_indexer(idx1, method="backfill") e1 = np.array([0, 0, 1, 1, 2], dtype=np.intp) - assert_almost_equal(r1, e1) + tm.assert_almost_equal(r1, e1) r2 = idx2.get_indexer(idx1[::-1], method="backfill") - assert_almost_equal(r2, e1[::-1]) + tm.assert_almost_equal(r2, e1[::-1]) rbfill1 = idx2.get_indexer(idx1, method="bfill") - assert_almost_equal(r1, rbfill1) + tm.assert_almost_equal(r1, rbfill1) # pass non-MultiIndex r1 = idx1.get_indexer(idx2.values) rexp1 = idx1.get_indexer(idx2) - assert_almost_equal(r1, rexp1) + tm.assert_almost_equal(r1, rexp1) r1 = idx1.get_indexer([1, 2, 3]) assert (r1 == [-1, -1, -1]).all() diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 0dc6d24202c34..8d0cb0edf51df 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -43,7 +43,6 @@ from pandas.tests.indexes.common import Base from pandas.tests.indexes.conftest import indices_dict import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal class TestIndex(Base): @@ -1452,7 +1451,7 @@ def test_get_indexer(self): r1 = index1.get_indexer(index2) e1 = np.array([1, 3, -1], dtype=np.intp) - assert_almost_equal(r1, e1) + tm.assert_almost_equal(r1, e1) @pytest.mark.parametrize("reverse", [True, False]) @pytest.mark.parametrize( @@ -1473,7 +1472,7 @@ def test_get_indexer_methods(self, reverse, expected, method): expected = expected[::-1] result = index2.get_indexer(index1, method=method) - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) def test_get_indexer_invalid(self): # GH10411 @@ -1921,7 +1920,7 @@ def test_get_value(self, index): values = np.random.randn(100) value = index[67] - assert_almost_equal(index.get_value(values, value), values[67]) + tm.assert_almost_equal(index.get_value(values, value), values[67]) @pytest.mark.parametrize("values", [["foo", "bar", "quux"], {"foo", "bar", "quux"}]) @pytest.mark.parametrize( diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index 8ed7f1a890c39..61d9d1d70c360 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -11,7 +11,6 @@ from pandas import Categorical, IntervalIndex from pandas.core.indexes.api import CategoricalIndex, Index import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal from .common import Base @@ -678,7 +677,7 @@ def test_get_indexer(self): for indexer in [idx2, list("abf"), Index(list("abf"))]: r1 = idx1.get_indexer(idx2) - assert_almost_equal(r1, np.array([0, 1, 2, -1], dtype=np.intp)) + tm.assert_almost_equal(r1, np.array([0, 1, 2, -1], dtype=np.intp)) msg = ( "method='pad' and method='backfill' not implemented yet for" diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py index 446b67d5f501d..4448b5e39684b 100644 --- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py +++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import Series, Timedelta, timedelta_range -from pandas.util.testing import assert_series_equal +import pandas.util.testing as tm class TestSlicing: @@ -18,15 +18,15 @@ def test_partial_slice(self): result = s["5 day":"6 day"] expected = s.iloc[86:134] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s["5 day":] expected = s.iloc[86:] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s[:"6 day"] expected = s.iloc[:134] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s["6 days, 23:11:12"] assert result == s.iloc[133] @@ -43,11 +43,11 @@ def test_partial_slice_high_reso(self): result = s["1 day 10:11:12":] expected = s.iloc[0:] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s["1 day 10:11:12.001":] expected = s.iloc[1000:] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s["1 days, 10:11:12.001001"] assert result == s.iloc[1001] @@ -57,9 +57,9 @@ def test_slice_with_negative_step(self): SLC = pd.IndexSlice def assert_slices_equivalent(l_slc, i_slc): - assert_series_equal(ts[l_slc], ts.iloc[i_slc]) - assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc]) - assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc]) + tm.assert_series_equal(ts[l_slc], ts.iloc[i_slc]) + tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc]) + tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc]) assert_slices_equivalent(SLC[Timedelta(hours=7) :: -1], SLC[7::-1]) assert_slices_equivalent(SLC["7 hours"::-1], SLC[7::-1]) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 2ef86ddf8c8bf..ba0af7dd8136c 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -16,11 +16,6 @@ timedelta_range, ) import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_index_equal, - assert_series_equal, -) from ..datetimelike import DatetimeLike @@ -118,7 +113,7 @@ def test_isin(self): result = index.isin(list(index)) assert result.all() - assert_almost_equal( + tm.assert_almost_equal( index.isin([index[2], 5]), np.array([False, False, True, False]) ) @@ -309,36 +304,36 @@ def test_freq_conversion(self): result = td / np.timedelta64(1, "D") expected = Series([31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = td.astype("timedelta64[D]") expected = Series([31, 31, 31, np.nan]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = td / np.timedelta64(1, "s") expected = Series([31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = td.astype("timedelta64[s]") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # tdi td = TimedeltaIndex(td) result = td / np.timedelta64(1, "D") expected = Index([31, 31, (31 * 86400 + 5 * 60 + 3) / 86400.0, np.nan]) - assert_index_equal(result, expected) + tm.assert_index_equal(result, expected) result = td.astype("timedelta64[D]") expected = Index([31, 31, 31, np.nan]) - assert_index_equal(result, expected) + tm.assert_index_equal(result, expected) result = td / np.timedelta64(1, "s") expected = Index([31 * 86400, 31 * 86400, 31 * 86400 + 5 * 60 + 3, np.nan]) - assert_index_equal(result, expected) + tm.assert_index_equal(result, expected) result = td.astype("timedelta64[s]") - assert_index_equal(result, expected) + tm.assert_index_equal(result, expected) @pytest.mark.parametrize("unit", ["Y", "y", "M"]) def test_unit_m_y_deprecated(self, unit): diff --git a/pandas/tests/indexes/timedeltas/test_tools.py b/pandas/tests/indexes/timedeltas/test_tools.py index 4aed0b1af81a6..2b4a6722666bf 100644 --- a/pandas/tests/indexes/timedeltas/test_tools.py +++ b/pandas/tests/indexes/timedeltas/test_tools.py @@ -8,7 +8,6 @@ import pandas as pd from pandas import Series, TimedeltaIndex, isna, to_timedelta import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal class TestTimedeltas: @@ -192,10 +191,10 @@ def test_to_timedelta_on_missing_values(self): expected = Series( [np.timedelta64(1000000000, "ns"), timedelta_NaT], dtype="<m8[ns]" ) - assert_series_equal(actual, expected) + tm.assert_series_equal(actual, expected) actual = pd.to_timedelta(Series(["00:00:01", pd.NaT])) - assert_series_equal(actual, expected) + tm.assert_series_equal(actual, expected) actual = pd.to_timedelta(np.nan) assert actual.value == timedelta_NaT.astype("int64")
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29289
2019-10-30T14:19:15Z
2019-10-31T07:55:23Z
2019-10-31T07:55:23Z
2019-10-31T07:55:28Z
CLN: Consistent pandas.util.testing imports in pandas/tests/groupby
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 0e30b104bf9d2..ad5d2315f7e33 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -17,7 +17,6 @@ qcut, ) import pandas.util.testing as tm -from pandas.util.testing import assert_equal, assert_frame_equal, assert_series_equal def cartesian_product_for_groupers(result, args, names): @@ -159,7 +158,7 @@ def f(x): exp_idx = CategoricalIndex(levels, categories=cats.categories, ordered=True) expected = expected.reindex(exp_idx) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) grouped = data.groupby(cats, observed=False) desc_result = grouped.describe() @@ -172,7 +171,7 @@ def f(x): ord_labels, ordered=True, categories=["foo", "bar", "baz", "qux"] ) expected = ord_data.groupby(exp_cats, sort=False, observed=False).describe() - assert_frame_equal(desc_result, expected) + tm.assert_frame_equal(desc_result, expected) # GH 10460 expc = Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True) @@ -206,7 +205,7 @@ def test_level_get_group(observed): ) result = g.get_group("a") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH#21636 flaky on py37; may be related to older numpy, see discussion @@ -232,21 +231,21 @@ def test_apply(ordered): # is coming back as Series([0., 1., 0.], index=["missing", "dense", "values"]) # when we expect Series(0., index=["values"]) result = grouped.apply(lambda x: np.mean(x)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # we coerce back to ints expected = expected.astype("int") result = grouped.mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = grouped.agg(np.mean) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # but for transform we should still get back the original index idx = MultiIndex.from_arrays([missing, dense], names=["missing", "dense"]) expected = Series(1, index=idx) result = grouped.apply(lambda x: 1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_observed(observed): @@ -335,7 +334,7 @@ def test_observed(observed): c, i = key result = groups_double_key.get_group(key) expected = df[(df.cat == c) & (df.ints == i)] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # gh-8869 # with as_index @@ -522,7 +521,7 @@ def test_datetime(): expected.index, categories=expected.index, ordered=True ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) grouped = data.groupby(cats, observed=False) desc_result = grouped.describe() @@ -531,7 +530,7 @@ def test_datetime(): ord_labels = cats.take(idx) ord_data = data.take(idx) expected = ord_data.groupby(ord_labels, observed=False).describe() - assert_frame_equal(desc_result, expected) + tm.assert_frame_equal(desc_result, expected) tm.assert_index_equal(desc_result.index, expected.index) tm.assert_index_equal( desc_result.index.get_level_values(0), expected.index.get_level_values(0) @@ -560,7 +559,7 @@ def test_categorical_index(): expected.index = CategoricalIndex( Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # with a cat column, should produce a cat index result = df.groupby("cats", observed=False).sum() @@ -568,7 +567,7 @@ def test_categorical_index(): expected.index = CategoricalIndex( Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_describe_categorical_columns(): @@ -757,7 +756,7 @@ def test_categorical_no_compress(): exp.index = CategoricalIndex( exp.index, categories=cats.categories, ordered=cats.ordered ) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3]) cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True) @@ -767,7 +766,7 @@ def test_categorical_no_compress(): exp.index = CategoricalIndex( exp.index, categories=cats.categories, ordered=cats.ordered ) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) cats = Categorical( ["a", "a", "a", "b", "b", "b", "c", "c", "c"], @@ -829,12 +828,12 @@ def test_sort2(): col = "range" result_sort = df.groupby(col, sort=True, observed=False).first() - assert_frame_equal(result_sort, expected_sort) + tm.assert_frame_equal(result_sort, expected_sort) # when categories is ordered, group is ordered by category's order expected_sort = result_sort result_sort = df.groupby(col, sort=False, observed=False).first() - assert_frame_equal(result_sort, expected_sort) + tm.assert_frame_equal(result_sort, expected_sort) df["range"] = Categorical(df["range"], ordered=False) index = CategoricalIndex( @@ -857,10 +856,10 @@ def test_sort2(): # this is an unordered categorical, but we allow this #### result_sort = df.groupby(col, sort=True, observed=False).first() - assert_frame_equal(result_sort, expected_sort) + tm.assert_frame_equal(result_sort, expected_sort) result_nosort = df.groupby(col, sort=False, observed=False).first() - assert_frame_equal(result_nosort, expected_nosort) + tm.assert_frame_equal(result_nosort, expected_nosort) def test_sort_datetimelike(): @@ -912,10 +911,14 @@ def test_sort_datetimelike(): ) col = "dt" - assert_frame_equal(result_sort, df.groupby(col, sort=True, observed=False).first()) + tm.assert_frame_equal( + result_sort, df.groupby(col, sort=True, observed=False).first() + ) # when categories is ordered, group is ordered by category's order - assert_frame_equal(result_sort, df.groupby(col, sort=False, observed=False).first()) + tm.assert_frame_equal( + result_sort, df.groupby(col, sort=False, observed=False).first() + ) # ordered = False df["dt"] = Categorical(df["dt"], ordered=False) @@ -942,8 +945,10 @@ def test_sort_datetimelike(): result_nosort.index = CategoricalIndex(index, categories=index, name="dt") col = "dt" - assert_frame_equal(result_sort, df.groupby(col, sort=True, observed=False).first()) - assert_frame_equal( + tm.assert_frame_equal( + result_sort, df.groupby(col, sort=True, observed=False).first() + ) + tm.assert_frame_equal( result_nosort, df.groupby(col, sort=False, observed=False).first() ) @@ -1022,7 +1027,7 @@ def test_groupby_multiindex_categorical_datetime(): names=["key1", "key2"], ) expected = DataFrame({"values": [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( @@ -1058,7 +1063,7 @@ def test_groupby_agg_observed_true_single_column(as_index, expected): result = df.groupby(["a", "b"], as_index=as_index, observed=True)["x"].sum() - assert_equal(result, expected) + tm.assert_equal(result, expected) @pytest.mark.parametrize("fill_value", [None, np.nan, pd.NaT]) @@ -1070,7 +1075,7 @@ def test_shift(fill_value): [None, "a", "b", "c"], categories=["a", "b", "c", "d"], ordered=False ) res = ct.shift(1, fill_value=fill_value) - assert_equal(res, expected) + tm.assert_equal(res, expected) @pytest.fixture @@ -1112,7 +1117,7 @@ def test_seriesgroupby_observed_true(df_cat, operation, kwargs): expected = Series(data=[1, 3, 2, 4], index=index, name="C") grouped = df_cat.groupby(["A", "B"], observed=True)["C"] result = getattr(grouped, operation)(sum) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("operation", ["agg", "apply"]) @@ -1130,7 +1135,7 @@ def test_seriesgroupby_observed_false_or_none(df_cat, observed, operation): expected = Series(data=[2, 4, np.nan, 1, np.nan, 3], index=index, name="C") grouped = df_cat.groupby(["A", "B"], observed=observed)["C"] result = getattr(grouped, operation)(sum) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -1185,7 +1190,7 @@ def test_seriesgroupby_observed_apply_dict(df_cat, observed, index, data): result = df_cat.groupby(["A", "B"], observed=observed)["C"].apply( lambda x: OrderedDict([("min", x.min()), ("max", x.max())]) ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("code", [([1, 0, 0]), ([0, 0, 0])]) @@ -1195,7 +1200,7 @@ def test_groupby_categorical_axis_1(code): cat = pd.Categorical.from_codes(code, categories=list("abc")) result = df.groupby(cat, axis=1).mean() expected = df.T.groupby(cat, axis=0).mean().T - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_cat_preserves_structure(observed, ordered_fixture): @@ -1212,7 +1217,7 @@ def test_groupby_cat_preserves_structure(observed, ordered_fixture): .reset_index() ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_get_nonexistent_category(): diff --git a/pandas/tests/groupby/test_counting.py b/pandas/tests/groupby/test_counting.py index 7e5180a5c7b2b..9882f12714d2d 100644 --- a/pandas/tests/groupby/test_counting.py +++ b/pandas/tests/groupby/test_counting.py @@ -4,7 +4,7 @@ import pytest from pandas import DataFrame, MultiIndex, Period, Series, Timedelta, Timestamp -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm class TestCounting: @@ -15,8 +15,8 @@ def test_cumcount(self): expected = Series([0, 1, 2, 0, 3]) - assert_series_equal(expected, g.cumcount()) - assert_series_equal(expected, sg.cumcount()) + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) def test_cumcount_empty(self): ge = DataFrame().groupby(level=0) @@ -25,8 +25,8 @@ def test_cumcount_empty(self): # edge case, as this is usually considered float e = Series(dtype="int64") - assert_series_equal(e, ge.cumcount()) - assert_series_equal(e, se.cumcount()) + tm.assert_series_equal(e, ge.cumcount()) + tm.assert_series_equal(e, se.cumcount()) def test_cumcount_dupe_index(self): df = DataFrame( @@ -37,8 +37,8 @@ def test_cumcount_dupe_index(self): expected = Series([0, 1, 2, 0, 3], index=[0] * 5) - assert_series_equal(expected, g.cumcount()) - assert_series_equal(expected, sg.cumcount()) + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) def test_cumcount_mi(self): mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]]) @@ -48,8 +48,8 @@ def test_cumcount_mi(self): expected = Series([0, 1, 2, 0, 3], index=mi) - assert_series_equal(expected, g.cumcount()) - assert_series_equal(expected, sg.cumcount()) + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) def test_cumcount_groupby_not_col(self): df = DataFrame( @@ -60,8 +60,8 @@ def test_cumcount_groupby_not_col(self): expected = Series([0, 1, 2, 0, 3], index=[0] * 5) - assert_series_equal(expected, g.cumcount()) - assert_series_equal(expected, sg.cumcount()) + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) def test_ngroup(self): df = DataFrame({"A": list("aaaba")}) @@ -70,8 +70,8 @@ def test_ngroup(self): expected = Series([0, 0, 0, 1, 0]) - assert_series_equal(expected, g.ngroup()) - assert_series_equal(expected, sg.ngroup()) + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) def test_ngroup_distinct(self): df = DataFrame({"A": list("abcde")}) @@ -80,8 +80,8 @@ def test_ngroup_distinct(self): expected = Series(range(5), dtype="int64") - assert_series_equal(expected, g.ngroup()) - assert_series_equal(expected, sg.ngroup()) + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) def test_ngroup_one_group(self): df = DataFrame({"A": [0] * 5}) @@ -90,8 +90,8 @@ def test_ngroup_one_group(self): expected = Series([0] * 5) - assert_series_equal(expected, g.ngroup()) - assert_series_equal(expected, sg.ngroup()) + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) def test_ngroup_empty(self): ge = DataFrame().groupby(level=0) @@ -100,14 +100,14 @@ def test_ngroup_empty(self): # edge case, as this is usually considered float e = Series(dtype="int64") - assert_series_equal(e, ge.ngroup()) - assert_series_equal(e, se.ngroup()) + tm.assert_series_equal(e, ge.ngroup()) + tm.assert_series_equal(e, se.ngroup()) def test_ngroup_series_matches_frame(self): df = DataFrame({"A": list("aaaba")}) s = Series(list("aaaba")) - assert_series_equal(df.groupby(s).ngroup(), s.groupby(s).ngroup()) + tm.assert_series_equal(df.groupby(s).ngroup(), s.groupby(s).ngroup()) def test_ngroup_dupe_index(self): df = DataFrame({"A": list("aaaba")}, index=[0] * 5) @@ -116,8 +116,8 @@ def test_ngroup_dupe_index(self): expected = Series([0, 0, 0, 1, 0], index=[0] * 5) - assert_series_equal(expected, g.ngroup()) - assert_series_equal(expected, sg.ngroup()) + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) def test_ngroup_mi(self): mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]]) @@ -126,8 +126,8 @@ def test_ngroup_mi(self): sg = g.A expected = Series([0, 0, 0, 1, 0], index=mi) - assert_series_equal(expected, g.ngroup()) - assert_series_equal(expected, sg.ngroup()) + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) def test_ngroup_groupby_not_col(self): df = DataFrame({"A": list("aaaba")}, index=[0] * 5) @@ -136,8 +136,8 @@ def test_ngroup_groupby_not_col(self): expected = Series([0, 0, 0, 1, 0], index=[0] * 5) - assert_series_equal(expected, g.ngroup()) - assert_series_equal(expected, sg.ngroup()) + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) def test_ngroup_descending(self): df = DataFrame(["a", "a", "b", "a", "b"], columns=["A"]) @@ -146,9 +146,9 @@ def test_ngroup_descending(self): ascending = Series([0, 0, 1, 0, 1]) descending = Series([1, 1, 0, 1, 0]) - assert_series_equal(descending, (g.ngroups - 1) - ascending) - assert_series_equal(ascending, g.ngroup(ascending=True)) - assert_series_equal(descending, g.ngroup(ascending=False)) + tm.assert_series_equal(descending, (g.ngroups - 1) - ascending) + tm.assert_series_equal(ascending, g.ngroup(ascending=True)) + tm.assert_series_equal(descending, g.ngroup(ascending=False)) def test_ngroup_matches_cumcount(self): # verify one manually-worked out case works @@ -162,8 +162,8 @@ def test_ngroup_matches_cumcount(self): expected_ngroup = Series([0, 1, 2, 0, 3]) expected_cumcount = Series([0, 0, 0, 1, 0]) - assert_series_equal(g_ngroup, expected_ngroup) - assert_series_equal(g_cumcount, expected_cumcount) + tm.assert_series_equal(g_ngroup, expected_ngroup) + tm.assert_series_equal(g_cumcount, expected_cumcount) def test_ngroup_cumcount_pair(self): # brute force comparison for all small series @@ -175,8 +175,8 @@ def test_ngroup_cumcount_pair(self): ngroupd = [order.index(val) for val in p] cumcounted = [p[:i].count(val) for i, val in enumerate(p)] - assert_series_equal(g.ngroup(), Series(ngroupd)) - assert_series_equal(g.cumcount(), Series(cumcounted)) + tm.assert_series_equal(g.ngroup(), Series(ngroupd)) + tm.assert_series_equal(g.cumcount(), Series(cumcounted)) def test_ngroup_respects_groupby_order(self): np.random.seed(0) @@ -191,8 +191,8 @@ def test_ngroup_respects_groupby_order(self): for j, ind in enumerate(group.index): df.loc[ind, "group_index"] = j - assert_series_equal(Series(df["group_id"].values), g.ngroup()) - assert_series_equal(Series(df["group_index"].values), g.cumcount()) + tm.assert_series_equal(Series(df["group_id"].values), g.ngroup()) + tm.assert_series_equal(Series(df["group_index"].values), g.cumcount()) @pytest.mark.parametrize( "datetimelike", @@ -214,7 +214,7 @@ def test_count_with_datetimelike(self, datetimelike): res = df.groupby("x").count() expected = DataFrame({"y": [2, 1]}, index=["a", "b"]) expected.index.name = "x" - assert_frame_equal(expected, res) + tm.assert_frame_equal(expected, res) def test_count_with_only_nans_in_first_group(self): # GH21956 @@ -222,4 +222,4 @@ def test_count_with_only_nans_in_first_group(self): result = df.groupby(["A", "B"]).C.count() mi = MultiIndex(levels=[[], ["a", "b"]], codes=[[], []], names=["A", "B"]) expected = Series([], index=mi, dtype=np.int64, name="C") - assert_series_equal(result, expected, check_index_type=False) + tm.assert_series_equal(result, expected, check_index_type=False) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 43e2a6f040414..e17181f55fdba 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -12,11 +12,6 @@ from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv import pandas.core.common as com import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) def test_repr(): @@ -43,17 +38,19 @@ def test_basic(dtype): agged = grouped.aggregate(np.mean) assert agged[1] == 1 - assert_series_equal(agged, grouped.agg(np.mean)) # shorthand - assert_series_equal(agged, grouped.mean()) - assert_series_equal(grouped.agg(np.sum), grouped.sum()) + tm.assert_series_equal(agged, grouped.agg(np.mean)) # shorthand + tm.assert_series_equal(agged, grouped.mean()) + tm.assert_series_equal(grouped.agg(np.sum), grouped.sum()) expected = grouped.apply(lambda x: x * x.sum()) transformed = grouped.transform(lambda x: x * x.sum()) assert transformed[7] == 12 - assert_series_equal(transformed, expected) + tm.assert_series_equal(transformed, expected) value_grouped = data.groupby(data) - assert_series_equal(value_grouped.aggregate(np.mean), agged, check_index_type=False) + tm.assert_series_equal( + value_grouped.aggregate(np.mean), agged, check_index_type=False + ) # complex agg agged = grouped.aggregate([np.mean, np.std]) @@ -78,7 +75,7 @@ def test_groupby_nonobject_dtype(mframe, df_mixed_floats): result = grouped.sum() expected = mframe.groupby(key.astype("O")).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH 3911, mixed frame non-conversion df = df_mixed_floats.copy() @@ -93,7 +90,7 @@ def max_value(group): [np.dtype("object")] * 2 + [np.dtype("float64")] * 2 + [np.dtype("int64")], index=["A", "B", "C", "D", "value"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_return_type(): @@ -151,7 +148,7 @@ def f(grp): expected = df.groupby("A").first()[["B"]] result = df.groupby("A").apply(f)[["B"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def f(grp): if grp.name == "Tiger": @@ -161,7 +158,7 @@ def f(grp): result = df.groupby("A").apply(f)[["B"]] e = expected.copy() e.loc["Tiger"] = np.nan - assert_frame_equal(result, e) + tm.assert_frame_equal(result, e) def f(grp): if grp.name == "Pony": @@ -171,7 +168,7 @@ def f(grp): result = df.groupby("A").apply(f)[["B"]] e = expected.copy() e.loc["Pony"] = np.nan - assert_frame_equal(result, e) + tm.assert_frame_equal(result, e) # 5592 revisited, with datetimes def f(grp): @@ -182,7 +179,7 @@ def f(grp): result = df.groupby("A").apply(f)[["C"]] e = df.groupby("A").first()[["C"]] e.loc["Pony"] = pd.NaT - assert_frame_equal(result, e) + tm.assert_frame_equal(result, e) # scalar outputs def f(grp): @@ -194,7 +191,7 @@ def f(grp): e = df.groupby("A").first()["C"].copy() e.loc["Pony"] = np.nan e.name = None - assert_series_equal(result, e) + tm.assert_series_equal(result, e) def test_pass_args_kwargs(ts, tsframe): @@ -212,29 +209,29 @@ def f(x, q=None, axis=0): agg_expected = ts_grouped.quantile(0.8) trans_expected = ts_grouped.transform(g) - assert_series_equal(apply_result, agg_expected) - assert_series_equal(agg_result, agg_expected) - assert_series_equal(trans_result, trans_expected) + tm.assert_series_equal(apply_result, agg_expected) + tm.assert_series_equal(agg_result, agg_expected) + tm.assert_series_equal(trans_result, trans_expected) agg_result = ts_grouped.agg(f, q=80) apply_result = ts_grouped.apply(f, q=80) trans_result = ts_grouped.transform(f, q=80) - assert_series_equal(agg_result, agg_expected) - assert_series_equal(apply_result, agg_expected) - assert_series_equal(trans_result, trans_expected) + tm.assert_series_equal(agg_result, agg_expected) + tm.assert_series_equal(apply_result, agg_expected) + tm.assert_series_equal(trans_result, trans_expected) # DataFrame df_grouped = tsframe.groupby(lambda x: x.month) agg_result = df_grouped.agg(np.percentile, 80, axis=0) apply_result = df_grouped.apply(DataFrame.quantile, 0.8) expected = df_grouped.quantile(0.8) - assert_frame_equal(apply_result, expected, check_names=False) - assert_frame_equal(agg_result, expected) + tm.assert_frame_equal(apply_result, expected, check_names=False) + tm.assert_frame_equal(agg_result, expected) agg_result = df_grouped.agg(f, q=80) apply_result = df_grouped.apply(DataFrame.quantile, q=0.8) - assert_frame_equal(agg_result, expected) - assert_frame_equal(apply_result, expected, check_names=False) + tm.assert_frame_equal(agg_result, expected) + tm.assert_frame_equal(apply_result, expected, check_names=False) def test_len(): @@ -280,7 +277,7 @@ def test_with_na_groups(dtype): agged = grouped.agg(len) expected = Series([4, 2], index=["bar", "foo"]) - assert_series_equal(agged, expected, check_dtype=False) + tm.assert_series_equal(agged, expected, check_dtype=False) # assert issubclass(agged.dtype.type, np.integer) @@ -291,7 +288,7 @@ def f(x): agged = grouped.agg(f) expected = Series([4, 2], index=["bar", "foo"]) - assert_series_equal(agged, expected, check_dtype=False) + tm.assert_series_equal(agged, expected, check_dtype=False) assert issubclass(agged.dtype.type, np.dtype(dtype).type) @@ -335,7 +332,7 @@ def f3(x): # correct result result1 = df.groupby("a").apply(f1) result2 = df2.groupby("a").apply(f1) - assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result2) # should fail (not the same number of levels) msg = "Cannot concat indices that do not have the same number of levels" @@ -356,13 +353,13 @@ def test_attr_wrapper(ts): result = grouped.std() expected = grouped.agg(lambda x: np.std(x, ddof=1)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # this is pretty cool result = grouped.describe() expected = {name: gp.describe() for name, gp in grouped} expected = DataFrame(expected).T - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # get attribute result = grouped.dtype @@ -386,7 +383,7 @@ def test_frame_groupby(tsframe): tscopy = tsframe.copy() tscopy["weekday"] = [x.weekday() for x in tscopy.index] stragged = tscopy.groupby("weekday").aggregate(np.mean) - assert_frame_equal(stragged, aggregated, check_names=False) + tm.assert_frame_equal(stragged, aggregated, check_names=False) # transform grouped = tsframe.head(30).groupby(lambda x: x.weekday()) @@ -426,7 +423,7 @@ def test_frame_groupby_columns(tsframe): # transform tf = lambda x: x - x.mean() groupedT = tsframe.T.groupby(mapping, axis=0) - assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf)) + tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf)) # iterate for k, v in grouped: @@ -469,7 +466,7 @@ def test_multi_func(df): expected = df.groupby(["A", "B"]).mean() # TODO groupby get drops names - assert_frame_equal( + tm.assert_frame_equal( agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False ) @@ -493,7 +490,7 @@ def test_multi_key_multiple_functions(df): agged = grouped.agg([np.mean, np.std]) expected = DataFrame({"mean": grouped.agg(np.mean), "std": grouped.agg(np.std)}) - assert_frame_equal(agged, expected) + tm.assert_frame_equal(agged, expected) def test_frame_multi_key_function_list(): @@ -554,7 +551,7 @@ def test_frame_multi_key_function_list(): ) assert isinstance(agged.index, MultiIndex) assert isinstance(expected.index, MultiIndex) - assert_frame_equal(agged, expected) + tm.assert_frame_equal(agged, expected) @pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()]) @@ -580,14 +577,14 @@ def test_groupby_multiple_columns(df, op): result_col = op(grouped[col]) pivoted = result1[col] exp = expected[col] - assert_series_equal(result_col, exp) - assert_series_equal(pivoted, exp) + tm.assert_series_equal(result_col, exp) + tm.assert_series_equal(pivoted, exp) # test single series works the same result = data["C"].groupby([data["A"], data["B"]]).mean() expected = data.groupby(["A", "B"]).mean()["C"] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_as_index_agg(df): @@ -597,12 +594,12 @@ def test_groupby_as_index_agg(df): result = grouped.agg(np.mean) expected = grouped.mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result2 = grouped.agg(OrderedDict([["C", np.mean], ["D", np.sum]])) expected2 = grouped.mean() expected2["D"] = grouped.sum()["D"] - assert_frame_equal(result2, expected2) + tm.assert_frame_equal(result2, expected2) grouped = df.groupby("A", as_index=True) expected3 = grouped["C"].sum() @@ -610,7 +607,7 @@ def test_groupby_as_index_agg(df): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result3 = grouped["C"].agg({"Q": np.sum}) - assert_frame_equal(result3, expected3) + tm.assert_frame_equal(result3, expected3) # multi-key @@ -618,17 +615,17 @@ def test_groupby_as_index_agg(df): result = grouped.agg(np.mean) expected = grouped.mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result2 = grouped.agg(OrderedDict([["C", np.mean], ["D", np.sum]])) expected2 = grouped.mean() expected2["D"] = grouped.sum()["D"] - assert_frame_equal(result2, expected2) + tm.assert_frame_equal(result2, expected2) expected3 = grouped["C"].sum() expected3 = DataFrame(expected3).rename(columns={"C": "Q"}) result3 = grouped["C"].agg({"Q": np.sum}) - assert_frame_equal(result3, expected3) + tm.assert_frame_equal(result3, expected3) # GH7115 & GH8112 & GH8582 df = DataFrame(np.random.randint(0, 100, (50, 3)), columns=["jim", "joe", "jolie"]) @@ -636,7 +633,7 @@ def test_groupby_as_index_agg(df): gr = df.groupby(ts) gr.nth(0) # invokes set_selection_from_grouper internally - assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum)) + tm.assert_frame_equal(gr.apply(sum), df.groupby(ts).apply(sum)) for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]: gr = df.groupby(ts, as_index=False) @@ -645,7 +642,7 @@ def test_groupby_as_index_agg(df): gr = df.groupby(ts.values, as_index=True) right = getattr(gr, attr)().reset_index(drop=True) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) def test_as_index_series_return_frame(df): @@ -655,22 +652,22 @@ def test_as_index_series_return_frame(df): result = grouped["C"].agg(np.sum) expected = grouped.agg(np.sum).loc[:, ["A", "C"]] assert isinstance(result, DataFrame) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result2 = grouped2["C"].agg(np.sum) expected2 = grouped2.agg(np.sum).loc[:, ["A", "B", "C"]] assert isinstance(result2, DataFrame) - assert_frame_equal(result2, expected2) + tm.assert_frame_equal(result2, expected2) result = grouped["C"].sum() expected = grouped.sum().loc[:, ["A", "C"]] assert isinstance(result, DataFrame) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result2 = grouped2["C"].sum() expected2 = grouped2.sum().loc[:, ["A", "B", "C"]] assert isinstance(result2, DataFrame) - assert_frame_equal(result2, expected2) + tm.assert_frame_equal(result2, expected2) def test_as_index_series_column_slice_raises(df): @@ -691,7 +688,7 @@ def test_groupby_as_index_cython(df): expected = data.groupby(["A"]).mean() expected.insert(0, "A", expected.index) expected.index = np.arange(len(expected)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # multi-key grouped = data.groupby(["A", "B"], as_index=False) @@ -702,7 +699,7 @@ def test_groupby_as_index_cython(df): expected.insert(0, "A", arrays[0]) expected.insert(1, "B", arrays[1]) expected.index = np.arange(len(expected)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_as_index_series_scalar(df): @@ -712,7 +709,7 @@ def test_groupby_as_index_series_scalar(df): result = grouped["C"].agg(len) expected = grouped.agg(len).loc[:, ["A", "B", "C"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_as_index_corner(df, ts): @@ -729,7 +726,7 @@ def test_groupby_multiple_key(df): df = tm.makeTimeDataFrame() grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) agged = grouped.sum() - assert_almost_equal(df.values, agged.values) + tm.assert_almost_equal(df.values, agged.values) grouped = df.T.groupby( [lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1 @@ -737,10 +734,10 @@ def test_groupby_multiple_key(df): agged = grouped.agg(lambda x: x.sum()) tm.assert_index_equal(agged.index, df.columns) - assert_almost_equal(df.T.values, agged.values) + tm.assert_almost_equal(df.T.values, agged.values) agged = grouped.agg(lambda x: x.sum()) - assert_almost_equal(df.T.values, agged.values) + tm.assert_almost_equal(df.T.values, agged.values) def test_groupby_multi_corner(df): @@ -752,7 +749,7 @@ def test_groupby_multi_corner(df): expected = df.groupby(["A", "B"]).mean() expected["bad"] = np.nan - assert_frame_equal(agged, expected) + tm.assert_frame_equal(agged, expected) def test_omit_nuisance(df): @@ -760,18 +757,18 @@ def test_omit_nuisance(df): result = grouped.mean() expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) agged = grouped.agg(np.mean) exp = grouped.mean() - assert_frame_equal(agged, exp) + tm.assert_frame_equal(agged, exp) df = df.loc[:, ["A", "C", "D"]] df["E"] = datetime.now() grouped = df.groupby("A") result = grouped.agg(np.sum) expected = grouped.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # won't work with axis = 1 grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1) @@ -785,7 +782,7 @@ def test_omit_nuisance_python_multiple(three_group): agged = grouped.agg(np.mean) exp = grouped.mean() - assert_frame_equal(agged, exp) + tm.assert_frame_equal(agged, exp) def test_empty_groups_corner(mframe): @@ -803,12 +800,12 @@ def test_empty_groups_corner(mframe): grouped = df.groupby(["k1", "k2"]) result = grouped.agg(np.mean) expected = grouped.mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) grouped = mframe[3:5].groupby(level=0) agged = grouped.apply(lambda x: x.mean()) agged_A = grouped["A"].apply(np.mean) - assert_series_equal(agged["A"], agged_A) + tm.assert_series_equal(agged["A"], agged_A) assert agged.index.name == "first" @@ -863,8 +860,8 @@ def test_groupby_level_mapper(mframe): expected1 = mframe.groupby(mapped_level1).sum() expected0.index.name, expected1.index.name = "first", "second" - assert_frame_equal(result0, expected0) - assert_frame_equal(result1, expected1) + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) def test_groupby_level_nonmulti(): @@ -905,10 +902,10 @@ def test_groupby_complex(): expected = Series((1 + 2j, 5 + 10j)) result = a.groupby(level=0).sum() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = a.sum(level=0) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_mutate_groups(): @@ -941,7 +938,7 @@ def f_no_copy(x): grpby_copy = df.groupby("cat1").apply(f_copy) grpby_no_copy = df.groupby("cat1").apply(f_no_copy) - assert_series_equal(grpby_copy, grpby_no_copy) + tm.assert_series_equal(grpby_copy, grpby_no_copy) def test_no_mutate_but_looks_like(): @@ -953,7 +950,7 @@ def test_no_mutate_but_looks_like(): result1 = df.groupby("key", group_keys=True).apply(lambda x: x[:].key) result2 = df.groupby("key", group_keys=True).apply(lambda x: x.key) - assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result2) def test_groupby_series_indexed_differently(): @@ -968,7 +965,7 @@ def test_groupby_series_indexed_differently(): grouped = s1.groupby(s2) agged = grouped.mean() exp = s1.groupby(s2.reindex(s1.index).get).mean() - assert_series_equal(agged, exp) + tm.assert_series_equal(agged, exp) def test_groupby_with_hier_columns(): @@ -1014,7 +1011,7 @@ def test_grouping_ndarray(df): result = grouped.sum() expected = df.groupby("A").sum() - assert_frame_equal( + tm.assert_frame_equal( result, expected, check_names=False ) # Note: no names when grouping by value @@ -1033,7 +1030,7 @@ def test_groupby_wrong_multi_labels(): result = grouped.agg(np.mean) expected = grouped.mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_series_with_name(df): @@ -1073,7 +1070,7 @@ def test_consistency_name(): expected = df.groupby(["A"]).B.count() result = df.B.groupby(df.A).count() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_name_propagation(df): @@ -1100,7 +1097,7 @@ def test_groupby_nonstring_columns(): grouped = df.groupby(0) result = grouped.mean() expected = df.groupby(df[0]).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_mixed_type_columns(): @@ -1173,13 +1170,13 @@ def test_groupby_dtype_inference_empty(): result = df.groupby("x").first() exp_index = Index([], name="x", dtype=np.float64) expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")}) - assert_frame_equal(result, expected, by_blocks=True) + tm.assert_frame_equal(result, expected, by_blocks=True) def test_groupby_list_infer_array_like(df): result = df.groupby(list(df["A"])).mean() expected = df.groupby(df["A"]).mean() - assert_frame_equal(result, expected, check_names=False) + tm.assert_frame_equal(result, expected, check_names=False) with pytest.raises(KeyError, match=r"^'foo'$"): df.groupby(list(df["A"][:-1])) @@ -1201,7 +1198,7 @@ def test_groupby_keys_same_size_as_index(): result = df.groupby([pd.Grouper(level=0, freq=freq), "metric"]).mean() expected = df.set_index([df.index, "metric"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_one_row(): @@ -1347,7 +1344,7 @@ def test_dont_clobber_name_column(): ) result = df.groupby("key").apply(lambda x: x) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_skip_group_keys(): @@ -1360,7 +1357,7 @@ def test_skip_group_keys(): pieces = [group.sort_values(by="A")[:3] for key, group in grouped] expected = pd.concat(pieces) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False) result = grouped.apply(lambda x: x.sort_values()[:3]) @@ -1368,7 +1365,7 @@ def test_skip_group_keys(): pieces = [group.sort_values()[:3] for key, group in grouped] expected = pd.concat(pieces) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_no_nonsense_name(float_frame): @@ -1402,7 +1399,7 @@ def g(group): expected = df.groupby("A")["C"].apply(g) assert isinstance(result, Series) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("grouper", ["A", ["A", "B"]]) @@ -1473,9 +1470,9 @@ def test_groupby_sort_multiindex_series(): mseries_result = Series([0, 2, 4], index=index) result = mseries.groupby(level=["a", "b"], sort=False).first() - assert_series_equal(result, mseries_result) + tm.assert_series_equal(result, mseries_result) result = mseries.groupby(level=["a", "b"], sort=True).first() - assert_series_equal(result, mseries_result.sort_index()) + tm.assert_series_equal(result, mseries_result.sort_index()) def test_groupby_reindex_inside_function(): @@ -1507,7 +1504,7 @@ def afunc(data): closure_bad = grouped.agg({"high": agg_before(11, np.max)}) closure_good = grouped.agg({"high": agg_before(11, np.max, True)}) - assert_frame_equal(closure_bad, closure_good) + tm.assert_frame_equal(closure_bad, closure_good) def test_groupby_multiindex_missing_pair(): @@ -1588,26 +1585,26 @@ def test_index_label_overlaps_location(): g = df.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = df.iloc[[1, 3, 4]] - assert_frame_equal(actual, expected) + tm.assert_frame_equal(actual, expected) ser = df[0] g = ser.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = ser.take([1, 3, 4]) - assert_series_equal(actual, expected) + tm.assert_series_equal(actual, expected) # ... and again, with a generic Index of floats df.index = df.index.astype(float) g = df.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = df.iloc[[1, 3, 4]] - assert_frame_equal(actual, expected) + tm.assert_frame_equal(actual, expected) ser = df[0] g = ser.groupby(list("ababb")) actual = g.filter(lambda x: len(x) > 2) expected = ser.take([1, 3, 4]) - assert_series_equal(actual, expected) + tm.assert_series_equal(actual, expected) def test_transform_doesnt_clobber_ints(): @@ -1652,7 +1649,7 @@ def test_groupby_preserves_sort(sort_column, group_column): g = df.groupby(group_column) def test_sort(x): - assert_frame_equal(x, x.sort_values(by=sort_column)) + tm.assert_frame_equal(x, x.sort_values(by=sort_column)) g.apply(test_sort) @@ -1681,7 +1678,7 @@ def test_group_shift_with_null_key(): ) result = g.shift(-1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_group_shift_with_fill_value(): @@ -1703,7 +1700,7 @@ def test_group_shift_with_fill_value(): ) result = g.shift(-1, fill_value=0)[["Z"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_pivot_table_values_key_error(): @@ -1734,7 +1731,7 @@ def test_empty_dataframe_groupby(): expected = DataFrame(columns=["B", "C"], dtype=np.float64) expected.index.name = "A" - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_tuple_warns(): @@ -1816,7 +1813,7 @@ def test_groupby_multiindex_nat(): result = ser.groupby(level=1).mean() expected = pd.Series([3.0, 2.5], index=["a", "b"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_empty_list_raises(): @@ -1841,7 +1838,7 @@ def test_groupby_multiindex_series_keys_len_equal_group_axis(): ei = pd.MultiIndex.from_arrays(index_array, names=index_names) expected = pd.Series([3], index=ei) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_groups_in_BaseGrouper(): @@ -1869,7 +1866,7 @@ def test_groupby_axis_1(group_name): results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T - assert_frame_equal(results, expected) + tm.assert_frame_equal(results, expected) # test on MI column iterables = [["bar", "baz", "foo"], ["one", "two"]] @@ -1877,7 +1874,7 @@ def test_groupby_axis_1(group_name): df = pd.DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi) results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T - assert_frame_equal(results, expected) + tm.assert_frame_equal(results, expected) @pytest.mark.parametrize( @@ -1943,7 +1940,7 @@ def test_shift_bfill_ffill_tz(tz_naive_fixture, op, expected): grouped = df.groupby("id") result = getattr(grouped, op)() expected = DataFrame(expected).assign(time=lambda x: x.time.dt.tz_localize(tz)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_only_none_group(): @@ -1953,4 +1950,4 @@ def test_groupby_only_none_group(): actual = df.groupby("g")["x"].transform("sum") expected = pd.Series([np.nan], name="x") - assert_series_equal(actual, expected) + tm.assert_series_equal(actual, expected) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index ab25d183ae3ff..e1fd8d7da6833 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -15,11 +15,6 @@ ) from pandas.core.groupby.grouper import Grouping import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) # selection # -------------------------------- @@ -57,12 +52,12 @@ def test_groupby_duplicated_column_errormsg(self): def test_column_select_via_attr(self, df): result = df.groupby("A").C.sum() expected = df.groupby("A")["C"].sum() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df["mean"] = 1.5 result = df.groupby("A").mean() expected = df.groupby("A").agg(np.mean) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_getitem_list_of_columns(self): df = DataFrame( @@ -81,9 +76,9 @@ def test_getitem_list_of_columns(self): expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean() - assert_frame_equal(result, expected) - assert_frame_equal(result2, expected) - assert_frame_equal(result3, expected) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + tm.assert_frame_equal(result3, expected) def test_getitem_numeric_column_names(self): # GH #13731 @@ -101,9 +96,9 @@ def test_getitem_numeric_column_names(self): expected = df.loc[:, [0, 2, 4]].groupby(0).mean() - assert_frame_equal(result, expected) - assert_frame_equal(result2, expected) - assert_frame_equal(result3, expected) + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + tm.assert_frame_equal(result3, expected) # grouping @@ -153,13 +148,13 @@ def test_grouper_multilevel_freq(self): result = df.groupby( [pd.Grouper(level="foo", freq="W"), pd.Grouper(level="bar", freq="W")] ).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Check integer level result = df.groupby( [pd.Grouper(level=0, freq="W"), pd.Grouper(level=1, freq="W")] ).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_grouper_creation_bug(self): @@ -170,14 +165,14 @@ def test_grouper_creation_bug(self): g = df.groupby(pd.Grouper(key="A")) result = g.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = g.apply(lambda x: x.sum()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) g = df.groupby(pd.Grouper(key="A", axis=0)) result = g.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH14334 # pd.Grouper(key=...) may be passed in a list @@ -188,7 +183,7 @@ def test_grouper_creation_bug(self): expected = df.groupby("A").sum() g = df.groupby([pd.Grouper(key="A")]) result = g.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Group by two columns # using a combination of strings and Grouper objects @@ -197,17 +192,17 @@ def test_grouper_creation_bug(self): # Group with two Grouper objects g = df.groupby([pd.Grouper(key="A"), pd.Grouper(key="B")]) result = g.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Group with a string and a Grouper object g = df.groupby(["A", pd.Grouper(key="B")]) result = g.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Group with a Grouper object and a string g = df.groupby([pd.Grouper(key="A"), "B"]) result = g.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH8866 s = Series( @@ -221,12 +216,12 @@ def test_grouper_creation_bug(self): expected = Series( [28], index=Index([Timestamp("2013-01-31")], freq="M", name="three") ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # just specifying a level breaks result = s.groupby(pd.Grouper(level="one")).sum() expected = s.groupby(level="one").sum() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_grouper_column_and_index(self): # GH 14327 @@ -243,24 +238,24 @@ def test_grouper_column_and_index(self): ) result = df_multi.groupby(["B", pd.Grouper(level="inner")]).mean() expected = df_multi.reset_index().groupby(["B", "inner"]).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Test the reverse grouping order result = df_multi.groupby([pd.Grouper(level="inner"), "B"]).mean() expected = df_multi.reset_index().groupby(["inner", "B"]).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Grouping a single-index frame by a column and the index should # be equivalent to resetting the index and grouping by two columns df_single = df_multi.reset_index("outer") result = df_single.groupby(["B", pd.Grouper(level="inner")]).mean() expected = df_single.reset_index().groupby(["B", "inner"]).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # Test the reverse grouping order result = df_single.groupby([pd.Grouper(level="inner"), "B"]).mean() expected = df_single.reset_index().groupby(["inner", "B"]).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_levels_and_columns(self): # GH9344, GH9049 @@ -294,13 +289,13 @@ def test_groupby_categorical_index_and_columns(self, observed): categories, categories=categories, ordered=True ) expected = DataFrame(data=expected_data, columns=expected_columns) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # test transposed version df = DataFrame(data.T, index=cat_columns) result = df.groupby(axis=0, level=0, observed=observed).sum() expected = DataFrame(data=expected_data.T, index=expected_columns) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_grouper_getting_correct_binner(self): @@ -323,7 +318,7 @@ def test_grouper_getting_correct_binner(self): names=["one", "two"], ), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_grouper_iter(self, df): assert sorted(df.groupby("A").grouper) == ["bar", "foo"] @@ -347,7 +342,7 @@ def test_groupby_dict_mapping(self): s = Series({"T1": 5}) result = s.groupby({"T1": "T2"}).agg(sum) expected = s.groupby(["T2"]).agg(sum) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([1.0, 2.0, 3.0, 4.0], index=list("abcd")) mapping = {"a": 0, "b": 0, "c": 1, "d": 1} @@ -356,9 +351,9 @@ def test_groupby_dict_mapping(self): result2 = s.groupby(mapping).agg(np.mean) expected = s.groupby([0, 0, 1, 1]).mean() expected2 = s.groupby([0, 0, 1, 1]).mean() - assert_series_equal(result, expected) - assert_series_equal(result, result2) - assert_series_equal(result, expected2) + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result, result2) + tm.assert_series_equal(result, expected2) def test_groupby_grouper_f_sanity_checked(self): dates = date_range("01-Jan-2013", periods=12, freq="MS") @@ -390,25 +385,25 @@ def test_multiindex_passthru(self): df.columns = pd.MultiIndex.from_tuples([(0, 1), (1, 1), (2, 1)]) result = df.groupby(axis=1, level=[0, 1]).first() - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_multiindex_negative_level(self, mframe): # GH 13901 result = mframe.groupby(level=-1).sum() expected = mframe.groupby(level="second").sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = mframe.groupby(level=-2).sum() expected = mframe.groupby(level="first").sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = mframe.groupby(level=[-2, -1]).sum() expected = mframe - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = mframe.groupby(level=[-1, "first"]).sum() expected = mframe.groupby(level=["second", "first"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_multifunc_select_col_integer_cols(self, df): df.columns = np.arange(len(df.columns)) @@ -483,23 +478,23 @@ def test_groupby_level(self, sort, mframe, df): assert result0.index.name == "first" assert result1.index.name == "second" - assert_frame_equal(result0, expected0) - assert_frame_equal(result1, expected1) + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) assert result0.index.name == frame.index.names[0] assert result1.index.name == frame.index.names[1] # groupby level name result0 = frame.groupby(level="first", sort=sort).sum() result1 = frame.groupby(level="second", sort=sort).sum() - assert_frame_equal(result0, expected0) - assert_frame_equal(result1, expected1) + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) # axis=1 result0 = frame.T.groupby(level=0, axis=1, sort=sort).sum() result1 = frame.T.groupby(level=1, axis=1, sort=sort).sum() - assert_frame_equal(result0, expected0.T) - assert_frame_equal(result1, expected1.T) + tm.assert_frame_equal(result0, expected0.T) + tm.assert_frame_equal(result1, expected1.T) # raise exception for non-MultiIndex msg = "level > 0 or level < -1 only valid with MultiIndex" @@ -528,7 +523,7 @@ def test_groupby_level_with_nas(self, sort): s = Series(np.arange(8.0), index=index) result = s.groupby(level=0, sort=sort).sum() expected = Series([6.0, 22.0], index=[0, 1]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) index = MultiIndex( levels=[[1, 0], [0, 1, 2, 3]], @@ -539,7 +534,7 @@ def test_groupby_level_with_nas(self, sort): s = Series(np.arange(8.0), index=index) result = s.groupby(level=0, sort=sort).sum() expected = Series([6.0, 18.0], index=[0.0, 1.0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_args(self, mframe): # PR8618 and issue 8015 @@ -564,12 +559,12 @@ def test_level_preserve_order(self, sort, labels, mframe): # GH 17537 grouped = mframe.groupby(level=0, sort=sort) exp_labels = np.array(labels, np.intp) - assert_almost_equal(grouped.grouper.labels[0], exp_labels) + tm.assert_almost_equal(grouped.grouper.labels[0], exp_labels) def test_grouping_labels(self, mframe): grouped = mframe.groupby(mframe.index.get_level_values(0)) exp_labels = np.array([2, 2, 2, 0, 0, 1, 1, 3, 3, 3], dtype=np.intp) - assert_almost_equal(grouped.grouper.labels[0], exp_labels) + tm.assert_almost_equal(grouped.grouper.labels[0], exp_labels) def test_list_grouper_with_nat(self): # GH 14715 @@ -603,7 +598,7 @@ def test_evaluate_with_empty_groups(self, func, expected): df = pd.DataFrame({1: [], 2: []}) g = df.groupby(1) result = getattr(g[2], func)(lambda x: x) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_empty(self): # https://github.com/pandas-dev/pandas/issues/27190 @@ -677,8 +672,8 @@ def test_get_group(self): result1 = g.get_group(key) result2 = g.get_group(Timestamp(key).to_pydatetime()) result3 = g.get_group(str(Timestamp(key))) - assert_frame_equal(result1, result2) - assert_frame_equal(result1, result3) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) g = df.groupby(["DATE", "label"]) @@ -686,8 +681,8 @@ def test_get_group(self): result1 = g.get_group(key) result2 = g.get_group((Timestamp(key[0]).to_pydatetime(), key[1])) result3 = g.get_group((str(Timestamp(key[0])), key[1])) - assert_frame_equal(result1, result2) - assert_frame_equal(result1, result3) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) # must pass a same-length tuple with multiple keys msg = "must supply a tuple to get_group with multiple grouping keys" @@ -712,7 +707,7 @@ def test_get_group_empty_bins(self, observed): # IOW '(0, 5]' result = g.get_group(pd.Interval(0, 5)) expected = DataFrame([3, 1], index=[0, 1]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) msg = r"Interval\(10, 15, closed='right'\)" with pytest.raises(KeyError, match=msg): @@ -724,14 +719,14 @@ def test_get_group_grouped_by_tuple(self): gr = df.groupby("ids") expected = DataFrame({"ids": [(1,), (1,)]}, index=[0, 2]) result = gr.get_group((1,)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) dt = pd.to_datetime(["2010-01-01", "2010-01-02", "2010-01-01", "2010-01-02"]) df = DataFrame({"ids": [(x,) for x in dt]}) gr = df.groupby("ids") result = gr.get_group(("2010-01-01",)) expected = DataFrame({"ids": [(dt[0],), (dt[0],)]}, index=[0, 2]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_with_empty(self): index = pd.DatetimeIndex(()) @@ -812,7 +807,7 @@ def test_multi_iter(self): e1, e2, e3 = expected[i] assert e1 == one assert e2 == two - assert_series_equal(three, e3) + tm.assert_series_equal(three, e3) def test_multi_iter_frame(self, three_group): k1 = np.array(["b", "b", "b", "a", "a", "a"]) @@ -837,7 +832,7 @@ def test_multi_iter_frame(self, three_group): e1, e2, e3 = expected[i] assert e1 == one assert e2 == two - assert_frame_equal(three, e3) + tm.assert_frame_equal(three, e3) # don't iterate through groups with no data df["k1"] = np.array(["b", "b", "b", "a", "a", "a"]) diff --git a/pandas/tests/groupby/test_index_as_string.py b/pandas/tests/groupby/test_index_as_string.py index 71d545e960566..f5c8873ff9417 100644 --- a/pandas/tests/groupby/test_index_as_string.py +++ b/pandas/tests/groupby/test_index_as_string.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm @pytest.fixture(params=[["inner"], ["inner", "outer"]]) @@ -49,7 +49,7 @@ def series(): def test_grouper_index_level_as_string(frame, key_strs, groupers): result = frame.groupby(key_strs).mean() expected = frame.groupby(groupers).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( @@ -79,4 +79,4 @@ def test_grouper_index_level_as_string_series(series, levels): # Compute and check result result = series.groupby(levels).mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index 2c4b56793580c..f83b284a35377 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, isna -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm def test_first_last_nth(df): @@ -13,24 +13,24 @@ def test_first_last_nth(df): expected = df.loc[[1, 0], ["B", "C", "D"]] expected.index = Index(["bar", "foo"], name="A") expected = expected.sort_index() - assert_frame_equal(first, expected) + tm.assert_frame_equal(first, expected) nth = grouped.nth(0) - assert_frame_equal(nth, expected) + tm.assert_frame_equal(nth, expected) last = grouped.last() expected = df.loc[[5, 7], ["B", "C", "D"]] expected.index = Index(["bar", "foo"], name="A") - assert_frame_equal(last, expected) + tm.assert_frame_equal(last, expected) nth = grouped.nth(-1) - assert_frame_equal(nth, expected) + tm.assert_frame_equal(nth, expected) nth = grouped.nth(1) expected = df.loc[[2, 3], ["B", "C", "D"]].copy() expected.index = Index(["foo", "bar"], name="A") expected = expected.sort_index() - assert_frame_equal(nth, expected) + tm.assert_frame_equal(nth, expected) # it works! grouped["B"].first() @@ -47,11 +47,11 @@ def test_first_last_nth(df): g = df.groupby("A") result = g.first() expected = df.iloc[[1, 2]].set_index("A") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = df.iloc[[1, 2]].set_index("A") result = g.nth(0, dropna="any") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_first_last_nth_dtypes(df_mixed_floats): @@ -66,19 +66,19 @@ def test_first_last_nth_dtypes(df_mixed_floats): expected = df.loc[[1, 0], ["B", "C", "D", "E", "F"]] expected.index = Index(["bar", "foo"], name="A") expected = expected.sort_index() - assert_frame_equal(first, expected) + tm.assert_frame_equal(first, expected) last = grouped.last() expected = df.loc[[5, 7], ["B", "C", "D", "E", "F"]] expected.index = Index(["bar", "foo"], name="A") expected = expected.sort_index() - assert_frame_equal(last, expected) + tm.assert_frame_equal(last, expected) nth = grouped.nth(1) expected = df.loc[[3, 2], ["B", "C", "D", "E", "F"]] expected.index = Index(["bar", "foo"], name="A") expected = expected.sort_index() - assert_frame_equal(nth, expected) + tm.assert_frame_equal(nth, expected) # GH 2763, first/last shifting dtypes idx = list(range(10)) @@ -93,23 +93,23 @@ def test_nth(): df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) g = df.groupby("A") - assert_frame_equal(g.nth(0), df.iloc[[0, 2]].set_index("A")) - assert_frame_equal(g.nth(1), df.iloc[[1]].set_index("A")) - assert_frame_equal(g.nth(2), df.loc[[]].set_index("A")) - assert_frame_equal(g.nth(-1), df.iloc[[1, 2]].set_index("A")) - assert_frame_equal(g.nth(-2), df.iloc[[0]].set_index("A")) - assert_frame_equal(g.nth(-3), df.loc[[]].set_index("A")) - assert_series_equal(g.B.nth(0), df.set_index("A").B.iloc[[0, 2]]) - assert_series_equal(g.B.nth(1), df.set_index("A").B.iloc[[1]]) - assert_frame_equal(g[["B"]].nth(0), df.loc[[0, 2], ["A", "B"]].set_index("A")) + tm.assert_frame_equal(g.nth(0), df.iloc[[0, 2]].set_index("A")) + tm.assert_frame_equal(g.nth(1), df.iloc[[1]].set_index("A")) + tm.assert_frame_equal(g.nth(2), df.loc[[]].set_index("A")) + tm.assert_frame_equal(g.nth(-1), df.iloc[[1, 2]].set_index("A")) + tm.assert_frame_equal(g.nth(-2), df.iloc[[0]].set_index("A")) + tm.assert_frame_equal(g.nth(-3), df.loc[[]].set_index("A")) + tm.assert_series_equal(g.B.nth(0), df.set_index("A").B.iloc[[0, 2]]) + tm.assert_series_equal(g.B.nth(1), df.set_index("A").B.iloc[[1]]) + tm.assert_frame_equal(g[["B"]].nth(0), df.loc[[0, 2], ["A", "B"]].set_index("A")) exp = df.set_index("A") - assert_frame_equal(g.nth(0, dropna="any"), exp.iloc[[1, 2]]) - assert_frame_equal(g.nth(-1, dropna="any"), exp.iloc[[1, 2]]) + tm.assert_frame_equal(g.nth(0, dropna="any"), exp.iloc[[1, 2]]) + tm.assert_frame_equal(g.nth(-1, dropna="any"), exp.iloc[[1, 2]]) exp["B"] = np.nan - assert_frame_equal(g.nth(7, dropna="any"), exp.iloc[[1, 2]]) - assert_frame_equal(g.nth(2, dropna="any"), exp.iloc[[1, 2]]) + tm.assert_frame_equal(g.nth(7, dropna="any"), exp.iloc[[1, 2]]) + tm.assert_frame_equal(g.nth(2, dropna="any"), exp.iloc[[1, 2]]) # out of bounds, regression from 0.13.1 # GH 6621 @@ -136,11 +136,11 @@ def test_nth(): result = df.groupby(level=0, as_index=False).nth(2) expected = df.iloc[[-1]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby(level=0, as_index=False).nth(3) expected = df.loc[[]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH 7559 # from the vbench @@ -149,7 +149,7 @@ def test_nth(): g = df[0] expected = s.groupby(g).first() expected2 = s.groupby(g).apply(lambda x: x.iloc[0]) - assert_series_equal(expected2, expected, check_names=False) + tm.assert_series_equal(expected2, expected, check_names=False) assert expected.name == 1 assert expected2.name == 1 @@ -163,7 +163,7 @@ def test_nth(): # related GH 7287 expected = s.groupby(g, sort=False).first() result = s.groupby(g, sort=False).nth(0, dropna="all") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) with pytest.raises(ValueError, match="For a DataFrame groupby"): s.groupby(g, sort=False).nth(0, dropna=True) @@ -173,20 +173,20 @@ def test_nth(): g = df.groupby("A") result = g.B.nth(0, dropna="all") expected = g.B.first() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # test multiple nth values df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]], columns=["A", "B"]) g = df.groupby("A") - assert_frame_equal(g.nth(0), df.iloc[[0, 3]].set_index("A")) - assert_frame_equal(g.nth([0]), df.iloc[[0, 3]].set_index("A")) - assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]].set_index("A")) - assert_frame_equal(g.nth([0, -1]), df.iloc[[0, 2, 3, 4]].set_index("A")) - assert_frame_equal(g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]].set_index("A")) - assert_frame_equal(g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]].set_index("A")) - assert_frame_equal(g.nth([2]), df.iloc[[2]].set_index("A")) - assert_frame_equal(g.nth([3, 4]), df.loc[[]].set_index("A")) + tm.assert_frame_equal(g.nth(0), df.iloc[[0, 3]].set_index("A")) + tm.assert_frame_equal(g.nth([0]), df.iloc[[0, 3]].set_index("A")) + tm.assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]].set_index("A")) + tm.assert_frame_equal(g.nth([0, -1]), df.iloc[[0, 2, 3, 4]].set_index("A")) + tm.assert_frame_equal(g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]].set_index("A")) + tm.assert_frame_equal(g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]].set_index("A")) + tm.assert_frame_equal(g.nth([2]), df.iloc[[2]].set_index("A")) + tm.assert_frame_equal(g.nth([3, 4]), df.loc[[]].set_index("A")) business_dates = pd.date_range(start="4/1/2014", end="6/30/2014", freq="B") df = DataFrame(1, index=business_dates, columns=["a", "b"]) @@ -210,7 +210,7 @@ def test_nth(): ] ) expected = DataFrame(1, columns=["a", "b"], index=expected_dates) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_nth_multi_index(three_group): @@ -219,7 +219,7 @@ def test_nth_multi_index(three_group): grouped = three_group.groupby(["A", "B"]) result = grouped.nth(0) expected = grouped.first() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( @@ -281,18 +281,18 @@ def test_first_last_tz(data, expected_first, expected_last): result = df.groupby("id", as_index=False).first() expected = DataFrame(expected_first) cols = ["id", "time", "foo"] - assert_frame_equal(result[cols], expected[cols]) + tm.assert_frame_equal(result[cols], expected[cols]) result = df.groupby("id", as_index=False)["time"].first() - assert_frame_equal(result, expected[["id", "time"]]) + tm.assert_frame_equal(result, expected[["id", "time"]]) result = df.groupby("id", as_index=False).last() expected = DataFrame(expected_last) cols = ["id", "time", "foo"] - assert_frame_equal(result[cols], expected[cols]) + tm.assert_frame_equal(result[cols], expected[cols]) result = df.groupby("id", as_index=False)["time"].last() - assert_frame_equal(result, expected[["id", "time"]]) + tm.assert_frame_equal(result, expected[["id", "time"]]) @pytest.mark.parametrize( @@ -322,7 +322,7 @@ def test_first_last_tz_multi_column(method, ts, alpha): }, index=pd.Index([1, 2], name="group"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_nth_multi_index_as_expected(): @@ -380,7 +380,7 @@ def test_nth_multi_index_as_expected(): names=["A", "B"], ), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_head_tail(): @@ -389,49 +389,49 @@ def test_groupby_head_tail(): g_not_as = df.groupby("A", as_index=False) # as_index= False, much easier - assert_frame_equal(df.loc[[0, 2]], g_not_as.head(1)) - assert_frame_equal(df.loc[[1, 2]], g_not_as.tail(1)) + tm.assert_frame_equal(df.loc[[0, 2]], g_not_as.head(1)) + tm.assert_frame_equal(df.loc[[1, 2]], g_not_as.tail(1)) empty_not_as = DataFrame( columns=df.columns, index=pd.Index([], dtype=df.index.dtype) ) empty_not_as["A"] = empty_not_as["A"].astype(df.A.dtype) empty_not_as["B"] = empty_not_as["B"].astype(df.B.dtype) - assert_frame_equal(empty_not_as, g_not_as.head(0)) - assert_frame_equal(empty_not_as, g_not_as.tail(0)) - assert_frame_equal(empty_not_as, g_not_as.head(-1)) - assert_frame_equal(empty_not_as, g_not_as.tail(-1)) + tm.assert_frame_equal(empty_not_as, g_not_as.head(0)) + tm.assert_frame_equal(empty_not_as, g_not_as.tail(0)) + tm.assert_frame_equal(empty_not_as, g_not_as.head(-1)) + tm.assert_frame_equal(empty_not_as, g_not_as.tail(-1)) - assert_frame_equal(df, g_not_as.head(7)) # contains all - assert_frame_equal(df, g_not_as.tail(7)) + tm.assert_frame_equal(df, g_not_as.head(7)) # contains all + tm.assert_frame_equal(df, g_not_as.tail(7)) # as_index=True, (used to be different) df_as = df - assert_frame_equal(df_as.loc[[0, 2]], g_as.head(1)) - assert_frame_equal(df_as.loc[[1, 2]], g_as.tail(1)) + tm.assert_frame_equal(df_as.loc[[0, 2]], g_as.head(1)) + tm.assert_frame_equal(df_as.loc[[1, 2]], g_as.tail(1)) empty_as = DataFrame(index=df_as.index[:0], columns=df.columns) empty_as["A"] = empty_not_as["A"].astype(df.A.dtype) empty_as["B"] = empty_not_as["B"].astype(df.B.dtype) - assert_frame_equal(empty_as, g_as.head(0)) - assert_frame_equal(empty_as, g_as.tail(0)) - assert_frame_equal(empty_as, g_as.head(-1)) - assert_frame_equal(empty_as, g_as.tail(-1)) + tm.assert_frame_equal(empty_as, g_as.head(0)) + tm.assert_frame_equal(empty_as, g_as.tail(0)) + tm.assert_frame_equal(empty_as, g_as.head(-1)) + tm.assert_frame_equal(empty_as, g_as.tail(-1)) - assert_frame_equal(df_as, g_as.head(7)) # contains all - assert_frame_equal(df_as, g_as.tail(7)) + tm.assert_frame_equal(df_as, g_as.head(7)) # contains all + tm.assert_frame_equal(df_as, g_as.tail(7)) # test with selection - assert_frame_equal(g_as[[]].head(1), df_as.loc[[0, 2], []]) - assert_frame_equal(g_as[["A"]].head(1), df_as.loc[[0, 2], ["A"]]) - assert_frame_equal(g_as[["B"]].head(1), df_as.loc[[0, 2], ["B"]]) - assert_frame_equal(g_as[["A", "B"]].head(1), df_as.loc[[0, 2]]) + tm.assert_frame_equal(g_as[[]].head(1), df_as.loc[[0, 2], []]) + tm.assert_frame_equal(g_as[["A"]].head(1), df_as.loc[[0, 2], ["A"]]) + tm.assert_frame_equal(g_as[["B"]].head(1), df_as.loc[[0, 2], ["B"]]) + tm.assert_frame_equal(g_as[["A", "B"]].head(1), df_as.loc[[0, 2]]) - assert_frame_equal(g_not_as[[]].head(1), df_as.loc[[0, 2], []]) - assert_frame_equal(g_not_as[["A"]].head(1), df_as.loc[[0, 2], ["A"]]) - assert_frame_equal(g_not_as[["B"]].head(1), df_as.loc[[0, 2], ["B"]]) - assert_frame_equal(g_not_as[["A", "B"]].head(1), df_as.loc[[0, 2]]) + tm.assert_frame_equal(g_not_as[[]].head(1), df_as.loc[[0, 2], []]) + tm.assert_frame_equal(g_not_as[["A"]].head(1), df_as.loc[[0, 2], ["A"]]) + tm.assert_frame_equal(g_not_as[["B"]].head(1), df_as.loc[[0, 2], ["B"]]) + tm.assert_frame_equal(g_not_as[["A", "B"]].head(1), df_as.loc[[0, 2]]) def test_group_selection_cache(): @@ -442,26 +442,26 @@ def test_group_selection_cache(): g = df.groupby("A") result1 = g.head(n=2) result2 = g.nth(0) - assert_frame_equal(result1, df) - assert_frame_equal(result2, expected) + tm.assert_frame_equal(result1, df) + tm.assert_frame_equal(result2, expected) g = df.groupby("A") result1 = g.tail(n=2) result2 = g.nth(0) - assert_frame_equal(result1, df) - assert_frame_equal(result2, expected) + tm.assert_frame_equal(result1, df) + tm.assert_frame_equal(result2, expected) g = df.groupby("A") result1 = g.nth(0) result2 = g.head(n=2) - assert_frame_equal(result1, expected) - assert_frame_equal(result2, df) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, df) g = df.groupby("A") result1 = g.nth(0) result2 = g.tail(n=2) - assert_frame_equal(result1, expected) - assert_frame_equal(result2, df) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, df) def test_nth_empty(): @@ -469,13 +469,13 @@ def test_nth_empty(): df = DataFrame(index=[0], columns=["a", "b", "c"]) result = df.groupby("a").nth(10) expected = DataFrame(index=Index([], name="a"), columns=["b", "c"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby(["a", "b"]).nth(10) expected = DataFrame( index=MultiIndex([[], []], [[], []], names=["a", "b"]), columns=["c"] ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_nth_column_order(): @@ -489,13 +489,13 @@ def test_nth_column_order(): expected = DataFrame( [["b", 100.0], ["c", 200.0]], columns=["C", "B"], index=Index([1, 2], name="A") ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby("A").nth(-1, dropna="any") expected = DataFrame( [["a", 50.0], ["d", 150.0]], columns=["C", "B"], index=Index([1, 2], name="A") ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("dropna", [None, "any", "all"]) @@ -510,4 +510,4 @@ def test_nth_nan_in_grouper(dropna): [[2, 3], [6, 7]], columns=list("bc"), index=Index(["abc", "def"], name="a") ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 7acddec002d98..109382d97440e 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -11,8 +11,7 @@ from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range from pandas.core.groupby.grouper import Grouper from pandas.core.groupby.ops import BinGrouper -from pandas.util import testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm class TestGroupBy: @@ -50,14 +49,14 @@ def test_groupby_with_timegrouper(self): expected.iloc[[0, 6, 18], 0] = np.array([24, 6, 9], dtype="int64") result1 = df.resample("5D").sum() - assert_frame_equal(result1, expected) + tm.assert_frame_equal(result1, expected) df_sorted = df.sort_index() result2 = df_sorted.groupby(pd.Grouper(freq="5D")).sum() - assert_frame_equal(result2, expected) + tm.assert_frame_equal(result2, expected) result3 = df.groupby(pd.Grouper(freq="5D")).sum() - assert_frame_equal(result3, expected) + tm.assert_frame_equal(result3, expected) @pytest.mark.parametrize("should_sort", [True, False]) def test_groupby_with_timegrouper_methods(self, should_sort): @@ -131,7 +130,7 @@ def test_timegrouper_with_reg_groups(self): ).set_index(["Date", "Buyer"]) result = df.groupby([pd.Grouper(freq="A"), "Buyer"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( { @@ -146,7 +145,7 @@ def test_timegrouper_with_reg_groups(self): } ).set_index(["Date", "Buyer"]) result = df.groupby([pd.Grouper(freq="6MS"), "Buyer"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df_original = DataFrame( { @@ -184,7 +183,7 @@ def test_timegrouper_with_reg_groups(self): ).set_index(["Date", "Buyer"]) result = df.groupby([pd.Grouper(freq="1D"), "Buyer"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby([pd.Grouper(freq="1M"), "Buyer"]).sum() expected = DataFrame( @@ -198,12 +197,12 @@ def test_timegrouper_with_reg_groups(self): ], } ).set_index(["Date", "Buyer"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # passing the name df = df.reset_index() result = df.groupby([pd.Grouper(freq="1M", key="Date"), "Buyer"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) with pytest.raises(KeyError, match="'The grouper name foo is not found'"): df.groupby([pd.Grouper(freq="1M", key="foo"), "Buyer"]).sum() @@ -211,9 +210,9 @@ def test_timegrouper_with_reg_groups(self): # passing the level df = df.set_index("Date") result = df.groupby([pd.Grouper(freq="1M", level="Date"), "Buyer"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby([pd.Grouper(freq="1M", level=0), "Buyer"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) with pytest.raises(ValueError): df.groupby([pd.Grouper(freq="1M", level="foo"), "Buyer"]).sum() @@ -233,7 +232,7 @@ def test_timegrouper_with_reg_groups(self): ], } ).set_index(["Date", "Buyer"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # error as we have both a level and a name! with pytest.raises(ValueError): @@ -246,19 +245,19 @@ def test_timegrouper_with_reg_groups(self): {"Quantity": [31], "Date": [datetime(2013, 10, 31, 0, 0)]} ).set_index("Date") result = df.groupby(pd.Grouper(freq="1M")).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby([pd.Grouper(freq="1M")]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( {"Quantity": [31], "Date": [datetime(2013, 11, 30, 0, 0)]} ).set_index("Date") result = df.groupby(pd.Grouper(freq="1M", key="Date")).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby([pd.Grouper(freq="1M", key="Date")]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("freq", ["D", "M", "A", "Q-APR"]) def test_timegrouper_with_reg_groups_freq(self, freq): @@ -316,10 +315,10 @@ def test_timegrouper_with_reg_groups_freq(self, freq): .groupby([pd.Grouper(freq=freq), "user_id"])["whole_cost"] .sum() ) - assert_series_equal(result1, expected) + tm.assert_series_equal(result1, expected) result2 = df.groupby([pd.Grouper(freq=freq), "user_id"])["whole_cost"].sum() - assert_series_equal(result2, expected) + tm.assert_series_equal(result2, expected) def test_timegrouper_get_group(self): # GH 6914 @@ -353,7 +352,7 @@ def test_timegrouper_get_group(self): for t, expected in zip(dt_list, expected_list): dt = pd.Timestamp(t) result = grouped.get_group(dt) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # multiple grouping expected_list = [ @@ -368,7 +367,7 @@ def test_timegrouper_get_group(self): for (b, t), expected in zip(g_list, expected_list): dt = pd.Timestamp(t) result = grouped.get_group((b, dt)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # with index df_original = df_original.set_index("Date") @@ -385,7 +384,7 @@ def test_timegrouper_get_group(self): for t, expected in zip(dt_list, expected_list): dt = pd.Timestamp(t) result = grouped.get_group(dt) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_timegrouper_apply_return_type_series(self): # Using `apply` with the `TimeGrouper` should give the @@ -400,7 +399,7 @@ def sumfunc_series(x): expected = df.groupby(pd.Grouper(key="date")).apply(sumfunc_series) result = df_dt.groupby(pd.Grouper(freq="M", key="date")).apply(sumfunc_series) - assert_frame_equal( + tm.assert_frame_equal( result.reset_index(drop=True), expected.reset_index(drop=True) ) @@ -417,7 +416,7 @@ def sumfunc_value(x): expected = df.groupby(pd.Grouper(key="date")).apply(sumfunc_value) result = df_dt.groupby(Grouper(freq="M", key="date")).apply(sumfunc_value) - assert_series_equal( + tm.assert_series_equal( result.reset_index(drop=True), expected.reset_index(drop=True) ) @@ -493,7 +492,7 @@ def test_groupby_groups_datetimeindex_tz(self): ) result = df.groupby(["datetime", "label"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # by level didx = pd.DatetimeIndex(dates, tz="Asia/Tokyo") @@ -513,7 +512,7 @@ def test_groupby_groups_datetimeindex_tz(self): ) result = df.groupby(level=0).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_frame_datetime64_handling_groupby(self): # it works! @@ -550,7 +549,7 @@ def test_groupby_multi_timezone(self): name="date", dtype=object, ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) tz = "America/Chicago" res_values = df.groupby("tz").date.get_group(tz) @@ -561,7 +560,7 @@ def test_groupby_multi_timezone(self): name="date", ) expected = pd.to_datetime(exp_values).dt.tz_localize(tz) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_groups_periods(self): dates = [ @@ -602,7 +601,7 @@ def test_groupby_groups_periods(self): ) result = df.groupby(["period", "label"]).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # by level didx = pd.PeriodIndex(dates, freq="H") @@ -622,7 +621,7 @@ def test_groupby_groups_periods(self): ) result = df.groupby(level=0).sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_first_datetime64(self): df = DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)]) @@ -644,7 +643,7 @@ def test_groupby_max_datetime64(self): df = DataFrame(dict(A=Timestamp("20130101"), B=np.arange(5))) expected = df.groupby("A")["A"].apply(lambda x: x.max()) result = df.groupby("A")["A"].max() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_datetime64_32_bit(self): # GH 6410 / numpy 4328 @@ -653,7 +652,7 @@ def test_groupby_datetime64_32_bit(self): df = DataFrame({"A": range(2), "B": [pd.Timestamp("2000-01-1")] * 2}) result = df.groupby("A")["B"].transform(min) expected = Series([pd.Timestamp("2000-01-1")] * 2, name="B") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_with_timezone_selection(self): # GH 11616 @@ -714,10 +713,10 @@ def test_first_last_max_min_on_time_data(self): grouped_test = df_test.groupby("group") grouped_ref = df_ref.groupby("group") - assert_frame_equal(grouped_ref.max(), grouped_test.max()) - assert_frame_equal(grouped_ref.min(), grouped_test.min()) - assert_frame_equal(grouped_ref.first(), grouped_test.first()) - assert_frame_equal(grouped_ref.last(), grouped_test.last()) + tm.assert_frame_equal(grouped_ref.max(), grouped_test.max()) + tm.assert_frame_equal(grouped_ref.min(), grouped_test.min()) + tm.assert_frame_equal(grouped_ref.first(), grouped_test.first()) + tm.assert_frame_equal(grouped_ref.last(), grouped_test.last()) def test_nunique_with_timegrouper_and_nat(self): # GH 17575 @@ -755,4 +754,4 @@ def test_scalar_call_versus_list_call(self): grouped = data_frame.groupby([grouper]) expected = grouped.count() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index d3972e6ba9008..db44a4a57230c 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -19,8 +19,7 @@ date_range, ) from pandas.core.groupby.groupby import DataError -from pandas.util import testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal +import pandas.util.testing as tm def assert_fp_equal(a, b): @@ -54,7 +53,7 @@ def test_transform(): .mean() ) result = df.groupby(key).transform(lambda x: x - x.mean()).groupby(key).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def demean(arr): return arr - arr.mean() @@ -67,7 +66,7 @@ def demean(arr): key = ["one", "two", "one", "two", "one"] result = people.groupby(key).transform(demean).groupby(key).mean() expected = people.groupby(key).apply(demean).groupby(key).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH 8430 df = tm.makeTimeDataFrame() @@ -91,10 +90,10 @@ def test_transform_fast(): expected = pd.Series(values, index=df.index, name="val") result = grp.transform(np.mean) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = grp.transform("mean") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 12737 df = pd.DataFrame( @@ -118,18 +117,18 @@ def test_transform_fast(): {"f": [1.1, 2.1, 2.1, 4.5], "d": dates, "i": [1, 2, 2, 4]}, columns=["f", "i", "d"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # selection result = df.groupby("grouping")[["f", "i"]].transform("first") expected = expected[["f", "i"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # dup columns df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["g", "a", "a"]) result = df.groupby("g").transform("first") expected = df.drop("g", axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_transform_broadcast(tsframe, ts): @@ -179,26 +178,26 @@ def test_transform_axis(tsframe): grouped = ts.groupby(lambda x: x.weekday()) result = ts - grouped.transform("mean") expected = grouped.apply(lambda x: x - x.mean()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) ts = ts.T grouped = ts.groupby(lambda x: x.weekday(), axis=1) result = ts - grouped.transform("mean") expected = grouped.apply(lambda x: (x.T - x.mean(1)).T) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # non-monotonic ts = tso.iloc[[1, 0] + list(range(2, len(base)))] grouped = ts.groupby(lambda x: x.weekday()) result = ts - grouped.transform("mean") expected = grouped.apply(lambda x: x - x.mean()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) ts = ts.T grouped = ts.groupby(lambda x: x.weekday(), axis=1) result = ts - grouped.transform("mean") expected = grouped.apply(lambda x: (x.T - x.mean(1)).T) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_transform_dtype(): @@ -207,7 +206,7 @@ def test_transform_dtype(): df = DataFrame([[1, 3], [2, 3]]) result = df.groupby(1).transform("mean") expected = DataFrame([[1.5], [1.5]]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_transform_bug(): @@ -216,7 +215,7 @@ def test_transform_bug(): df = DataFrame(dict(A=Timestamp("20130101"), B=np.arange(5))) result = df.groupby("A")["B"].transform(lambda x: x.rank(ascending=False)) expected = Series(np.arange(5, 0, step=-1), name="B") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_transform_numeric_to_boolean(): @@ -226,11 +225,11 @@ def test_transform_numeric_to_boolean(): df = pd.DataFrame({"A": [1.1, 2.2], "B": [1, 2]}) result = df.groupby("B").A.transform(lambda x: True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = pd.DataFrame({"A": [1, 2], "B": [1, 2]}) result = df.groupby("B").A.transform(lambda x: True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_transform_datetime_to_timedelta(): @@ -245,11 +244,11 @@ def test_transform_datetime_to_timedelta(): df.groupby("A")["A"].transform(lambda x: x.max() - x.min() + base_time) - base_time ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # this does date math and causes the transform to return timedelta result = df.groupby("A")["A"].transform(lambda x: x.max() - x.min()) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_transform_datetime_to_numeric(): @@ -261,7 +260,7 @@ def test_transform_datetime_to_numeric(): ) expected = Series([-0.5, 0.5], name="b") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # convert dt to int df = DataFrame({"a": 1, "b": date_range("2015-01-01", periods=2, freq="D")}) @@ -270,7 +269,7 @@ def test_transform_datetime_to_numeric(): ) expected = Series([0, 1], name="b") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_transform_casting(): @@ -315,7 +314,7 @@ def test_dispatch_transform(tsframe): filled = grouped.fillna(method="pad") fillit = lambda x: x.fillna(method="pad") expected = df.groupby(lambda x: x.month).transform(fillit) - assert_frame_equal(filled, expected) + tm.assert_frame_equal(filled, expected) def test_transform_select_columns(df): @@ -325,7 +324,7 @@ def test_transform_select_columns(df): selection = df[["C", "D"]] expected = selection.groupby(df["A"]).transform(f) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_transform_exclude_nuisance(df): @@ -339,17 +338,17 @@ def test_transform_exclude_nuisance(df): expected = DataFrame(expected) result = df.groupby("A").transform(np.mean) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_transform_function_aliases(df): result = df.groupby("A").transform("mean") expected = df.groupby("A").transform(np.mean) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby("A")["C"].transform("mean") expected = df.groupby("A")["C"].transform(np.mean) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_series_fast_transform_date(): @@ -365,7 +364,7 @@ def test_series_fast_transform_date(): pd.Timestamp("2014-1-4"), ] expected = pd.Series(dates, name="d") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_transform_length(): @@ -383,7 +382,7 @@ def nsum(x): df.groupby("col1")["col2"].transform(nsum), ] for result in results: - assert_series_equal(result, expected, check_names=False) + tm.assert_series_equal(result, expected, check_names=False) def test_transform_coercion(): @@ -396,7 +395,7 @@ def test_transform_coercion(): expected = g.transform(np.mean) result = g.transform(lambda x: np.mean(x)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_transform_with_int(): @@ -417,14 +416,14 @@ def test_groupby_transform_with_int(): expected = DataFrame( dict(B=np.nan, C=Series([-1, 0, 1, -1, 0, 1], dtype="float64")) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # int case df = DataFrame(dict(A=[1, 1, 1, 2, 2, 2], B=1, C=[1, 2, 3, 1, 2, 3], D="foo")) with np.errstate(all="ignore"): result = df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) expected = DataFrame(dict(B=np.nan, C=[-1, 0, 1, -1, 0, 1])) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # int that needs float conversion s = Series([2, 3, 4, 10, 5, -1]) @@ -437,12 +436,12 @@ def test_groupby_transform_with_int(): s2 = s.iloc[3:6] s2 = (s2 - s2.mean()) / s2.std() expected = DataFrame(dict(B=np.nan, C=concat([s1, s2]))) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # int downcasting result = df.groupby("A").transform(lambda x: x * 2 / 2) expected = DataFrame(dict(B=1, C=[2, 3, 4, 10, 5, -1])) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_transform_with_nan_group(): @@ -452,7 +451,7 @@ def test_groupby_transform_with_nan_group(): expected = pd.Series( [1.0, 1.0, 2.0, 3.0, np.nan, 6.0, 6.0, 9.0, 9.0, 9.0], name="a" ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_transform_mixed_type(): @@ -479,7 +478,7 @@ def f(group): with pd.option_context("mode.chained_assignment", None): for key, group in grouped: res = f(group) - assert_frame_equal(res, result.loc[key]) + tm.assert_frame_equal(res, result.loc[key]) def _check_cython_group_transform_cumulative(pd_op, np_op, dtype): @@ -838,11 +837,11 @@ def interweave(list_obj): if as_series: result = getattr(df.groupby("key")["val"], fill_method)(limit=limit) exp = Series(_exp_vals, name="val") - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) else: result = getattr(df.groupby("key"), fill_method)(limit=limit) exp = DataFrame({"val": _exp_vals}) - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) @pytest.mark.parametrize("fill_method", ["ffill", "bfill"]) @@ -989,7 +988,7 @@ def test_transform_absent_categories(func): df = DataFrame(dict(x=Categorical(x_vals, x_cats), y=y)) result = getattr(df.y.groupby(df.x), func)() expected = df.y - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("func", ["ffill", "bfill", "shift"]) @@ -1000,7 +999,7 @@ def test_ffill_not_in_axis(func, key, val): result = getattr(df.groupby(**{key: val}), func)() expected = df - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_transform_invalid_name_raises(): @@ -1073,4 +1072,4 @@ def test_transform_lambda_with_datetimetz(): ], name="time", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected)
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29287
2019-10-30T14:11:57Z
2019-10-31T07:52:51Z
2019-10-31T07:52:50Z
2019-10-31T07:53:08Z
CLN: Consistent pandas.util.testing imports in pandas/tests/resample
diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py index 51e309130e45d..dc72800227c0e 100644 --- a/pandas/tests/resample/test_base.py +++ b/pandas/tests/resample/test_base.py @@ -11,12 +11,6 @@ from pandas.core.indexes.period import PeriodIndex, period_range from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_index_equal, - assert_series_equal, -) # a fixture value can be overridden by the test parameter value. Note that the # value of the fixture can be overridden this way even if the test doesn't use @@ -53,7 +47,7 @@ def test_asfreq(series_and_frame, freq, create_index): result = obj.resample(freq).asfreq() new_index = create_index(obj.index[0], obj.index[-1], freq=freq) expected = obj.reindex(new_index) - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) @pytest.mark.parametrize( @@ -67,21 +61,21 @@ def test_asfreq_fill_value(series, create_index): result = s.resample("1H").asfreq() new_index = create_index(s.index[0], s.index[-1], freq="1H") expected = s.reindex(new_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) frame = s.to_frame("value") frame.iloc[1] = None result = frame.resample("1H").asfreq(fill_value=4.0) new_index = create_index(frame.index[0], frame.index[-1], freq="1H") expected = frame.reindex(new_index, fill_value=4.0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @all_ts def test_resample_interpolate(frame): # # 12925 df = frame - assert_frame_equal( + tm.assert_frame_equal( df.resample("1T").asfreq().interpolate(), df.resample("1T").interpolate() ) @@ -113,9 +107,9 @@ def test_resample_empty_series(freq, empty_series, resample_method): expected.index = s.index.asfreq(freq=freq) else: expected.index = s.index._shallow_copy(freq=freq) - assert_index_equal(result.index, expected.index) + tm.assert_index_equal(result.index, expected.index) assert result.index.freq == expected.index.freq - assert_series_equal(result, expected, check_dtype=False) + tm.assert_series_equal(result, expected, check_dtype=False) @all_ts @@ -135,9 +129,9 @@ def test_resample_empty_dataframe(empty_frame, freq, resample_method): expected.index = df.index.asfreq(freq=freq) else: expected.index = df.index._shallow_copy(freq=freq) - assert_index_equal(result.index, expected.index) + tm.assert_index_equal(result.index, expected.index) assert result.index.freq == expected.index.freq - assert_almost_equal(result, expected, check_dtype=False) + tm.assert_almost_equal(result, expected, check_dtype=False) # test size for GH13212 (currently stays as df) @@ -186,12 +180,12 @@ def test_resample_loffset_arg_type(frame, create_index): if isinstance(expected.index, TimedeltaIndex): msg = "DataFrame are different" with pytest.raises(AssertionError, match=msg): - assert_frame_equal(result_agg, expected) + tm.assert_frame_equal(result_agg, expected) with pytest.raises(AssertionError, match=msg): - assert_frame_equal(result_how, expected) + tm.assert_frame_equal(result_how, expected) else: - assert_frame_equal(result_agg, expected) - assert_frame_equal(result_how, expected) + tm.assert_frame_equal(result_agg, expected) + tm.assert_frame_equal(result_how, expected) @all_ts @@ -202,7 +196,7 @@ def test_apply_to_empty_series(empty_series): result = s.resample(freq).apply(lambda x: 1) expected = s.resample(freq).apply(np.sum) - assert_series_equal(result, expected, check_dtype=False) + tm.assert_series_equal(result, expected, check_dtype=False) @all_ts @@ -214,7 +208,7 @@ def test_resampler_is_iterable(series): resampled = series.resample(freq) for (rk, rv), (gk, gv) in zip(resampled, grouped): assert rk == gk - assert_series_equal(rv, gv) + tm.assert_series_equal(rv, gv) @all_ts diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index fb3d428bcf4bf..a29f910261b58 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -15,11 +15,6 @@ from pandas.core.indexes.period import Period, period_range from pandas.core.resample import DatetimeIndex, _get_timestamp_range_edges import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) import pandas.tseries.offsets as offsets from pandas.tseries.offsets import BDay, Minute @@ -71,7 +66,7 @@ def test_custom_grouper(index): # GH2763 - return in put dtype if we can result = g.agg(np.sum) - assert_series_equal(result, expect) + tm.assert_series_equal(result, expect) df = DataFrame(np.random.rand(len(dti), 10), index=dti, dtype="float64") r = df.groupby(b).agg(np.sum) @@ -109,7 +104,7 @@ def test_resample_basic(series, closed, expected): s = series expected = expected(s) result = s.resample("5min", closed=closed, label="right").mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_integerarray(): @@ -123,13 +118,13 @@ def test_resample_integerarray(): index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.resample("3T").mean() expected = Series( [1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64" ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_basic_grouper(series): @@ -137,7 +132,7 @@ def test_resample_basic_grouper(series): result = s.resample("5Min").last() grouper = Grouper(freq=Minute(5), closed="left", label="left") expected = s.groupby(grouper).agg(lambda x: x[-1]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -178,7 +173,7 @@ def test_resample_how(series, downsample_method): result = getattr( s.resample("5min", closed="right", label="right"), downsample_method )() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -205,7 +200,7 @@ def _ohlc(group): ) result = s.resample("5min", closed="right", label="right").ohlc() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("func", ["min", "max", "sum", "prod", "mean", "var", "std"]) @@ -241,10 +236,10 @@ def __call__(self, x): df_partial2 = df.resample("M").apply(partial(fn, a=2)) df_class = df.resample("M").apply(FnClass()) - assert_frame_equal(df_standard, df_lambda) - assert_frame_equal(df_standard, df_partial) - assert_frame_equal(df_standard, df_partial2) - assert_frame_equal(df_standard, df_class) + tm.assert_frame_equal(df_standard, df_lambda) + tm.assert_frame_equal(df_standard, df_partial) + tm.assert_frame_equal(df_standard, df_partial2) + tm.assert_frame_equal(df_standard, df_class) def test_resample_rounding(): @@ -282,31 +277,31 @@ def test_resample_rounding(): expected = DataFrame( {"value": [4, 9, 4, 2]}, index=date_range("2014-11-08", freq="6s", periods=4) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.resample("7s").sum() expected = DataFrame( {"value": [4, 10, 4, 1]}, index=date_range("2014-11-08", freq="7s", periods=4) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.resample("11s").sum() expected = DataFrame( {"value": [11, 8]}, index=date_range("2014-11-08", freq="11s", periods=2) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.resample("13s").sum() expected = DataFrame( {"value": [13, 6]}, index=date_range("2014-11-08", freq="13s", periods=2) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.resample("17s").sum() expected = DataFrame( {"value": [16, 3]}, index=date_range("2014-11-08", freq="17s", periods=2) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_basic_from_daily(): @@ -388,12 +383,12 @@ def test_resample_upsampling_picked_but_not_correct(): ) result = s.resample("D").count() - assert_series_equal(result, Series(1, index=expected.index)) + tm.assert_series_equal(result, Series(1, index=expected.index)) result1 = s.resample("D").sum() result2 = s.resample("D").mean() - assert_series_equal(result1, expected) - assert_series_equal(result2, expected) + tm.assert_series_equal(result1, expected) + tm.assert_series_equal(result2, expected) def test_resample_frame_basic(): @@ -408,10 +403,10 @@ def test_resample_frame_basic(): g._cython_agg_general(f) result = df.resample("A").mean() - assert_series_equal(result["A"], df["A"].resample("A").mean()) + tm.assert_series_equal(result["A"], df["A"].resample("A").mean()) result = df.resample("M").mean() - assert_series_equal(result["A"], df["A"].resample("M").mean()) + tm.assert_series_equal(result["A"], df["A"].resample("M").mean()) df.resample("M", kind="period").mean() df.resample("W-WED", kind="period").mean() @@ -431,7 +426,7 @@ def test_resample_loffset(loffset): [s[0], s[1:6].mean(), s[6:11].mean(), s[11:].mean()], index=idx + timedelta(minutes=1), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) assert result.index.freq == Minute(5) # from daily @@ -456,7 +451,7 @@ def test_resample_loffset_upsample(): idx = date_range("1/1/2000", periods=4, freq="5min") expected = Series([s[0], s[5], s[10], s[-1]], index=idx + timedelta(minutes=1)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_loffset_count(): @@ -472,13 +467,13 @@ def test_resample_loffset_count(): ) expected = Series(10, index=expected_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Same issue should apply to .size() since it goes through # same code path result = ts.resample("10S", loffset="1s").size() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_upsample(): @@ -519,7 +514,7 @@ def test_resample_how_method(): Timestamp("2015-03-31 21:49:50"), ], ) - assert_series_equal(s.resample("10S").mean(), expected) + tm.assert_series_equal(s.resample("10S").mean(), expected) def test_resample_extra_index_point(): @@ -530,7 +525,7 @@ def test_resample_extra_index_point(): index = date_range(start="20150101", end="20150331", freq="B") df = DataFrame({"A": Series(range(len(index)), index=index)}, dtype="int64") result = df.resample("BM").last() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_upsample_with_limit(): @@ -539,7 +534,7 @@ def test_upsample_with_limit(): result = ts.resample("t").ffill(limit=2) expected = ts.reindex(result.index, method="ffill", limit=2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_nearest_upsample_with_limit(): @@ -548,7 +543,7 @@ def test_nearest_upsample_with_limit(): result = ts.resample("t").nearest(limit=2) expected = ts.reindex(result.index, method="nearest", limit=2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_ohlc(series): @@ -601,7 +596,7 @@ def test_resample_ohlc_result(): df = DataFrame(data=np.arange(len(index)), index=index) result = df.resample("B").mean() expected = df.reindex(index=date_range(rng[0], rng[-1], freq="B")) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_ohlc_dataframe(): @@ -627,7 +622,7 @@ def test_resample_ohlc_dataframe(): axis=1, keys=["VOLUME", "PRICE"], ) - assert_frame_equal(exp, res) + tm.assert_frame_equal(exp, res) df.columns = [["a", "b"], ["c", "d"]] res = df.resample("H").ohlc() @@ -643,7 +638,7 @@ def test_resample_ohlc_dataframe(): ("b", "d", "close"), ] ) - assert_frame_equal(exp, res) + tm.assert_frame_equal(exp, res) # dupe columns fail atm # df.columns = ['PRICE', 'PRICE'] @@ -662,7 +657,7 @@ def test_resample_dup_index(): result = df.resample("Q", axis=1).mean() expected = df.groupby(lambda x: int((x.month - 1) / 3), axis=1).mean() expected.columns = [Period(year=2000, quarter=i + 1, freq="Q") for i in range(4)] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_reresample(): @@ -681,22 +676,22 @@ def test_resample_timestamp_to_period(simple_date_range_series): result = ts.resample("A-DEC", kind="period").mean() expected = ts.resample("A-DEC").mean() expected.index = period_range("1990", "2000", freq="a-dec") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.resample("A-JUN", kind="period").mean() expected = ts.resample("A-JUN").mean() expected.index = period_range("1990", "2000", freq="a-jun") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.resample("M", kind="period").mean() expected = ts.resample("M").mean() expected.index = period_range("1990-01", "2000-01", freq="M") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.resample("M", kind="period").mean() expected = ts.resample("M").mean() expected.index = period_range("1990-01", "2000-01", freq="M") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_ohlc_5min(): @@ -728,8 +723,8 @@ def test_downsample_non_unique(): expected = ts.groupby(lambda x: x.month).mean() assert len(result) == 2 - assert_almost_equal(result[0], expected[1]) - assert_almost_equal(result[1], expected[2]) + tm.assert_almost_equal(result[0], expected[1]) + tm.assert_almost_equal(result[1], expected[2]) def test_asfreq_non_unique(): @@ -766,7 +761,7 @@ def test_resample_anchored_ticks(): for freq in freqs: result = ts[2:].resample(freq, closed="left", label="left").mean() expected = ts.resample(freq, closed="left", label="left").mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_single_group(): @@ -774,11 +769,11 @@ def test_resample_single_group(): rng = date_range("2000-1-1", "2000-2-10", freq="D") ts = Series(np.random.randn(len(rng)), index=rng) - assert_series_equal(ts.resample("M").sum(), ts.resample("M").apply(mysum)) + tm.assert_series_equal(ts.resample("M").sum(), ts.resample("M").apply(mysum)) rng = date_range("2000-1-1", "2000-1-10", freq="D") ts = Series(np.random.randn(len(rng)), index=rng) - assert_series_equal(ts.resample("M").sum(), ts.resample("M").apply(mysum)) + tm.assert_series_equal(ts.resample("M").sum(), ts.resample("M").apply(mysum)) # GH 3849 s = Series( @@ -787,7 +782,7 @@ def test_resample_single_group(): ) expected = Series([0.75], index=[Timestamp("20070915")]) result = s.resample("D").apply(lambda x: np.std(x)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_base(): @@ -809,7 +804,7 @@ def test_resample_float_base(): base = 17 + 43.51 / 60 result = s.resample("3min", base=base).size() expected = Series(3, index=pd.DatetimeIndex(["2018-11-26 16:17:43.51"])) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_daily_anchored(): @@ -819,7 +814,7 @@ def test_resample_daily_anchored(): result = ts[2:].resample("D", closed="left", label="left").mean() expected = ts.resample("D", closed="left", label="left").mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_to_period_monthly_buglet(): @@ -844,7 +839,7 @@ def test_period_with_agg(): expected = s2.to_timestamp().resample("D").mean().to_period() result = s2.resample("D").agg(lambda x: x.mean()) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_segfault(): @@ -862,7 +857,7 @@ def test_resample_segfault(): ).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) + tm.assert_frame_equal(result, expected) def test_resample_dtype_preservation(): @@ -909,7 +904,7 @@ def test_weekly_resample_buglet(): resampled = ts.resample("W").mean() expected = ts.resample("W-SUN").mean() - assert_series_equal(resampled, expected) + tm.assert_series_equal(resampled, expected) def test_monthly_resample_error(): @@ -933,7 +928,7 @@ def test_nanosecond_resample_error(): exp_indx = pd.date_range(start=pd.to_datetime(exp_start), periods=10, freq="100n") exp = Series(range(len(exp_indx)), index=exp_indx) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_resample_anchored_intraday(simple_date_range_series): @@ -1051,7 +1046,7 @@ def test_resample_not_monotonic(): result = ts.resample("D").sum() exp = ts.sort_index().resample("D").sum() - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_resample_median_bug_1688(): @@ -1130,9 +1125,9 @@ def test_resample_consistency(): r10 = s.resample("10Min").bfill() # s10_2, r10, r10_2, rl should all be equal - assert_series_equal(s10_2, r10) - assert_series_equal(s10_2, r10_2) - assert_series_equal(s10_2, rl) + tm.assert_series_equal(s10_2, r10) + tm.assert_series_equal(s10_2, r10_2) + tm.assert_series_equal(s10_2, rl) def test_resample_timegrouper(): @@ -1158,10 +1153,10 @@ def test_resample_timegrouper(): name="A", ) expected = DataFrame({"B": [1, 0, 2, 2, 1]}, index=exp_idx) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby(pd.Grouper(freq="M", key="A")).count() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame(dict(A=dates, B=np.arange(len(dates)), C=np.arange(len(dates)))) result = df.set_index("A").resample("M").count() @@ -1170,10 +1165,10 @@ def test_resample_timegrouper(): index=exp_idx, columns=["B", "C"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.groupby(pd.Grouper(freq="M", key="A")).count() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_nunique(): @@ -1198,13 +1193,13 @@ def test_resample_nunique(): for t in [r, g]: result = r.ID.nunique() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.ID.resample("D").nunique() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = df.ID.groupby(pd.Grouper(freq="D")).nunique() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_nunique_preserves_column_level_names(): @@ -1228,9 +1223,9 @@ def test_resample_nunique_with_date_gap(): # Since all elements are unique, these should all be the same results = [r.count(), r.nunique(), r.agg(Series.nunique), r.agg("nunique")] - assert_series_equal(results[0], results[1]) - assert_series_equal(results[0], results[2]) - assert_series_equal(results[0], results[3]) + tm.assert_series_equal(results[0], results[1]) + tm.assert_series_equal(results[0], results[2]) + tm.assert_series_equal(results[0], results[3]) @pytest.mark.parametrize("n", [10000, 100000]) @@ -1259,7 +1254,7 @@ def test_resample_group_info(n, k): arr = np.bincount(bins[mask] - 1, minlength=len(ix)).astype("int64", copy=False) right = Series(arr, index=ix) - assert_series_equal(left, right) + tm.assert_series_equal(left, right) def test_resample_size(): @@ -1274,7 +1269,7 @@ def test_resample_size(): val = np.bincount(bins, minlength=len(ix) + 1)[1:].astype("int64", copy=False) right = Series(val, index=ix) - assert_series_equal(left, right) + tm.assert_series_equal(left, right) def test_resample_across_dst(): @@ -1305,7 +1300,7 @@ def test_resample_across_dst(): result = df.resample(rule="H").sum() expected = DataFrame([5, 5], index=dti2) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_with_dst_time_change(): @@ -1322,18 +1317,18 @@ def test_groupby_with_dst_time_change(): index = pd.DatetimeIndex(expected_index_values) expected = pd.DataFrame([1.0] + ([np.nan] * 21) + [2.0], index=index) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_dst_anchor(): # 5172 dti = DatetimeIndex([datetime(2012, 11, 4, 23)], tz="US/Eastern") df = DataFrame([5], index=dti) - assert_frame_equal( + tm.assert_frame_equal( df.resample(rule="D").sum(), DataFrame([5], index=df.index.normalize()) ) df.resample(rule="MS").sum() - assert_frame_equal( + tm.assert_frame_equal( df.resample(rule="MS").sum(), DataFrame([5], index=DatetimeIndex([datetime(2012, 11, 1)], tz="US/Eastern")), ) @@ -1343,7 +1338,7 @@ def test_resample_dst_anchor(): df = DataFrame({"a": values, "b": values, "c": values}, index=dti, dtype="int64") how = {"a": "min", "b": "max", "c": "count"} - assert_frame_equal( + tm.assert_frame_equal( df.resample("W-MON").agg(how)[["a", "b", "c"]], DataFrame( { @@ -1356,7 +1351,7 @@ def test_resample_dst_anchor(): "W-MON Frequency", ) - assert_frame_equal( + tm.assert_frame_equal( df.resample("2W-MON").agg(how)[["a", "b", "c"]], DataFrame( { @@ -1371,7 +1366,7 @@ def test_resample_dst_anchor(): "2W-MON Frequency", ) - assert_frame_equal( + tm.assert_frame_equal( df.resample("MS").agg(how)[["a", "b", "c"]], DataFrame( {"a": [0, 48, 1538], "b": [47, 1537, 1586], "c": [48, 1490, 49]}, @@ -1380,7 +1375,7 @@ def test_resample_dst_anchor(): "MS Frequency", ) - assert_frame_equal( + tm.assert_frame_equal( df.resample("2MS").agg(how)[["a", "b", "c"]], DataFrame( {"a": [0, 1538], "b": [1537, 1586], "c": [1538, 49]}, @@ -1390,7 +1385,7 @@ def test_resample_dst_anchor(): ) df_daily = df["10/26/2013":"10/29/2013"] - assert_frame_equal( + tm.assert_frame_equal( df_daily.resample("D").agg({"a": "min", "b": "max", "c": "count"})[ ["a", "b", "c"] ], @@ -1461,17 +1456,17 @@ def test_resample_with_nat(): ["1970-01-01 00:00:00", "1970-01-01 00:00:01", "1970-01-01 00:00:02"] ) frame_1s = DataFrame([3, 7, 11], index=index_1s) - assert_frame_equal(frame.resample("1s").mean(), frame_1s) + tm.assert_frame_equal(frame.resample("1s").mean(), frame_1s) index_2s = DatetimeIndex(["1970-01-01 00:00:00", "1970-01-01 00:00:02"]) frame_2s = DataFrame([5, 11], index=index_2s) - assert_frame_equal(frame.resample("2s").mean(), frame_2s) + tm.assert_frame_equal(frame.resample("2s").mean(), frame_2s) index_3s = DatetimeIndex(["1970-01-01 00:00:00"]) frame_3s = DataFrame([7], index=index_3s) - assert_frame_equal(frame.resample("3s").mean(), frame_3s) + tm.assert_frame_equal(frame.resample("3s").mean(), frame_3s) - assert_frame_equal(frame.resample("60s").mean(), frame_3s) + tm.assert_frame_equal(frame.resample("60s").mean(), frame_3s) def test_resample_datetime_values(): @@ -1513,7 +1508,7 @@ def f(data, add_arg): df = pd.DataFrame({"A": 1, "B": 2}, index=pd.date_range("2017", periods=10)) result = df.groupby("A").resample("D").agg(f, multiplier) expected = df.groupby("A").resample("D").mean().multiply(multiplier) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("k", [1, 2, 3]) @@ -1543,7 +1538,7 @@ def test_resample_equivalent_offsets(n1, freq1, n2, freq2, k): result1 = s.resample(str(n1_) + freq1).mean() result2 = s.resample(str(n2_) + freq2).mean() - assert_series_equal(result1, result2) + tm.assert_series_equal(result1, result2) @pytest.mark.parametrize( diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 30febe3d2cc83..93ce7a9480b35 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -15,11 +15,6 @@ from pandas.core.indexes.period import Period, PeriodIndex, period_range from pandas.core.resample import _get_period_range_edges import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) import pandas.tseries.offsets as offsets @@ -50,7 +45,7 @@ def test_asfreq(self, series_and_frame, freq, kind): new_index = date_range(start=start, end=end, freq=freq, closed="left") expected = obj.to_timestamp().reindex(new_index).to_period(freq) result = obj.resample(freq, kind=kind).asfreq() - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) def test_asfreq_fill_value(self, series): # test for fill value during resampling, issue 3715 @@ -63,7 +58,7 @@ def test_asfreq_fill_value(self, series): ) expected = s.to_timestamp().reindex(new_index, fill_value=4.0) result = s.resample("1H", kind="timestamp").asfreq(fill_value=4.0) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) frame = s.to_frame("value") new_index = date_range( @@ -73,7 +68,7 @@ def test_asfreq_fill_value(self, series): ) expected = frame.to_timestamp().reindex(new_index, fill_value=3.0) result = frame.resample("1H", kind="timestamp").asfreq(fill_value=3.0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("freq", ["H", "12H", "2D", "W"]) @pytest.mark.parametrize("kind", [None, "period", "timestamp"]) @@ -108,7 +103,7 @@ def test_annual_upsample_cases( result = getattr(ts.resample(targ, convention=conv), meth)() expected = result.to_timestamp(targ, how=conv) expected = expected.asfreq(targ, meth).to_period() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_basic_downsample(self, simple_period_range_series): ts = simple_period_range_series("1/1/1990", "6/30/1995", freq="M") @@ -116,11 +111,11 @@ def test_basic_downsample(self, simple_period_range_series): expected = ts.groupby(ts.index.year).mean() expected.index = period_range("1/1/1990", "6/30/1995", freq="a-dec") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # this is ok - assert_series_equal(ts.resample("a-dec").mean(), result) - assert_series_equal(ts.resample("a").mean(), result) + tm.assert_series_equal(ts.resample("a-dec").mean(), result) + tm.assert_series_equal(ts.resample("a").mean(), result) @pytest.mark.parametrize( "rule,expected_error_msg", @@ -149,7 +144,7 @@ def test_basic_upsample(self, freq, simple_period_range_series): resampled = result.resample(freq, convention="end").ffill() expected = result.to_timestamp(freq, how="end") expected = expected.asfreq(freq, "ffill").to_period(freq) - assert_series_equal(resampled, expected) + tm.assert_series_equal(resampled, expected) def test_upsample_with_limit(self): rng = period_range("1/1/2000", periods=5, freq="A") @@ -157,14 +152,14 @@ def test_upsample_with_limit(self): result = ts.resample("M", convention="end").ffill(limit=2) expected = ts.asfreq("M").reindex(result.index, method="ffill", limit=2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_annual_upsample(self, simple_period_range_series): ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="A-DEC") df = DataFrame({"a": ts}) rdf = df.resample("D").ffill() exp = df["a"].resample("D").ffill() - assert_series_equal(rdf["a"], exp) + tm.assert_series_equal(rdf["a"], exp) rng = period_range("2000", "2003", freq="A-DEC") ts = Series([1, 2, 3, 4], index=rng) @@ -173,7 +168,7 @@ def test_annual_upsample(self, simple_period_range_series): ex_index = period_range("2000-01", "2003-12", freq="M") expected = ts.asfreq("M", how="start").reindex(ex_index, method="ffill") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("month", MONTHS) @pytest.mark.parametrize("target", ["D", "B", "M"]) @@ -186,7 +181,7 @@ def test_quarterly_upsample( result = ts.resample(target, convention=convention).ffill() expected = result.to_timestamp(target, how=convention) expected = expected.asfreq(target, "ffill").to_period() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("target", ["D", "B"]) @pytest.mark.parametrize("convention", ["start", "end"]) @@ -195,7 +190,7 @@ def test_monthly_upsample(self, target, convention, simple_period_range_series): result = ts.resample(target, convention=convention).ffill() expected = result.to_timestamp(target, how=convention) expected = expected.asfreq(target, "ffill").to_period() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_basic(self): # GH3609 @@ -211,9 +206,9 @@ def test_resample_basic(self): ) expected = Series([34.5, 79.5], index=index) result = s.to_period().resample("T", kind="period").mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result2 = s.resample("T", kind="period").mean() - assert_series_equal(result2, expected) + tm.assert_series_equal(result2, expected) @pytest.mark.parametrize( "freq,expected_vals", [("M", [31, 29, 31, 9]), ("2M", [31 + 29, 31 + 9])] @@ -226,7 +221,7 @@ def test_resample_count(self, freq, expected_vals): start="2000", freq=freq, periods=len(expected_vals) ) expected = Series(expected_vals, index=expected_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_same_freq(self, resample_method): @@ -237,7 +232,7 @@ def test_resample_same_freq(self, resample_method): expected = series result = getattr(series.resample("M"), resample_method)() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_incompat_freq(self): msg = ( @@ -268,7 +263,7 @@ def test_with_local_timezone_pytz(self): # Pacific expected_index = pd.period_range(start=start, end=end, freq="D") - offsets.Day() expected = Series(1, index=expected_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_with_pytz(self): # GH 13238 @@ -279,7 +274,7 @@ def test_resample_with_pytz(self): expected = Series( 2, index=pd.DatetimeIndex(["2017-01-01", "2017-01-02"], tz="US/Eastern") ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Especially assert that the timezone is LMT for pytz assert result.index.tz == pytz.timezone("US/Eastern") @@ -308,7 +303,7 @@ def test_with_local_timezone_dateutil(self): pd.period_range(start=start, end=end, freq="D", name="idx") - offsets.Day() ) expected = Series(1, index=expected_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_nonexistent_time_bin_edge(self): # GH 19375 @@ -350,7 +345,7 @@ def test_fill_method_and_how_upsample(self): ) last = s.resample("M").ffill() both = s.resample("M").ffill().resample("M").last().astype("int64") - assert_series_equal(last, both) + tm.assert_series_equal(last, both) @pytest.mark.parametrize("day", DAYS) @pytest.mark.parametrize("target", ["D", "B"]) @@ -361,14 +356,14 @@ def test_weekly_upsample(self, day, target, convention, simple_period_range_seri result = ts.resample(target, convention=convention).ffill() expected = result.to_timestamp(target, how=convention) expected = expected.asfreq(target, "ffill").to_period() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_to_timestamps(self, simple_period_range_series): ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="M") result = ts.resample("A-DEC", kind="timestamp").mean() expected = ts.to_timestamp(how="start").resample("A-DEC").mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_to_quarterly(self, simple_period_range_series): for month in MONTHS: @@ -387,7 +382,7 @@ def test_resample_to_quarterly(self, simple_period_range_series): expected = stamps.reindex(qdates.to_timestamp("D", "s"), method="ffill") expected.index = qdates - assert_series_equal(quar_ts, expected) + tm.assert_series_equal(quar_ts, expected) # conforms, but different month ts = simple_period_range_series("1990", "1992", freq="A-JUN") @@ -400,7 +395,7 @@ def test_resample_to_quarterly(self, simple_period_range_series): # .to_timestamp('D') # expected = expected.resample('Q-MAR').ffill() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_fill_missing(self): rng = PeriodIndex([2000, 2005, 2007, 2009], freq="A") @@ -410,7 +405,7 @@ def test_resample_fill_missing(self): stamps = s.to_timestamp() filled = s.resample("A").ffill() expected = stamps.resample("A").ffill().to_period("A") - assert_series_equal(filled, expected) + tm.assert_series_equal(filled, expected) def test_cant_fill_missing_dups(self): rng = PeriodIndex([2000, 2005, 2005, 2007, 2007], freq="A") @@ -428,20 +423,20 @@ def test_resample_5minute(self, freq, kind): if kind != "timestamp": expected = expected.to_period(freq) result = ts.resample(freq, kind=kind).mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_upsample_daily_business_daily(self, simple_period_range_series): ts = simple_period_range_series("1/1/2000", "2/1/2000", freq="B") result = ts.resample("D").asfreq() expected = ts.asfreq("D").reindex(period_range("1/3/2000", "2/1/2000")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) ts = simple_period_range_series("1/1/2000", "2/1/2000") result = ts.resample("H", convention="s").asfreq() exp_rng = period_range("1/1/2000", "2/1/2000 23:00", freq="H") expected = ts.asfreq("H", how="s").reindex(exp_rng) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_irregular_sparse(self): dr = date_range(start="1/1/2012", freq="5min", periods=1000) @@ -451,7 +446,7 @@ def test_resample_irregular_sparse(self): result = subset.resample("10min").apply(len) expected = s.resample("10min").apply(len).loc[result.index] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_weekly_all_na(self): rng = date_range("1/1/2000", periods=10, freq="W-WED") @@ -463,7 +458,7 @@ def test_resample_weekly_all_na(self): result = ts.resample("W-THU").asfreq().ffill()[:-1] expected = ts.asfreq("W-THU").ffill() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_tz_localized(self): dr = date_range(start="2012-4-13", end="2012-5-1") @@ -481,7 +476,7 @@ def test_resample_tz_localized(self): exp = ts_local_naive.resample("W").mean().tz_localize("America/Los_Angeles") - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) # it works result = ts_local.resample("D").mean() @@ -496,13 +491,13 @@ def test_resample_tz_localized(self): ex_index = date_range("2001-09-21", periods=1, freq="D", tz="Australia/Sydney") expected = Series([1.5], index=ex_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # for good measure result = s.resample("D", kind="period").mean() ex_index = period_range("2001-09-20", periods=1, freq="D") expected = Series([1.5], index=ex_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 6397 # comparing an offset that doesn't propagate tz's @@ -523,7 +518,7 @@ def test_resample_tz_localized(self): .agg({"first": np.sum, "second": np.mean}) .reindex(columns=["first", "second"]) ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_closed_left_corner(self): # #1465 @@ -535,7 +530,7 @@ def test_closed_left_corner(self): result = s.resample("10min", closed="left", label="right").mean() exp = s[1:].resample("10min", closed="left", label="right").mean() - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) result = s.resample("10min", closed="left", label="left").mean() exp = s[1:].resample("10min", closed="left", label="left").mean() @@ -543,7 +538,7 @@ def test_closed_left_corner(self): ex_index = date_range(start="1/1/2012 9:30", freq="10min", periods=3) tm.assert_index_equal(result.index, ex_index) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_quarterly_resampling(self): rng = period_range("2000Q1", periods=10, freq="Q-DEC") @@ -551,7 +546,7 @@ def test_quarterly_resampling(self): result = ts.resample("A").mean() exp = ts.to_timestamp().resample("A").mean().to_period() - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_resample_weekly_bug_1726(self): # 8/6/12 is a Monday @@ -595,7 +590,7 @@ def test_resample_with_dst_time_change(self): [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) + tm.assert_frame_equal(result, expected) def test_resample_bms_2752(self): # GH2753 @@ -616,7 +611,7 @@ def test_resample_bms_2752(self): # result = ts.resample('D', convention='span').mean() - # assert_series_equal(result, expected) + # tm.assert_series_equal(result, expected) def test_default_right_closed_label(self): end_freq = ["D", "Q", "M", "D"] @@ -627,7 +622,7 @@ def test_default_right_closed_label(self): df = DataFrame(np.random.randn(len(idx), 2), idx) resampled = df.resample(to_freq).mean() - assert_frame_equal( + tm.assert_frame_equal( resampled, df.resample(to_freq, closed="right", label="right").mean() ) @@ -640,7 +635,7 @@ def test_default_left_closed_label(self): df = DataFrame(np.random.randn(len(idx), 2), idx) resampled = df.resample(to_freq).mean() - assert_frame_equal( + tm.assert_frame_equal( resampled, df.resample(to_freq, closed="left", label="left").mean() ) @@ -660,7 +655,7 @@ def test_evenly_divisible_with_no_extra_bins(self): result = df.resample("5D").mean() expected = pd.concat([df.iloc[0:5].mean(), df.iloc[5:].mean()], axis=1).T expected.index = [Timestamp("2000-1-1"), Timestamp("2000-1-6")] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) index = date_range(start="2001-5-4", periods=28) df = DataFrame( @@ -702,7 +697,7 @@ def test_evenly_divisible_with_no_extra_bins(self): index=index, ) result = df.resample("7D").count() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( [ @@ -718,7 +713,7 @@ def test_evenly_divisible_with_no_extra_bins(self): index=index, ) result = df.resample("7D").sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("kind", ["period", None, "timestamp"]) @pytest.mark.parametrize("agg_arg", ["mean", {"value": "mean"}, ["mean"]]) @@ -741,8 +736,8 @@ def test_loffset_returns_datetimeindex(self, frame, kind, agg_arg): result_how = df.resample("2D", how=agg_arg, loffset="2H", kind=kind) if isinstance(agg_arg, list): expected.columns = pd.MultiIndex.from_tuples([("value", "mean")]) - assert_frame_equal(result_agg, expected) - assert_frame_equal(result_how, expected) + tm.assert_frame_equal(result_agg, expected) + tm.assert_frame_equal(result_how, expected) @pytest.mark.parametrize("freq, period_mult", [("H", 24), ("12H", 2)]) @pytest.mark.parametrize("kind", [None, "period"]) @@ -757,7 +752,7 @@ def test_upsampling_ohlc(self, freq, period_mult, kind): new_index = period_range(start="2000", freq=freq, periods=period_mult * len(pi)) expected = expected.reindex(new_index) result = s.resample(freq, kind=kind).ohlc() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "periods, values", @@ -807,7 +802,7 @@ def test_resample_with_nat(self, periods, values, freq, expected_values): ) expected = DataFrame(expected_values, index=expected_index) result = frame.resample(freq).mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_with_only_nat(self): # GH 13224 @@ -816,7 +811,7 @@ def test_resample_with_only_nat(self): expected_index = PeriodIndex(data=[], freq=pi.freq) expected = DataFrame(index=expected_index) result = frame.resample("1s").mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "start,end,start_freq,end_freq,base", @@ -848,7 +843,7 @@ def test_resample_with_non_zero_base(self, start, end, start_freq, end_freq, bas # to_timestamp casts 24H -> D result = result.asfreq(end_freq) if end_freq == "24H" else result expected = s.to_timestamp().resample(end_freq, base=base).mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "first,last,offset,exp_first,exp_last", diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 94bc884d66835..cbdfbb7a3100b 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -8,7 +8,6 @@ from pandas import DataFrame, Series from pandas.core.indexes.datetimes import date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal dti = date_range(start=datetime(2005, 1, 1), end=datetime(2005, 1, 10), freq="Min") @@ -64,7 +63,7 @@ def test_groupby_resample_api(): index = pd.MultiIndex.from_arrays([[1] * 8 + [2] * 8, i], names=["group", "date"]) expected = DataFrame({"val": [5] * 7 + [6] + [7] * 7 + [8]}, index=index) result = df.groupby("group").apply(lambda x: x.resample("1D").ffill())[["val"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_groupby_resample_on_api(): @@ -83,7 +82,7 @@ def test_groupby_resample_on_api(): expected = df.set_index("dates").groupby("key").resample("D").mean() result = df.groupby("key").resample("D", on="dates").mean() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_pipe(test_frame): @@ -158,11 +157,11 @@ def tests_skip_nuisance(test_frame): r = df.resample("H") result = r[["A", "B"]].sum() expected = pd.concat([r.A.sum(), r.B.sum()], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = r[["A", "B", "C"]].sum() result = r.sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_downsample_but_actually_upsampling(): @@ -175,7 +174,7 @@ def test_downsample_but_actually_upsampling(): [0, 20, 40, 60, 80], index=pd.date_range("2012-01-01 00:00:00", freq="20s", periods=5), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_combined_up_downsampling_of_irregular(): @@ -191,7 +190,7 @@ def test_combined_up_downsampling_of_irregular(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = ts2.resample("2s", how="mean", fill_method="ffill") expected = ts2.resample("2s").mean().ffill() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_transform(): @@ -199,7 +198,7 @@ def test_transform(): r = test_series.resample("20min") expected = test_series.groupby(pd.Grouper(freq="20min")).transform("mean") result = r.transform("mean") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_fillna(): @@ -211,11 +210,11 @@ def test_fillna(): expected = r.ffill() result = r.fillna(method="ffill") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = r.bfill() result = r.fillna(method="bfill") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) msg = ( r"Invalid fill method\. Expecting pad \(ffill\), backfill" @@ -233,7 +232,7 @@ def test_apply_without_aggregation(): for t in [g, r]: result = t.apply(lambda x: x) - assert_series_equal(result, test_series) + tm.assert_series_equal(result, test_series) def test_agg_consistency(): @@ -251,7 +250,7 @@ def test_agg_consistency(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): expected = r[["A", "B", "C"]].agg({"r1": "mean", "r2": "sum"}) result = r.agg({"r1": "mean", "r2": "sum"}) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) # TODO: once GH 14008 is fixed, move these tests into @@ -289,31 +288,31 @@ def test_agg(): expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "std"]]) for t in cases: result = t.aggregate([np.mean, np.std]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = pd.concat([a_mean, b_std], axis=1) for t in cases: result = t.aggregate({"A": np.mean, "B": np.std}) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) expected = pd.concat([a_mean, a_std], axis=1) expected.columns = pd.MultiIndex.from_tuples([("A", "mean"), ("A", "std")]) for t in cases: result = t.aggregate({"A": ["mean", "std"]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = pd.concat([a_mean, a_sum], axis=1) expected.columns = ["mean", "sum"] for t in cases: result = t["A"].aggregate(["mean", "sum"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = pd.concat([a_mean, a_sum], axis=1) expected.columns = pd.MultiIndex.from_tuples([("A", "mean"), ("A", "sum")]) for t in cases: with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = t.aggregate({"A": {"mean": "mean", "sum": "sum"}}) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) expected = pd.concat([a_mean, a_sum, b_mean, b_sum], axis=1) expected.columns = pd.MultiIndex.from_tuples( @@ -327,7 +326,7 @@ def test_agg(): "B": {"mean2": "mean", "sum2": "sum"}, } ) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) expected.columns = pd.MultiIndex.from_tuples( @@ -335,7 +334,7 @@ def test_agg(): ) for t in cases: result = t.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]}) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) expected = pd.concat([a_mean, a_sum, b_mean, b_sum], axis=1) expected.columns = pd.MultiIndex.from_tuples( @@ -374,7 +373,7 @@ def test_agg_misc(): result = t.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)}) rcustom = t["B"].apply(lambda x: np.std(x, ddof=1)) expected = pd.concat([r["A"].sum(), rcustom], axis=1) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) # agg with renamers expected = pd.concat( @@ -389,7 +388,7 @@ def test_agg_misc(): result = t[["A", "B"]].agg( OrderedDict([("result1", np.sum), ("result2", np.mean)]) ) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) # agg with different hows expected = pd.concat( @@ -400,12 +399,12 @@ def test_agg_misc(): ) for t in cases: result = t.agg(OrderedDict([("A", ["sum", "std"]), ("B", ["mean", "std"])])) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) # equivalent of using a selection list / or not for t in cases: result = t[["A", "B"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]}) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) # series like aggs for t in cases: @@ -413,7 +412,7 @@ def test_agg_misc(): result = t["A"].agg({"A": ["sum", "std"]}) expected = pd.concat([t["A"].sum(), t["A"].std()], axis=1) expected.columns = pd.MultiIndex.from_tuples([("A", "sum"), ("A", "std")]) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) expected = pd.concat( [t["A"].agg(["sum", "std"]), t["A"].agg(["mean", "std"])], axis=1 @@ -423,7 +422,7 @@ def test_agg_misc(): ) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = t["A"].agg({"A": ["sum", "std"], "B": ["mean", "std"]}) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) # errors # invalid names in the agg specification @@ -469,11 +468,11 @@ def test_agg_nested_dicts(): result = t[["A", "B"]].agg( {"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}} ) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = t.agg({"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}}) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) def test_try_aggregate_non_existing_column(): @@ -534,10 +533,10 @@ def test_selection_api_validation(): exp = df_exp.resample("2D").sum() exp.index.name = "date" - assert_frame_equal(exp, df.resample("2D", on="date").sum()) + tm.assert_frame_equal(exp, df.resample("2D", on="date").sum()) exp.index.name = "d" - assert_frame_equal(exp, df.resample("2D", level="d").sum()) + tm.assert_frame_equal(exp, df.resample("2D", level="d").sum()) @pytest.mark.parametrize( @@ -564,4 +563,4 @@ def test_agg_with_datetime_index_list_agg_func(col_name): ), columns=pd.MultiIndex(levels=[[col_name], ["mean"]], codes=[[0], [0]]), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index 9053a7ebfea2b..7efc6b0d466b9 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -6,7 +6,6 @@ from pandas import DataFrame, Series, Timestamp from pandas.core.indexes.datetimes import date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal test_frame = DataFrame( {"A": [1] * 20 + [2] * 12 + [3] * 8, "B": np.arange(40)}, @@ -56,7 +55,7 @@ def f(x): expected = df.groupby("id").apply(f) result = df.set_index("date").groupby("id").resample("D").asfreq() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df = DataFrame( { @@ -71,7 +70,7 @@ def f(x): expected = df.groupby("group").apply(f) result = df.groupby("group").resample("1D").ffill() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_getitem(): @@ -80,13 +79,13 @@ def test_getitem(): expected = g.B.apply(lambda x: x.resample("2s").mean()) result = g.resample("2s").B.mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = g.B.resample("2s").mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = g.resample("2s").mean().B - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_getitem_multiple(): @@ -105,10 +104,10 @@ def test_getitem_multiple(): ), name="buyer", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = r["buyer"].count() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_resample_on_api_with_getitem(): @@ -118,7 +117,7 @@ def test_groupby_resample_on_api_with_getitem(): ) exp = df.set_index("date").groupby("id").resample("2D")["data"].sum() result = df.groupby("id").resample("2D", on="date")["data"].sum() - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_nearest(): @@ -144,7 +143,7 @@ def test_nearest(): freq="20S", ), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_methods(): @@ -154,37 +153,37 @@ def test_methods(): for f in ["first", "last", "median", "sem", "sum", "mean", "min", "max"]: result = getattr(r, f)() expected = g.apply(lambda x: getattr(x.resample("2s"), f)()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) for f in ["size"]: result = getattr(r, f)() expected = g.apply(lambda x: getattr(x.resample("2s"), f)()) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) for f in ["count"]: result = getattr(r, f)() expected = g.apply(lambda x: getattr(x.resample("2s"), f)()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # series only for f in ["nunique"]: result = getattr(r.B, f)() expected = g.B.apply(lambda x: getattr(x.resample("2s"), f)()) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) for f in ["nearest", "backfill", "ffill", "asfreq"]: result = getattr(r, f)() expected = g.apply(lambda x: getattr(x.resample("2s"), f)()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = r.ohlc() expected = g.apply(lambda x: x.resample("2s").ohlc()) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) for f in ["std", "var"]: result = getattr(r, f)(ddof=1) expected = g.apply(lambda x: getattr(x.resample("2s"), f)(ddof=1)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_apply(): @@ -199,13 +198,13 @@ def f(x): return x.resample("2s").sum() result = r.apply(f) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def f(x): return x.resample("2s").apply(lambda y: y.sum()) result = g.apply(f) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_apply_with_mutated_index(): @@ -220,12 +219,12 @@ def f(x): expected = df.groupby(pd.Grouper(freq="M")).apply(f) result = df.resample("M").apply(f) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # A case for series expected = df["col1"].groupby(pd.Grouper(freq="M")).apply(f) result = df["col1"].resample("M").apply(f) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_groupby_with_label(): @@ -245,7 +244,7 @@ def test_resample_groupby_with_label(): data={"col0": [0, 0, 2, 2], "col1": [1, 1, 2, 1]}, index=mindex ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_consistency_with_window(): @@ -275,4 +274,4 @@ def test_median_duplicate_columns(): expected = df2.resample("5s").median() result = df.resample("5s").median() expected.columns = result.columns - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 648d78d92e7d4..574182ae99c5c 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -9,7 +9,6 @@ from pandas.core.groupby.grouper import Grouper from pandas.core.indexes.datetimes import date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal test_series = Series(np.random.randn(1000), index=date_range("1/1/2000", periods=1000)) @@ -27,7 +26,7 @@ def f(x): applied.index = applied.index.droplevel(0) expected.index = expected.index.droplevel(0) - assert_series_equal(applied, expected) + tm.assert_series_equal(applied, expected) def test_count(): @@ -38,11 +37,11 @@ def test_count(): grouper = Grouper(freq="A", label="right", closed="right") result = test_series.groupby(grouper).count() expected.index = result.index - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = test_series.resample("A").count() expected.index = result.index - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_numpy_reduction(): @@ -51,7 +50,7 @@ def test_numpy_reduction(): expected = test_series.groupby(lambda x: x.year).agg(np.prod) expected.index = result.index - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_iteration(): @@ -153,7 +152,7 @@ def test_aggregate_normal(resample_method): expected.index = date_range(start='2013-01-01', freq='D', periods=5, name='key') dt_result = getattr(dt_grouped, func)(3) - assert_frame_equal(expected, dt_result) + tm.assert_frame_equal(expected, dt_result) """ @@ -210,7 +209,7 @@ def test_aggregate_with_nat(func, fill_value): expected = normal_result.append(pad) expected = expected.sort_index() expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key") - assert_frame_equal(expected, dt_result) + tm.assert_frame_equal(expected, dt_result) assert dt_result.index.name == "key" @@ -240,7 +239,7 @@ def test_aggregate_with_nat_size(): expected = normal_result.append(pad) expected = expected.sort_index() expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key") - assert_series_equal(expected, dt_result) + tm.assert_series_equal(expected, dt_result) assert dt_result.index.name == "key" diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py index 9ce419d5cd20a..7a6ebf826ca4d 100644 --- a/pandas/tests/resample/test_timedelta.py +++ b/pandas/tests/resample/test_timedelta.py @@ -6,7 +6,6 @@ from pandas import DataFrame, Series from pandas.core.indexes.timedeltas import timedelta_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal def test_asfreq_bug(): @@ -16,7 +15,7 @@ def test_asfreq_bug(): data=[1, np.nan, np.nan, 3], index=timedelta_range("0 day", periods=4, freq="1T"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_with_nat(): @@ -27,7 +26,7 @@ def test_resample_with_nat(): {"value": [2.5, np.nan, 5.0]}, index=timedelta_range("0 day", periods=3, freq="1S"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_resample_as_freq_with_subperiod(): @@ -53,11 +52,11 @@ def test_resample_with_timedeltas(): ) result = df.resample("30T").sum() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) s = df["A"] result = s.resample("30T").sum() - assert_series_equal(result, expected["A"]) + tm.assert_series_equal(result, expected["A"]) def test_resample_single_period_timedelta(): @@ -67,7 +66,7 @@ def test_resample_single_period_timedelta(): expected = Series( [1, 5, 4], index=pd.timedelta_range("1 day", freq="2s", periods=3) ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_timedelta_idempotency(): @@ -77,7 +76,7 @@ def test_resample_timedelta_idempotency(): series = Series(range(9), index=index) result = series.resample("10L").mean() expected = series - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_resample_base_with_timedeltaindex():
Part of #29272 Fyi: the changes were created via a script posted in the issue - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29286
2019-10-30T14:02:39Z
2019-10-31T07:48:57Z
2019-10-31T07:48:57Z
2019-10-31T07:49:06Z
CLN: Consistent pandas.util.testing imports in pandas/tests/reshape
diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 305d7b9781634..925eaac45045d 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -8,7 +8,6 @@ from pandas import DataFrame, Index, MultiIndex, Series, concat, merge from pandas.tests.reshape.merge.test_merge import NGROUPS, N, get_test_data import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal a_ = np.array @@ -194,7 +193,7 @@ def test_join_on(self): expected = DataFrame( {"key": ["a", "a", "b", "b", "c"], "value": [0, 0, 1, 1, 2]} ) - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) # Test when some are missing df_a = DataFrame([[1], [2], [3]], index=["a", "b", "c"], columns=["one"]) @@ -281,7 +280,7 @@ def test_join_on_pass_vector(self): join_col = self.target.pop("C") result = self.target.join(self.source, on=join_col) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_join_with_len0(self): # nothing to merge @@ -314,12 +313,12 @@ def test_join_on_singlekey_list(self): joined = df.join(df2, on=["key"]) expected = df.join(df2, on="key") - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) def test_join_on_series(self): result = self.target.join(self.source["MergedA"], on="C") expected = self.target.join(self.source[["MergedA"]], on="C") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_join_on_series_buglet(self): # GH #638 @@ -341,11 +340,11 @@ def test_join_index_mixed(self, join_type): joined = df1.join(df2, how=join_type) expected = _join_by_hand(df1, df2, how=join_type) - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) joined = df2.join(df1, how=join_type) expected = _join_by_hand(df2, df1, how=join_type) - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) def test_join_index_mixed_overlap(self): df1 = DataFrame( @@ -377,7 +376,7 @@ def test_join_index_mixed_overlap(self): df1.columns = expected_columns[:4] df2.columns = expected_columns[4:] expected = _join_by_hand(df1, df2) - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) def test_join_empty_bug(self): # generated an exception in 0.4.3 @@ -416,7 +415,7 @@ def test_join_multiindex(self): ex_index = Index(index1.values).union(Index(index2.values)) expected = df1.reindex(ex_index).join(df2.reindex(ex_index)) expected.index.names = index1.names - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) assert joined.index.names == index1.names df1 = df1.sort_index(level=1) @@ -427,7 +426,7 @@ def test_join_multiindex(self): expected = df1.reindex(ex_index).join(df2.reindex(ex_index)) expected.index.names = index1.names - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) assert joined.index.names == index1.names def test_join_inner_multiindex(self): @@ -475,7 +474,7 @@ def test_join_inner_multiindex(self): how="inner", sort=False, ) - assert_frame_equal(joined, expected2.reindex_like(joined)) + tm.assert_frame_equal(joined, expected2.reindex_like(joined)) expected2 = merge( to_join, @@ -490,7 +489,7 @@ def test_join_inner_multiindex(self): expected.index = joined.index assert joined.index.is_monotonic - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) # _assert_same_contents(expected, expected2.loc[:, expected.columns]) @@ -528,7 +527,7 @@ def test_join_float64_float32(self): assert rs.dtypes["md"] == "float32" xp = xpdf.merge(s, left_on="a", right_index=True) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_join_many_non_unique_index(self): df1 = DataFrame({"a": [1, 1], "b": [1, 1], "c": [10, 20]}) @@ -547,7 +546,7 @@ def test_join_many_non_unique_index(self): expected = expected[result.columns] expected["a"] = expected.a.astype("int64") expected["b"] = expected.b.astype("int64") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) df1 = DataFrame({"a": [1, 1, 1], "b": [1, 1, 1], "c": [10, 20, 30]}) df2 = DataFrame({"a": [1, 1, 1], "b": [1, 1, 2], "d": [100, 200, 300]}) @@ -562,7 +561,7 @@ def test_join_many_non_unique_index(self): result = result.reset_index() - assert_frame_equal(result, expected.loc[:, result.columns]) + tm.assert_frame_equal(result, expected.loc[:, result.columns]) # GH 11519 df = DataFrame( @@ -580,9 +579,9 @@ def test_join_many_non_unique_index(self): outer = df.join(s, how="outer") left = df.join(s, how="left") right = df.join(s, how="right") - assert_frame_equal(inner, outer) - assert_frame_equal(inner, left) - assert_frame_equal(inner, right) + tm.assert_frame_equal(inner, outer) + tm.assert_frame_equal(inner, left) + tm.assert_frame_equal(inner, right) def test_join_sort(self): left = DataFrame({"key": ["foo", "bar", "baz", "foo"], "value": [1, 2, 3, 4]}) @@ -597,7 +596,7 @@ def test_join_sort(self): }, index=[1, 2, 0, 3], ) - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) # smoke test joined = left.join(right, on="key", sort=False) @@ -684,7 +683,7 @@ def test_join_many_mixed(self): df3 = df.loc[:, ["key"]] result = df1.join([df2, df3]) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_join_dups(self): @@ -702,7 +701,7 @@ def test_join_dups(self): expected = concat([df, df], axis=1) result = df.join(df, rsuffix="_2") result.columns = expected.columns - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # GH 4975, invalid join on dups w = DataFrame(np.random.randn(4, 2), columns=["x", "y"]) @@ -716,7 +715,7 @@ def test_join_dups(self): dta = dta.merge(w, left_index=True, right_index=True) expected = concat([x, y, z, w], axis=1) expected.columns = ["x_x", "y_x", "x_y", "y_y", "x_x", "y_x", "x_y", "y_y"] - assert_frame_equal(dta, expected) + tm.assert_frame_equal(dta, expected) def test_join_multi_to_multi(self, join_type): # GH 20475 @@ -736,7 +735,7 @@ def test_join_multi_to_multi(self, join_type): .merge(right.reset_index(), on=["abc", "xy"], how=join_type) .set_index(["abc", "xy", "num"]) ) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) msg = ( r"len\(left_on\) must equal the number of levels in the index" ' of "right"' @@ -769,7 +768,7 @@ def test_join_on_tz_aware_datetimeindex(self): result = df1.join(df2.set_index("date"), on="date") expected = df1.copy() expected["vals_2"] = pd.Series([np.nan] * 2 + list("tuv"), dtype=object) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def _check_join(left, right, result, join_col, how="left", lsuffix="_x", rsuffix="_y"): diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 19555a0c7e4c3..37c0b57bc7581 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -29,7 +29,6 @@ from pandas.core.reshape.concat import concat from pandas.core.reshape.merge import MergeError, merge import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal N = 50 NGROUPS = 8 @@ -128,7 +127,7 @@ def test_merge_inner_join_empty(self): df_a = pd.DataFrame({"a": [1, 2]}, index=[0, 1], dtype="int64") result = pd.merge(df_empty, df_a, left_index=True, right_index=True) expected = pd.DataFrame({"a": []}, index=[], dtype="int64") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_merge_common(self): joined = merge(self.df, self.df2) @@ -142,7 +141,7 @@ def test_merge_index_as_on_arg(self): right = self.df2.set_index("key1") result = merge(left, right, on="key1") expected = merge(self.df, self.df2, on="key1").set_index("key1") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_merge_index_singlekey_right_vs_left(self): left = DataFrame( @@ -156,7 +155,7 @@ def test_merge_index_singlekey_right_vs_left(self): merged2 = merge( right, left, right_on="key", left_index=True, how="right", sort=False ) - assert_frame_equal(merged1, merged2.loc[:, merged1.columns]) + tm.assert_frame_equal(merged1, merged2.loc[:, merged1.columns]) merged1 = merge( left, right, left_on="key", right_index=True, how="left", sort=True @@ -164,7 +163,7 @@ def test_merge_index_singlekey_right_vs_left(self): merged2 = merge( right, left, right_on="key", left_index=True, how="right", sort=True ) - assert_frame_equal(merged1, merged2.loc[:, merged1.columns]) + tm.assert_frame_equal(merged1, merged2.loc[:, merged1.columns]) def test_merge_index_singlekey_inner(self): left = DataFrame( @@ -175,11 +174,11 @@ def test_merge_index_singlekey_inner(self): # inner join result = merge(left, right, left_on="key", right_index=True, how="inner") expected = left.join(right, on="key").loc[result.index] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = merge(right, left, right_on="key", left_index=True, how="inner") expected = left.join(right, on="key").loc[result.index] - assert_frame_equal(result, expected.loc[:, result.columns]) + tm.assert_frame_equal(result, expected.loc[:, result.columns]) def test_merge_misspecified(self): msg = "Must pass right_on or right_index=True" @@ -296,7 +295,7 @@ def test_intelligently_handle_join_key(self): }, columns=["value", "key", "rvalue"], ) - assert_frame_equal(joined, expected) + tm.assert_frame_equal(joined, expected) def test_merge_join_key_dtype_cast(self): # #8596 @@ -331,7 +330,7 @@ def test_handle_join_key_pass_array(self): merged = merge(left, right, left_on="key", right_on=key, how="outer") merged2 = merge(right, left, left_on=key, right_on="key", how="outer") - assert_series_equal(merged["key"], merged2["key"]) + tm.assert_series_equal(merged["key"], merged2["key"]) assert merged["key"].notna().all() assert merged2["key"].notna().all() @@ -406,10 +405,10 @@ def test_left_merge_empty_dataframe(self): right = DataFrame({"key": []}) result = merge(left, right, on="key", how="left") - assert_frame_equal(result, left) + tm.assert_frame_equal(result, left) result = merge(right, left, on="key", how="right") - assert_frame_equal(result, left) + tm.assert_frame_equal(result, left) @pytest.mark.parametrize( "kwarg", @@ -540,7 +539,7 @@ def test_merge_empty_frame(self, series_of_dtype, series_of_dtype2): columns=["value_x", "key", "value_y"], ) actual = df_empty.merge(df, on="key") - assert_frame_equal(actual, expected) + tm.assert_frame_equal(actual, expected) def test_merge_all_na_column(self, series_of_dtype, series_of_dtype_all_na): # GH 25183 @@ -561,7 +560,7 @@ def test_merge_all_na_column(self, series_of_dtype, series_of_dtype_all_na): columns=["key", "value_x", "value_y"], ) actual = df_left.merge(df_right, on="key") - assert_frame_equal(actual, expected) + tm.assert_frame_equal(actual, expected) def test_merge_nosort(self): # GH#2098, TODO: anything to do? @@ -589,7 +588,7 @@ def test_merge_nosort(self): result = df.merge(new, on="var3", sort=False) exp = merge(df, new, on="var3", sort=False) - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) assert (df.var3.unique() == result.var3.unique()).all() @@ -610,7 +609,7 @@ def test_merge_nan_right(self): .set_index(None) .reset_index()[["i1", "i2", "i1_", "i3"]] ) - assert_frame_equal(result, expected, check_dtype=False) + tm.assert_frame_equal(result, expected, check_dtype=False) df1 = DataFrame({"i1": [0, 1], "i2": [0.5, 1.5]}) df2 = DataFrame({"i1": [0], "i3": [0.7]}) @@ -623,7 +622,7 @@ def test_merge_nan_right(self): "i3": {0: 0.69999999999999996, 1: np.nan}, } )[["i1", "i2", "i1_", "i3"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_merge_type(self): class NotADataFrame(DataFrame): @@ -650,7 +649,7 @@ def test_join_append_timedeltas(self): "t": [timedelta(0, 22500), timedelta(0, 22500)], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) td = np.timedelta64(300000000) lhs = DataFrame(Series([td, td], index=["A", "B"])) @@ -663,7 +662,7 @@ def test_join_append_timedeltas(self): "0r": Series([td, pd.NaT], index=list("AB")), } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_other_datetime_unit(self): # GH 13389 @@ -729,7 +728,7 @@ def test_overlapping_columns_error_message(self): } ) expected.columns = ["key", "foo", "foo", "bar", "bar"] - assert_frame_equal(merge(df, df2), expected) + tm.assert_frame_equal(merge(df, df2), expected) # #2649, #10639 df2.columns = ["key1", "foo", "foo"] @@ -761,7 +760,7 @@ def test_merge_on_datetime64tz(self): } ) result = pd.merge(left, right, on="key", how="outer") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) left = pd.DataFrame( { @@ -785,7 +784,7 @@ def test_merge_on_datetime64tz(self): } ) result = pd.merge(left, right, on="key", how="outer") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert result["value_x"].dtype == "datetime64[ns, US/Eastern]" assert result["value_y"].dtype == "datetime64[ns, US/Eastern]" @@ -844,7 +843,7 @@ def test_merge_datetime64tz_with_dst_transition(self): "value_y": [np.nan] * 4 + [2] * 3, } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_merge_non_unique_period_index(self): # GH #16871 @@ -878,7 +877,7 @@ def test_merge_on_periods(self): } ) result = pd.merge(left, right, on="key", how="outer") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) left = pd.DataFrame( {"key": [1, 2], "value": pd.period_range("20151010", periods=2, freq="D")} @@ -897,7 +896,7 @@ def test_merge_on_periods(self): } ) result = pd.merge(left, right, on="key", how="outer") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) assert result["value_x"].dtype == "Period[D]" assert result["value_y"].dtype == "Period[D]" @@ -950,13 +949,13 @@ def test_indicator(self): ] test = merge(df1, df2, on="col1", how="outer", indicator=True) - assert_frame_equal(test, df_result) + tm.assert_frame_equal(test, df_result) test = df1.merge(df2, on="col1", how="outer", indicator=True) - assert_frame_equal(test, df_result) + tm.assert_frame_equal(test, df_result) # No side effects - assert_frame_equal(df1, df1_copy) - assert_frame_equal(df2, df2_copy) + tm.assert_frame_equal(df1, df1_copy) + tm.assert_frame_equal(df2, df2_copy) # Check with custom name df_result_custom_name = df_result @@ -967,11 +966,11 @@ def test_indicator(self): test_custom_name = merge( df1, df2, on="col1", how="outer", indicator="custom_name" ) - assert_frame_equal(test_custom_name, df_result_custom_name) + tm.assert_frame_equal(test_custom_name, df_result_custom_name) test_custom_name = df1.merge( df2, on="col1", how="outer", indicator="custom_name" ) - assert_frame_equal(test_custom_name, df_result_custom_name) + tm.assert_frame_equal(test_custom_name, df_result_custom_name) # Check only accepts strings and booleans msg = "indicator option can only accept boolean or string arguments" @@ -1043,9 +1042,9 @@ def test_indicator(self): ) test5 = merge(df3, df4, on=["col1", "col2"], how="outer", indicator=True) - assert_frame_equal(test5, hand_coded_result) + tm.assert_frame_equal(test5, hand_coded_result) test5 = df3.merge(df4, on=["col1", "col2"], how="outer", indicator=True) - assert_frame_equal(test5, hand_coded_result) + tm.assert_frame_equal(test5, hand_coded_result) def test_validation(self): left = DataFrame( @@ -1066,8 +1065,8 @@ def test_validation(self): right_copy = right.copy() result = merge(left, right, left_index=True, right_index=True, validate="1:1") - assert_frame_equal(left, left_copy) - assert_frame_equal(right, right_copy) + tm.assert_frame_equal(left, left_copy) + tm.assert_frame_equal(right, right_copy) # make sure merge still correct expected = DataFrame( @@ -1084,7 +1083,7 @@ def test_validation(self): result = merge( left, right, left_index=True, right_index=True, validate="one_to_one" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected_2 = DataFrame( { @@ -1096,12 +1095,12 @@ def test_validation(self): ) result = merge(left, right, on="a", validate="1:1") - assert_frame_equal(left, left_copy) - assert_frame_equal(right, right_copy) - assert_frame_equal(result, expected_2) + tm.assert_frame_equal(left, left_copy) + tm.assert_frame_equal(right, right_copy) + tm.assert_frame_equal(result, expected_2) result = merge(left, right, on="a", validate="one_to_one") - assert_frame_equal(result, expected_2) + tm.assert_frame_equal(result, expected_2) # One index, one column expected_3 = DataFrame( @@ -1122,7 +1121,7 @@ def test_validation(self): right_on="a", validate="one_to_one", ) - assert_frame_equal(result, expected_3) + tm.assert_frame_equal(result, expected_3) # Dups on right right_w_dups = right.append(pd.DataFrame({"a": ["e"], "c": ["moo"]}, index=[4])) @@ -1231,7 +1230,7 @@ def test_validation(self): merge(left, right, on="a", validate="1:1") result = merge(left, right, on=["a", "b"], validate="1:1") - assert_frame_equal(result, expected_multi) + tm.assert_frame_equal(result, expected_multi) def test_merge_two_empty_df_no_division_error(self): # GH17776, PR #17846 @@ -1293,7 +1292,7 @@ def test_merge_on_index_with_more_values(self, how, index, expected_index): columns=["a", "key", "b"], ) expected.set_index(expected_index, inplace=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_merge_right_index_right(self): # Note: the expected output here is probably incorrect. @@ -1354,7 +1353,7 @@ def _check_merge(x, y): expected = expected.set_index("index") # TODO check_names on merge? - assert_frame_equal(result, expected, check_names=False) + tm.assert_frame_equal(result, expected, check_names=False) class TestMergeDtypes: @@ -1432,10 +1431,10 @@ def test_merge_on_ints_floats(self, int_vals, float_vals, exp_vals): expected = DataFrame(exp_vals) result = A.merge(B, left_on="X", right_on="Y") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = B.merge(A, left_on="Y", right_on="X") - assert_frame_equal(result, expected[["Y", "X"]]) + tm.assert_frame_equal(result, expected[["Y", "X"]]) def test_merge_key_dtype_cast(self): # GH 17044 @@ -1459,18 +1458,18 @@ def test_merge_on_ints_floats_warning(self): with tm.assert_produces_warning(UserWarning): result = A.merge(B, left_on="X", right_on="Y") - assert_frame_equal(result, expected) + tm.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"]]) + tm.assert_frame_equal(result, expected[["Y", "X"]]) # test no warning if float has NaNs B = DataFrame({"Y": [np.nan, np.nan, 3.0]}) with tm.assert_produces_warning(None): result = B.merge(A, left_on="Y", right_on="X") - assert_frame_equal(result, expected[["Y", "X"]]) + tm.assert_frame_equal(result, expected[["Y", "X"]]) def test_merge_incompat_infer_boolean_object(self): # GH21119: bool + object bool merge OK @@ -1479,9 +1478,9 @@ def test_merge_incompat_infer_boolean_object(self): expected = DataFrame({"key": [True, False]}, dtype=object) result = pd.merge(df1, df2, on="key") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = pd.merge(df2, df1, on="key") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # with missing value df1 = DataFrame({"key": Series([True, False, np.nan], dtype=object)}) @@ -1489,9 +1488,9 @@ def test_merge_incompat_infer_boolean_object(self): expected = DataFrame({"key": [True, False]}, dtype=object) result = pd.merge(df1, df2, on="key") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = pd.merge(df2, df1, on="key") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "df1_vals, df2_vals", @@ -1600,7 +1599,7 @@ def test_identical(self, left): [CategoricalDtype(), np.dtype("O"), np.dtype("O")], index=["X", "Y_x", "Y_y"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_basic(self, left, right): # we have matching Categorical dtypes in X @@ -1611,7 +1610,7 @@ def test_basic(self, left, right): [CategoricalDtype(), np.dtype("O"), np.dtype("int64")], index=["X", "Y", "Z"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_merge_categorical(self): # GH 9426 @@ -1679,7 +1678,7 @@ def tests_merge_categorical_unordered_equal(self): "Right": ["A1", "B1", "C1"], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_other_columns(self, left, right): # non-merge columns should preserve if possible @@ -1691,7 +1690,7 @@ def test_other_columns(self, left, right): [CategoricalDtype(), np.dtype("O"), CategoricalDtype()], index=["X", "Y", "Z"], ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # categories are preserved assert left.X.values.is_dtype_equal(merged.X.values) @@ -1720,7 +1719,7 @@ def test_dtype_on_merged_different(self, change, join_type, left, right): expected = Series( [np.dtype("O"), np.dtype("O"), np.dtype("int64")], index=["X", "Y", "Z"] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_self_join_multiple_categories(self): # GH 16767 @@ -1760,7 +1759,7 @@ def test_self_join_multiple_categories(self): # self-join should equal ourselves result = pd.merge(df, df, on=list(df.columns)) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_dtype_on_categorical_dates(self): # GH 16900 @@ -1785,13 +1784,13 @@ def test_dtype_on_categorical_dates(self): columns=["date", "num2", "num4"], ) result_outer = pd.merge(df, df2, how="outer", on=["date"]) - assert_frame_equal(result_outer, expected_outer) + tm.assert_frame_equal(result_outer, expected_outer) expected_inner = pd.DataFrame( [[pd.Timestamp("2001-01-01"), 1.1, 1.3]], columns=["date", "num2", "num4"] ) result_inner = pd.merge(df, df2, how="inner", on=["date"]) - assert_frame_equal(result_inner, expected_inner) + tm.assert_frame_equal(result_inner, expected_inner) @pytest.mark.parametrize("ordered", [True, False]) @pytest.mark.parametrize( @@ -1815,7 +1814,7 @@ def test_merging_with_bool_or_int_cateorical_column( {"id": [2, 4], "cat": expected_categories, "num": [1, 9]} ) expected["cat"] = expected["cat"].astype(CDT(categories, ordered=ordered)) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) def test_merge_on_int_array(self): # GH 23020 @@ -1824,7 +1823,7 @@ def test_merge_on_int_array(self): expected = pd.DataFrame( {"A": pd.Series([1, 2, np.nan], dtype="Int64"), "B_x": 1, "B_y": 1} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.fixture @@ -1915,7 +1914,7 @@ def test_merge_index_types(index): expected = DataFrame( OrderedDict([("left_data", [1, 2]), ("right_data", [1.0, 2.0])]), index=index ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( @@ -2111,7 +2110,7 @@ def test_merge_on_cat_and_ext_array(): result = pd.merge(left, right, how="inner", on="a") expected = right.copy() - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_merge_multiindex_columns(): diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index 2e9ae80323159..e12aad870f1c1 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -7,7 +7,7 @@ import pandas as pd from pandas import Timedelta, merge_asof, read_csv, to_datetime from pandas.core.reshape.merge import MergeError -from pandas.util.testing import assert_frame_equal +import pandas.util.testing as tm class TestAsOfMerge: @@ -44,7 +44,7 @@ def test_examples1(self): ) result = pd.merge_asof(left, right, on="a") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_examples2(self): """ doc-string examples """ @@ -131,7 +131,7 @@ def test_examples2(self): tolerance=pd.Timedelta("10ms"), allow_exact_matches=False, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_examples3(self): """ doc-string examples """ @@ -145,7 +145,7 @@ def test_examples3(self): ) result = pd.merge_asof(left, right, on="a", direction="forward") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_examples4(self): """ doc-string examples """ @@ -159,7 +159,7 @@ def test_examples4(self): ) result = pd.merge_asof(left, right, on="a", direction="nearest") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic(self): @@ -168,7 +168,7 @@ def test_basic(self): quotes = self.quotes result = merge_asof(trades, quotes, on="time", by="ticker") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_categorical(self): @@ -180,7 +180,7 @@ def test_basic_categorical(self): expected.ticker = expected.ticker.astype("category") result = merge_asof(trades, quotes, on="time", by="ticker") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_left_index(self): @@ -196,7 +196,7 @@ def test_basic_left_index(self): expected.index = result.index # time column appears after left"s columns expected = expected[result.columns] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_right_index(self): @@ -207,7 +207,7 @@ def test_basic_right_index(self): result = merge_asof( trades, quotes, left_on="time", right_index=True, by="ticker" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_left_index_right_index(self): @@ -218,7 +218,7 @@ def test_basic_left_index_right_index(self): result = merge_asof( trades, quotes, left_index=True, right_index=True, by="ticker" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_multi_index(self): @@ -260,7 +260,7 @@ def test_basic_left_by_right_by(self): result = merge_asof( trades, quotes, on="time", left_by="ticker", right_by="ticker" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_missing_right_by(self): @@ -271,7 +271,7 @@ def test_missing_right_by(self): q = quotes[quotes.ticker != "MSFT"] result = merge_asof(trades, q, on="time", by="ticker") expected.loc[expected.ticker == "MSFT", ["bid", "ask"]] = np.nan - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_multiby(self): # GH13936 @@ -336,7 +336,7 @@ def test_multiby(self): ) result = pd.merge_asof(trades, quotes, on="time", by=["ticker", "exch"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_multiby_heterogeneous_types(self): # GH13936 @@ -401,7 +401,7 @@ def test_multiby_heterogeneous_types(self): ) result = pd.merge_asof(trades, quotes, on="time", by=["ticker", "exch"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_multiby_indexed(self): # GH15676 @@ -439,7 +439,7 @@ def test_multiby_indexed(self): left, right, left_index=True, right_index=True, by=["k1", "k2"] ) - assert_frame_equal(expected, result) + tm.assert_frame_equal(expected, result) with pytest.raises(MergeError): pd.merge_asof( @@ -458,7 +458,7 @@ def test_basic2(self, datapath): quotes = self.read_data(datapath, "quotes2.csv", dedupe=True) result = merge_asof(trades, quotes, on="time", by="ticker") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_no_by(self): f = ( @@ -473,7 +473,7 @@ def test_basic_no_by(self): quotes = f(self.quotes) result = merge_asof(trades, quotes, on="time") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_valid_join_keys(self): @@ -498,7 +498,7 @@ def test_with_duplicates(self, datapath): ) result = merge_asof(self.trades, q, on="time", by="ticker") expected = self.read_data(datapath, "asof.csv") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_with_duplicates_no_on(self): @@ -508,7 +508,7 @@ def test_with_duplicates_no_on(self): expected = pd.DataFrame( {"key": [1, 1, 3], "left_val": [1, 2, 3], "right_val": [1, 1, 3]} ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_valid_allow_exact_matches(self): @@ -602,7 +602,7 @@ def test_tolerance(self, tolerance): result = merge_asof(trades, quotes, on="time", by="ticker", tolerance=tolerance) expected = self.tolerance - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_tolerance_forward(self): # GH14887 @@ -615,7 +615,7 @@ def test_tolerance_forward(self): ) result = pd.merge_asof(left, right, on="a", direction="forward", tolerance=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_tolerance_nearest(self): # GH14887 @@ -628,7 +628,7 @@ def test_tolerance_nearest(self): ) result = pd.merge_asof(left, right, on="a", direction="nearest", tolerance=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_tolerance_tz(self): # GH 14844 @@ -668,7 +668,7 @@ def test_tolerance_tz(self): "value2": list("BCDEE"), } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_tolerance_float(self): # GH22981 @@ -686,7 +686,7 @@ def test_tolerance_float(self): ) result = pd.merge_asof(left, right, on="a", direction="nearest", tolerance=0.5) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_index_tolerance(self): # GH 15135 @@ -702,7 +702,7 @@ def test_index_tolerance(self): by="ticker", tolerance=pd.Timedelta("1day"), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches(self): @@ -710,7 +710,7 @@ def test_allow_exact_matches(self): self.trades, self.quotes, on="time", by="ticker", allow_exact_matches=False ) expected = self.allow_exact_matches - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches_forward(self): # GH14887 @@ -725,7 +725,7 @@ def test_allow_exact_matches_forward(self): result = pd.merge_asof( left, right, on="a", direction="forward", allow_exact_matches=False ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches_nearest(self): # GH14887 @@ -740,7 +740,7 @@ def test_allow_exact_matches_nearest(self): result = pd.merge_asof( left, right, on="a", direction="nearest", allow_exact_matches=False ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches_and_tolerance(self): @@ -753,7 +753,7 @@ def test_allow_exact_matches_and_tolerance(self): allow_exact_matches=False, ) expected = self.allow_exact_matches_and_tolerance - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches_and_tolerance2(self): # GH 13695 @@ -777,7 +777,7 @@ def test_allow_exact_matches_and_tolerance2(self): "version": [2], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = pd.merge_asof(df1, df2, on="time", allow_exact_matches=False) expected = pd.DataFrame( @@ -787,7 +787,7 @@ def test_allow_exact_matches_and_tolerance2(self): "version": [1], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = pd.merge_asof( df1, @@ -803,7 +803,7 @@ def test_allow_exact_matches_and_tolerance2(self): "version": [np.nan], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches_and_tolerance3(self): # GH 13709 @@ -840,7 +840,7 @@ def test_allow_exact_matches_and_tolerance3(self): "version": [np.nan, np.nan], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches_and_tolerance_forward(self): # GH14887 @@ -860,7 +860,7 @@ def test_allow_exact_matches_and_tolerance_forward(self): allow_exact_matches=False, tolerance=1, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_allow_exact_matches_and_tolerance_nearest(self): # GH14887 @@ -880,7 +880,7 @@ def test_allow_exact_matches_and_tolerance_nearest(self): allow_exact_matches=False, tolerance=1, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_forward_by(self): # GH14887 @@ -910,7 +910,7 @@ def test_forward_by(self): ) result = pd.merge_asof(left, right, on="a", by="b", direction="forward") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_nearest_by(self): # GH14887 @@ -940,7 +940,7 @@ def test_nearest_by(self): ) result = pd.merge_asof(left, right, on="a", by="b", direction="nearest") - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_by_int(self): # we specialize by type, so test that this is correct @@ -1001,7 +1001,7 @@ def test_by_int(self): columns=["time", "key", "value1", "value2"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_on_float(self): # mimics how to determine the minimum-price variation @@ -1031,7 +1031,7 @@ def test_on_float(self): columns=["symbol", "price", "mpv"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_on_specialized_type(self, any_real_dtype): # see gh-13936 @@ -1062,7 +1062,7 @@ def test_on_specialized_type(self, any_real_dtype): ) expected.value = dtype(expected.value) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_on_specialized_type_by_int(self, any_real_dtype): # see gh-13936 @@ -1098,7 +1098,7 @@ def test_on_specialized_type_by_int(self, any_real_dtype): ) expected.value = dtype(expected.value) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_on_float_by_int(self): # type specialize both "by" and "on" parameters @@ -1155,7 +1155,7 @@ def test_on_float_by_int(self): columns=["symbol", "exch", "price", "mpv"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_merge_datatype_error_raises(self): msg = r"incompatible merge keys \[0\] .*, must be the same type" @@ -1224,7 +1224,7 @@ def test_merge_by_col_tz_aware(self): [[pd.Timestamp("2018-01-01", tz="UTC"), 2, "a", "b"]], columns=["by_col", "on_col", "values_x", "values_y"], ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_by_mixed_tz_aware(self): # GH 26649 @@ -1250,7 +1250,7 @@ def test_by_mixed_tz_aware(self): columns=["by_col1", "by_col2", "on_col", "value_x"], ) expected["value_y"] = np.array([np.nan], dtype=object) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_timedelta_tolerance_nearest(self): # GH 27642 @@ -1286,7 +1286,7 @@ def test_timedelta_tolerance_nearest(self): left, right, on="time", tolerance=Timedelta("1ms"), direction="nearest" ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_int_type_tolerance(self, any_int_dtype): # GH #28870 @@ -1302,4 +1302,4 @@ def test_int_type_tolerance(self, any_int_dtype): expected["a"] = expected["a"].astype(any_int_dtype) result = pd.merge_asof(left, right, on="a", tolerance=10) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/merge/test_merge_index_as_string.py b/pandas/tests/reshape/merge/test_merge_index_as_string.py index 5e3bf03a0a4ec..4e0f570567c07 100644 --- a/pandas/tests/reshape/merge/test_merge_index_as_string.py +++ b/pandas/tests/reshape/merge/test_merge_index_as_string.py @@ -2,7 +2,7 @@ import pytest from pandas import DataFrame -from pandas.util.testing import assert_frame_equal +import pandas.util.testing as tm @pytest.fixture @@ -136,7 +136,7 @@ def test_merge_indexes_and_columns_on(left_df, right_df, on, how): # Perform merge result = left_df.merge(right_df, on=on, how=how) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) @pytest.mark.parametrize( @@ -159,7 +159,7 @@ def test_merge_indexes_and_columns_lefton_righton( # Perform merge result = left_df.merge(right_df, left_on=left_on, right_on=right_on, how=how) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) @pytest.mark.parametrize("left_index", ["inner", ["inner", "outer"]]) @@ -185,4 +185,4 @@ def test_join_indexes_and_columns_on(df1, df2, left_index, join_type): right_df, on=["outer", "inner"], how=join_type, lsuffix="_x", rsuffix="_y" ) - assert_frame_equal(result, expected, check_like=True) + tm.assert_frame_equal(result, expected, check_like=True) diff --git a/pandas/tests/reshape/merge/test_merge_ordered.py b/pandas/tests/reshape/merge/test_merge_ordered.py index a9f23313a83b9..6d6429fb4e6b5 100644 --- a/pandas/tests/reshape/merge/test_merge_ordered.py +++ b/pandas/tests/reshape/merge/test_merge_ordered.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import DataFrame, merge_ordered -from pandas.util.testing import assert_frame_equal +import pandas.util.testing as tm class TestMergeOrdered: @@ -22,7 +22,7 @@ def test_basic(self): } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_ffill(self): result = merge_ordered(self.left, self.right, on="key", fill_method="ffill") @@ -33,7 +33,7 @@ def test_ffill(self): "rvalue": [np.nan, 1, 2, 3, 3, 4], } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_multigroup(self): left = pd.concat([self.left, self.left], ignore_index=True) @@ -52,12 +52,12 @@ def test_multigroup(self): ) expected["group"] = ["a"] * 6 + ["b"] * 6 - assert_frame_equal(result, expected.loc[:, result.columns]) + tm.assert_frame_equal(result, expected.loc[:, result.columns]) result2 = merge_ordered( self.right, left, on="key", right_by="group", fill_method="ffill" ) - assert_frame_equal(result, result2.loc[:, result.columns]) + tm.assert_frame_equal(result, result2.loc[:, result.columns]) result = merge_ordered(left, self.right, on="key", left_by="group") assert result["group"].notna().all() @@ -114,4 +114,4 @@ def test_doc_example(self): } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index eda7bc0ec4df7..5c930e01c735d 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -29,8 +29,7 @@ ) import pandas.core.common as com from pandas.tests.extension.decimal import to_decimal -from pandas.util import testing as tm -from pandas.util.testing import assert_frame_equal, makeCustomDataframe as mkdf +import pandas.util.testing as tm @pytest.fixture(params=[True, False]) @@ -860,7 +859,7 @@ def test_append_length0_frame(self, sort): df5 = df.append(df3, sort=sort) expected = DataFrame(index=[0, 1], columns=["A", "B", "C"]) - assert_frame_equal(df5, expected) + tm.assert_frame_equal(df5, expected) def test_append_records(self): arr1 = np.zeros((2,), dtype=("i4,f4,a10")) @@ -874,7 +873,7 @@ def test_append_records(self): result = df1.append(df2, ignore_index=True) expected = DataFrame(np.concatenate((arr1, arr2))) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # rewrite sort fixture, since we also want to test default of None def test_append_sorts(self, sort_with_none): @@ -981,7 +980,7 @@ def test_append_same_columns_type(self, index): expected = pd.DataFrame( [[1.0, 2.0, 3.0], [4, 5, 6], [7, 8, np.nan]], index=[0, 1, 2], columns=index ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # ser wider than df ser_index = index @@ -994,7 +993,7 @@ def test_append_same_columns_type(self, index): index=[0, 1, 2], columns=ser_index, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "df_columns, series_index", @@ -1021,7 +1020,7 @@ def test_append_different_columns_types(self, df_columns, series_index): index=[0, 1, 2], columns=combined_columns, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "index_can_append", indexes_can_append, ids=lambda x: x.__class__.__name__ @@ -1109,7 +1108,7 @@ def test_append_dtype_coerce(self, sort): else: expected = expected[["start_time", "end_time"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_append_missing_column_proper_upcast(self, sort): df1 = DataFrame({"A": np.array([1, 2, 3, 4], dtype="i8")}) @@ -1138,7 +1137,7 @@ def test_append_empty_frame_to_series_with_dateutil_tz(self): # These columns get cast to object after append expected["a"] = expected["a"].astype(float) expected["b"] = expected["b"].astype(float) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) class TestConcatenate: @@ -1364,7 +1363,7 @@ def test_concat_multiindex_with_none_in_index_names(self): expected = pd.DataFrame( {"col": list(range(5)) * 2}, index=index, dtype=np.int32 ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = concat([df, df[:2]], keys=[1, 2], names=["level2"]) level2 = [1] * 5 + [2] * 2 @@ -1373,7 +1372,7 @@ def test_concat_multiindex_with_none_in_index_names(self): tuples = list(zip(level2, level1, no_name)) index = pd.MultiIndex.from_tuples(tuples, names=["level2", "level1", None]) expected = pd.DataFrame({"col": no_name}, index=index, dtype=np.int32) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_keys_and_levels(self): df = DataFrame(np.random.randn(1, 3)) @@ -1494,12 +1493,12 @@ def test_dups_index(self): ) result = concat([df, df], axis=1) - assert_frame_equal(result.iloc[:, :4], df) - assert_frame_equal(result.iloc[:, 4:], df) + tm.assert_frame_equal(result.iloc[:, :4], df) + tm.assert_frame_equal(result.iloc[:, 4:], df) result = concat([df, df], axis=0) - assert_frame_equal(result.iloc[:10], df) - assert_frame_equal(result.iloc[10:], df) + tm.assert_frame_equal(result.iloc[:10], df) + tm.assert_frame_equal(result.iloc[10:], df) # multi dtypes df = concat( @@ -1513,23 +1512,23 @@ def test_dups_index(self): ) result = concat([df, df], axis=1) - assert_frame_equal(result.iloc[:, :6], df) - assert_frame_equal(result.iloc[:, 6:], df) + tm.assert_frame_equal(result.iloc[:, :6], df) + tm.assert_frame_equal(result.iloc[:, 6:], df) result = concat([df, df], axis=0) - assert_frame_equal(result.iloc[:10], df) - assert_frame_equal(result.iloc[10:], df) + tm.assert_frame_equal(result.iloc[:10], df) + tm.assert_frame_equal(result.iloc[10:], df) # append result = df.iloc[0:8, :].append(df.iloc[8:]) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.iloc[0:8, :].append(df.iloc[8:9]).append(df.iloc[9:10]) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) expected = concat([df, df], axis=0) result = df.append(df) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_with_mixed_tuples(self, sort): # 10697 @@ -1563,14 +1562,14 @@ def test_handle_empty_objects(self, sort): ) empty = DataFrame() result = concat([df, empty], axis=1) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = concat([empty, df], axis=1) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = concat([df, empty]) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = concat([empty, df]) - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) def test_concat_mixed_objs(self): @@ -1588,25 +1587,25 @@ def test_concat_mixed_objs(self): np.repeat(arr, 2).reshape(-1, 2), index=index, columns=[0, 0] ) result = concat([df, df], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( np.repeat(arr, 2).reshape(-1, 2), index=index, columns=[0, 1] ) result = concat([s1, s2], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( np.repeat(arr, 3).reshape(-1, 3), index=index, columns=[0, 1, 2] ) result = concat([s1, s2, s1], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame( np.repeat(arr, 5).reshape(-1, 5), index=index, columns=[0, 0, 1, 2, 3] ) result = concat([s1, df, s2, s2, s1], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # with names s1.name = "foo" @@ -1614,32 +1613,32 @@ def test_concat_mixed_objs(self): np.repeat(arr, 3).reshape(-1, 3), index=index, columns=["foo", 0, 0] ) result = concat([s1, df, s2], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) s2.name = "bar" expected = DataFrame( np.repeat(arr, 3).reshape(-1, 3), index=index, columns=["foo", 0, "bar"] ) result = concat([s1, df, s2], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # ignore index expected = DataFrame( np.repeat(arr, 3).reshape(-1, 3), index=index, columns=[0, 1, 2] ) result = concat([s1, df, s2], axis=1, ignore_index=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # axis 0 expected = DataFrame( np.tile(arr, 3).reshape(-1, 1), index=index.tolist() * 3, columns=[0] ) result = concat([s1, df, s2]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame(np.tile(arr, 3).reshape(-1, 1), columns=[0]) result = concat([s1, df, s2], ignore_index=True) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_empty_dtype_coerce(self): @@ -1705,11 +1704,11 @@ def test_concat_series_axis1(self, sort=sort): result = concat(pieces, axis=1) expected = DataFrame(pieces).T - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = concat(pieces, keys=["A", "B", "C"], axis=1) expected = DataFrame(pieces, index=["A", "B", "C"]).T - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # preserve series names, #2489 s = Series(randn(5), name="A") @@ -1717,7 +1716,7 @@ def test_concat_series_axis1(self, sort=sort): result = concat([s, s2], axis=1) expected = DataFrame({"A": s, "B": s2}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) s2.name = None result = concat([s, s2], axis=1) @@ -1728,7 +1727,7 @@ def test_concat_series_axis1(self, sort=sort): s2 = Series(randn(4), index=["d", "a", "b", "c"], name="B") result = concat([s, s2], axis=1, sort=sort) expected = DataFrame({"A": s, "B": s2}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_series_axis1_names_applied(self): # ensure names argument is not ignored on axis=1, #23490 @@ -1738,14 +1737,14 @@ def test_concat_series_axis1_names_applied(self): expected = DataFrame( [[1, 4], [2, 5], [3, 6]], columns=pd.Index(["a", "b"], name="A") ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = concat([s, s2], axis=1, keys=[("a", 1), ("b", 2)], names=["A", "B"]) expected = DataFrame( [[1, 4], [2, 5], [3, 6]], columns=MultiIndex.from_tuples([("a", 1), ("b", 2)], names=["A", "B"]), ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_single_with_key(self): df = DataFrame(np.random.randn(10, 4)) @@ -1818,7 +1817,7 @@ def test_concat_bug_2972(self): expected = DataFrame({0: ts0, 1: ts1}) expected.columns = ["same name", "same name"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_bug_3602(self): @@ -1844,7 +1843,7 @@ def test_concat_bug_3602(self): expected.columns = ["firmNo", "prc", "stringvar", "C", "misc", "prc"] result = concat([df1, df2], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_inner_join_empty(self): # GH 15328 @@ -1854,7 +1853,7 @@ def test_concat_inner_join_empty(self): for how, expected in [("inner", df_expected), ("outer", df_a)]: result = pd.concat([df_a, df_empty], axis=1, join=how) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_series_axis1_same_names_ignore_index(self): dates = date_range("01-Jan-2013", "01-Jan-2014", freq="MS")[0:-1] @@ -1872,12 +1871,12 @@ def test_concat_iterables(self): df1 = DataFrame([1, 2, 3]) df2 = DataFrame([4, 5, 6]) expected = DataFrame([1, 2, 3, 4, 5, 6]) - assert_frame_equal(concat((df1, df2), ignore_index=True), expected) - assert_frame_equal(concat([df1, df2], ignore_index=True), expected) - assert_frame_equal( + tm.assert_frame_equal(concat((df1, df2), ignore_index=True), expected) + tm.assert_frame_equal(concat([df1, df2], ignore_index=True), expected) + tm.assert_frame_equal( concat((df for df in (df1, df2)), ignore_index=True), expected ) - assert_frame_equal(concat(deque((df1, df2)), ignore_index=True), expected) + tm.assert_frame_equal(concat(deque((df1, df2)), ignore_index=True), expected) class CustomIterator1: def __len__(self): @@ -1889,19 +1888,19 @@ def __getitem__(self, index): except KeyError: raise IndexError - assert_frame_equal(pd.concat(CustomIterator1(), ignore_index=True), expected) + tm.assert_frame_equal(pd.concat(CustomIterator1(), ignore_index=True), expected) class CustomIterator2(abc.Iterable): def __iter__(self): yield df1 yield df2 - assert_frame_equal(pd.concat(CustomIterator2(), ignore_index=True), expected) + tm.assert_frame_equal(pd.concat(CustomIterator2(), ignore_index=True), expected) def test_concat_invalid(self): # trying to concat a ndframe with a non-ndframe - df1 = mkdf(10, 2) + df1 = tm.makeCustomDataframe(10, 2) msg = ( "cannot concatenate object of type '{}';" " only Series and DataFrame objs are valid" @@ -1911,8 +1910,8 @@ def test_concat_invalid(self): concat([df1, obj]) def test_concat_invalid_first_argument(self): - df1 = mkdf(10, 2) - df2 = mkdf(10, 2) + df1 = tm.makeCustomDataframe(10, 2) + df2 = tm.makeCustomDataframe(10, 2) msg = ( "first argument must be an iterable of pandas " 'objects, you passed an object of type "DataFrame"' @@ -1937,7 +1936,7 @@ def test_concat_invalid_first_argument(self): reader = read_csv(StringIO(data), chunksize=1) result = concat(reader, ignore_index=True) expected = read_csv(StringIO(data)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_NaT_series(self): # GH 11693 @@ -1981,7 +1980,7 @@ def test_concat_tz_frame(self): # concat df3 = pd.concat([df2.A.to_frame(), df2.B.to_frame()], axis=1) - assert_frame_equal(df2, df3) + tm.assert_frame_equal(df2, df3) def test_concat_tz_series(self): # gh-11755: tz and no tz @@ -2087,7 +2086,7 @@ def test_concat_NaT_dataframes_all_NaT_axis_0(self, tz1, tz2, s): if tz1 != tz2: expected = expected.astype(object) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("tz1", [None, "UTC"]) @pytest.mark.parametrize("tz2", [None, "UTC"]) @@ -2103,7 +2102,7 @@ def test_concat_NaT_dataframes_all_NaT_axis_1(self, tz1, tz2): } ) result = pd.concat([first, second], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("tz1", [None, "UTC"]) @pytest.mark.parametrize("tz2", [None, "UTC"]) @@ -2132,7 +2131,7 @@ def test_concat_NaT_series_dataframe_all_NaT(self, tz1, tz2): expected = expected.astype(object) result = pd.concat([first, second]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("tz", [None, "UTC"]) def test_concat_NaT_dataframes(self, tz): @@ -2154,7 +2153,7 @@ def test_concat_NaT_dataframes(self, tz): ) result = pd.concat([first, second], axis=0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_period_series(self): x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) @@ -2237,7 +2236,7 @@ def test_concat_empty_series_timelike(self, tz, values): } ) result = concat([first, second], axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_default_index(self): # is_series and ignore_index @@ -2619,7 +2618,7 @@ def test_concat_empty_and_non_empty_frame_regression(): df2 = pd.DataFrame({"foo": []}) expected = pd.DataFrame({"foo": [1.0]}) result = pd.concat([df1, df2]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_concat_empty_and_non_empty_series_regression(): diff --git a/pandas/tests/reshape/test_reshape.py b/pandas/tests/reshape/test_reshape.py index 66a24fa57a68c..2e94eeba1d05b 100644 --- a/pandas/tests/reshape/test_reshape.py +++ b/pandas/tests/reshape/test_reshape.py @@ -9,7 +9,6 @@ from pandas import Categorical, DataFrame, Index, Series, get_dummies from pandas.core.arrays.sparse import SparseArray, SparseDtype import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal class TestGetDummies: @@ -48,14 +47,14 @@ def test_basic(self, sparse, dtype): if sparse: expected = expected.apply(pd.SparseArray, fill_value=0.0) result = get_dummies(s_list, sparse=sparse, dtype=dtype) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = get_dummies(s_series, sparse=sparse, dtype=dtype) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected.index = list("ABC") result = get_dummies(s_series_index, sparse=sparse, dtype=dtype) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_types(self, sparse, dtype): # GH 10531 @@ -134,7 +133,7 @@ def test_include_na(self, sparse, dtype): ) if sparse: exp = exp.apply(pd.SparseArray, fill_value=0.0) - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) # Sparse dataframes do not allow nan labelled columns, see #GH8822 res_na = get_dummies(s, dummy_na=True, sparse=sparse, dtype=dtype) @@ -147,7 +146,7 @@ def test_include_na(self, sparse, dtype): exp_na.columns = res_na.columns if sparse: exp_na = exp_na.apply(pd.SparseArray, fill_value=0.0) - assert_frame_equal(res_na, exp_na) + tm.assert_frame_equal(res_na, exp_na) res_just_na = get_dummies([np.nan], dummy_na=True, sparse=sparse, dtype=dtype) exp_just_na = DataFrame( @@ -169,7 +168,7 @@ def test_unicode(self, sparse): ) if sparse: exp = exp.apply(pd.SparseArray, fill_value=0) - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) def test_dataframe_dummies_all_obj(self, df, sparse): df = df[["A", "B"]] @@ -188,7 +187,7 @@ def test_dataframe_dummies_all_obj(self, df, sparse): } ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_mix_default(self, df, sparse, dtype): result = get_dummies(df, sparse=sparse, dtype=dtype) @@ -208,7 +207,7 @@ def test_dataframe_dummies_mix_default(self, df, sparse, dtype): } ) expected = expected[["C", "A_a", "A_b", "B_b", "B_c"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_prefix_list(self, df, sparse): prefixes = ["from_A", "from_B"] @@ -229,7 +228,7 @@ def test_dataframe_dummies_prefix_list(self, df, sparse): typ = pd.SparseArray if sparse else pd.Series expected[cols] = expected[cols].apply(lambda x: typ(x)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_prefix_str(self, df, sparse): # not that you should do this... @@ -255,7 +254,7 @@ def test_dataframe_dummies_prefix_str(self, df, sparse): axis=1, ) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_subset(self, df, sparse): result = get_dummies(df, prefix=["from_A"], columns=["A"], sparse=sparse) @@ -272,7 +271,7 @@ def test_dataframe_dummies_subset(self, df, sparse): if sparse: cols = ["from_A_a", "from_A_b"] expected[cols] = expected[cols].astype(pd.SparseDtype("uint8", 0)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_prefix_sep(self, df, sparse): result = get_dummies(df, prefix_sep="..", sparse=sparse) @@ -292,14 +291,14 @@ def test_dataframe_dummies_prefix_sep(self, df, sparse): cols = ["A..a", "A..b", "B..b", "B..c"] expected[cols] = expected[cols].astype(pd.SparseDtype("uint8", 0)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) 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) + tm.assert_frame_equal(result, expected) result = get_dummies(df, prefix_sep={"A": "..", "B": "__"}, sparse=sparse) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_prefix_bad_length(self, df, sparse): with pytest.raises(ValueError): @@ -329,7 +328,7 @@ def test_dataframe_dummies_prefix_dict(self, sparse): if sparse: expected[columns] = expected[columns].astype(pd.SparseDtype("uint8", 0)) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_with_na(self, df, sparse, dtype): df.loc[3, :] = [np.nan, np.nan, np.nan] @@ -356,11 +355,11 @@ def test_dataframe_dummies_with_na(self, df, sparse, dtype): } ).sort_index(axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) 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) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_with_categorical(self, df, sparse, dtype): df["cat"] = pd.Categorical(["x", "y", "y"]) @@ -384,7 +383,7 @@ def test_dataframe_dummies_with_categorical(self, df, sparse, dtype): } ).sort_index(axis=1) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "get_dummies_kwargs,expected", @@ -411,7 +410,7 @@ def test_dataframe_dummies_unicode(self, get_dummies_kwargs, expected): # GH22084 pd.get_dummies incorrectly encodes unicode characters # in dataframe column names result = get_dummies(**get_dummies_kwargs) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_drop_first(self, sparse): # GH12402 Add a new parameter `drop_first` to avoid collinearity @@ -425,14 +424,14 @@ def test_basic_drop_first(self, sparse): result = get_dummies(s_list, drop_first=True, sparse=sparse) if sparse: expected = expected.apply(pd.SparseArray, fill_value=0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = get_dummies(s_series, drop_first=True, sparse=sparse) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected.index = list("ABC") result = get_dummies(s_series_index, drop_first=True, sparse=sparse) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_drop_first_one_level(self, sparse): # Test the case that categorical variable only has one level. @@ -443,14 +442,14 @@ def test_basic_drop_first_one_level(self, sparse): expected = DataFrame(index=np.arange(3)) result = get_dummies(s_list, drop_first=True, sparse=sparse) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = get_dummies(s_series, drop_first=True, sparse=sparse) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) expected = DataFrame(index=list("ABC")) result = get_dummies(s_series_index, drop_first=True, sparse=sparse) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_basic_drop_first_NA(self, sparse): # Test NA handling together with drop_first @@ -460,7 +459,7 @@ def test_basic_drop_first_NA(self, sparse): if sparse: exp = exp.apply(pd.SparseArray, fill_value=0) - assert_frame_equal(res, exp) + tm.assert_frame_equal(res, exp) res_na = get_dummies(s_NA, dummy_na=True, drop_first=True, sparse=sparse) exp_na = DataFrame({"b": [0, 1, 0], np.nan: [0, 0, 1]}, dtype=np.uint8).reindex( @@ -468,13 +467,13 @@ def test_basic_drop_first_NA(self, sparse): ) if sparse: exp_na = exp_na.apply(pd.SparseArray, fill_value=0) - assert_frame_equal(res_na, exp_na) + tm.assert_frame_equal(res_na, exp_na) res_just_na = get_dummies( [np.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) + tm.assert_frame_equal(res_just_na, exp_just_na) def test_dataframe_dummies_drop_first(self, df, sparse): df = df[["A", "B"]] @@ -482,7 +481,7 @@ def test_dataframe_dummies_drop_first(self, df, sparse): expected = DataFrame({"A_b": [0, 1, 0], "B_c": [0, 0, 1]}, dtype=np.uint8) if sparse: expected = expected.apply(pd.SparseArray, fill_value=0) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_drop_first_with_categorical(self, df, sparse, dtype): df["cat"] = pd.Categorical(["x", "y", "y"]) @@ -496,7 +495,7 @@ def test_dataframe_dummies_drop_first_with_categorical(self, df, sparse, dtype): if sparse: for col in cols: expected[col] = pd.SparseArray(expected[col]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_dataframe_dummies_drop_first_with_na(self, df, sparse): df.loc[3, :] = [np.nan, np.nan, np.nan] @@ -519,11 +518,11 @@ def test_dataframe_dummies_drop_first_with_na(self, df, sparse): for col in cols: expected[col] = pd.SparseArray(expected[col]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = get_dummies(df, dummy_na=False, drop_first=True, sparse=sparse) expected = expected[["C", "A_b", "B_c"]] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_int_int(self): data = Series([1, 2, 1])
Part of #29272 Fyi: the changes were created via a script posted in the issue - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29285
2019-10-30T13:58:01Z
2019-10-31T07:47:27Z
2019-10-31T07:47:27Z
2019-10-31T07:47:36Z
DOC: Fix SS06 formatting errors in Styler docstrings
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index abf2caf3914e0..545d6a674411a 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -574,6 +574,7 @@ def __deepcopy__(self, memo): def clear(self): """ Reset the styler, removing any previously applied styles. + Returns None. """ self.ctx.clear() @@ -632,8 +633,9 @@ def _apply(self, func, axis=0, subset=None, **kwargs): def apply(self, func, axis=0, subset=None, **kwargs): """ - Apply a function column-wise, row-wise, or table-wise, - updating the HTML representation with the result. + Apply a function column-wise, row-wise, or table-wise. + + Updates the HTML representation with the result. Parameters ---------- @@ -691,8 +693,9 @@ def _applymap(self, func, subset=None, **kwargs): def applymap(self, func, subset=None, **kwargs): """ - Apply a function elementwise, updating the HTML - representation with the result. + Apply a function elementwise. + + Updates the HTML representation with the result. Parameters ---------- @@ -719,9 +722,10 @@ def applymap(self, func, subset=None, **kwargs): def where(self, cond, value, other=None, subset=None, **kwargs): """ - Apply a function elementwise, updating the HTML - representation with a style which is selected in - accordance with the return value of a function. + Apply a function elementwise. + + Updates the HTML representation with a style which is + selected in accordance with the return value of a function. .. versionadded:: 0.21.0 @@ -812,8 +816,9 @@ def export(self): def use(self, styles): """ - Set the styles on the current Styler, possibly using styles - from ``Styler.export``. + Set the styles on the current Styler. + + Possibly uses styles from ``Styler.export``. Parameters ---------- @@ -960,10 +965,10 @@ def background_gradient( text_color_threshold=0.408, ): """ - Color the background in a gradient according to - the data in each column (optionally row). + Color the background in a gradient style. - Requires matplotlib. + The background color is determined according + to the data in each column (optionally row). Requires matplotlib. Parameters ---------- @@ -1077,8 +1082,7 @@ def css(rgba): def set_properties(self, subset=None, **kwargs): """ - Convenience method for setting one or more non-data dependent - properties or each cell. + Method to set one or more non-data dependent properties or each cell. Parameters ---------- @@ -1318,8 +1322,9 @@ def _highlight_extrema(data, color="yellow", max_=True): @classmethod def from_custom_template(cls, searchpath, name): """ - Factory function for creating a subclass of ``Styler`` - with a custom template and Jinja environment. + Factory function for creating a subclass of ``Styler``. + + Uses a custom template and Jinja environment. Parameters ----------
Errors fixed (from the list in #29254 ): pandas.io.formats.style.Styler.from_custom_template pandas.io.formats.style.Styler.apply pandas.io.formats.style.Styler.applymap pandas.io.formats.style.Styler.set_properties pandas.io.formats.style.Styler.clear pandas.io.formats.style.Styler.background_gradient pandas.io.formats.style.Styler.use pandas.io.formats.style.Styler.where Validated the fixes with ```python scripts/validate_docstrings.py``` Refrencing issue: #29254
https://api.github.com/repos/pandas-dev/pandas/pulls/29283
2019-10-30T09:39:08Z
2019-10-31T08:03:54Z
2019-10-31T08:03:54Z
2019-10-31T10:05:03Z
Remove and from typo.
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 5e16cee1de89c..fa1669b1f3343 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -60,7 +60,7 @@ Previously, strings were typically stored in object-dtype NumPy arrays. .. warning:: - ``StringDtype`` and is currently considered experimental. The implementation + ``StringDtype`` is currently considered experimental. The implementation and parts of the API may change without warning. The text extension type solves several issues with object-dtype NumPy arrays:
- [X] closes #29274 - [ ] tests added / passed - [ ] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29281
2019-10-30T08:43:01Z
2019-10-30T11:56:52Z
2019-10-30T11:56:51Z
2019-10-30T12:43:49Z
CLN: algorithms cleanup, de-duplication, typing
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index ca36546b8937a..98a090ef26f2a 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -77,27 +77,27 @@ def _ensure_data(values, dtype=None): Returns ------- - (ndarray, pandas_dtype, algo dtype as a string) - + values : ndarray + pandas_dtype : str or dtype """ # we check some simple dtypes first if is_object_dtype(dtype): - return ensure_object(np.asarray(values)), "object", "object" + return ensure_object(np.asarray(values)), "object" elif is_object_dtype(values) and dtype is None: - return ensure_object(np.asarray(values)), "object", "object" + return ensure_object(np.asarray(values)), "object" try: if is_bool_dtype(values) or is_bool_dtype(dtype): # we are actually coercing to uint64 # until our algos support uint8 directly (see TODO) - return np.asarray(values).astype("uint64"), "bool", "uint64" + return np.asarray(values).astype("uint64"), "bool" elif is_signed_integer_dtype(values) or is_signed_integer_dtype(dtype): - return ensure_int64(values), "int64", "int64" + return ensure_int64(values), "int64" elif is_unsigned_integer_dtype(values) or is_unsigned_integer_dtype(dtype): - return ensure_uint64(values), "uint64", "uint64" + return ensure_uint64(values), "uint64" elif is_float_dtype(values) or is_float_dtype(dtype): - return ensure_float64(values), "float64", "float64" + return ensure_float64(values), "float64" elif is_complex_dtype(values) or is_complex_dtype(dtype): # ignore the fact that we are casting to float @@ -105,12 +105,12 @@ def _ensure_data(values, dtype=None): with catch_warnings(): simplefilter("ignore", np.ComplexWarning) values = ensure_float64(values) - return values, "float64", "float64" + return values, "float64" except (TypeError, ValueError, OverflowError): # if we are trying to coerce to a dtype # and it is incompat this will fall thru to here - return ensure_object(values), "object", "object" + return ensure_object(values), "object" # datetimelike if ( @@ -136,14 +136,14 @@ def _ensure_data(values, dtype=None): # Note: this is reached by DataFrame.rank calls GH#27027 asi8 = values.view("i8") dtype = values.dtype - return asi8, dtype, "int64" + return asi8, dtype from pandas import DatetimeIndex values = DatetimeIndex(values) dtype = values.dtype - return values.asi8, dtype, "int64" + return values.asi8, dtype elif is_categorical_dtype(values) and ( is_categorical_dtype(dtype) or dtype is None @@ -156,11 +156,11 @@ def _ensure_data(values, dtype=None): # until our algos support int* directly (not all do) values = ensure_int64(values) - return values, dtype, "int64" + return values, dtype # we have failed, return object values = np.asarray(values, dtype=np.object) - return ensure_object(values), "object", "object" + return ensure_object(values), "object" def _reconstruct_data(values, dtype, original): @@ -227,16 +227,9 @@ def _get_hashtable_algo(values): htable : HashTable subclass values : ndarray """ - values, _, ndtype = _ensure_data(values) - - if ndtype == "object": - - # it's cheaper to use a String Hash Table than Object; we infer - # including nulls because that is the only difference between - # StringHashTable and ObjectHashtable - if lib.infer_dtype(values, skipna=False) in ["string"]: - ndtype = "string" + values, _ = _ensure_data(values) + ndtype = _check_object_for_strings(values) htable = _hashtables[ndtype] return htable, values @@ -245,13 +238,33 @@ def _get_values_for_rank(values): if is_categorical_dtype(values): values = values._values_for_rank() - values, _, ndtype = _ensure_data(values) - return values, ndtype + values, _ = _ensure_data(values) + return values def _get_data_algo(values): - values, ndtype = _get_values_for_rank(values) + values = _get_values_for_rank(values) + + ndtype = _check_object_for_strings(values) + htable = _hashtables.get(ndtype, _hashtables["object"]) + + return htable, values + + +def _check_object_for_strings(values) -> str: + """ + Check if we can use string hashtable instead of object hashtable. + Parameters + ---------- + values : ndarray + ndtype : str + + Returns + ------- + str + """ + ndtype = values.dtype.name if ndtype == "object": # it's cheaper to use a String Hash Table than Object; we infer @@ -259,10 +272,7 @@ def _get_data_algo(values): # StringHashTable and ObjectHashtable if lib.infer_dtype(values, skipna=False) in ["string"]: ndtype = "string" - - htable = _hashtables.get(ndtype, _hashtables["object"]) - - return htable, values + return ndtype # --------------- # @@ -367,9 +377,9 @@ def unique(values): unique1d = unique -def isin(comps, values): +def isin(comps, values) -> np.ndarray: """ - Compute the isin boolean array + Compute the isin boolean array. Parameters ---------- @@ -378,7 +388,8 @@ def isin(comps, values): Returns ------- - boolean array same length as comps + ndarray[bool] + Same length as `comps`. """ if not is_list_like(comps): @@ -406,21 +417,21 @@ def isin(comps, values): comps = com.values_from_object(comps) - comps, dtype, _ = _ensure_data(comps) - values, _, _ = _ensure_data(values, dtype=dtype) + comps, dtype = _ensure_data(comps) + values, _ = _ensure_data(values, dtype=dtype) # faster for larger cases to use np.in1d - f = lambda x, y: htable.ismember_object(x, values) + f = htable.ismember_object # GH16012 # Ensure np.in1d doesn't get object types or it *may* throw an exception if len(comps) > 1000000 and not is_object_dtype(comps): - f = lambda x, y: np.in1d(x, y) + f = np.in1d elif is_integer_dtype(comps): try: values = values.astype("int64", copy=False) comps = comps.astype("int64", copy=False) - f = lambda x, y: htable.ismember_int64(x, y) + f = htable.ismember_int64 except (TypeError, ValueError, OverflowError): values = values.astype(object) comps = comps.astype(object) @@ -429,7 +440,7 @@ def isin(comps, values): try: values = values.astype("float64", copy=False) comps = comps.astype("float64", copy=False) - f = lambda x, y: htable.ismember_float64(x, y) + f = htable.ismember_float64 except (TypeError, ValueError): values = values.astype(object) comps = comps.astype(object) @@ -437,7 +448,7 @@ def isin(comps, values): return f(comps, values) -def _factorize_array(values, na_sentinel=-1, size_hint=None, na_value=None): +def _factorize_array(values, na_sentinel: int = -1, size_hint=None, na_value=None): """ Factorize an array-like to labels and uniques. @@ -598,7 +609,7 @@ def _factorize_array(values, na_sentinel=-1, size_hint=None, na_value=None): ) @Appender(_shared_docs["factorize"]) @deprecate_kwarg(old_arg_name="order", new_arg_name=None) -def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): +def factorize(values, sort: bool = False, order=None, na_sentinel=-1, size_hint=None): # Implementation notes: This method is responsible for 3 things # 1.) coercing data to array-like (ndarray, Index, extension array) # 2.) factorizing labels and uniques @@ -616,7 +627,7 @@ def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): labels, uniques = values.factorize(na_sentinel=na_sentinel) dtype = original.dtype else: - values, dtype, _ = _ensure_data(values) + values, dtype = _ensure_data(values) if original.dtype.kind in ["m", "M"]: na_value = na_value_for_dtype(original.dtype) @@ -654,7 +665,7 @@ def value_counts( normalize: bool = False, bins=None, dropna: bool = True, -): +) -> ABCSeries: """ Compute a histogram of the counts of non-null values. @@ -677,15 +688,15 @@ def value_counts( ------- Series """ - from pandas.core.series import Series, Index + from pandas.core.series import Series name = getattr(values, "name", None) if bins is not None: - try: - from pandas.core.reshape.tile import cut + from pandas.core.reshape.tile import cut - values = Series(values) + values = Series(values) + try: ii = cut(values, bins, include_lowest=True) except TypeError: raise TypeError("bins argument only works with numeric data.") @@ -715,8 +726,6 @@ def value_counts( else: keys, counts = _value_counts_arraylike(values, dropna) - if not isinstance(keys, Index): - keys = Index(keys) result = Series(counts, index=keys, name=name) if sort: @@ -728,24 +737,25 @@ def value_counts( return result -def _value_counts_arraylike(values, dropna): +def _value_counts_arraylike(values, dropna: bool): """ Parameters ---------- values : arraylike - dropna : boolean + dropna : bool Returns ------- - (uniques, counts) - + uniques : np.ndarray or ExtensionArray + counts : np.ndarray """ values = _ensure_arraylike(values) original = values - values, dtype, ndtype = _ensure_data(values) + values, _ = _ensure_data(values) + ndtype = values.dtype.name - if needs_i8_conversion(dtype): - # i8 + if needs_i8_conversion(original.dtype): + # datetime, timedelta, or period keys, counts = htable.value_count_int64(values, dropna) @@ -771,7 +781,7 @@ def _value_counts_arraylike(values, dropna): return keys, counts -def duplicated(values, keep="first"): +def duplicated(values, keep="first") -> np.ndarray: """ Return boolean ndarray denoting duplicate values. @@ -791,12 +801,13 @@ def duplicated(values, keep="first"): duplicated : ndarray """ - values, _, ndtype = _ensure_data(values) + values, _ = _ensure_data(values) + ndtype = values.dtype.name f = getattr(htable, "duplicated_{dtype}".format(dtype=ndtype)) return f(values, keep=keep) -def mode(values, dropna: bool = True): +def mode(values, dropna: bool = True) -> ABCSeries: """ Returns the mode(s) of an array. @@ -828,7 +839,8 @@ def mode(values, dropna: bool = True): mask = values.isnull() values = values[~mask] - values, _, ndtype = _ensure_data(values) + values, _ = _ensure_data(values) + ndtype = values.dtype.name f = getattr(htable, "mode_{dtype}".format(dtype=ndtype)) result = f(values, dropna=dropna) @@ -841,7 +853,14 @@ def mode(values, dropna: bool = True): return Series(result) -def rank(values, axis=0, method="average", na_option="keep", ascending=True, pct=False): +def rank( + values, + axis: int = 0, + method: str = "average", + na_option: str = "keep", + ascending: bool = True, + pct: bool = False, +): """ Rank the values along a given axis. @@ -866,7 +885,7 @@ def rank(values, axis=0, method="average", na_option="keep", ascending=True, pct (e.g. 1, 2, 3) or in percentile form (e.g. 0.333..., 0.666..., 1). """ if values.ndim == 1: - values, _ = _get_values_for_rank(values) + values = _get_values_for_rank(values) ranks = algos.rank_1d( values, ties_method=method, @@ -875,7 +894,7 @@ def rank(values, axis=0, method="average", na_option="keep", ascending=True, pct pct=pct, ) elif values.ndim == 2: - values, _ = _get_values_for_rank(values) + values = _get_values_for_rank(values) ranks = algos.rank_2d( values, axis=axis, @@ -1055,7 +1074,7 @@ def _get_score(at): class SelectN: - def __init__(self, obj, n, keep): + def __init__(self, obj, n: int, keep: str): self.obj = obj self.n = n self.keep = keep @@ -1118,7 +1137,7 @@ def compute(self, method): return dropped[slc].sort_values(ascending=ascending).head(n) # fast method - arr, pandas_dtype, _ = _ensure_data(dropped.values) + arr, pandas_dtype = _ensure_data(dropped.values) if method == "nlargest": arr = -arr if is_integer_dtype(pandas_dtype): @@ -1165,7 +1184,7 @@ class SelectNFrame(SelectN): nordered : DataFrame """ - def __init__(self, obj, n, keep, columns): + def __init__(self, obj, n: int, keep: str, columns): super().__init__(obj, n, keep) if not is_list_like(columns) or isinstance(columns, tuple): columns = [columns] @@ -1304,7 +1323,7 @@ def _take_2d_multi_object(arr, indexer, out, fill_value, mask_info): out[i, j] = arr[u_, v] -def _take_nd_object(arr, indexer, out, axis, fill_value, mask_info): +def _take_nd_object(arr, indexer, out, axis: int, fill_value, mask_info): if mask_info is not None: mask, needs_masking = mask_info else: @@ -1421,7 +1440,7 @@ def _take_nd_object(arr, indexer, out, axis, fill_value, mask_info): } -def _get_take_nd_function(ndim, arr_dtype, out_dtype, axis=0, mask_info=None): +def _get_take_nd_function(ndim, arr_dtype, out_dtype, axis: int = 0, mask_info=None): if ndim <= 2: tup = (arr_dtype.name, out_dtype.name) if ndim == 1: @@ -1446,16 +1465,16 @@ def _get_take_nd_function(ndim, arr_dtype, out_dtype, axis=0, mask_info=None): func = _convert_wrapper(func, out_dtype) return func - def func(arr, indexer, out, fill_value=np.nan): + def func2(arr, indexer, out, fill_value=np.nan): indexer = ensure_int64(indexer) _take_nd_object( arr, indexer, out, axis=axis, fill_value=fill_value, mask_info=mask_info ) - return func + return func2 -def take(arr, indices, axis=0, allow_fill=False, fill_value=None): +def take(arr, indices, axis=0, allow_fill: bool = False, fill_value=None): """ Take elements from an array. @@ -1549,7 +1568,13 @@ def take(arr, indices, axis=0, allow_fill=False, fill_value=None): def take_nd( - arr, indexer, axis=0, out=None, fill_value=np.nan, mask_info=None, allow_fill=True + arr, + indexer, + axis=0, + out=None, + fill_value=np.nan, + mask_info=None, + allow_fill: bool = True, ): """ Specialized Cython take which sets NaN values in one pass @@ -1636,9 +1661,9 @@ def take_nd( # at this point, it's guaranteed that dtype can hold both the arr values # and the fill_value if out is None: - out_shape = list(arr.shape) - out_shape[axis] = len(indexer) - out_shape = tuple(out_shape) + out_shape_ = list(arr.shape) + out_shape_[axis] = len(indexer) + out_shape = tuple(out_shape_) if arr.flags.f_contiguous and axis == arr.ndim - 1: # minor tweak that can make an order-of-magnitude difference # for dataframes initialized directly from 2-d ndarrays
https://api.github.com/repos/pandas-dev/pandas/pulls/29280
2019-10-30T03:01:36Z
2019-10-30T11:50:18Z
2019-10-30T11:50:18Z
2019-10-30T14:33:07Z
CLN: Consistent pandas.util.testing imports in pandas/tests/util
diff --git a/pandas/tests/util/test_assert_almost_equal.py b/pandas/tests/util/test_assert_almost_equal.py index 5a677d629e72d..f430e2893ca33 100644 --- a/pandas/tests/util/test_assert_almost_equal.py +++ b/pandas/tests/util/test_assert_almost_equal.py @@ -2,7 +2,7 @@ import pytest from pandas import DataFrame, Index, Series, Timestamp -from pandas.util.testing import assert_almost_equal +import pandas.util.testing as tm def _assert_almost_equal_both(a, b, **kwargs): @@ -18,10 +18,10 @@ def _assert_almost_equal_both(a, b, **kwargs): b : object The second object to compare. kwargs : dict - The arguments passed to `assert_almost_equal`. + The arguments passed to `tm.assert_almost_equal`. """ - assert_almost_equal(a, b, **kwargs) - assert_almost_equal(b, a, **kwargs) + tm.assert_almost_equal(a, b, **kwargs) + tm.assert_almost_equal(b, a, **kwargs) def _assert_not_almost_equal(a, b, **kwargs): @@ -35,10 +35,10 @@ def _assert_not_almost_equal(a, b, **kwargs): b : object The second object to compare. kwargs : dict - The arguments passed to `assert_almost_equal`. + The arguments passed to `tm.assert_almost_equal`. """ try: - assert_almost_equal(a, b, **kwargs) + tm.assert_almost_equal(a, b, **kwargs) msg = ( "{a} and {b} were approximately equal when they shouldn't have been" ).format(a=a, b=b) @@ -240,7 +240,7 @@ def test_assert_almost_equal_value_mismatch(): msg = "expected 2\\.00000 but got 1\\.00000, with decimal 5" with pytest.raises(AssertionError, match=msg): - assert_almost_equal(1, 2) + tm.assert_almost_equal(1, 2) @pytest.mark.parametrize( @@ -257,7 +257,7 @@ def test_assert_almost_equal_class_mismatch(a, b, klass1, klass2): ) with pytest.raises(AssertionError, match=msg): - assert_almost_equal(a, b) + tm.assert_almost_equal(a, b) def test_assert_almost_equal_value_mismatch1(): @@ -268,7 +268,7 @@ def test_assert_almost_equal_value_mismatch1(): \\[right\\]: \\[1\\.0, nan, 3\\.0\\]""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal(np.array([np.nan, 2, 3]), np.array([1, np.nan, 3])) + tm.assert_almost_equal(np.array([np.nan, 2, 3]), np.array([1, np.nan, 3])) def test_assert_almost_equal_value_mismatch2(): @@ -279,7 +279,7 @@ def test_assert_almost_equal_value_mismatch2(): \\[right\\]: \\[1, 3\\]""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal(np.array([1, 2]), np.array([1, 3])) + tm.assert_almost_equal(np.array([1, 2]), np.array([1, 3])) def test_assert_almost_equal_value_mismatch3(): @@ -290,7 +290,7 @@ def test_assert_almost_equal_value_mismatch3(): \\[right\\]: \\[\\[1, 3\\], \\[3, 4\\], \\[5, 6\\]\\]""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal( + tm.assert_almost_equal( np.array([[1, 2], [3, 4], [5, 6]]), np.array([[1, 3], [3, 4], [5, 6]]) ) @@ -303,7 +303,7 @@ def test_assert_almost_equal_value_mismatch4(): \\[right\\]: \\[\\[1, 3\\], \\[3, 4\\]\\]""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal(np.array([[1, 2], [3, 4]]), np.array([[1, 3], [3, 4]])) + tm.assert_almost_equal(np.array([[1, 2], [3, 4]]), np.array([[1, 3], [3, 4]])) def test_assert_almost_equal_shape_mismatch_override(): @@ -313,7 +313,7 @@ def test_assert_almost_equal_shape_mismatch_override(): \\[left\\]: \\(2L*,\\) \\[right\\]: \\(3L*,\\)""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal(np.array([1, 2]), np.array([3, 4, 5]), obj="Index") + tm.assert_almost_equal(np.array([1, 2]), np.array([3, 4, 5]), obj="Index") def test_assert_almost_equal_unicode(): @@ -325,7 +325,7 @@ def test_assert_almost_equal_unicode(): \\[right\\]: \\[á, à, å\\]""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal(np.array(["á", "à", "ä"]), np.array(["á", "à", "å"])) + tm.assert_almost_equal(np.array(["á", "à", "ä"]), np.array(["á", "à", "å"])) def test_assert_almost_equal_timestamp(): @@ -339,7 +339,7 @@ def test_assert_almost_equal_timestamp(): \\[right\\]: \\[2011-01-01 00:00:00, 2011-01-02 00:00:00\\]""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal(a, b) + tm.assert_almost_equal(a, b) def test_assert_almost_equal_iterable_length_mismatch(): @@ -350,7 +350,7 @@ def test_assert_almost_equal_iterable_length_mismatch(): \\[right\\]: 3""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal([1, 2], [3, 4, 5]) + tm.assert_almost_equal([1, 2], [3, 4, 5]) def test_assert_almost_equal_iterable_values_mismatch(): @@ -361,4 +361,4 @@ def test_assert_almost_equal_iterable_values_mismatch(): \\[right\\]: \\[1, 3\\]""" with pytest.raises(AssertionError, match=msg): - assert_almost_equal([1, 2], [1, 3]) + tm.assert_almost_equal([1, 2], [1, 3]) diff --git a/pandas/tests/util/test_assert_categorical_equal.py b/pandas/tests/util/test_assert_categorical_equal.py index d51dd8b36751a..44400498ddc64 100644 --- a/pandas/tests/util/test_assert_categorical_equal.py +++ b/pandas/tests/util/test_assert_categorical_equal.py @@ -1,7 +1,7 @@ import pytest from pandas import Categorical -from pandas.util.testing import assert_categorical_equal +import pandas.util.testing as tm @pytest.mark.parametrize( @@ -9,7 +9,7 @@ [Categorical([1, 2, 3, 4]), Categorical([1, 2, 3, 4], categories=[1, 2, 3, 4, 5])], ) def test_categorical_equal(c): - assert_categorical_equal(c, c) + tm.assert_categorical_equal(c, c) @pytest.mark.parametrize("check_category_order", [True, False]) @@ -25,9 +25,9 @@ def test_categorical_equal_order_mismatch(check_category_order): \\[left\\]: Int64Index\\(\\[1, 2, 3, 4\\], dtype='int64'\\) \\[right\\]: Int64Index\\(\\[4, 3, 2, 1\\], dtype='int64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_categorical_equal(c1, c2, **kwargs) + tm.assert_categorical_equal(c1, c2, **kwargs) else: - assert_categorical_equal(c1, c2, **kwargs) + tm.assert_categorical_equal(c1, c2, **kwargs) def test_categorical_equal_categories_mismatch(): @@ -41,7 +41,7 @@ def test_categorical_equal_categories_mismatch(): c2 = Categorical([1, 2, 3, 5]) with pytest.raises(AssertionError, match=msg): - assert_categorical_equal(c1, c2) + tm.assert_categorical_equal(c1, c2) def test_categorical_equal_codes_mismatch(): @@ -56,7 +56,7 @@ def test_categorical_equal_codes_mismatch(): c2 = Categorical([1, 2, 3, 4], categories=categories) with pytest.raises(AssertionError, match=msg): - assert_categorical_equal(c1, c2) + tm.assert_categorical_equal(c1, c2) def test_categorical_equal_ordered_mismatch(): @@ -71,7 +71,7 @@ def test_categorical_equal_ordered_mismatch(): c2 = Categorical(data, ordered=True) with pytest.raises(AssertionError, match=msg): - assert_categorical_equal(c1, c2) + tm.assert_categorical_equal(c1, c2) @pytest.mark.parametrize("obj", ["index", "foo", "pandas"]) @@ -89,4 +89,4 @@ def test_categorical_equal_object_override(obj): c2 = Categorical(data, ordered=True) with pytest.raises(AssertionError, match=msg): - assert_categorical_equal(c1, c2, obj=obj) + tm.assert_categorical_equal(c1, c2, obj=obj) diff --git a/pandas/tests/util/test_assert_extension_array_equal.py b/pandas/tests/util/test_assert_extension_array_equal.py index 43a474da2bbda..cecf9273004d7 100644 --- a/pandas/tests/util/test_assert_extension_array_equal.py +++ b/pandas/tests/util/test_assert_extension_array_equal.py @@ -2,7 +2,7 @@ import pytest from pandas.core.arrays.sparse import SparseArray -from pandas.util.testing import assert_extension_array_equal +import pandas.util.testing as tm @pytest.mark.parametrize( @@ -27,9 +27,9 @@ def test_assert_extension_array_equal_not_exact(kwargs): \\[right\\]: \\[-0\\.17387645482.*, 0\\.341414801642.*\\]""" with pytest.raises(AssertionError, match=msg): - assert_extension_array_equal(arr1, arr2, **kwargs) + tm.assert_extension_array_equal(arr1, arr2, **kwargs) else: - assert_extension_array_equal(arr1, arr2, **kwargs) + tm.assert_extension_array_equal(arr1, arr2, **kwargs) @pytest.mark.parametrize( @@ -50,9 +50,9 @@ def test_assert_extension_array_equal_less_precise(check_less_precise): \\[right\\]: \\[0\\.5, 0\\.123457\\]""" with pytest.raises(AssertionError, match=msg): - assert_extension_array_equal(arr1, arr2, **kwargs) + tm.assert_extension_array_equal(arr1, arr2, **kwargs) else: - assert_extension_array_equal(arr1, arr2, **kwargs) + tm.assert_extension_array_equal(arr1, arr2, **kwargs) def test_assert_extension_array_equal_dtype_mismatch(check_dtype): @@ -71,9 +71,9 @@ def test_assert_extension_array_equal_dtype_mismatch(check_dtype): \\[right\\]: Sparse\\[int32, 0\\]""" with pytest.raises(AssertionError, match=msg): - assert_extension_array_equal(arr1, arr2, **kwargs) + tm.assert_extension_array_equal(arr1, arr2, **kwargs) else: - assert_extension_array_equal(arr1, arr2, **kwargs) + tm.assert_extension_array_equal(arr1, arr2, **kwargs) def test_assert_extension_array_equal_missing_values(): @@ -88,7 +88,7 @@ def test_assert_extension_array_equal_missing_values(): \\[right\\]: \\[True, False, False, False\\]""" with pytest.raises(AssertionError, match=msg): - assert_extension_array_equal(arr1, arr2) + tm.assert_extension_array_equal(arr1, arr2) @pytest.mark.parametrize("side", ["left", "right"]) @@ -104,4 +104,4 @@ def test_assert_extension_array_equal_non_extension_array(side): ) with pytest.raises(AssertionError, match=msg): - assert_extension_array_equal(*args) + tm.assert_extension_array_equal(*args) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index 86e5d506e0779..b46a8460a28b2 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -1,7 +1,7 @@ import pytest from pandas import DataFrame -from pandas.util.testing import assert_frame_equal +import pandas.util.testing as tm @pytest.fixture(params=[True, False]) @@ -27,10 +27,10 @@ def _assert_frame_equal_both(a, b, **kwargs): b : DataFrame The second DataFrame to compare. kwargs : dict - The arguments passed to `assert_frame_equal`. + The arguments passed to `tm.assert_frame_equal`. """ - assert_frame_equal(a, b, **kwargs) - assert_frame_equal(b, a, **kwargs) + tm.assert_frame_equal(a, b, **kwargs) + tm.assert_frame_equal(b, a, **kwargs) def _assert_not_frame_equal(a, b, **kwargs): @@ -44,10 +44,10 @@ def _assert_not_frame_equal(a, b, **kwargs): b : DataFrame The second DataFrame to compare. kwargs : dict - The arguments passed to `assert_frame_equal`. + The arguments passed to `tm.assert_frame_equal`. """ try: - assert_frame_equal(a, b, **kwargs) + tm.assert_frame_equal(a, b, **kwargs) msg = "The two DataFrames were equal when they shouldn't have been" pytest.fail(msg=msg) @@ -68,7 +68,7 @@ def _assert_not_frame_equal_both(a, b, **kwargs): b : DataFrame The second DataFrame to compare. kwargs : dict - The arguments passed to `assert_frame_equal`. + The arguments passed to `tm.assert_frame_equal`. """ _assert_not_frame_equal(a, b, **kwargs) _assert_not_frame_equal(b, a, **kwargs) @@ -82,7 +82,7 @@ def test_frame_equal_row_order_mismatch(check_like, obj_fixture): if not check_like: # Do not ignore row-column orderings. msg = "{obj}.index are different".format(obj=obj_fixture) with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, check_like=check_like, obj=obj_fixture) + tm.assert_frame_equal(df1, df2, check_like=check_like, obj=obj_fixture) else: _assert_frame_equal_both(df1, df2, check_like=check_like, obj=obj_fixture) @@ -98,7 +98,7 @@ def test_frame_equal_shape_mismatch(df1, df2, obj_fixture): msg = "{obj} are different".format(obj=obj_fixture) with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, obj=obj_fixture) + tm.assert_frame_equal(df1, df2, obj=obj_fixture) @pytest.mark.parametrize( @@ -127,9 +127,9 @@ def test_frame_equal_index_dtype_mismatch(df1, df2, msg, check_index_type): if check_index_type: with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, **kwargs) + tm.assert_frame_equal(df1, df2, **kwargs) else: - assert_frame_equal(df1, df2, **kwargs) + tm.assert_frame_equal(df1, df2, **kwargs) def test_empty_dtypes(check_dtype): @@ -143,9 +143,9 @@ def test_empty_dtypes(check_dtype): if check_dtype: msg = r"Attributes of DataFrame\..* are different" with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, **kwargs) + tm.assert_frame_equal(df1, df2, **kwargs) else: - assert_frame_equal(df1, df2, **kwargs) + tm.assert_frame_equal(df1, df2, **kwargs) def test_frame_equal_index_mismatch(obj_fixture): @@ -161,7 +161,7 @@ def test_frame_equal_index_mismatch(obj_fixture): df2 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "d"]) with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, obj=obj_fixture) + tm.assert_frame_equal(df1, df2, obj=obj_fixture) def test_frame_equal_columns_mismatch(obj_fixture): @@ -177,7 +177,7 @@ def test_frame_equal_columns_mismatch(obj_fixture): df2 = DataFrame({"A": [1, 2, 3], "b": [4, 5, 6]}, index=["a", "b", "c"]) with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, obj=obj_fixture) + tm.assert_frame_equal(df1, df2, obj=obj_fixture) def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): @@ -193,7 +193,7 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): df2 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 7]}) with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture) + tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture) @pytest.mark.parametrize( @@ -222,8 +222,8 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): def test_frame_equal_unicode(df1, df2, msg, by_blocks_fixture, obj_fixture): # see gh-20503 # - # Test ensures that `assert_frame_equals` raises the right exception + # Test ensures that `tm.assert_frame_equals` raises the right exception # when comparing DataFrames containing differing unicode objects. msg = msg.format(obj=obj_fixture) with pytest.raises(AssertionError, match=msg): - assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture) + tm.assert_frame_equal(df1, df2, by_blocks=by_blocks_fixture, obj=obj_fixture) diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index 270f765caebd0..8c3f242f0c96b 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -2,7 +2,7 @@ import pytest from pandas import Categorical, Index, MultiIndex, NaT -from pandas.util.testing import assert_index_equal +import pandas.util.testing as tm def test_index_equal_levels_mismatch(): @@ -20,7 +20,7 @@ def test_index_equal_levels_mismatch(): idx2 = MultiIndex.from_tuples([("A", 1), ("A", 2), ("B", 3), ("B", 4)]) with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, exact=False) + tm.assert_index_equal(idx1, idx2, exact=False) def test_index_equal_values_mismatch(check_exact): @@ -34,7 +34,7 @@ def test_index_equal_values_mismatch(check_exact): idx2 = MultiIndex.from_tuples([("A", 1), ("A", 2), ("B", 3), ("B", 4)]) with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, check_exact=check_exact) + tm.assert_index_equal(idx1, idx2, check_exact=check_exact) def test_index_equal_length_mismatch(check_exact): @@ -48,7 +48,7 @@ def test_index_equal_length_mismatch(check_exact): idx2 = Index([1, 2, 3, 4]) with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, check_exact=check_exact) + tm.assert_index_equal(idx1, idx2, check_exact=check_exact) def test_index_equal_class_mismatch(check_exact): @@ -62,7 +62,7 @@ def test_index_equal_class_mismatch(check_exact): idx2 = Index([1, 2, 3.0]) with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, exact=True, check_exact=check_exact) + tm.assert_index_equal(idx1, idx2, exact=True, check_exact=check_exact) def test_index_equal_values_close(check_exact): @@ -77,9 +77,9 @@ def test_index_equal_values_close(check_exact): \\[right\\]: Float64Index\\(\\[1.0, 2.0, 3.0000000001\\], dtype='float64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, check_exact=check_exact) + tm.assert_index_equal(idx1, idx2, check_exact=check_exact) else: - assert_index_equal(idx1, idx2, check_exact=check_exact) + tm.assert_index_equal(idx1, idx2, check_exact=check_exact) def test_index_equal_values_less_close(check_exact, check_less_precise): @@ -95,9 +95,9 @@ def test_index_equal_values_less_close(check_exact, check_less_precise): \\[right\\]: Float64Index\\(\\[1.0, 2.0, 3.0001\\], dtype='float64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, **kwargs) + tm.assert_index_equal(idx1, idx2, **kwargs) else: - assert_index_equal(idx1, idx2, **kwargs) + tm.assert_index_equal(idx1, idx2, **kwargs) def test_index_equal_values_too_far(check_exact, check_less_precise): @@ -112,7 +112,7 @@ def test_index_equal_values_too_far(check_exact, check_less_precise): \\[right\\]: Int64Index\\(\\[1, 2, 4\\], dtype='int64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, **kwargs) + tm.assert_index_equal(idx1, idx2, **kwargs) def test_index_equal_level_values_mismatch(check_exact, check_less_precise): @@ -127,7 +127,7 @@ def test_index_equal_level_values_mismatch(check_exact, check_less_precise): \\[right\\]: Int64Index\\(\\[1, 2, 3, 4\\], dtype='int64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, **kwargs) + tm.assert_index_equal(idx1, idx2, **kwargs) @pytest.mark.parametrize( @@ -145,14 +145,14 @@ def test_index_equal_names(name1, name2): idx2 = Index([1, 2, 3], name=name2) if name1 == name2 or name1 is name2: - assert_index_equal(idx1, idx2) + tm.assert_index_equal(idx1, idx2) else: name1 = "'x'" if name1 == "x" else name1 name2 = "'x'" if name2 == "x" else name2 msg = msg.format(name1=name1, name2=name2) with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2) + tm.assert_index_equal(idx1, idx2) def test_index_equal_category_mismatch(check_categorical): @@ -168,6 +168,6 @@ def test_index_equal_category_mismatch(check_categorical): if check_categorical: with pytest.raises(AssertionError, match=msg): - assert_index_equal(idx1, idx2, check_categorical=check_categorical) + tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical) else: - assert_index_equal(idx1, idx2, check_categorical=check_categorical) + tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical) diff --git a/pandas/tests/util/test_assert_interval_array_equal.py b/pandas/tests/util/test_assert_interval_array_equal.py index e4435b5f008e8..b264b484a04ab 100644 --- a/pandas/tests/util/test_assert_interval_array_equal.py +++ b/pandas/tests/util/test_assert_interval_array_equal.py @@ -1,7 +1,7 @@ import pytest from pandas import interval_range -from pandas.util.testing import assert_interval_array_equal +import pandas.util.testing as tm @pytest.mark.parametrize( @@ -14,7 +14,7 @@ ) def test_interval_array_equal(kwargs): arr = interval_range(**kwargs).values - assert_interval_array_equal(arr, arr) + tm.assert_interval_array_equal(arr, arr) def test_interval_array_equal_closed_mismatch(): @@ -30,7 +30,7 @@ def test_interval_array_equal_closed_mismatch(): \\[right\\]: right""" with pytest.raises(AssertionError, match=msg): - assert_interval_array_equal(arr1, arr2) + tm.assert_interval_array_equal(arr1, arr2) def test_interval_array_equal_periods_mismatch(): @@ -46,7 +46,7 @@ def test_interval_array_equal_periods_mismatch(): \\[right\\]: 6, Int64Index\\(\\[0, 1, 2, 3, 4, 5\\], dtype='int64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_interval_array_equal(arr1, arr2) + tm.assert_interval_array_equal(arr1, arr2) def test_interval_array_equal_end_mismatch(): @@ -62,7 +62,7 @@ def test_interval_array_equal_end_mismatch(): \\[right\\]: Int64Index\\(\\[0, 4, 8, 12, 16\\], dtype='int64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_interval_array_equal(arr1, arr2) + tm.assert_interval_array_equal(arr1, arr2) def test_interval_array_equal_start_mismatch(): @@ -78,4 +78,4 @@ def test_interval_array_equal_start_mismatch(): \\[right\\]: Int64Index\\(\\[1, 2, 3, 4\\], dtype='int64'\\)""" with pytest.raises(AssertionError, match=msg): - assert_interval_array_equal(arr1, arr2) + tm.assert_interval_array_equal(arr1, arr2) diff --git a/pandas/tests/util/test_assert_numpy_array_equal.py b/pandas/tests/util/test_assert_numpy_array_equal.py index 59f77d18a8929..53bcedf3a16f1 100644 --- a/pandas/tests/util/test_assert_numpy_array_equal.py +++ b/pandas/tests/util/test_assert_numpy_array_equal.py @@ -2,7 +2,7 @@ import pytest from pandas import Timestamp -from pandas.util.testing import assert_numpy_array_equal +import pandas.util.testing as tm def test_assert_numpy_array_equal_shape_mismatch(): @@ -13,14 +13,14 @@ def test_assert_numpy_array_equal_shape_mismatch(): \\[right\\]: \\(3L*,\\)""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5])) + tm.assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5])) def test_assert_numpy_array_equal_bad_type(): expected = "Expected type" with pytest.raises(AssertionError, match=expected): - assert_numpy_array_equal(1, 2) + tm.assert_numpy_array_equal(1, 2) @pytest.mark.parametrize( @@ -37,7 +37,7 @@ def test_assert_numpy_array_equal_class_mismatch(a, b, klass1, klass2): ) with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(a, b) + tm.assert_numpy_array_equal(a, b) def test_assert_numpy_array_equal_value_mismatch1(): @@ -48,7 +48,7 @@ def test_assert_numpy_array_equal_value_mismatch1(): \\[right\\]: \\[1\\.0, nan, 3\\.0\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(np.array([np.nan, 2, 3]), np.array([1, np.nan, 3])) + tm.assert_numpy_array_equal(np.array([np.nan, 2, 3]), np.array([1, np.nan, 3])) def test_assert_numpy_array_equal_value_mismatch2(): @@ -59,7 +59,7 @@ def test_assert_numpy_array_equal_value_mismatch2(): \\[right\\]: \\[1, 3\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(np.array([1, 2]), np.array([1, 3])) + tm.assert_numpy_array_equal(np.array([1, 2]), np.array([1, 3])) def test_assert_numpy_array_equal_value_mismatch3(): @@ -70,7 +70,7 @@ def test_assert_numpy_array_equal_value_mismatch3(): \\[right\\]: \\[\\[1, 3\\], \\[3, 4\\], \\[5, 6\\]\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal( + tm.assert_numpy_array_equal( np.array([[1, 2], [3, 4], [5, 6]]), np.array([[1, 3], [3, 4], [5, 6]]) ) @@ -83,7 +83,7 @@ def test_assert_numpy_array_equal_value_mismatch4(): \\[right\\]: \\[1\\.1, 2.0\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(np.array([1.1, 2.000001]), np.array([1.1, 2.0])) + tm.assert_numpy_array_equal(np.array([1.1, 2.000001]), np.array([1.1, 2.0])) def test_assert_numpy_array_equal_value_mismatch5(): @@ -94,7 +94,7 @@ def test_assert_numpy_array_equal_value_mismatch5(): \\[right\\]: \\[\\[1, 3\\], \\[3, 4\\], \\[5, 6\\]\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal( + tm.assert_numpy_array_equal( np.array([[1, 2], [3, 4], [5, 6]]), np.array([[1, 3], [3, 4], [5, 6]]) ) @@ -107,7 +107,9 @@ def test_assert_numpy_array_equal_value_mismatch6(): \\[right\\]: \\[\\[1, 3\\], \\[3, 4\\]\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(np.array([[1, 2], [3, 4]]), np.array([[1, 3], [3, 4]])) + tm.assert_numpy_array_equal( + np.array([[1, 2], [3, 4]]), np.array([[1, 3], [3, 4]]) + ) def test_assert_numpy_array_equal_shape_mismatch_override(): @@ -118,13 +120,13 @@ def test_assert_numpy_array_equal_shape_mismatch_override(): \\[right\\]: \\(3L*,\\)""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5]), obj="Index") + tm.assert_numpy_array_equal(np.array([1, 2]), np.array([3, 4, 5]), obj="Index") def test_numpy_array_equal_unicode(): # see gh-20503 # - # Test ensures that `assert_numpy_array_equals` raises the right + # Test ensures that `tm.assert_numpy_array_equals` raises the right # exception when comparing np.arrays containing differing unicode objects. msg = """numpy array are different @@ -133,7 +135,9 @@ def test_numpy_array_equal_unicode(): \\[right\\]: \\[á, à, å\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(np.array(["á", "à", "ä"]), np.array(["á", "à", "å"])) + tm.assert_numpy_array_equal( + np.array(["á", "à", "ä"]), np.array(["á", "à", "å"]) + ) def test_numpy_array_equal_object(): @@ -147,7 +151,7 @@ def test_numpy_array_equal_object(): \\[right\\]: \\[2011-01-01 00:00:00, 2011-01-02 00:00:00\\]""" with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(a, b) + tm.assert_numpy_array_equal(a, b) @pytest.mark.parametrize("other_type", ["same", "copy"]) @@ -170,6 +174,6 @@ def test_numpy_array_equal_copy_flag(other_type, check_same): if msg is not None: with pytest.raises(AssertionError, match=msg): - assert_numpy_array_equal(a, other, check_same=check_same) + tm.assert_numpy_array_equal(a, other, check_same=check_same) else: - assert_numpy_array_equal(a, other, check_same=check_same) + tm.assert_numpy_array_equal(a, other, check_same=check_same) diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py index bad3f2e67f8bb..0a6047c4662ba 100644 --- a/pandas/tests/util/test_assert_series_equal.py +++ b/pandas/tests/util/test_assert_series_equal.py @@ -1,7 +1,7 @@ import pytest from pandas import Categorical, DataFrame, Series -from pandas.util.testing import assert_series_equal +import pandas.util.testing as tm def _assert_series_equal_both(a, b, **kwargs): @@ -17,10 +17,10 @@ def _assert_series_equal_both(a, b, **kwargs): b : Series The second Series to compare. kwargs : dict - The arguments passed to `assert_series_equal`. + The arguments passed to `tm.assert_series_equal`. """ - assert_series_equal(a, b, **kwargs) - assert_series_equal(b, a, **kwargs) + tm.assert_series_equal(a, b, **kwargs) + tm.assert_series_equal(b, a, **kwargs) def _assert_not_series_equal(a, b, **kwargs): @@ -34,10 +34,10 @@ def _assert_not_series_equal(a, b, **kwargs): b : Series The second Series to compare. kwargs : dict - The arguments passed to `assert_series_equal`. + The arguments passed to `tm.assert_series_equal`. """ try: - assert_series_equal(a, b, **kwargs) + tm.assert_series_equal(a, b, **kwargs) msg = "The two Series were equal when they shouldn't have been" pytest.fail(msg=msg) @@ -58,7 +58,7 @@ def _assert_not_series_equal_both(a, b, **kwargs): b : Series The second Series to compare. kwargs : dict - The arguments passed to `assert_series_equal`. + The arguments passed to `tm.assert_series_equal`. """ _assert_not_series_equal(a, b, **kwargs) _assert_not_series_equal(b, a, **kwargs) @@ -114,7 +114,7 @@ def test_less_precise(data1, data2, dtype, check_less_precise): ): msg = "Series values are different" with pytest.raises(AssertionError, match=msg): - assert_series_equal(s1, s2, **kwargs) + tm.assert_series_equal(s1, s2, **kwargs) else: _assert_series_equal_both(s1, s2, **kwargs) @@ -145,9 +145,9 @@ def test_series_equal_index_dtype(s1, s2, msg, check_index_type): if check_index_type: with pytest.raises(AssertionError, match=msg): - assert_series_equal(s1, s2, **kwargs) + tm.assert_series_equal(s1, s2, **kwargs) else: - assert_series_equal(s1, s2, **kwargs) + tm.assert_series_equal(s1, s2, **kwargs) def test_series_equal_length_mismatch(check_less_precise): @@ -161,7 +161,7 @@ def test_series_equal_length_mismatch(check_less_precise): s2 = Series([1, 2, 3, 4]) with pytest.raises(AssertionError, match=msg): - assert_series_equal(s1, s2, check_less_precise=check_less_precise) + tm.assert_series_equal(s1, s2, check_less_precise=check_less_precise) def test_series_equal_values_mismatch(check_less_precise): @@ -175,7 +175,7 @@ def test_series_equal_values_mismatch(check_less_precise): s2 = Series([1, 2, 4]) with pytest.raises(AssertionError, match=msg): - assert_series_equal(s1, s2, check_less_precise=check_less_precise) + tm.assert_series_equal(s1, s2, check_less_precise=check_less_precise) def test_series_equal_categorical_mismatch(check_categorical): @@ -191,6 +191,6 @@ def test_series_equal_categorical_mismatch(check_categorical): if check_categorical: with pytest.raises(AssertionError, match=msg): - assert_series_equal(s1, s2, check_categorical=check_categorical) + tm.assert_series_equal(s1, s2, check_categorical=check_categorical) else: _assert_series_equal_both(s1, s2, check_categorical=check_categorical)
Part of #29272 Fyi: All changes are generated from a script posted in the issue. - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29278
2019-10-30T01:52:40Z
2019-10-30T11:56:23Z
2019-10-30T11:56:23Z
2019-10-30T11:56:26Z
CLN: Consistent pandas.util.testing imports in pandas/tests/series/indexing
diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py index 331747b6cd056..7509d21b8832f 100644 --- a/pandas/tests/series/indexing/test_alter_index.py +++ b/pandas/tests/series/indexing/test_alter_index.py @@ -6,7 +6,6 @@ import pandas as pd from pandas import Categorical, Series, date_range, isna import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal @pytest.mark.parametrize( @@ -41,8 +40,8 @@ def test_align(datetime_series, first_slice, second_slice, join_type, fill): ea = ea.fillna(fill) eb = eb.fillna(fill) - assert_series_equal(aa, ea) - assert_series_equal(ab, eb) + tm.assert_series_equal(aa, ea) + tm.assert_series_equal(ab, eb) assert aa.name == "ts" assert ea.name == "ts" assert ab.name == "ts" @@ -75,8 +74,8 @@ def test_align_fill_method( ea = ea.fillna(method=method, limit=limit) eb = eb.fillna(method=method, limit=limit) - assert_series_equal(aa, ea) - assert_series_equal(ab, eb) + tm.assert_series_equal(aa, ea) + tm.assert_series_equal(ab, eb) def test_align_nocopy(datetime_series): @@ -197,12 +196,12 @@ def test_reindex_nan(): ts = Series([2, 3, 5, 7], index=[1, 4, np.nan, 8]) i, j = [np.nan, 1, np.nan, 8, 4, np.nan], [2, 0, 2, 3, 1, 2] - assert_series_equal(ts.reindex(i), ts.iloc[j]) + tm.assert_series_equal(ts.reindex(i), ts.iloc[j]) ts.index = ts.index.astype("object") # reindex coerces index.dtype to float, loc/iloc doesn't - assert_series_equal(ts.reindex(i), ts.iloc[j], check_index_type=False) + tm.assert_series_equal(ts.reindex(i), ts.iloc[j], check_index_type=False) def test_reindex_series_add_nat(): @@ -239,7 +238,7 @@ def test_reindex_corner(datetime_series): # pass non-Index reindexed = datetime_series.reindex(list(datetime_series.index)) - assert_series_equal(datetime_series, reindexed) + tm.assert_series_equal(datetime_series, reindexed) # bad fill method ts = datetime_series[::2] @@ -257,10 +256,10 @@ def test_reindex_pad(): reindexed = s2.reindex(s.index, method="pad") reindexed2 = s2.reindex(s.index, method="ffill") - assert_series_equal(reindexed, reindexed2) + tm.assert_series_equal(reindexed, reindexed2) expected = Series([0, 0, 2, 2, 4, 4, 6, 6, 8, 8], index=np.arange(10)) - assert_series_equal(reindexed, expected) + tm.assert_series_equal(reindexed, expected) # GH4604 s = Series([1, 2, 3, 4, 5], index=["a", "b", "c", "d", "e"]) @@ -269,27 +268,27 @@ def test_reindex_pad(): # this changes dtype because the ffill happens after result = s.reindex(new_index).ffill() - assert_series_equal(result, expected.astype("float64")) + tm.assert_series_equal(result, expected.astype("float64")) result = s.reindex(new_index).ffill(downcast="infer") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([1, 5, 3, 5], index=new_index) result = s.reindex(new_index, method="ffill") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # inference of new dtype s = Series([True, False, False, True], index=list("abcd")) new_index = "agc" result = s.reindex(list(new_index)).ffill() expected = Series([True, True, False], index=list(new_index)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH4618 shifted series downcasting s = Series(False, index=range(0, 5)) result = s.shift(1).fillna(method="bfill") expected = Series(False, index=range(0, 5)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_reindex_nearest(): @@ -297,23 +296,23 @@ def test_reindex_nearest(): target = [0.1, 0.9, 1.5, 2.0] actual = s.reindex(target, method="nearest") expected = Series(np.around(target).astype("int64"), target) - assert_series_equal(expected, actual) + tm.assert_series_equal(expected, actual) actual = s.reindex_like(actual, method="nearest") - assert_series_equal(expected, actual) + tm.assert_series_equal(expected, actual) actual = s.reindex_like(actual, method="nearest", tolerance=1) - assert_series_equal(expected, actual) + tm.assert_series_equal(expected, actual) actual = s.reindex_like(actual, method="nearest", tolerance=[1, 2, 3, 4]) - assert_series_equal(expected, actual) + tm.assert_series_equal(expected, actual) actual = s.reindex(target, method="nearest", tolerance=0.2) expected = Series([0, 1, np.nan, 2], target) - assert_series_equal(expected, actual) + tm.assert_series_equal(expected, actual) actual = s.reindex(target, method="nearest", tolerance=[0.3, 0.01, 0.4, 3]) expected = Series([0, np.nan, np.nan, 2], target) - assert_series_equal(expected, actual) + tm.assert_series_equal(expected, actual) def test_reindex_backfill(): @@ -385,7 +384,7 @@ def test_reindex_categorical(): def test_reindex_like(datetime_series): other = datetime_series[::2] - assert_series_equal( + tm.assert_series_equal( datetime_series.reindex(other.index), datetime_series.reindex_like(other) ) @@ -399,7 +398,7 @@ def test_reindex_like(datetime_series): result = series1.reindex_like(series2, method="pad") expected = Series([5, np.nan], index=[day1, day3]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_reindex_fill_value(): @@ -408,11 +407,11 @@ def test_reindex_fill_value(): floats = Series([1.0, 2.0, 3.0]) result = floats.reindex([1, 2, 3]) expected = Series([2.0, 3.0, np.nan], index=[1, 2, 3]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = floats.reindex([1, 2, 3], fill_value=0) expected = Series([2.0, 3.0, 0], index=[1, 2, 3]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # ----------------------------------------------------------- # ints @@ -420,13 +419,13 @@ def test_reindex_fill_value(): result = ints.reindex([1, 2, 3]) expected = Series([2.0, 3.0, np.nan], index=[1, 2, 3]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # don't upcast result = ints.reindex([1, 2, 3], fill_value=0) expected = Series([2, 3, 0], index=[1, 2, 3]) assert issubclass(result.dtype.type, np.integer) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # ----------------------------------------------------------- # objects @@ -434,11 +433,11 @@ def test_reindex_fill_value(): result = objects.reindex([1, 2, 3]) expected = Series([2, 3, np.nan], index=[1, 2, 3], dtype=object) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = objects.reindex([1, 2, 3], fill_value="foo") expected = Series([2, 3, "foo"], index=[1, 2, 3], dtype=object) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # ------------------------------------------------------------ # bools @@ -446,11 +445,11 @@ def test_reindex_fill_value(): result = bools.reindex([1, 2, 3]) expected = Series([False, True, np.nan], index=[1, 2, 3], dtype=object) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = bools.reindex([1, 2, 3], fill_value=False) expected = Series([False, True, False], index=[1, 2, 3]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_reindex_datetimeindexes_tz_naive_and_aware(): @@ -474,7 +473,7 @@ def test_rename(): s = Series(range(1, 6), index=pd.Index(range(2, 7), name="IntIndex")) result = s.rename(str) expected = s.rename(lambda i: str(i)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) assert result.name == expected.name diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index bcbb162697e50..c2912cf3ce53f 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -7,7 +7,6 @@ from pandas import Index, Series, Timestamp, date_range, isna from pandas.core.indexing import IndexingError import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal from pandas.tseries.offsets import BDay @@ -19,7 +18,7 @@ def test_getitem_boolean(string_series): # passing list is OK result = s[list(mask)] expected = s[mask] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) tm.assert_index_equal(result.index, s.index[mask]) @@ -35,12 +34,12 @@ def test_getitem_boolean_empty(): s = Series(["A", "B"]) expected = Series(np.nan, index=["C"], dtype=object) result = s[Series(["C"], dtype=object)] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series(["A", "B"]) expected = Series(dtype=object, index=Index([], dtype="int64")) result = s[Series([], dtype=object)] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # invalid because of the boolean indexer # that's empty or not-aligned @@ -65,14 +64,14 @@ def test_getitem_boolean_object(string_series): # getitem result = s[omask] expected = s[mask] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # setitem s2 = s.copy() cop = s.copy() cop[omask] = 5 s2[mask] = 5 - assert_series_equal(cop, s2) + tm.assert_series_equal(cop, s2) # nans raise exception omask[5:10] = np.nan @@ -111,14 +110,14 @@ def test_setitem_boolean(string_series): result = string_series.copy() result[mask] = string_series * 2 expected = string_series * 2 - assert_series_equal(result[mask], expected[mask]) + tm.assert_series_equal(result[mask], expected[mask]) # needs alignment result = string_series.copy() result[mask] = (string_series * 2)[0:5] expected = (string_series * 2)[0:5].reindex_like(string_series) expected[-mask] = string_series[mask] - assert_series_equal(result[mask], expected[mask]) + tm.assert_series_equal(result[mask], expected[mask]) def test_get_set_boolean_different_order(string_series): @@ -131,12 +130,12 @@ def test_get_set_boolean_different_order(string_series): expected = string_series.copy() expected[expected > 0] = 0 - assert_series_equal(copy, expected) + tm.assert_series_equal(copy, expected) # getting sel = string_series[ordered > 0] exp = string_series[string_series > 0] - assert_series_equal(sel, exp) + tm.assert_series_equal(sel, exp) def test_where_unsafe_int(sint_dtype): @@ -146,7 +145,7 @@ def test_where_unsafe_int(sint_dtype): s[mask] = range(2, 7) expected = Series(list(range(2, 7)) + list(range(5, 10)), dtype=sint_dtype) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_where_unsafe_float(float_dtype): @@ -157,7 +156,7 @@ def test_where_unsafe_float(float_dtype): data = list(range(2, 7)) + list(range(5, 10)) expected = Series(data, dtype=float_dtype) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) @pytest.mark.parametrize( @@ -178,7 +177,7 @@ def test_where_unsafe_upcast(dtype, expected_dtype): mask = s < 5 expected = Series(values + list(range(5, 10)), dtype=expected_dtype) s[mask] = values - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_where_unsafe(): @@ -190,21 +189,21 @@ def test_where_unsafe(): expected = Series(list(range(6)) + values, dtype="float64") s[mask] = values - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # see gh-3235 s = Series(np.arange(10), dtype="int64") mask = s < 5 s[mask] = range(2, 7) expected = Series(list(range(2, 7)) + list(range(5, 10)), dtype="int64") - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) assert s.dtype == expected.dtype s = Series(np.arange(10), dtype="int64") mask = s > 5 s[mask] = [0] * 4 expected = Series([0, 1, 2, 3, 4, 5] + [0] * 4, dtype="int64") - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) s = Series(np.arange(10)) mask = s > 5 @@ -220,7 +219,7 @@ def test_where_unsafe(): s = Series([1, 2, 3, 4]) result = s.where(s > 2, np.nan) expected = Series([np.nan, np.nan, 3, 4]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 4667 # setting with None changes dtype @@ -233,7 +232,7 @@ def test_where_unsafe(): s[s > 8] = None result = s[isna(s)] expected = Series(np.nan, index=[9]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_where(): @@ -242,10 +241,10 @@ def test_where(): rs = s.where(cond).dropna() rs2 = s[cond] - assert_series_equal(rs, rs2) + tm.assert_series_equal(rs, rs2) rs = s.where(cond, -s) - assert_series_equal(rs, s.abs()) + tm.assert_series_equal(rs, s.abs()) rs = s.where(cond) assert s.shape == rs.shape @@ -257,12 +256,12 @@ def test_where(): expected = s2[cond].reindex(s2.index[:3]).reindex(s2.index) rs = s2.where(cond[:3]) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) expected = s2.abs() expected.iloc[0] = s2[0] rs = s2.where(cond[:3], -s2) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) def test_where_error(): @@ -279,7 +278,7 @@ def test_where_error(): s = Series([1, 2]) s[[True, False]] = [0, 1] expected = Series([0, 2]) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # failures msg = "cannot assign mismatch length to masked array" @@ -301,7 +300,7 @@ def test_where_array_like(klass): expected = Series([np.nan, 2, 3]) result = s.where(klass(cond)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -363,7 +362,7 @@ def test_where_setitem_invalid(): s[0:3] = list(range(3)) expected = Series([0, 1, 2]) - assert_series_equal(s.astype(np.int64), expected) + tm.assert_series_equal(s.astype(np.int64), expected) # slice with step s = Series(list("abcdef")) @@ -374,7 +373,7 @@ def test_where_setitem_invalid(): s = Series(list("abcdef")) s[0:4:2] = list(range(2)) expected = Series([0, "b", 1, "d", "e", "f"]) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # neg slices s = Series(list("abcdef")) @@ -384,7 +383,7 @@ def test_where_setitem_invalid(): s[-3:-1] = list(range(2)) expected = Series(["a", "b", "c", 0, 1, "f"]) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # list s = Series(list("abc")) @@ -401,7 +400,7 @@ def test_where_setitem_invalid(): s = Series(list("abc")) s[0] = list(range(10)) expected = Series([list(range(10)), "b", "c"]) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) @pytest.mark.parametrize("size", range(2, 6)) @@ -429,15 +428,15 @@ def test_broadcast(size, mask, item, box): s = Series(data) s[selection] = box(item) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) s = Series(data) result = s.where(~selection, box(item)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series(data) result = s.mask(selection, box(item)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_where_inplace(): @@ -447,12 +446,12 @@ def test_where_inplace(): rs = s.copy() rs.where(cond, inplace=True) - assert_series_equal(rs.dropna(), s[cond]) - assert_series_equal(rs, s.where(cond)) + tm.assert_series_equal(rs.dropna(), s[cond]) + tm.assert_series_equal(rs, s.where(cond)) rs = s.copy() rs.where(cond, -s, inplace=True) - assert_series_equal(rs, s.where(cond, -s)) + tm.assert_series_equal(rs, s.where(cond, -s)) def test_where_dups(): @@ -463,17 +462,17 @@ def test_where_dups(): comb = pd.concat([s1, s2]) result = comb.where(comb < 2) expected = Series([0, 1, np.nan, 0, 1, np.nan], index=[0, 1, 2, 0, 1, 2]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 4548 # inplace updating not working with dups comb[comb < 1] = 5 expected = Series([5, 1, 2, 5, 1, 2], index=[0, 1, 2, 0, 1, 2]) - assert_series_equal(comb, expected) + tm.assert_series_equal(comb, expected) comb[comb < 2] += 10 expected = Series([5, 11, 2, 5, 11, 2], index=[0, 1, 2, 0, 1, 2]) - assert_series_equal(comb, expected) + tm.assert_series_equal(comb, expected) def test_where_numeric_with_string(): @@ -508,20 +507,20 @@ def test_where_timedelta_coerce(): mask = np.array([False, False]) rs = s.where(mask, [10, 10]) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, 10) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, 10.0) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, [10.0, 10.0]) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, [10.0, np.nan]) expected = Series([10, None], dtype="object") - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) def test_where_datetime_conversion(): @@ -530,27 +529,27 @@ def test_where_datetime_conversion(): mask = np.array([False, False]) rs = s.where(mask, [10, 10]) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, 10) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, 10.0) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, [10.0, 10.0]) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) rs = s.where(mask, [10.0, np.nan]) expected = Series([10, None], dtype="object") - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) # GH 15701 timestamps = ["2016-12-31 12:00:04+00:00", "2016-12-31 12:00:04.010000+00:00"] s = Series([pd.Timestamp(t) for t in timestamps]) rs = s.where(Series([False, True])) expected = Series([pd.NaT, s[1]]) - assert_series_equal(rs, expected) + tm.assert_series_equal(rs, expected) def test_where_dt_tz_values(tz_naive_fixture): @@ -565,7 +564,7 @@ def test_where_dt_tz_values(tz_naive_fixture): exp = pd.Series( pd.DatetimeIndex(["20150101", "20150102", "20160516"], tz=tz_naive_fixture) ) - assert_series_equal(exp, result) + tm.assert_series_equal(exp, result) def test_mask(): @@ -574,25 +573,25 @@ def test_mask(): cond = s > 0 rs = s.where(~cond, np.nan) - assert_series_equal(rs, s.mask(cond)) + tm.assert_series_equal(rs, s.mask(cond)) rs = s.where(~cond) rs2 = s.mask(cond) - assert_series_equal(rs, rs2) + tm.assert_series_equal(rs, rs2) rs = s.where(~cond, -s) rs2 = s.mask(cond, -s) - assert_series_equal(rs, rs2) + tm.assert_series_equal(rs, rs2) cond = Series([True, False, False, True, False], index=s.index) s2 = -(s.abs()) rs = s2.where(~cond[:3]) rs2 = s2.mask(cond[:3]) - assert_series_equal(rs, rs2) + tm.assert_series_equal(rs, rs2) rs = s2.where(~cond[:3], -s2) rs2 = s2.mask(cond[:3], -s2) - assert_series_equal(rs, rs2) + tm.assert_series_equal(rs, rs2) msg = "Array conditional must be same shape as self" with pytest.raises(ValueError, match=msg): @@ -604,7 +603,7 @@ def test_mask(): s = Series([1, 2, 3, 4]) result = s.mask(s > 2, np.nan) expected = Series([1, 2, np.nan, np.nan]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # see gh-21891 s = Series([1, 2]) @@ -620,9 +619,9 @@ def test_mask_inplace(): rs = s.copy() rs.mask(cond, inplace=True) - assert_series_equal(rs.dropna(), s[~cond]) - assert_series_equal(rs, s.mask(cond)) + tm.assert_series_equal(rs.dropna(), s[~cond]) + tm.assert_series_equal(rs, s.mask(cond)) rs = s.copy() rs.mask(cond, -s, inplace=True) - assert_series_equal(rs, s.mask(cond, -s)) + tm.assert_series_equal(rs, s.mask(cond, -s)) diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index bf8d34cd62ff2..fab3310fa3dfe 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -9,11 +9,6 @@ import pandas as pd from pandas import DataFrame, DatetimeIndex, NaT, Series, Timestamp, date_range import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) """ @@ -35,7 +30,7 @@ def test_fancy_getitem(): assert s[Timestamp(datetime(2009, 1, 2))] == 48 with pytest.raises(KeyError, match=r"^'2009-1-3'$"): s["2009-1-3"] - assert_series_equal( + tm.assert_series_equal( s["3/6/2009":"2009-06-05"], s[datetime(2009, 3, 6) : datetime(2009, 6, 5)] ) @@ -93,7 +88,7 @@ def test_dti_reset_index_round_trip(): d2 = d1.reset_index() assert d2.dtypes[0] == np.dtype("M8[ns]") d3 = d2.set_index("index") - assert_frame_equal(d1, d3, check_names=False) + tm.assert_frame_equal(d1, d3, check_names=False) # #2329 stamp = datetime(2012, 11, 22) @@ -115,7 +110,7 @@ def test_series_set_value(): expected = Series([1.0, np.nan], index=index) - assert_series_equal(s2, expected) + tm.assert_series_equal(s2, expected) # FIXME: dont leave commented-out # s = Series(index[:1], index[:1]) @@ -139,17 +134,17 @@ def test_slicing_datetimes(): index=[datetime(2001, 1, i, 10, 00) for i in [1, 2, 3, 4]], ) result = df.loc[datetime(2001, 1, 1, 10) :] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.loc[: datetime(2001, 1, 4, 10)] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.loc[datetime(2001, 1, 1, 10) : datetime(2001, 1, 4, 10)] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.loc[datetime(2001, 1, 1, 11) :] expected = df.iloc[1:] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.loc["20010101 11":] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # duplicates df = pd.DataFrame( @@ -158,17 +153,17 @@ def test_slicing_datetimes(): ) result = df.loc[datetime(2001, 1, 1, 10) :] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.loc[: datetime(2001, 1, 4, 10)] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.loc[datetime(2001, 1, 1, 10) : datetime(2001, 1, 4, 10)] - assert_frame_equal(result, df) + tm.assert_frame_equal(result, df) result = df.loc[datetime(2001, 1, 1, 11) :] expected = df.iloc[1:] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = df.loc["20010101 11":] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_frame_datetime64_duplicated(): @@ -196,18 +191,18 @@ def test_getitem_setitem_datetime_tz_pytz(): result = ts.copy() result["1990-01-01 09:00:00+00:00"] = 0 result["1990-01-01 09:00:00+00:00"] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) result = ts.copy() result["1990-01-01 03:00:00-06:00"] = 0 result["1990-01-01 03:00:00-06:00"] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) # repeat with datetimes result = ts.copy() result[datetime(1990, 1, 1, 9, tzinfo=tz("UTC"))] = 0 result[datetime(1990, 1, 1, 9, tzinfo=tz("UTC"))] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) result = ts.copy() @@ -215,7 +210,7 @@ def test_getitem_setitem_datetime_tz_pytz(): date = tz("US/Central").localize(datetime(1990, 1, 1, 3)) result[date] = 0 result[date] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) def test_getitem_setitem_datetime_tz_dateutil(): @@ -238,23 +233,23 @@ def test_getitem_setitem_datetime_tz_dateutil(): result = ts.copy() result["1990-01-01 09:00:00+00:00"] = 0 result["1990-01-01 09:00:00+00:00"] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) result = ts.copy() result["1990-01-01 03:00:00-06:00"] = 0 result["1990-01-01 03:00:00-06:00"] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) # repeat with datetimes result = ts.copy() result[datetime(1990, 1, 1, 9, tzinfo=tz("UTC"))] = 0 result[datetime(1990, 1, 1, 9, tzinfo=tz("UTC"))] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) result = ts.copy() result[datetime(1990, 1, 1, 3, tzinfo=tz("America/Chicago"))] = 0 result[datetime(1990, 1, 1, 3, tzinfo=tz("America/Chicago"))] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) def test_getitem_setitem_datetimeindex(): @@ -270,29 +265,29 @@ def test_getitem_setitem_datetimeindex(): result = ts.copy() result["1990-01-01 04:00:00"] = 0 result["1990-01-01 04:00:00"] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) result = ts["1990-01-01 04:00:00":"1990-01-01 07:00:00"] expected = ts[4:8] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.copy() result["1990-01-01 04:00:00":"1990-01-01 07:00:00"] = 0 result["1990-01-01 04:00:00":"1990-01-01 07:00:00"] = ts[4:8] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) 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) + tm.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) + tm.assert_series_equal(result, expected) # repeat all the above with naive datetimes result = ts[datetime(1990, 1, 1, 4)] @@ -302,16 +297,16 @@ def test_getitem_setitem_datetimeindex(): result = ts.copy() result[datetime(1990, 1, 1, 4)] = 0 result[datetime(1990, 1, 1, 4)] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) result = ts[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] expected = ts[4:8] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.copy() result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = 0 result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = ts[4:8] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) lb = datetime(1990, 1, 1, 4) rb = datetime(1990, 1, 1, 7) @@ -325,7 +320,7 @@ def test_getitem_setitem_datetimeindex(): 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) + tm.assert_series_equal(result, expected) result = ts[ts.index[4]] expected = ts[4] @@ -333,22 +328,22 @@ def test_getitem_setitem_datetimeindex(): result = ts[ts.index[4:8]] expected = ts[4:8] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.copy() result[ts.index[4:8]] = 0 result[4:8] = ts[4:8] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) # also test partial date slicing result = ts["1990-01-02"] expected = ts[24:48] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.copy() result["1990-01-02"] = 0 result["1990-01-02"] = ts[24:48] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) def test_getitem_setitem_periodindex(): @@ -365,22 +360,22 @@ def test_getitem_setitem_periodindex(): result = ts.copy() result["1990-01-01 04"] = 0 result["1990-01-01 04"] = ts[4] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) result = ts["1990-01-01 04":"1990-01-01 07"] expected = ts[4:8] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.copy() result["1990-01-01 04":"1990-01-01 07"] = 0 result["1990-01-01 04":"1990-01-01 07"] = ts[4:8] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) lb = "1990-01-01 04" rb = "1990-01-01 07" result = ts[(ts.index >= lb) & (ts.index <= rb)] expected = ts[4:8] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 2782 result = ts[ts.index[4]] @@ -389,12 +384,12 @@ def test_getitem_setitem_periodindex(): result = ts[ts.index[4:8]] expected = ts[4:8] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.copy() result[ts.index[4:8]] = 0 result[4:8] = ts[4:8] - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) # FutureWarning from NumPy. @@ -406,7 +401,7 @@ def test_getitem_median_slice_bug(): indexer = [slice(6, 7, None)] result = s[indexer] expected = s[indexer[0]] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_datetime_indexing(): @@ -524,14 +519,14 @@ def test_duplicate_dates_indexing(dups): total = (ts.index == date).sum() expected = ts[mask] if total > 1: - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) else: - assert_almost_equal(result, expected[0]) + tm.assert_almost_equal(result, expected[0]) cp = ts.copy() cp[date] = 0 expected = Series(np.where(mask, 0, ts), index=ts.index) - assert_series_equal(cp, expected) + tm.assert_series_equal(cp, expected) with pytest.raises(KeyError, match=r"^947116800000000000$"): ts[datetime(2000, 1, 6)] @@ -548,17 +543,17 @@ def test_range_slice(): result = ts["1/2/2000":] expected = ts[1:] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts["1/2/2000":"1/3/2000"] expected = ts[1:4] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_groupby_average_dup_values(dups): result = dups.groupby(level=0).mean() expected = dups.groupby(dups.index).mean() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_indexing_over_size_cutoff(): @@ -642,7 +637,7 @@ def compare(slobj): result = ts2[slobj].copy() result = result.sort_index() expected = ts[slobj] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) compare(slice("2011-01-01", "2011-01-15")) compare(slice("2010-12-30", "2011-01-15")) @@ -656,7 +651,7 @@ def compare(slobj): # single values result = ts2["2011"].sort_index() expected = ts["2011"] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # diff freq rng = date_range(datetime(2005, 1, 1), periods=20, freq="M") @@ -680,7 +675,7 @@ def test_indexing(): df = DataFrame(dict(A=ts)) result = df["2001"]["A"] - assert_series_equal(expected, result) + tm.assert_series_equal(expected, result) # setting ts["2001"] = 1 @@ -690,18 +685,18 @@ def test_indexing(): df.loc["2001", "A"] = 1 result = df["2001"]["A"] - assert_series_equal(expected, result) + tm.assert_series_equal(expected, result) # GH3546 (not including times on the last day) idx = date_range(start="2013-05-31 00:00", end="2013-05-31 23:00", freq="H") ts = Series(range(len(idx)), index=idx) expected = ts["2013-05"] - assert_series_equal(expected, ts) + tm.assert_series_equal(expected, ts) idx = date_range(start="2013-05-31 00:00", end="2013-05-31 23:59", freq="S") ts = Series(range(len(idx)), index=idx) expected = ts["2013-05"] - assert_series_equal(expected, ts) + tm.assert_series_equal(expected, ts) idx = [ Timestamp("2013-05-31 00:00"), @@ -709,7 +704,7 @@ def test_indexing(): ] ts = Series(range(len(idx)), index=idx) expected = ts["2013"] - assert_series_equal(expected, ts) + tm.assert_series_equal(expected, ts) # GH14826, indexing with a seconds resolution string / datetime object df = DataFrame( @@ -763,7 +758,7 @@ def test_round_nat(method, freq): s = Series([pd.NaT]) expected = Series(pd.NaT) round_method = getattr(s.dt, method) - assert_series_equal(round_method(freq), expected) + tm.assert_series_equal(round_method(freq), expected) def test_setitem_tuple_with_datetimetz(): @@ -774,4 +769,4 @@ def test_setitem_tuple_with_datetimetz(): expected = result.copy() result[(0, 1)] = np.nan expected.iloc[0] = np.nan - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/indexing/test_iloc.py b/pandas/tests/series/indexing/test_iloc.py index 199f57f6e0764..eef4d89af3832 100644 --- a/pandas/tests/series/indexing/test_iloc.py +++ b/pandas/tests/series/indexing/test_iloc.py @@ -1,7 +1,7 @@ import numpy as np from pandas import Series -from pandas.util.testing import assert_almost_equal, assert_series_equal +import pandas.util.testing as tm def test_iloc(): @@ -10,12 +10,12 @@ def test_iloc(): for i in range(len(s)): result = s.iloc[i] exp = s[s.index[i]] - assert_almost_equal(result, exp) + tm.assert_almost_equal(result, exp) # pass a slice result = s.iloc[slice(1, 3)] expected = s.loc[2:4] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # test slice is a view result[:] = 0 @@ -24,7 +24,7 @@ def test_iloc(): # list of integers result = s.iloc[[0, 2, 3, 4, 5]] expected = s.reindex(s.index[[0, 2, 3, 4, 5]]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_iloc_nonunique(): diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index d1c93990e9167..4673dabca811b 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -10,7 +10,6 @@ import pandas as pd from pandas import Categorical, DataFrame, MultiIndex, Series, Timedelta, Timestamp import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal from pandas.tseries.offsets import BDay @@ -43,11 +42,11 @@ def test_basic_getitem_with_labels(datetime_series): result = datetime_series[indices] expected = datetime_series.reindex(indices) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = datetime_series[indices[0] : indices[2]] expected = datetime_series.loc[indices[0] : indices[2]] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # integer indexes, be careful s = Series(np.random.randn(10), index=list(range(0, 20, 2))) @@ -56,12 +55,12 @@ def test_basic_getitem_with_labels(datetime_series): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s[inds] expected = s.reindex(inds) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s[arr_inds] expected = s.reindex(arr_inds) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH12089 # with tz for values @@ -83,7 +82,7 @@ def test_getitem_setitem_ellipsis(): np.fix(s) result = s[...] - assert_series_equal(result, s) + tm.assert_series_equal(result, s) s[...] = 5 assert (result == 5).all() @@ -129,8 +128,8 @@ def test_getitem_generator(string_series): result = string_series[gen] result2 = string_series[iter(string_series > 0)] expected = string_series[string_series > 0] - assert_series_equal(result, expected) - assert_series_equal(result2, expected) + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, expected) def test_type_promotion(): @@ -140,7 +139,7 @@ def test_type_promotion(): s["b"] = 3.0 s["c"] = "foo" expected = Series([pd.Timestamp("2016-01-01"), 3.0, "foo"], index=["a", "b", "c"]) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) @pytest.mark.parametrize( @@ -162,7 +161,7 @@ def test_getitem_with_duplicates_indices(result_1, duplicate_item, expected_1): # GH 17610 result = result_1.append(duplicate_item) expected = expected_1.append(duplicate_item) - assert_series_equal(result[1], expected) + tm.assert_series_equal(result[1], expected) assert result[2] == result_1[2] @@ -268,14 +267,14 @@ def test_getitem_dups_with_missing(): with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = s[["foo", "bar", "bah", "bam"]] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_getitem_dups(): s = Series(range(5), index=["A", "A", "B", "C", "C"], dtype=np.int64) expected = Series([3, 4], index=["C", "C"], dtype=np.int64) result = s["C"] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_setitem_ambiguous_keyerror(): @@ -285,12 +284,12 @@ def test_setitem_ambiguous_keyerror(): s2 = s.copy() s2[1] = 5 expected = s.append(Series([5], index=[1])) - assert_series_equal(s2, expected) + tm.assert_series_equal(s2, expected) s2 = s.copy() s2.loc[1] = 5 expected = s.append(Series([5], index=[1])) - assert_series_equal(s2, expected) + tm.assert_series_equal(s2, expected) def test_getitem_dataframe(): @@ -326,19 +325,19 @@ def test_setitem(datetime_series, string_series): app = Series([1], index=["foobar"], name="series") expected = string_series.append(app) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # Test for issue #10193 key = pd.Timestamp("2012-01-01") series = pd.Series() series[key] = 47 expected = pd.Series(47, [key]) - assert_series_equal(series, expected) + tm.assert_series_equal(series, expected) series = pd.Series([], pd.DatetimeIndex([], freq="D")) series[key] = 47 expected = pd.Series(47, pd.DatetimeIndex([key], freq="D")) - assert_series_equal(series, expected) + tm.assert_series_equal(series, expected) def test_setitem_dtypes(): @@ -348,23 +347,23 @@ def test_setitem_dtypes(): s = Series([1, 2, 3]) s.iloc[0] = np.nan - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) s = Series([1, 2, 3]) s.loc[0] = np.nan - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) s = Series([1, 2, 3]) s[0] = np.nan - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) s = Series([False]) s.loc[0] = np.nan - assert_series_equal(s, Series([np.nan])) + tm.assert_series_equal(s, Series([np.nan])) s = Series([False, True]) s.loc[0] = np.nan - assert_series_equal(s, Series([np.nan, 1.0])) + tm.assert_series_equal(s, Series([np.nan, 1.0])) def test_set_value(datetime_series, string_series): @@ -405,7 +404,7 @@ def test_basic_getitem_setitem_corner(datetime_series): # weird lists. [slice(0, 5)] will work but not two slices result = datetime_series[[slice(None, 5)]] expected = datetime_series[:5] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # OK msg = r"unhashable type(: 'slice')?" @@ -587,17 +586,17 @@ def test_loc_setitem(string_series): expected = string_series.copy() expected[[3, 4, 7]] = 5 - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result.iloc[5:10] = 10 expected[5:10] = 10 - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # set slice with indices d1, d2 = string_series.index[[5, 15]] result.loc[d1:d2] = 6 expected[5:16] = 6 # because it's inclusive - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # set index value string_series.loc[d1] = 4 @@ -611,18 +610,18 @@ def test_setitem_na(): expected = Series([np.nan, 3, np.nan, 5, np.nan, 7, np.nan, 9, np.nan]) s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10]) s[::2] = np.nan - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # gets coerced to float, right? expected = Series([np.nan, 1, np.nan, 0]) s = Series([True, True, False, False]) s[::2] = np.nan - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) expected = Series([np.nan, np.nan, np.nan, np.nan, np.nan, 5, 6, 7, 8, 9]) s = Series(np.arange(10)) s[:5] = np.nan - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_timedelta_assignment(): @@ -787,7 +786,7 @@ def test_cast_on_putmask(): s[[True, False]] = Series([0], index=[1], dtype="int64") expected = Series([0, 2], index=[1, 2], dtype="int64") - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_type_promote_putmask(): @@ -796,19 +795,19 @@ def test_type_promote_putmask(): left, mask = ts.copy(), ts > 0 right = ts[mask].copy().map(str) left[mask] = right - assert_series_equal(left, ts.map(lambda t: str(t) if t > 0 else t)) + tm.assert_series_equal(left, ts.map(lambda t: str(t) if t > 0 else t)) s = Series([0, 1, 2, 0]) mask = s > 0 s2 = s[mask].map(str) s[mask] = s2 - assert_series_equal(s, Series([0, "1", "2", 0])) + tm.assert_series_equal(s, Series([0, "1", "2", 0])) s = Series([0, "foo", "bar", 0]) mask = Series([False, True, True, False]) s2 = s[mask] s[mask] = s2 - assert_series_equal(s, Series([0, "foo", "bar", 0])) + tm.assert_series_equal(s, Series([0, "foo", "bar", 0])) def test_multilevel_preserve_name(): @@ -868,7 +867,7 @@ def test_pop(): assert result == 4 expected = Series([0, 0], index=["A", "C"], name=4) - assert_series_equal(k, expected) + tm.assert_series_equal(k, expected) def test_take(): @@ -896,14 +895,14 @@ def test_take_categorical(): expected = Series( pd.Categorical(["b", "b", "a"], categories=["a", "b", "c"]), index=[1, 1, 0] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_head_tail(string_series): - assert_series_equal(string_series.head(), string_series[:5]) - assert_series_equal(string_series.head(0), string_series[0:0]) - assert_series_equal(string_series.tail(), string_series[-5:]) - assert_series_equal(string_series.tail(0), string_series[0:0]) + tm.assert_series_equal(string_series.head(), string_series[:5]) + tm.assert_series_equal(string_series.head(0), string_series[0:0]) + tm.assert_series_equal(string_series.tail(), string_series[-5:]) + tm.assert_series_equal(string_series.tail(0), string_series[0:0]) def test_uint_drop(any_int_dtype): diff --git a/pandas/tests/series/indexing/test_loc.py b/pandas/tests/series/indexing/test_loc.py index d3402725130fb..e6b5b5df2b000 100644 --- a/pandas/tests/series/indexing/test_loc.py +++ b/pandas/tests/series/indexing/test_loc.py @@ -3,7 +3,7 @@ import pandas as pd from pandas import Series, Timestamp -from pandas.util.testing import assert_series_equal +import pandas.util.testing as tm @pytest.mark.parametrize("val,expected", [(2 ** 63 - 1, 3), (2 ** 63, 4)]) @@ -15,18 +15,18 @@ def test_loc_uint64(val, expected): def test_loc_getitem(string_series, datetime_series): inds = string_series.index[[3, 4, 7]] - assert_series_equal(string_series.loc[inds], string_series.reindex(inds)) - assert_series_equal(string_series.iloc[5::2], string_series[5::2]) + tm.assert_series_equal(string_series.loc[inds], string_series.reindex(inds)) + tm.assert_series_equal(string_series.iloc[5::2], string_series[5::2]) # slice with indices d1, d2 = datetime_series.index[[5, 15]] result = datetime_series.loc[d1:d2] expected = datetime_series.truncate(d1, d2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # boolean mask = string_series > string_series.median() - assert_series_equal(string_series.loc[mask], string_series[mask]) + tm.assert_series_equal(string_series.loc[mask], string_series[mask]) # ask for index value assert datetime_series.loc[d1] == datetime_series[d1] @@ -62,8 +62,8 @@ def test_loc_getitem_setitem_integer_slice_keyerrors(): result2 = s.loc[3:11] expected = s.reindex([4, 6, 8, 10]) - assert_series_equal(result, expected) - assert_series_equal(result2, expected) + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, expected) # non-monotonic, raise KeyError s2 = s.iloc[list(range(5)) + list(range(9, 4, -1))] @@ -76,7 +76,7 @@ def test_loc_getitem_setitem_integer_slice_keyerrors(): def test_loc_getitem_iterator(string_series): idx = iter(string_series.index[:10]) result = string_series.loc[idx] - assert_series_equal(result, string_series[:10]) + tm.assert_series_equal(result, string_series[:10]) def test_loc_setitem_boolean(string_series): @@ -86,7 +86,7 @@ def test_loc_setitem_boolean(string_series): result.loc[mask] = 0 expected = string_series expected[mask] = 0 - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_loc_setitem_corner(string_series): @@ -104,13 +104,13 @@ def test_basic_setitem_with_labels(datetime_series): exp = datetime_series.copy() cp[indices] = 0 exp.loc[indices] = 0 - assert_series_equal(cp, exp) + tm.assert_series_equal(cp, exp) cp = datetime_series.copy() exp = datetime_series.copy() cp[indices[0] : indices[2]] = 0 exp.loc[indices[0] : indices[2]] = 0 - assert_series_equal(cp, exp) + tm.assert_series_equal(cp, exp) # integer indexes, be careful s = Series(np.random.randn(10), index=list(range(0, 20, 2))) @@ -121,13 +121,13 @@ def test_basic_setitem_with_labels(datetime_series): exp = s.copy() s[inds] = 0 s.loc[inds] = 0 - assert_series_equal(cp, exp) + tm.assert_series_equal(cp, exp) cp = s.copy() exp = s.copy() s[arr_inds] = 0 s.loc[arr_inds] = 0 - assert_series_equal(cp, exp) + tm.assert_series_equal(cp, exp) inds_notfound = [0, 4, 5, 6] arr_inds_notfound = np.array([0, 4, 5, 6]) diff --git a/pandas/tests/series/indexing/test_numeric.py b/pandas/tests/series/indexing/test_numeric.py index 083324101f437..bcddcf843df06 100644 --- a/pandas/tests/series/indexing/test_numeric.py +++ b/pandas/tests/series/indexing/test_numeric.py @@ -4,7 +4,6 @@ import pandas as pd from pandas import DataFrame, Index, Series import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal def test_get(): @@ -126,11 +125,11 @@ def test_get_nan_multiple(): idx = [2, 30] with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert_series_equal(s.get(idx), Series([2, np.nan], index=idx)) + tm.assert_series_equal(s.get(idx), Series([2, np.nan], index=idx)) idx = [2, np.nan] with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - assert_series_equal(s.get(idx), Series([2, np.nan], index=idx)) + tm.assert_series_equal(s.get(idx), Series([2, np.nan], index=idx)) # GH 17295 - all missing keys idx = [20, 30] @@ -147,11 +146,11 @@ def test_delitem(): del s[0] expected = Series(range(1, 5), index=range(1, 5)) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) del s[1] expected = Series(range(2, 5), index=range(2, 5)) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # empty s = Series() @@ -162,20 +161,20 @@ def test_delitem(): # only 1 left, del, add, del s = Series(1) del s[0] - assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="int64"))) + tm.assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="int64"))) s[0] = 1 - assert_series_equal(s, Series(1)) + tm.assert_series_equal(s, Series(1)) del s[0] - assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="int64"))) + tm.assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="int64"))) # Index(dtype=object) s = Series(1, index=["a"]) del s["a"] - assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="object"))) + tm.assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="object"))) s["a"] = 1 - assert_series_equal(s, Series(1, index=["a"])) + tm.assert_series_equal(s, Series(1, index=["a"])) del s["a"] - assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="object"))) + tm.assert_series_equal(s, Series(dtype="int64", index=Index([], dtype="object"))) def test_slice_float64(): @@ -188,10 +187,10 @@ def test_slice_float64(): result = s[start:end] expected = s.iloc[5:16] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.loc[start:end] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame(np.random.randn(20, 3), index=index) @@ -217,19 +216,19 @@ def test_getitem_negative_out_of_bounds(): def test_getitem_regression(): s = Series(range(5), index=list(range(5))) result = s[list(range(5))] - assert_series_equal(result, s) + tm.assert_series_equal(result, s) def test_getitem_setitem_slice_bug(): s = Series(range(10), index=list(range(10))) result = s[-12:] - assert_series_equal(result, s) + tm.assert_series_equal(result, s) result = s[-7:] - assert_series_equal(result, s[3:]) + tm.assert_series_equal(result, s[3:]) result = s[:-12] - assert_series_equal(result, s[:0]) + tm.assert_series_equal(result, s[:0]) s = Series(range(10), index=list(range(10))) s[-12:] = 0 @@ -244,7 +243,7 @@ def test_getitem_setitem_slice_integers(): result = s[:4] expected = s.reindex([2, 4, 6, 8]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s[:4] = 0 assert (s[:4] == 0).all() @@ -259,7 +258,7 @@ def test_setitem_float_labels(): s.loc[1] = "zoo" tmp.iloc[2] = "zoo" - assert_series_equal(s, tmp) + tm.assert_series_equal(s, tmp) def test_slice_float_get_set(datetime_series):
Part of #29272 Fyi: the changes were created via a script posted in the issue - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29277
2019-10-30T01:41:01Z
2019-10-30T11:55:01Z
2019-10-30T11:55:01Z
2019-10-30T11:55:16Z
CLN: update imports in tests
diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index a1de205afc0e2..bbd97291fab3f 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -15,7 +15,6 @@ import pandas as pd from pandas import NaT, Period, Timedelta, Timestamp, offsets -import pandas.core.indexes.period as period import pandas.util.testing as tm @@ -942,7 +941,7 @@ def test_equal(self): assert self.january1 == self.january2 def test_equal_Raises_Value(self): - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): self.january1 == self.day def test_notEqual(self): @@ -953,7 +952,7 @@ def test_greater(self): assert self.february > self.january1 def test_greater_Raises_Value(self): - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): self.january1 > self.day def test_greater_Raises_Type(self): @@ -964,7 +963,7 @@ def test_greaterEqual(self): assert self.january1 >= self.january2 def test_greaterEqual_Raises_Value(self): - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): self.january1 >= self.day with pytest.raises(TypeError): @@ -974,7 +973,7 @@ def test_smallerEqual(self): assert self.january1 <= self.january2 def test_smallerEqual_Raises_Value(self): - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): self.january1 <= self.day def test_smallerEqual_Raises_Type(self): @@ -985,7 +984,7 @@ def test_smaller(self): assert self.january1 < self.february def test_smaller_Raises_Value(self): - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): self.january1 < self.day def test_smaller_Raises_Type(self): @@ -1026,7 +1025,7 @@ def test_sub_delta(self): result = left - right assert result == 4 * right.freq - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): left - Period("2007-01", freq="M") def test_add_integer(self): @@ -1097,16 +1096,16 @@ def test_sub(self): assert per2 - per1 == 14 * off msg = r"Input has different freq=M from Period\(freq=D\)" - with pytest.raises(period.IncompatibleFrequency, match=msg): + with pytest.raises(IncompatibleFrequency, match=msg): per1 - Period("2011-02", freq="M") @pytest.mark.parametrize("n", [1, 2, 3, 4]) def test_sub_n_gt_1_ticks(self, tick_classes, n): # GH 23878 - p1 = pd.Period("19910905", freq=tick_classes(n)) - p2 = pd.Period("19920406", freq=tick_classes(n)) + p1 = Period("19910905", freq=tick_classes(n)) + p2 = Period("19920406", freq=tick_classes(n)) - expected = pd.Period(str(p2), freq=p2.freq.base) - pd.Period( + expected = Period(str(p2), freq=p2.freq.base) - Period( str(p1), freq=p1.freq.base ) @@ -1117,10 +1116,10 @@ def test_sub_n_gt_1_ticks(self, tick_classes, n): @pytest.mark.parametrize( "offset, kwd_name", [ - (pd.offsets.YearEnd, "month"), - (pd.offsets.QuarterEnd, "startingMonth"), - (pd.offsets.MonthEnd, None), - (pd.offsets.Week, "weekday"), + (offsets.YearEnd, "month"), + (offsets.QuarterEnd, "startingMonth"), + (offsets.MonthEnd, None), + (offsets.Week, "weekday"), ], ) def test_sub_n_gt_1_offsets(self, offset, kwd_name, n, normalize): @@ -1128,12 +1127,10 @@ def test_sub_n_gt_1_offsets(self, offset, kwd_name, n, normalize): kwds = {kwd_name: 3} if kwd_name is not None else {} p1_d = "19910905" p2_d = "19920406" - p1 = pd.Period(p1_d, freq=offset(n, normalize, **kwds)) - p2 = pd.Period(p2_d, freq=offset(n, normalize, **kwds)) + p1 = Period(p1_d, freq=offset(n, normalize, **kwds)) + p2 = Period(p2_d, freq=offset(n, normalize, **kwds)) - expected = pd.Period(p2_d, freq=p2.freq.base) - pd.Period( - p1_d, freq=p1.freq.base - ) + expected = Period(p2_d, freq=p2.freq.base) - Period(p1_d, freq=p1.freq.base) assert (p2 - p1) == expected @@ -1152,14 +1149,14 @@ def test_add_offset(self): np.timedelta64(365, "D"), timedelta(365), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): o + p for freq in ["M", "2M", "3M"]: @@ -1179,14 +1176,14 @@ def test_add_offset(self): np.timedelta64(365, "D"), timedelta(365), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): o + p # freq is Tick @@ -1226,14 +1223,14 @@ def test_add_offset(self): np.timedelta64(4, "h"), timedelta(hours=23), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): o + p for freq in ["H", "2H", "3H"]: @@ -1272,14 +1269,14 @@ def test_add_offset(self): np.timedelta64(3200, "s"), timedelta(hours=23, minutes=30), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p + o if isinstance(o, np.timedelta64): with pytest.raises(TypeError): o + p else: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): o + p def test_add_offset_nat(self): @@ -1376,7 +1373,7 @@ def test_sub_offset(self): np.timedelta64(365, "D"), timedelta(365), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p - o for freq in ["M", "2M", "3M"]: @@ -1391,7 +1388,7 @@ def test_sub_offset(self): np.timedelta64(365, "D"), timedelta(365), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p - o # freq is Tick @@ -1411,7 +1408,7 @@ def test_sub_offset(self): np.timedelta64(4, "h"), timedelta(hours=23), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p - o for freq in ["H", "2H", "3H"]: @@ -1434,7 +1431,7 @@ def test_sub_offset(self): np.timedelta64(3200, "s"), timedelta(hours=23, minutes=30), ]: - with pytest.raises(period.IncompatibleFrequency): + with pytest.raises(IncompatibleFrequency): p - o def test_sub_offset_nat(self): @@ -1530,10 +1527,10 @@ def test_period_ops_offset(self): assert result == exp msg = r"Input cannot be converted to Period\(freq=D\)" - with pytest.raises(period.IncompatibleFrequency, match=msg): + with pytest.raises(IncompatibleFrequency, match=msg): p + offsets.Hour(2) - with pytest.raises(period.IncompatibleFrequency, match=msg): + with pytest.raises(IncompatibleFrequency, match=msg): p - offsets.Hour(2) diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index 52f32d41a02ff..2ba55b22a7c54 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -8,7 +8,7 @@ import pytest import pandas as pd -from pandas import NaT, Timedelta, Timestamp +from pandas import NaT, Timedelta, Timestamp, offsets from pandas.core import ops import pandas.util.testing as tm @@ -28,7 +28,7 @@ class TestTimedeltaAdditionSubtraction: timedelta(seconds=10), np.timedelta64(10, "s"), np.timedelta64(10000000000, "ns"), - pd.offsets.Second(10), + offsets.Second(10), ], ) def test_td_add_sub_ten_seconds(self, ten_seconds): @@ -50,7 +50,7 @@ def test_td_add_sub_ten_seconds(self, ten_seconds): Timedelta("1 days, 00:00:10"), timedelta(days=1, seconds=10), np.timedelta64(1, "D") + np.timedelta64(10, "s"), - pd.offsets.Day() + pd.offsets.Second(10), + offsets.Day() + offsets.Second(10), ], ) def test_td_add_sub_one_day_ten_seconds(self, one_day_ten_secs): @@ -114,7 +114,7 @@ def test_td_add_timedelta64(self, op): def test_td_add_offset(self, op): td = Timedelta(10, unit="d") - result = op(td, pd.offsets.Hour(6)) + result = op(td, offsets.Hour(6)) assert isinstance(result, Timedelta) assert result == Timedelta(days=10, hours=6) @@ -167,7 +167,7 @@ def test_td_sub_td64_nat(self): def test_td_sub_offset(self): td = Timedelta(10, unit="d") - result = td - pd.offsets.Hour(1) + result = td - offsets.Hour(1) assert isinstance(result, Timedelta) assert result == Timedelta(239, unit="h") @@ -192,7 +192,7 @@ def test_td_rsub_nat(self): assert result is NaT def test_td_rsub_offset(self): - result = pd.offsets.Hour(1) - Timedelta(10, unit="d") + result = offsets.Hour(1) - Timedelta(10, unit="d") assert isinstance(result, Timedelta) assert result == Timedelta(-239, unit="h") @@ -306,7 +306,7 @@ def test_td_div_timedeltalike_scalar(self): # GH#19738 td = Timedelta(10, unit="d") - result = td / pd.offsets.Hour(1) + result = td / offsets.Hour(1) assert result == 240 assert td / td == 1 @@ -342,7 +342,7 @@ def test_td_div_nan(self, nan): def test_td_rdiv_timedeltalike_scalar(self): # GH#19738 td = Timedelta(10, unit="d") - result = pd.offsets.Hour(1) / td + result = offsets.Hour(1) / td assert result == 1 / 240.0 assert np.timedelta64(60, "h") / td == 0.25 @@ -370,8 +370,8 @@ def test_td_floordiv_null_scalar(self): def test_td_floordiv_offsets(self): # GH#19738 td = Timedelta(hours=3, minutes=4) - assert td // pd.offsets.Hour(1) == 3 - assert td // pd.offsets.Minute(2) == 92 + assert td // offsets.Hour(1) == 3 + assert td // offsets.Minute(2) == 92 def test_td_floordiv_invalid_scalar(self): # GH#18846 @@ -441,7 +441,7 @@ def test_td_rfloordiv_null_scalar(self): def test_td_rfloordiv_offsets(self): # GH#19738 - assert pd.offsets.Hour(1) // Timedelta(minutes=25) == 2 + assert offsets.Hour(1) // Timedelta(minutes=25) == 2 def test_td_rfloordiv_invalid_scalar(self): # GH#18846 @@ -532,7 +532,7 @@ def test_mod_offset(self): # GH#19365 td = Timedelta(hours=37) - result = td % pd.offsets.Hour(5) + result = td % offsets.Hour(5) assert isinstance(result, Timedelta) assert result == Timedelta(hours=2) @@ -633,7 +633,7 @@ def test_divmod_offset(self): # GH#19365 td = Timedelta(days=2, hours=6) - result = divmod(td, pd.offsets.Hour(-4)) + result = divmod(td, offsets.Hour(-4)) assert result[0] == -14 assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(hours=-2) @@ -653,7 +653,7 @@ def test_rdivmod_pytimedelta(self): assert result[1] == Timedelta(hours=6) def test_rdivmod_offset(self): - result = divmod(pd.offsets.Hour(54), Timedelta(hours=-4)) + result = divmod(offsets.Hour(54), Timedelta(hours=-4)) assert result[0] == -14 assert isinstance(result[1], Timedelta) assert result[1] == Timedelta(hours=-2) diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index e4980be49d35f..9bb6c991a930a 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -5,7 +5,7 @@ import numpy as np import pytest -from pandas._libs.tslibs import NaT, iNaT +from pandas._libs.tslibs import NaT, Timestamp, iNaT import pandas as pd from pandas import Series, Timedelta, TimedeltaIndex, timedelta_range, to_timedelta @@ -15,17 +15,17 @@ class TestTimedeltaArithmetic: def test_arithmetic_overflow(self): with pytest.raises(OverflowError): - pd.Timestamp("1700-01-01") + pd.Timedelta(13 * 19999, unit="D") + Timestamp("1700-01-01") + Timedelta(13 * 19999, unit="D") with pytest.raises(OverflowError): - pd.Timestamp("1700-01-01") + timedelta(days=13 * 19999) + Timestamp("1700-01-01") + timedelta(days=13 * 19999) def test_array_timedelta_floordiv(self): # https://github.com/pandas-dev/pandas/issues/19761 ints = pd.date_range("2012-10-08", periods=4, freq="D").view("i8") msg = r"Use 'array // timedelta.value'" with tm.assert_produces_warning(FutureWarning) as m: - result = ints // pd.Timedelta(1, unit="s") + result = ints // Timedelta(1, unit="s") assert msg in str(m[0].message) expected = np.array( @@ -283,7 +283,7 @@ def check(value): rng.milliseconds # components - tup = pd.to_timedelta(-1, "us").components + tup = to_timedelta(-1, "us").components assert tup.days == -1 assert tup.hours == 23 assert tup.minutes == 59 @@ -512,7 +512,7 @@ def test_round(self): t1 = timedelta_range("1 days", periods=3, freq="1 min 2 s 3 us") t2 = -1 * t1 t1a = timedelta_range("1 days", periods=3, freq="1 min 2 s") - t1c = pd.TimedeltaIndex([1, 1, 1], unit="D") + t1c = TimedeltaIndex([1, 1, 1], unit="D") # note that negative times round DOWN! so don't give whole numbers for (freq, s1, s2) in [ @@ -554,7 +554,7 @@ def test_round(self): freq=None, ), ), - ("d", t1c, pd.TimedeltaIndex([-1, -1, -1], unit="D")), + ("d", t1c, TimedeltaIndex([-1, -1, -1], unit="D")), ]: r1 = t1.round(freq) @@ -575,11 +575,11 @@ def test_contains(self): # Checking for any NaT-like objects # GH 13603 td = to_timedelta(range(5), unit="d") + pd.offsets.Hour(1) - for v in [pd.NaT, None, float("nan"), np.nan]: + for v in [NaT, None, float("nan"), np.nan]: assert not (v in td) - td = to_timedelta([pd.NaT]) - for v in [pd.NaT, None, float("nan"), np.nan]: + td = to_timedelta([NaT]) + for v in [NaT, None, float("nan"), np.nan]: assert v in td def test_identity(self): @@ -668,11 +668,11 @@ def conv(v): def test_overflow(self): # GH 9442 s = Series(pd.date_range("20130101", periods=100000, freq="H")) - s[0] += pd.Timedelta("1s 1ms") + s[0] += Timedelta("1s 1ms") # mean result = (s - s.min()).mean() - expected = pd.Timedelta((pd.TimedeltaIndex((s - s.min())).asi8 / len(s)).sum()) + expected = Timedelta((TimedeltaIndex((s - s.min())).asi8 / len(s)).sum()) # the computation is converted to float so # might be some loss of precision @@ -748,41 +748,41 @@ def test_total_seconds_precision(self): assert (30.0 - Timedelta("30S").total_seconds()) < 1e-20 def test_timedelta_arithmetic(self): - data = pd.Series(["nat", "32 days"], dtype="timedelta64[ns]") + data = Series(["nat", "32 days"], dtype="timedelta64[ns]") deltas = [timedelta(days=1), Timedelta(1, unit="D")] for delta in deltas: result_method = data.add(delta) result_operator = data + delta - expected = pd.Series(["nat", "33 days"], dtype="timedelta64[ns]") + expected = Series(["nat", "33 days"], dtype="timedelta64[ns]") tm.assert_series_equal(result_operator, expected) tm.assert_series_equal(result_method, expected) result_method = data.sub(delta) result_operator = data - delta - expected = pd.Series(["nat", "31 days"], dtype="timedelta64[ns]") + expected = Series(["nat", "31 days"], dtype="timedelta64[ns]") tm.assert_series_equal(result_operator, expected) tm.assert_series_equal(result_method, expected) # GH 9396 result_method = data.div(delta) result_operator = data / delta - expected = pd.Series([np.nan, 32.0], dtype="float64") + expected = Series([np.nan, 32.0], dtype="float64") tm.assert_series_equal(result_operator, expected) tm.assert_series_equal(result_method, expected) def test_apply_to_timedelta(self): - timedelta_NaT = pd.to_timedelta("NaT") + timedelta_NaT = to_timedelta("NaT") list_of_valid_strings = ["00:00:01", "00:00:02"] - a = pd.to_timedelta(list_of_valid_strings) - b = Series(list_of_valid_strings).apply(pd.to_timedelta) + a = to_timedelta(list_of_valid_strings) + b = Series(list_of_valid_strings).apply(to_timedelta) # Can't compare until apply on a Series gives the correct dtype # assert_series_equal(a, b) - list_of_strings = ["00:00:01", np.nan, pd.NaT, timedelta_NaT] + list_of_strings = ["00:00:01", np.nan, NaT, timedelta_NaT] # TODO: unused? - a = pd.to_timedelta(list_of_strings) # noqa - b = Series(list_of_strings).apply(pd.to_timedelta) # noqa + a = to_timedelta(list_of_strings) # noqa + b = Series(list_of_strings).apply(to_timedelta) # noqa # Can't compare until apply on a Series gives the correct dtype # assert_series_equal(a, b) @@ -824,7 +824,7 @@ def test_resolution_deprecated(self): (Timedelta(0, unit="ns"), False), (Timedelta(-10, unit="ns"), True), (Timedelta(None), True), - (pd.NaT, True), + (NaT, True), ], ) def test_truthiness(value, expected): diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py index a05de78e299f7..351f0f9ad3b5b 100644 --- a/pandas/tests/tseries/offsets/test_offsets_properties.py +++ b/pandas/tests/tseries/offsets/test_offsets_properties.py @@ -15,6 +15,7 @@ import pytest import pandas as pd +from pandas import Timestamp from pandas.tseries.offsets import ( BMonthBegin, @@ -36,15 +37,15 @@ with warnings.catch_warnings(): warnings.simplefilter("ignore") - min_dt = pd.Timestamp(1900, 1, 1).to_pydatetime() - max_dt = pd.Timestamp(1900, 1, 1).to_pydatetime() + min_dt = Timestamp(1900, 1, 1).to_pydatetime() + max_dt = Timestamp(1900, 1, 1).to_pydatetime() gen_date_range = st.builds( pd.date_range, start=st.datetimes( # TODO: Choose the min/max values more systematically - min_value=pd.Timestamp(1900, 1, 1).to_pydatetime(), - max_value=pd.Timestamp(2100, 1, 1).to_pydatetime(), + min_value=Timestamp(1900, 1, 1).to_pydatetime(), + max_value=Timestamp(2100, 1, 1).to_pydatetime(), ), periods=st.integers(min_value=2, max_value=100), freq=st.sampled_from("Y Q M D H T s ms us ns".split()), diff --git a/pandas/tests/tslibs/test_timedeltas.py b/pandas/tests/tslibs/test_timedeltas.py index d4bd7c2d5486c..86d5cc749b5e1 100644 --- a/pandas/tests/tslibs/test_timedeltas.py +++ b/pandas/tests/tslibs/test_timedeltas.py @@ -3,8 +3,7 @@ from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds -import pandas as pd -from pandas import Timedelta +from pandas import Timedelta, offsets @pytest.mark.parametrize( @@ -13,7 +12,7 @@ (np.timedelta64(14, "D"), 14 * 24 * 3600 * 1e9), (Timedelta(minutes=-7), -7 * 60 * 1e9), (Timedelta(minutes=-7).to_pytimedelta(), -7 * 60 * 1e9), - (pd.offsets.Nano(125), 125), + (offsets.Nano(125), 125), (1, 1), (np.int64(2), 2), (np.int32(3), 3),
Medium-term goal is to separate out tslibs-only parts of these tests to make sure we have sufficient coverage in isolation.
https://api.github.com/repos/pandas-dev/pandas/pulls/29275
2019-10-29T22:12:31Z
2019-10-31T14:24:03Z
2019-10-31T14:24:03Z
2019-10-31T14:43:40Z
CLN: Consistent pandas.util.testing imports in pandas/tests/series
diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index c8e1c04f3e3fb..457c976137c11 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -22,12 +22,6 @@ from pandas.core.indexes.datetimes import Timestamp from pandas.core.indexes.timedeltas import TimedeltaIndex import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_index_equal, - assert_series_equal, -) class TestSeriesAnalytics: @@ -108,11 +102,11 @@ def test_argsort(self, datetime_series): result = s.argsort() expected = Series(range(5), dtype="int64") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = shifted.argsort() expected = Series(list(range(4)) + [-1], dtype="int64") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_argsort_stable(self): s = Series(np.random.randint(0, 100, size=10000)) @@ -248,7 +242,7 @@ def test_np_diff(self): s = Series(np.arange(5)) r = np.diff(s) - assert_series_equal(Series([np.nan, 0, 0, 0, np.nan]), r) + tm.assert_series_equal(Series([np.nan, 0, 0, 0, np.nan]), r) def test_int_diff(self): # int dtype @@ -267,23 +261,23 @@ def test_tz_diff(self): # neg n result = ts.diff(-1) expected = ts - ts.shift(-1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # 0 result = ts.diff(0) expected = ts - ts - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # datetime diff (GH3100) s = Series(date_range("20130102", periods=5)) result = s.diff() expected = s - s.shift(1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # timedelta diff result = result - result.shift(1) # previous result expected = expected.diff() # previously expected - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # with tz s = Series( @@ -291,7 +285,7 @@ def test_tz_diff(self): ) result = s.diff() expected = Series(TimedeltaIndex(["NaT"] + ["1 days"] * 4), name="foo") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "input,output,diff", @@ -302,14 +296,14 @@ def test_bool_diff(self, input, output, diff): s = Series(input) result = s.diff() expected = Series(output) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_obj_diff(self): # object series s = Series([False, True, 5.0, np.nan, True, False]) result = s.diff() expected = s - s.shift(1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def _check_accum_op(self, name, datetime_series_, check_dtype=True): func = getattr(np, name) @@ -358,7 +352,7 @@ def test_round(self, datetime_series): expected = Series( np.round(datetime_series.values, 2), index=datetime_series.index, name="ts" ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) assert result.name == datetime_series.name def test_numpy_round(self): @@ -366,7 +360,7 @@ def test_numpy_round(self): s = Series([1.53, 1.36, 0.06]) out = np.round(s, decimals=0) expected = Series([2.0, 1.0, 0.0]) - assert_series_equal(out, expected) + tm.assert_series_equal(out, expected) msg = "the 'out' parameter is not supported" with pytest.raises(ValueError, match=msg): @@ -378,7 +372,7 @@ def test_numpy_round_nan(self): with tm.assert_produces_warning(None): result = s.round() expected = Series([2.0, np.nan, 0.0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_built_in_round(self): s = Series([1.123, 2.123, 3.123], index=range(3)) @@ -555,10 +549,10 @@ def test_count(self, datetime_series): left = ts.count(level=1) right = Series([2, 3, 1], index=[1, 2, np.nan]) - assert_series_equal(left, right) + tm.assert_series_equal(left, right) ts.iloc[[0, 3, 5]] = np.nan - assert_series_equal(ts.count(level=1), right - 1) + tm.assert_series_equal(ts.count(level=1), right - 1) def test_dot(self): a = Series(np.random.randn(4), index=["p", "q", "r", "s"]) @@ -568,21 +562,21 @@ def test_dot(self): result = a.dot(b) expected = Series(np.dot(a.values, b.values), index=["1", "2", "3"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Check index alignment b2 = b.reindex(index=reversed(b.index)) result = a.dot(b) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Check ndarray argument result = a.dot(b.values) assert np.all(result == expected.values) - assert_almost_equal(a.dot(b["2"].values), expected["2"]) + tm.assert_almost_equal(a.dot(b["2"].values), expected["2"]) # Check series argument - assert_almost_equal(a.dot(b["1"]), expected["1"]) - assert_almost_equal(a.dot(b2["1"]), expected["1"]) + tm.assert_almost_equal(a.dot(b["1"]), expected["1"]) + tm.assert_almost_equal(a.dot(b2["1"]), expected["1"]) msg = r"Dot product shape mismatch, \(4,\) vs \(3,\)" # exception raised is of type Exception @@ -602,53 +596,53 @@ def test_matmul(self): # Series @ DataFrame -> Series result = operator.matmul(a, b) expected = Series(np.dot(a.values, b.values), index=["1", "2", "3"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # DataFrame @ Series -> Series result = operator.matmul(b.T, a) expected = Series(np.dot(b.T.values, a.T.values), index=["1", "2", "3"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Series @ Series -> scalar result = operator.matmul(a, a) expected = np.dot(a.values, a.values) - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) # GH 21530 # vector (1D np.array) @ Series (__rmatmul__) result = operator.matmul(a.values, a) expected = np.dot(a.values, a.values) - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) # GH 21530 # vector (1D list) @ Series (__rmatmul__) result = operator.matmul(a.values.tolist(), a) expected = np.dot(a.values, a.values) - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) # GH 21530 # matrix (2D np.array) @ Series (__rmatmul__) result = operator.matmul(b.T.values, a) expected = np.dot(b.T.values, a.values) - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) # GH 21530 # matrix (2D nested lists) @ Series (__rmatmul__) result = operator.matmul(b.T.values.tolist(), a) expected = np.dot(b.T.values, a.values) - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) # mixed dtype DataFrame @ Series a["p"] = int(a.p) result = operator.matmul(b.T, a) expected = Series(np.dot(b.T.values, a.T.values), index=["1", "2", "3"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # different dtypes DataFrame @ Series a = a.astype(int) result = operator.matmul(b.T, a) expected = Series(np.dot(b.T.values, a.T.values), index=["1", "2", "3"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) msg = r"Dot product shape mismatch, \(4,\) vs \(3,\)" # exception raised is of type Exception @@ -671,7 +665,7 @@ def test_clip(self, datetime_series): result = datetime_series.clip(-0.5, 0.5) expected = np.clip(datetime_series, -0.5, 0.5) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) assert isinstance(expected, Series) def test_clip_types_and_nulls(self): @@ -698,12 +692,12 @@ def test_clip_with_na_args(self): # GH # 17276 s = Series([1, 2, 3]) - assert_series_equal(s.clip(np.nan), Series([1, 2, 3])) - assert_series_equal(s.clip(upper=np.nan, lower=np.nan), Series([1, 2, 3])) + tm.assert_series_equal(s.clip(np.nan), Series([1, 2, 3])) + tm.assert_series_equal(s.clip(upper=np.nan, lower=np.nan), Series([1, 2, 3])) # GH #19992 - assert_series_equal(s.clip(lower=[0, 4, np.nan]), Series([1, 4, np.nan])) - assert_series_equal(s.clip(upper=[1, np.nan, 1]), Series([1, np.nan, 1])) + tm.assert_series_equal(s.clip(lower=[0, 4, np.nan]), Series([1, 4, np.nan])) + tm.assert_series_equal(s.clip(upper=[1, np.nan, 1]), Series([1, np.nan, 1])) def test_clip_against_series(self): # GH #6966 @@ -712,15 +706,15 @@ def test_clip_against_series(self): threshold = Series([1.0, 2.0, 3.0]) with tm.assert_produces_warning(FutureWarning): - assert_series_equal(s.clip_lower(threshold), Series([1.0, 2.0, 4.0])) + tm.assert_series_equal(s.clip_lower(threshold), Series([1.0, 2.0, 4.0])) with tm.assert_produces_warning(FutureWarning): - assert_series_equal(s.clip_upper(threshold), Series([1.0, 1.0, 3.0])) + tm.assert_series_equal(s.clip_upper(threshold), Series([1.0, 1.0, 3.0])) lower = Series([1.0, 2.0, 3.0]) upper = Series([1.5, 2.5, 3.5]) - assert_series_equal(s.clip(lower, upper), Series([1.0, 2.0, 3.5])) - assert_series_equal(s.clip(1.5, upper), Series([1.5, 1.5, 3.5])) + tm.assert_series_equal(s.clip(lower, upper), Series([1.0, 2.0, 3.5])) + tm.assert_series_equal(s.clip(1.5, upper), Series([1.5, 1.5, 3.5])) @pytest.mark.parametrize("inplace", [True, False]) @pytest.mark.parametrize("upper", [[1, 2, 3], np.asarray([1, 2, 3])]) @@ -745,7 +739,7 @@ def test_clip_with_datetimes(self): expected = Series( [Timestamp("2015-12-01 09:30:00"), Timestamp("2015-12-01 09:30:30")] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) t = Timestamp("2015-12-01 09:30:30", tz="US/Eastern") s = Series( @@ -761,7 +755,7 @@ def test_clip_with_datetimes(self): Timestamp("2015-12-01 09:30:30", tz="US/Eastern"), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_cummethods_bool(self): # GH 6270 @@ -780,7 +774,7 @@ def test_cummethods_bool(self): for s, method in args: expected = Series(methods[method](s.values)) result = getattr(s, method)() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) e = pd.Series([False, True, np.nan, False]) cse = pd.Series([0, 1, np.nan, 1], dtype=object) @@ -791,14 +785,14 @@ def test_cummethods_bool(self): for method in methods: res = getattr(e, method)() - assert_series_equal(res, expecteds[method]) + tm.assert_series_equal(res, expecteds[method]) def test_isin(self): s = Series(["A", "B", "C", "a", "B", "B", "A", "C"]) result = s.isin(["A", "C"]) expected = Series([True, False, True, False, False, False, True, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH: 16012 # This specific issue has to have a series over 1e6 in len, but the @@ -835,28 +829,28 @@ def test_isin_with_i8(self): s = Series(date_range("jan-01-2013", "jan-05-2013")) result = s.isin(s[0:2]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.isin(s[0:2].values) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # fails on dtype conversion in the first place result = s.isin(s[0:2].values.astype("datetime64[D]")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.isin([s[1]]) - assert_series_equal(result, expected2) + tm.assert_series_equal(result, expected2) result = s.isin([np.datetime64(s[1])]) - assert_series_equal(result, expected2) + tm.assert_series_equal(result, expected2) result = s.isin(set(s[0:2])) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # timedelta64[ns] s = Series(pd.to_timedelta(range(5), unit="d")) result = s.isin(s[0:2]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("empty", [[], Series(), np.array([])]) def test_isin_empty(self, empty): @@ -913,17 +907,17 @@ def test_repeat(self): reps = s.repeat(5) exp = Series(s.values.repeat(5), index=s.index.values.repeat(5)) - assert_series_equal(reps, exp) + tm.assert_series_equal(reps, exp) to_rep = [2, 3, 4] reps = s.repeat(to_rep) exp = Series(s.values.repeat(to_rep), index=s.index.values.repeat(to_rep)) - assert_series_equal(reps, exp) + tm.assert_series_equal(reps, exp) def test_numpy_repeat(self): s = Series(np.arange(3), name="x") expected = Series(s.values.repeat(2), name="x", index=s.index.values.repeat(2)) - assert_series_equal(np.repeat(s, 2), expected) + tm.assert_series_equal(np.repeat(s, 2), expected) msg = "the 'axis' parameter is not supported" with pytest.raises(ValueError, match=msg): @@ -1000,16 +994,16 @@ def test_sort_index_level(self): backwards = s.iloc[[1, 0]] res = s.sort_index(level="A") - assert_series_equal(backwards, res) + tm.assert_series_equal(backwards, res) res = s.sort_index(level=["A", "B"]) - assert_series_equal(backwards, res) + tm.assert_series_equal(backwards, res) res = s.sort_index(level="A", sort_remaining=False) - assert_series_equal(s, res) + tm.assert_series_equal(s, res) res = s.sort_index(level=["A", "B"], sort_remaining=False) - assert_series_equal(s, res) + tm.assert_series_equal(s, res) def test_apply_categorical(self): values = pd.Categorical(list("ABBABCD"), categories=list("DCBA"), ordered=True) @@ -1032,26 +1026,26 @@ def test_shift_int(self, datetime_series): ts = datetime_series.astype(int) shifted = ts.shift(1) expected = ts.astype(float).shift(1) - assert_series_equal(shifted, expected) + tm.assert_series_equal(shifted, expected) def test_shift_categorical(self): # GH 9416 s = pd.Series(["a", "b", "c", "d"], dtype="category") - assert_series_equal(s.iloc[:-1], s.shift(1).shift(-1).dropna()) + tm.assert_series_equal(s.iloc[:-1], s.shift(1).shift(-1).dropna()) sp1 = s.shift(1) - assert_index_equal(s.index, sp1.index) + tm.assert_index_equal(s.index, sp1.index) assert np.all(sp1.values.codes[:1] == -1) assert np.all(s.values.codes[:-1] == sp1.values.codes[1:]) sn2 = s.shift(-2) - assert_index_equal(s.index, sn2.index) + tm.assert_index_equal(s.index, sn2.index) assert np.all(sn2.values.codes[-2:] == -1) assert np.all(s.values.codes[2:] == sn2.values.codes[:-2]) - assert_index_equal(s.values.categories, sp1.values.categories) - assert_index_equal(s.values.categories, sn2.values.categories) + tm.assert_index_equal(s.values.categories, sp1.values.categories) + tm.assert_index_equal(s.values.categories, sn2.values.categories) def test_unstack(self): @@ -1069,10 +1063,10 @@ def test_unstack(self): columns=["one", "three", "two"], ) - assert_frame_equal(unstacked, expected) + tm.assert_frame_equal(unstacked, expected) unstacked = s.unstack(level=0) - assert_frame_equal(unstacked, expected.T) + tm.assert_frame_equal(unstacked, expected.T) index = MultiIndex( levels=[["bar"], ["one", "two", "three"], [0, 1]], @@ -1085,7 +1079,7 @@ def test_unstack(self): ) expected = DataFrame({"bar": s.values}, index=exp_index).sort_index(level=0) unstacked = s.unstack(0).sort_index() - assert_frame_equal(unstacked, expected) + tm.assert_frame_equal(unstacked, expected) # GH5873 idx = pd.MultiIndex.from_arrays([[101, 102], [3.5, np.nan]]) @@ -1094,7 +1088,7 @@ def test_unstack(self): right = DataFrame( [[np.nan, 1], [2, np.nan]], index=[101, 102], columns=[np.nan, 3.5] ) - assert_frame_equal(left, right) + tm.assert_frame_equal(left, right) idx = pd.MultiIndex.from_arrays( [ @@ -1110,7 +1104,7 @@ def test_unstack(self): ) tpls = [("a", 1), ("a", 2), ("b", np.nan), ("b", 1)] right.index = pd.MultiIndex.from_tuples(tpls) - assert_frame_equal(ts.unstack(level=0), right) + tm.assert_frame_equal(ts.unstack(level=0), right) def test_value_counts_datetime(self): # most dtypes are tested in test_base.py @@ -1381,25 +1375,25 @@ def test_nsmallest_nlargest(self, s_main_dtypes_split): # object that are numbers, object that are strings s = s_main_dtypes_split - assert_series_equal(s.nsmallest(2), s.iloc[[2, 1]]) - assert_series_equal(s.nsmallest(2, keep="last"), s.iloc[[2, 3]]) + tm.assert_series_equal(s.nsmallest(2), s.iloc[[2, 1]]) + tm.assert_series_equal(s.nsmallest(2, keep="last"), s.iloc[[2, 3]]) empty = s.iloc[0:0] - assert_series_equal(s.nsmallest(0), empty) - assert_series_equal(s.nsmallest(-1), empty) - assert_series_equal(s.nlargest(0), empty) - assert_series_equal(s.nlargest(-1), empty) + tm.assert_series_equal(s.nsmallest(0), empty) + tm.assert_series_equal(s.nsmallest(-1), empty) + tm.assert_series_equal(s.nlargest(0), empty) + tm.assert_series_equal(s.nlargest(-1), empty) - assert_series_equal(s.nsmallest(len(s)), s.sort_values()) - assert_series_equal(s.nsmallest(len(s) + 1), s.sort_values()) - assert_series_equal(s.nlargest(len(s)), s.iloc[[4, 0, 1, 3, 2]]) - assert_series_equal(s.nlargest(len(s) + 1), s.iloc[[4, 0, 1, 3, 2]]) + tm.assert_series_equal(s.nsmallest(len(s)), s.sort_values()) + tm.assert_series_equal(s.nsmallest(len(s) + 1), s.sort_values()) + tm.assert_series_equal(s.nlargest(len(s)), s.iloc[[4, 0, 1, 3, 2]]) + tm.assert_series_equal(s.nlargest(len(s) + 1), s.iloc[[4, 0, 1, 3, 2]]) def test_misc(self): s = Series([3.0, np.nan, 1, 2, 5]) - assert_series_equal(s.nlargest(), s.iloc[[4, 0, 3, 2]]) - assert_series_equal(s.nsmallest(), s.iloc[[2, 3, 0, 4]]) + tm.assert_series_equal(s.nlargest(), s.iloc[[4, 0, 3, 2]]) + tm.assert_series_equal(s.nsmallest(), s.iloc[[2, 3, 0, 4]]) msg = 'keep must be either "first", "last"' with pytest.raises(ValueError, match=msg): @@ -1413,16 +1407,16 @@ def test_misc(self): expected_last = Series([1] * 3, index=[5, 4, 3]) result = s.nsmallest(3) - assert_series_equal(result, expected_first) + tm.assert_series_equal(result, expected_first) result = s.nsmallest(3, keep="last") - assert_series_equal(result, expected_last) + tm.assert_series_equal(result, expected_last) result = s.nlargest(3) - assert_series_equal(result, expected_first) + tm.assert_series_equal(result, expected_first) result = s.nlargest(3, keep="last") - assert_series_equal(result, expected_last) + tm.assert_series_equal(result, expected_last) @pytest.mark.parametrize("n", range(1, 5)) def test_n(self, n): @@ -1431,11 +1425,11 @@ def test_n(self, n): s = Series([1, 4, 3, 2], index=[0, 0, 1, 1]) result = s.nlargest(n) expected = s.sort_values(ascending=False).head(n) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.nsmallest(n) expected = s.sort_values().head(n) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_boundary_integer(self, nselect_method, any_int_dtype): # GH 21426 @@ -1467,11 +1461,11 @@ def test_duplicate_keep_all_ties(self): s = Series([10, 9, 8, 7, 7, 7, 7, 6]) result = s.nlargest(4, keep="all") expected = Series([10, 9, 8, 7, 7, 7, 7]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.nsmallest(2, keep="all") expected = Series([6, 7, 7, 7, 7], index=[7, 3, 4, 5, 6]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "data,expected", [([True, False], [True]), ([True, False, True, True], [True])] @@ -1481,7 +1475,7 @@ def test_boolean(self, data, expected): s = Series(data) result = s.nlargest(1) expected = Series(expected) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) class TestCategoricalSeriesAnalytics: diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index f2435e8c804db..656bf5a0e8a44 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -20,7 +20,6 @@ from pandas.core.arrays import PeriodArray from pandas.core.indexes.datetimes import Timestamp import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal, ensure_clean import pandas.io.formats.printing as printing @@ -110,15 +109,15 @@ def test_getitem_preserve_name(self, datetime_series): def test_pickle_datetimes(self, datetime_series): unp_ts = self._pickle_roundtrip(datetime_series) - assert_series_equal(unp_ts, datetime_series) + tm.assert_series_equal(unp_ts, datetime_series) def test_pickle_strings(self, string_series): unp_series = self._pickle_roundtrip(string_series) - assert_series_equal(unp_series, string_series) + tm.assert_series_equal(unp_series, string_series) def _pickle_roundtrip(self, obj): - with ensure_clean() as path: + with tm.ensure_clean() as path: obj.to_pickle(path) unpickled = pd.read_pickle(path) return unpickled @@ -399,16 +398,16 @@ def test_copy_tzaware(self): # default deep is True if deep is None or deep is True: # Did not modify original Series - assert_series_equal(s2, expected2) - assert_series_equal(s, expected) + tm.assert_series_equal(s2, expected2) + tm.assert_series_equal(s, expected) else: # we DID modify the original Series - assert_series_equal(s2, expected2) - assert_series_equal(s, expected2) + tm.assert_series_equal(s2, expected2) + tm.assert_series_equal(s, expected2) def test_axis_alias(self): s = Series([1, 2, np.nan]) - assert_series_equal(s.dropna(axis="rows"), s.dropna(axis="index")) + tm.assert_series_equal(s.dropna(axis="rows"), s.dropna(axis="index")) assert s.dropna().sum("rows") == 3 assert s._get_axis_number("rows") == 0 assert s._get_axis_name("rows") == "index" @@ -490,7 +489,7 @@ def test_str_attribute(self): s = Series([" jack", "jill ", " jesse ", "frank"]) for method in methods: expected = Series([getattr(str, method)(x) for x in s.values]) - assert_series_equal(getattr(Series.str, method)(s.str), expected) + tm.assert_series_equal(getattr(Series.str, method)(s.str), expected) # str accessor only valid with string values s = Series(range(5)) diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index 65a0822bbc55f..e56294669a546 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -8,7 +8,6 @@ from pandas import DataFrame, Index, Series, isna from pandas.conftest import _get_cython_table_params import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal class TestSeriesApply: @@ -47,12 +46,12 @@ def test_apply_same_length_inference_bug(self): result = s.apply(f) expected = s.map(f) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([1, 2, 3]) result = s.apply(f) expected = s.map(f) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_apply_dont_convert_dtype(self): s = Series(np.random.randn(10)) @@ -184,22 +183,22 @@ def test_transform(self, string_series): # ufunc result = string_series.transform(np.sqrt) expected = f_sqrt.copy() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = string_series.apply(np.sqrt) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # list-like result = string_series.transform([np.sqrt]) expected = f_sqrt.to_frame().copy() expected.columns = ["sqrt"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = string_series.transform([np.sqrt]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = string_series.transform(["sqrt"]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # multiple items in list # these are in the order as if we are applying both functions per @@ -207,11 +206,11 @@ def test_transform(self, string_series): expected = pd.concat([f_sqrt, f_abs], axis=1) expected.columns = ["sqrt", "absolute"] result = string_series.apply([np.sqrt, np.abs]) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) result = string_series.transform(["sqrt", "abs"]) expected.columns = ["sqrt", "abs"] - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) # dict, provide renaming expected = pd.concat([f_sqrt, f_abs], axis=1) @@ -219,7 +218,7 @@ def test_transform(self, string_series): expected = expected.unstack().rename("series") result = string_series.apply({"foo": np.sqrt, "bar": np.abs}) - assert_series_equal(result.reindex_like(expected), expected) + tm.assert_series_equal(result.reindex_like(expected), expected) def test_transform_and_agg_error(self, string_series): # we are trying to transform with an aggregator @@ -317,7 +316,7 @@ def test_replicate_describe(self, string_series): ] ) ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_reduce(self, string_series): # reductions with named functions @@ -327,7 +326,7 @@ def test_reduce(self, string_series): ["sum", "mean"], name=string_series.name, ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_non_callable_aggregates(self): # test agg using non-callable series attributes @@ -341,7 +340,7 @@ def test_non_callable_aggregates(self): # test when mixed w/ callable reducers result = s.agg(["size", "count", "mean"]) expected = Series(OrderedDict([("size", 3.0), ("count", 2.0), ("mean", 1.5)])) - assert_series_equal(result[expected.index], expected) + tm.assert_series_equal(result[expected.index], expected) @pytest.mark.parametrize( "series, func, expected", @@ -516,7 +515,7 @@ def test_map_compat(self): s = Series([True, True, False], index=[1, 2, 3]) result = s.map({True: "foo", False: "bar"}) expected = Series(["foo", "foo", "bar"], index=[1, 2, 3]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_map_int(self): left = Series({"a": 1.0, "b": 2.0, "c": 3.0, "d": 4}) @@ -547,7 +546,7 @@ def test_map_na_exclusion(self): result = s.map(lambda x: x * 2, na_action="ignore") exp = s * 2 - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_map_dict_with_tuple_keys(self): """ @@ -572,7 +571,7 @@ def test_map_counter(self): counter["c"] += 1 result = s.map(counter) expected = Series([0, 5, 1], index=[1, 2, 3]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_map_defaultdict(self): s = Series([1, 2, 3], index=["a", "b", "c"]) @@ -580,7 +579,7 @@ def test_map_defaultdict(self): default_dict[1] = "stuff" result = s.map(default_dict) expected = Series(["stuff", "blank", "blank"], index=["a", "b", "c"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_map_dict_subclass_with_missing(self): """ @@ -596,7 +595,7 @@ def __missing__(self, key): dictionary = DictWithMissing({3: "three"}) result = s.map(dictionary) expected = Series(["missing", "missing", "three"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_map_dict_subclass_without_missing(self): class DictWithoutMissing(dict): @@ -606,7 +605,7 @@ class DictWithoutMissing(dict): dictionary = DictWithoutMissing({3: "three"}) result = s.map(dictionary) expected = Series([np.nan, np.nan, "three"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_map_box(self): vals = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")] @@ -729,11 +728,11 @@ def test_apply_series_on_date_time_index_aware_series(self, dti, exp): # Calling apply on a localized time series should not cause an error index = dti.tz_localize("UTC").index result = pd.Series(index).apply(lambda x: pd.Series([1, 2])) - assert_frame_equal(result, exp) + tm.assert_frame_equal(result, exp) def test_apply_scaler_on_date_time_index_aware_series(self): # GH 25959 # Calling apply on a localized time series should not cause an error series = tm.makeTimeSeries(nper=30).tz_localize("UTC") result = pd.Series(series.index).apply(lambda x: 1) - assert_series_equal(result, pd.Series(np.ones(30), dtype="int64")) + tm.assert_series_equal(result, pd.Series(np.ones(30), dtype="int64")) diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py index 78d666720c091..b2ecd7c4997f1 100644 --- a/pandas/tests/series/test_combine_concat.py +++ b/pandas/tests/series/test_combine_concat.py @@ -6,7 +6,6 @@ import pandas as pd from pandas import DataFrame, DatetimeIndex, Series, date_range import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal class TestSeriesCombine: @@ -28,7 +27,7 @@ def test_append_many(self, datetime_series): pieces = [datetime_series[:5], datetime_series[5:10], datetime_series[10:]] result = pieces[0].append(pieces[1:]) - assert_series_equal(result, datetime_series) + tm.assert_series_equal(result, datetime_series) def test_append_duplicates(self): # GH 13677 @@ -110,7 +109,7 @@ def test_combine_first(self): s = Series([1.0, 2, 3], index=[0, 1, 2]) result = s.combine_first(Series([], index=[])) s.index = s.index.astype("O") - assert_series_equal(s, result) + tm.assert_series_equal(s, result) def test_update(self): s = Series([1.5, np.nan, 3.0, 4.0, np.nan]) @@ -118,7 +117,7 @@ def test_update(self): s.update(s2) expected = Series([1.5, 3.5, 3.0, 5.0, np.nan]) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # GH 3217 df = DataFrame([{"a": 1}, {"a": 3, "b": 2}]) @@ -128,7 +127,7 @@ def test_update(self): expected = DataFrame( [[1, np.nan, "foo"], [3, 2.0, np.nan]], columns=["a", "b", "c"] ) - assert_frame_equal(df, expected) + tm.assert_frame_equal(df, expected) @pytest.mark.parametrize( "other, dtype, expected", @@ -161,7 +160,7 @@ def test_update_dtypes(self, other, dtype, expected): other = Series(other, index=[1, 3]) s.update(other) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_concat_empty_series_dtypes_roundtrips(self): @@ -226,7 +225,7 @@ def test_combine_first_dt_tz_values(self, tz_naive_fixture): tz=tz_naive_fixture, ) exp = pd.Series(exp_vals, name="ser1") - assert_series_equal(exp, result) + tm.assert_series_equal(exp, result) def test_concat_empty_series_dtypes(self): @@ -324,13 +323,13 @@ def test_combine_first_dt64(self): s1 = to_datetime(Series([np.NaN, "2011"])) rs = s0.combine_first(s1) xp = to_datetime(Series(["2010", "2011"])) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) s0 = to_datetime(Series(["2010", np.NaN])) s1 = Series([np.NaN, "2011"]) rs = s0.combine_first(s1) xp = Series([datetime(2010, 1, 1), "2011"]) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) class TestTimeseries: diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index ca14f0fd05869..fb2a8dde96e2b 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -29,7 +29,6 @@ ) from pandas.core.arrays import period_array import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal class TestSeriesConstructors: @@ -120,40 +119,40 @@ def test_constructor_empty(self, input_class): # these are Index() and RangeIndex() which don't compare type equal # but are just .equals - assert_series_equal(empty, empty2, check_index_type=False) + tm.assert_series_equal(empty, empty2, check_index_type=False) # With explicit dtype: empty = Series(dtype="float64") empty2 = Series(input_class(), dtype="float64") - assert_series_equal(empty, empty2, check_index_type=False) + tm.assert_series_equal(empty, empty2, check_index_type=False) # GH 18515 : with dtype=category: empty = Series(dtype="category") empty2 = Series(input_class(), dtype="category") - assert_series_equal(empty, empty2, check_index_type=False) + tm.assert_series_equal(empty, empty2, check_index_type=False) if input_class is not list: # With index: empty = Series(index=range(10)) empty2 = Series(input_class(), index=range(10)) - assert_series_equal(empty, empty2) + tm.assert_series_equal(empty, empty2) # With index and dtype float64: empty = Series(np.nan, index=range(10)) empty2 = Series(input_class(), index=range(10), dtype="float64") - assert_series_equal(empty, empty2) + tm.assert_series_equal(empty, empty2) # GH 19853 : with empty string, index and dtype str empty = Series("", dtype=str, index=range(3)) empty2 = Series("", index=range(3)) - assert_series_equal(empty, empty2) + tm.assert_series_equal(empty, empty2) @pytest.mark.parametrize("input_arg", [np.nan, float("nan")]) def test_constructor_nan(self, input_arg): empty = Series(dtype="float64", index=range(10)) empty2 = Series(input_arg, index=range(10)) - assert_series_equal(empty, empty2, check_index_type=False) + tm.assert_series_equal(empty, empty2, check_index_type=False) @pytest.mark.parametrize( "dtype", @@ -198,7 +197,7 @@ def test_constructor_series(self): s1 = Series([4, 7, -5, 3], index=index1) s2 = Series(s1, index=index2) - assert_series_equal(s2, s1.sort_index()) + tm.assert_series_equal(s2, s1.sort_index()) def test_constructor_iterable(self): # GH 21987 @@ -209,19 +208,19 @@ def __iter__(self): expected = Series(list(range(10)), dtype="int64") result = Series(Iter(), dtype="int64") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_sequence(self): # GH 21987 expected = Series(list(range(10)), dtype="int64") result = Series(range(10), dtype="int64") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_single_str(self): # GH 21987 expected = Series(["abc"]) result = Series("abc") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_list_like(self): @@ -231,7 +230,7 @@ def test_constructor_list_like(self): expected = Series([1, 2, 3], dtype="int64") for obj in [[1, 2, 3], (1, 2, 3), np.array([1, 2, 3], dtype="int64")]: result = Series(obj, index=[0, 1, 2]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("dtype", ["bool", "int32", "int64", "float64"]) def test_constructor_index_dtype(self, dtype): @@ -256,12 +255,12 @@ def test_constructor_list_str(self, input_vals, string_dtype): # when dtype is str, 'str', or 'U' result = Series(input_vals, dtype=string_dtype) expected = Series(input_vals).astype(string_dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_list_str_na(self, string_dtype): result = Series([1.0, 2.0, np.nan], dtype=string_dtype) expected = Series(["1.0", "2.0", np.nan], dtype=object) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) assert np.isnan(result[2]) def test_constructor_generator(self): @@ -269,12 +268,12 @@ def test_constructor_generator(self): result = Series(gen) exp = Series(range(10)) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) gen = (i for i in range(10)) result = Series(gen, index=range(10, 20)) exp.index = range(10, 20) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_constructor_map(self): # GH8909 @@ -282,12 +281,12 @@ def test_constructor_map(self): result = Series(m) exp = Series(range(10)) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) m = map(lambda x: x, range(10)) result = Series(m, index=range(10, 20)) exp.index = range(10, 20) - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_constructor_categorical(self): cat = pd.Categorical([0, 1, 2, 0, 1, 2], ["a", "b", "c"], fastpath=True) @@ -456,58 +455,58 @@ def test_constructor_maskedarray(self): data = ma.masked_all((3,), dtype=float) result = Series(data) expected = Series([np.nan, np.nan, np.nan]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[0] = 0.0 data[2] = 2.0 index = ["a", "b", "c"] result = Series(data, index=index) expected = Series([0.0, np.nan, 2.0], index=index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[1] = 1.0 result = Series(data, index=index) expected = Series([0.0, 1.0, 2.0], index=index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data = ma.masked_all((3,), dtype=int) result = Series(data) expected = Series([np.nan, np.nan, np.nan], dtype=float) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[0] = 0 data[2] = 2 index = ["a", "b", "c"] result = Series(data, index=index) expected = Series([0, np.nan, 2], index=index, dtype=float) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[1] = 1 result = Series(data, index=index) expected = Series([0, 1, 2], index=index, dtype=int) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data = ma.masked_all((3,), dtype=bool) result = Series(data) expected = Series([np.nan, np.nan, np.nan], dtype=object) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[0] = True data[2] = False index = ["a", "b", "c"] result = Series(data, index=index) expected = Series([True, np.nan, False], index=index, dtype=object) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[1] = True result = Series(data, index=index) expected = Series([True, True, False], index=index, dtype=bool) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data = ma.masked_all((3,), dtype="M8[ns]") result = Series(data) expected = Series([iNaT, iNaT, iNaT], dtype="M8[ns]") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[0] = datetime(2001, 1, 1) data[2] = datetime(2001, 1, 3) @@ -518,7 +517,7 @@ def test_constructor_maskedarray(self): index=index, dtype="M8[ns]", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) data[1] = datetime(2001, 1, 2) result = Series(data, index=index) @@ -527,7 +526,7 @@ def test_constructor_maskedarray(self): index=index, dtype="M8[ns]", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_maskedarray_hardened(self): # Check numpy masked arrays with hard masks -- from GH24574 @@ -643,7 +642,7 @@ def test_constructor_pass_none(self): # inference on the index s = Series(index=np.array([None])) expected = Series(index=Index([None])) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_constructor_pass_nan_nat(self): # GH 13467 @@ -683,7 +682,7 @@ def test_constructor_coerce_float_fail(self, any_int_dtype): def test_constructor_coerce_float_valid(self, float_dtype): s = Series([1, 2, 3.5], dtype=float_dtype) expected = Series([1, 2, 3.5]).astype(float_dtype) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_constructor_dtype_no_cast(self): # see gh-1572 @@ -815,7 +814,7 @@ def test_constructor_dtype_datetime64(self): for dtype in ["s", "D", "ms", "us", "ns"]: values1 = dates.view(np.ndarray).astype("M8[{0}]".format(dtype)) result = Series(values1, dates) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 13876 # coerce to non-ns to object properly @@ -823,7 +822,7 @@ def test_constructor_dtype_datetime64(self): for dtype in ["s", "D", "ms", "us", "ns"]: values1 = dates.view(np.ndarray).astype("M8[{0}]".format(dtype)) result = Series(values1, index=dates, dtype=object) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # leave datetime.date alone dates2 = np.array([d.date() for d in dates.to_pydatetime()], dtype=object) @@ -900,14 +899,14 @@ def test_constructor_with_datetime_tz(self): ) result = s[Series([True, True, False], index=s.index)] - assert_series_equal(result, s[0:2]) + tm.assert_series_equal(result, s[0:2]) result = s.iloc[0:1] - assert_series_equal(result, Series(dr[0:1])) + tm.assert_series_equal(result, Series(dr[0:1])) # concat result = pd.concat([s.iloc[0:1], s.iloc[1:]]) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) # short str assert "datetime64[ns, US/Eastern]" in str(s) @@ -946,7 +945,7 @@ def test_constructor_with_datetime_tz(self): # with all NaT s = Series(pd.NaT, index=[0, 1], dtype="datetime64[ns, US/Eastern]") expected = Series(pd.DatetimeIndex(["NaT", "NaT"], tz="US/Eastern")) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64]) @pytest.mark.parametrize("dtype", ["M8", "m8"]) @@ -967,7 +966,7 @@ def test_constructor_with_naive_string_and_datetimetz_dtype(self, arg): # GH 17415: With naive string result = Series([arg], dtype="datetime64[ns, CET]") expected = Series(pd.Timestamp(arg)).dt.tz_localize("CET") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_construction_interval(self): # construction from interval & array of intervals @@ -1020,13 +1019,13 @@ def test_constructor_periodindex(self): s = Series(pi) assert s.dtype == "Period[D]" expected = Series(pi.astype(object)) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_constructor_dict(self): d = {"a": 0.0, "b": 1.0, "c": 2.0} result = Series(d, index=["b", "c", "d", "a"]) expected = Series([1, 2, np.nan, 0], index=["b", "c", "d", "a"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) pidx = tm.makePeriodIndex(100) d = {pidx[0]: 0, pidx[1]: 1} @@ -1034,7 +1033,7 @@ def test_constructor_dict(self): expected = Series(np.nan, pidx) expected.iloc[0] = 0 expected.iloc[1] = 1 - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_dict_order(self): # GH19018 @@ -1054,7 +1053,7 @@ def test_constructor_dict_nan_key(self, value): d = {1: "a", value: "b", float("nan"): "c", 4: "d"} result = Series(d).sort_values() expected = Series(["a", "b", "c", "d"], index=[1, value, np.nan, 4]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # MultiIndex: d = {(1, 1): "a", (2, np.nan): "b", (3, value): "c"} @@ -1062,7 +1061,7 @@ def test_constructor_dict_nan_key(self, value): expected = Series( ["a", "b", "c"], index=Index([(1, 1), (2, np.nan), (3, value)]) ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_dict_datetime64_index(self): # GH 9456 @@ -1083,9 +1082,9 @@ def create_data(constructor): result_datetime = Series(data_datetime) result_Timestamp = Series(data_Timestamp) - assert_series_equal(result_datetime64, expected) - assert_series_equal(result_datetime, expected) - assert_series_equal(result_Timestamp, expected) + tm.assert_series_equal(result_datetime64, expected) + tm.assert_series_equal(result_datetime, expected) + tm.assert_series_equal(result_Timestamp, expected) def test_constructor_list_of_tuples(self): data = [(1, 1), (2, 2), (2, 3)] @@ -1234,7 +1233,7 @@ def test_constructor_mixed_tz(self): [Timestamp("20130101"), Timestamp("20130101", tz="US/Eastern")], dtype="object", ) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) def test_NaT_scalar(self): series = Series([0, 1000, 2000, iNaT], dtype="M8[ns]") @@ -1249,7 +1248,7 @@ def test_NaT_cast(self): # GH10747 result = Series([np.nan]).astype("M8[ns]") expected = Series([NaT]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_constructor_name_hashable(self): for n in [777, 777.0, "name", datetime(2001, 11, 11), (1,), "\u05D0"]: @@ -1273,7 +1272,7 @@ def test_convert_non_ns(self): arr = np.array([1, 2, 3], dtype="timedelta64[s]") s = Series(arr) expected = Series(pd.timedelta_range("00:00:01", periods=3, freq="s")) - assert_series_equal(s, expected) + tm.assert_series_equal(s, expected) # convert from a numpy array of non-ns datetime64 # note that creating a numpy datetime64 is in LOCAL time!!!! @@ -1282,12 +1281,12 @@ def test_convert_non_ns(self): s = Series( np.array(["2013-01-01", "2013-01-02", "2013-01-03"], dtype="datetime64[D]") ) - assert_series_equal(s, Series(date_range("20130101", periods=3, freq="D"))) + tm.assert_series_equal(s, Series(date_range("20130101", periods=3, freq="D"))) # s = Series(np.array(['2013-01-01 00:00:01','2013-01-01 # 00:00:02','2013-01-01 00:00:03'],dtype='datetime64[s]')) - # assert_series_equal(s,date_range('20130101 + # tm.assert_series_equal(s,date_range('20130101 # 00:00:01',period=3,freq='s')) @pytest.mark.parametrize( diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index c9092917cb0c6..1346f2fd57f10 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -27,7 +27,6 @@ from pandas.core.arrays import PeriodArray import pandas.core.common as com import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal class TestSeriesDatetimeValues: @@ -587,11 +586,11 @@ def test_between(self): result = s[s.between(s[3], s[17])] expected = s[3:18].dropna() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s[s.between(s[3], s[17], inclusive=False)] expected = s[5:16].dropna() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_date_tz(self): # GH11757 @@ -601,8 +600,8 @@ def test_date_tz(self): ) s = Series(rng) expected = Series([date(2014, 4, 4), date(2014, 7, 18), date(2015, 11, 22)]) - assert_series_equal(s.dt.date, expected) - assert_series_equal(s.apply(lambda x: x.date()), expected) + tm.assert_series_equal(s.dt.date, expected) + tm.assert_series_equal(s.apply(lambda x: x.date()), expected) def test_datetime_understood(self): # Ensures it doesn't fail to create the right series diff --git a/pandas/tests/series/test_internals.py b/pandas/tests/series/test_internals.py index d35198ca70f37..187c5d90407ce 100644 --- a/pandas/tests/series/test_internals.py +++ b/pandas/tests/series/test_internals.py @@ -7,7 +7,6 @@ from pandas import NaT, Series, Timestamp from pandas.core.internals.blocks import IntBlock import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal class TestSeriesInternals: @@ -19,15 +18,15 @@ def test_convert(self): s = Series(["a", "b", "c"]) results = s._convert(datetime=True, coerce=True) expected = Series([NaT] * 3) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) results = s._convert(numeric=True, coerce=True) expected = Series([np.nan] * 3) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) expected = Series([NaT] * 3, dtype=np.dtype("m8[ns]")) results = s._convert(timedelta=True, coerce=True) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) dt = datetime(2001, 1, 1, 0, 0) td = dt - datetime(2000, 1, 1, 0, 0) @@ -36,79 +35,79 @@ def test_convert(self): s = Series(["a", "3.1415", dt, td]) results = s._convert(datetime=True, coerce=True) expected = Series([NaT, NaT, dt, NaT]) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) results = s._convert(numeric=True, coerce=True) expected = Series([np.nan, 3.1415, np.nan, np.nan]) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) results = s._convert(timedelta=True, coerce=True) expected = Series([NaT, NaT, NaT, td], dtype=np.dtype("m8[ns]")) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) # Test standard conversion returns original results = s._convert(datetime=True) - assert_series_equal(results, s) + tm.assert_series_equal(results, s) results = s._convert(numeric=True) expected = Series([np.nan, 3.1415, np.nan, np.nan]) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) results = s._convert(timedelta=True) - assert_series_equal(results, s) + tm.assert_series_equal(results, s) # test pass-through and non-conversion when other types selected s = Series(["1.0", "2.0", "3.0"]) results = s._convert(datetime=True, numeric=True, timedelta=True) expected = Series([1.0, 2.0, 3.0]) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) results = s._convert(True, False, True) - assert_series_equal(results, s) + tm.assert_series_equal(results, s) s = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)], dtype="O") results = s._convert(datetime=True, numeric=True, timedelta=True) expected = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)]) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) results = s._convert(datetime=False, numeric=True, timedelta=True) - assert_series_equal(results, s) + tm.assert_series_equal(results, s) td = datetime(2001, 1, 1, 0, 0) - datetime(2000, 1, 1, 0, 0) s = Series([td, td], dtype="O") results = s._convert(datetime=True, numeric=True, timedelta=True) expected = Series([td, td]) - assert_series_equal(results, expected) + tm.assert_series_equal(results, expected) results = s._convert(True, True, False) - assert_series_equal(results, s) + tm.assert_series_equal(results, s) s = Series([1.0, 2, 3], index=["a", "b", "c"]) result = s._convert(numeric=True) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) # force numeric conversion r = s.copy().astype("O") r["a"] = "1" result = r._convert(numeric=True) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) r = s.copy().astype("O") r["a"] = "1." result = r._convert(numeric=True) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) r = s.copy().astype("O") r["a"] = "garbled" result = r._convert(numeric=True) expected = s.copy() expected["a"] = np.nan - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 4119, not converting a mixed type (e.g.floats and object) s = Series([1, "na", 3, 4]) result = s._convert(datetime=True, numeric=True) expected = Series([1, np.nan, 3, 4]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([1, "", 3, 4]) result = s._convert(datetime=True, numeric=True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # dates s = Series( @@ -137,10 +136,10 @@ def test_convert(self): [Timestamp("20010101"), Timestamp("20010102"), Timestamp("20010103")], dtype="M8[ns]", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s._convert(datetime=True, coerce=True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series( [ @@ -156,19 +155,19 @@ def test_convert(self): dtype="M8[ns]", ) result = s2._convert(datetime=True, numeric=False, timedelta=False, coerce=True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s2._convert(datetime=True, coerce=True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series(["foo", "bar", 1, 1.0], dtype="O") result = s._convert(datetime=True, coerce=True) expected = Series([NaT] * 2 + [Timestamp(1)] * 2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # preserver if non-object s = Series([1], dtype="float32") result = s._convert(datetime=True, coerce=True) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) # r = s.copy() # r[0] = np.nan @@ -180,10 +179,10 @@ def test_convert(self): for x in "abcdefghijklmnopqrstuvwxyz": s = Series([x]) result = s._convert(datetime=True, coerce=True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([x.upper()]) result = s._convert(datetime=True, coerce=True) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_convert_no_arg_error(self): s = Series(["1.0", "2"]) diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py index 0ddf1dfcabb59..f954e6fb4bf98 100644 --- a/pandas/tests/series/test_io.py +++ b/pandas/tests/series/test_io.py @@ -8,12 +8,6 @@ import pandas as pd from pandas import DataFrame, Series import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, - ensure_clean, -) from pandas.io.common import _get_handle @@ -34,7 +28,7 @@ def read_csv(self, path, **kwargs): @pytest.mark.parametrize("arg", ["path", "header", "both"]) def test_to_csv_deprecation(self, arg, datetime_series): # see gh-19715 - with ensure_clean() as path: + with tm.ensure_clean() as path: if arg == "path": kwargs = dict(path=path, header=False) elif arg == "header": @@ -47,14 +41,14 @@ def test_to_csv_deprecation(self, arg, datetime_series): # Make sure roundtrip still works. ts = self.read_csv(path) - assert_series_equal(datetime_series, ts, check_names=False) + tm.assert_series_equal(datetime_series, ts, check_names=False) def test_from_csv(self, datetime_series, string_series): - with ensure_clean() as path: + with tm.ensure_clean() as path: datetime_series.to_csv(path, header=False) ts = self.read_csv(path) - assert_series_equal(datetime_series, ts, check_names=False) + tm.assert_series_equal(datetime_series, ts, check_names=False) assert ts.name is None assert ts.index.name is None @@ -66,7 +60,7 @@ def test_from_csv(self, datetime_series, string_series): string_series.to_csv(path, header=False) series = self.read_csv(path) - assert_series_equal(string_series, series, check_names=False) + tm.assert_series_equal(string_series, series, check_names=False) assert series.name is None assert series.index.name is None @@ -82,16 +76,16 @@ def test_from_csv(self, datetime_series, string_series): check_series = Series( {datetime(1998, 1, 1): 1.0, datetime(1999, 1, 1): 2.0} ) - assert_series_equal(check_series, series) + tm.assert_series_equal(check_series, series) series = self.read_csv(path, sep="|", parse_dates=False) check_series = Series({"1998-01-01": 1.0, "1999-01-01": 2.0}) - assert_series_equal(check_series, series) + tm.assert_series_equal(check_series, series) def test_to_csv(self, datetime_series): import io - with ensure_clean() as path: + with tm.ensure_clean() as path: datetime_series.to_csv(path, header=False) with io.open(path, newline=None) as f: @@ -100,7 +94,7 @@ def test_to_csv(self, datetime_series): datetime_series.to_csv(path, index=False, header=False) arr = np.loadtxt(path) - assert_almost_equal(arr, datetime_series.values) + tm.assert_almost_equal(arr, datetime_series.values) def test_to_csv_unicode_index(self): buf = StringIO() @@ -110,17 +104,17 @@ def test_to_csv_unicode_index(self): buf.seek(0) s2 = self.read_csv(buf, index_col=0, encoding="UTF-8") - assert_series_equal(s, s2) + tm.assert_series_equal(s, s2) def test_to_csv_float_format(self): - with ensure_clean() as filename: + with tm.ensure_clean() as filename: ser = Series([0.123456, 0.234567, 0.567567]) ser.to_csv(filename, float_format="%.2f", header=False) rs = self.read_csv(filename) xp = Series([0.12, 0.23, 0.57]) - assert_series_equal(rs, xp) + tm.assert_series_equal(rs, xp) def test_to_csv_list_entries(self): s = Series(["jack and jill", "jesse and frank"]) @@ -153,7 +147,7 @@ def test_to_csv_path_is_none(self): ) def test_to_csv_compression(self, s, encoding, compression): - with ensure_clean() as filename: + with tm.ensure_clean() as filename: s.to_csv(filename, compression=compression, encoding=encoding, header=True) # test the round trip - to_csv -> read_csv @@ -164,7 +158,7 @@ def test_to_csv_compression(self, s, encoding, compression): index_col=0, squeeze=True, ) - assert_series_equal(s, result) + tm.assert_series_equal(s, result) # test the round trip using file handle - to_csv -> read_csv f, _handles = _get_handle( @@ -179,7 +173,7 @@ def test_to_csv_compression(self, s, encoding, compression): index_col=0, squeeze=True, ) - assert_series_equal(s, result) + tm.assert_series_equal(s, result) # explicitly ensure file was compressed with tm.decompress_file(filename, compression) as fh: @@ -187,7 +181,7 @@ def test_to_csv_compression(self, s, encoding, compression): assert s.name in text with tm.decompress_file(filename, compression) as fh: - assert_series_equal( + tm.assert_series_equal( s, pd.read_csv(fh, index_col=0, squeeze=True, encoding=encoding) ) @@ -195,7 +189,7 @@ def test_to_csv_interval_index(self): # GH 28210 s = Series(["foo", "bar", "baz"], index=pd.interval_range(0, 3)) - with ensure_clean("__tmp_to_csv_interval_index__.csv") as path: + with tm.ensure_clean("__tmp_to_csv_interval_index__.csv") as path: s.to_csv(path, header=False) result = self.read_csv(path, index_col=0, squeeze=True) @@ -203,7 +197,7 @@ def test_to_csv_interval_index(self): expected = s.copy() expected.index = expected.index.astype(str) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) class TestSeriesIO: @@ -211,20 +205,20 @@ def test_to_frame(self, datetime_series): datetime_series.name = None rs = datetime_series.to_frame() xp = pd.DataFrame(datetime_series.values, index=datetime_series.index) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) datetime_series.name = "testname" rs = datetime_series.to_frame() xp = pd.DataFrame( dict(testname=datetime_series.values), index=datetime_series.index ) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) rs = datetime_series.to_frame(name="testdifferent") xp = pd.DataFrame( dict(testdifferent=datetime_series.values), index=datetime_series.index ) - assert_frame_equal(rs, xp) + tm.assert_frame_equal(rs, xp) def test_timeseries_periodindex(self): # GH2891 @@ -251,7 +245,7 @@ def test_pickle_categorical_ordered_from_sentinel(self): def _pickle_roundtrip_name(self, obj): - with ensure_clean() as path: + with tm.ensure_clean() as path: obj.to_pickle(path) unpickled = pd.read_pickle(path) return unpickled @@ -271,7 +265,7 @@ class SubclassedFrame(DataFrame): result = s.to_frame() assert isinstance(result, SubclassedFrame) expected = SubclassedFrame({"X": [1, 2, 3]}) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "mapping", (dict, collections.defaultdict(list), collections.OrderedDict) diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 835514ea724ab..0751e1fb8b906 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -22,7 +22,6 @@ ) from pandas.core.series import remove_na import pandas.util.testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal def _skip_if_no_pchip(): @@ -77,7 +76,7 @@ def test_timedelta_fillna(self): timedelta(days=1, seconds=9 * 3600 + 60 + 1), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # interpreted as seconds, deprecated with tm.assert_produces_warning(FutureWarning): @@ -90,7 +89,7 @@ def test_timedelta_fillna(self): timedelta(days=1, seconds=9 * 3600 + 60 + 1), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = td.fillna(timedelta(days=1, seconds=1)) expected = Series( @@ -101,7 +100,7 @@ def test_timedelta_fillna(self): timedelta(days=1, seconds=9 * 3600 + 60 + 1), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = td.fillna(np.timedelta64(int(1e9))) expected = Series( @@ -112,7 +111,7 @@ def test_timedelta_fillna(self): timedelta(days=1, seconds=9 * 3600 + 60 + 1), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = td.fillna(NaT) expected = Series( @@ -124,7 +123,7 @@ def test_timedelta_fillna(self): ], dtype="m8[ns]", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # ffill td[2] = np.nan @@ -132,7 +131,7 @@ def test_timedelta_fillna(self): with tm.assert_produces_warning(FutureWarning): expected = td.fillna(0) expected[0] = np.nan - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # bfill td[2] = np.nan @@ -140,7 +139,7 @@ def test_timedelta_fillna(self): with tm.assert_produces_warning(FutureWarning): expected = td.fillna(0) expected[2] = timedelta(days=1, seconds=9 * 3600 + 60 + 1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_datetime64_fillna(self): @@ -164,11 +163,11 @@ def test_datetime64_fillna(self): Timestamp("20130103 9:01:01"), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.fillna(NaT) expected = s - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # ffill result = s.ffill() @@ -180,7 +179,7 @@ def test_datetime64_fillna(self): Timestamp("20130103 9:01:01"), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # bfill result = s.bfill() @@ -192,7 +191,7 @@ def test_datetime64_fillna(self): Timestamp("20130103 9:01:01"), ] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 6587 # make sure that we are treating as integer when filling @@ -207,7 +206,7 @@ def test_datetime64_fillna(self): dtype="M8[ns]", ) result = s.fillna(method="backfill") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_datetime64_tz_fillna(self): @@ -424,7 +423,7 @@ def test_datetime64_tz_fillna(self): pd.Timestamp("2012-11-11 00:00:00+01:00"), ] ) - assert_series_equal(df.fillna(method="pad"), exp) + tm.assert_series_equal(df.fillna(method="pad"), exp) df = pd.Series([pd.NaT, pd.Timestamp("2012-11-11 00:00:00+01:00")]) exp = pd.Series( @@ -433,7 +432,7 @@ def test_datetime64_tz_fillna(self): pd.Timestamp("2012-11-11 00:00:00+01:00"), ] ) - assert_series_equal(df.fillna(method="bfill"), exp) + tm.assert_series_equal(df.fillna(method="bfill"), exp) def test_datetime64_non_nano_fillna(self): # GH#27419 @@ -457,28 +456,28 @@ def test_fillna_consistency(self): [Timestamp("20130101"), Timestamp("2013-01-01", tz="US/Eastern")], dtype="object", ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # where (we ignore the errors=) result = s.where( [True, False], Timestamp("20130101", tz="US/Eastern"), errors="ignore" ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.where( [True, False], Timestamp("20130101", tz="US/Eastern"), errors="ignore" ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # with a non-datetime result = s.fillna("foo") expected = Series([Timestamp("20130101"), "foo"]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # assignment s2 = s.copy() s2[1] = "foo" - assert_series_equal(s2, expected) + tm.assert_series_equal(s2, expected) def test_datetime64tz_fillna_round_issue(self): # GH 14872 @@ -497,7 +496,7 @@ def test_datetime64tz_fillna_round_issue(self): ] ) - assert_series_equal(filled, expected) + tm.assert_series_equal(filled, expected) def test_fillna_downcast(self): # GH 15277 @@ -505,18 +504,18 @@ def test_fillna_downcast(self): s = pd.Series([1.0, np.nan]) result = s.fillna(0, downcast="infer") expected = pd.Series([1, 0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # infer int64 from float64 when fillna value is a dict s = pd.Series([1.0, np.nan]) result = s.fillna({1: 0}, downcast="infer") expected = pd.Series([1, 0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_fillna_int(self): s = Series(np.random.randint(-100, 100, 50)) s.fillna(method="ffill", inplace=True) - assert_series_equal(s.fillna(method="ffill", inplace=False), s) + tm.assert_series_equal(s.fillna(method="ffill", inplace=False), s) def test_fillna_raise(self): s = Series(np.random.randint(-100, 100, 50)) @@ -635,15 +634,15 @@ def test_fillna_nat(self): expected = series.copy() expected.values[3] = expected.values[2] - assert_series_equal(filled, expected) - assert_series_equal(filled2, expected) + tm.assert_series_equal(filled, expected) + tm.assert_series_equal(filled2, expected) df = DataFrame({"A": series}) filled = df.fillna(method="pad") filled2 = df.fillna(value=series.values[2]) expected = DataFrame({"A": expected}) - assert_frame_equal(filled, expected) - assert_frame_equal(filled2, expected) + tm.assert_frame_equal(filled, expected) + tm.assert_frame_equal(filled2, expected) series = Series([iNaT, 0, 1, 2], dtype="M8[ns]") @@ -653,15 +652,15 @@ def test_fillna_nat(self): expected = series.copy() expected[0] = expected[1] - assert_series_equal(filled, expected) - assert_series_equal(filled2, expected) + tm.assert_series_equal(filled, expected) + tm.assert_series_equal(filled2, expected) df = DataFrame({"A": series}) filled = df.fillna(method="bfill") filled2 = df.fillna(value=series[1]) expected = DataFrame({"A": expected}) - assert_frame_equal(filled, expected) - assert_frame_equal(filled2, expected) + tm.assert_frame_equal(filled, expected) + tm.assert_frame_equal(filled2, expected) def test_isna_for_inf(self): s = Series(["a", np.inf, np.nan, 1.0]) @@ -714,39 +713,39 @@ def test_fillna(self, datetime_series): s2 = Series([1]) result = s1.fillna(s2) expected = Series([1.0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s1.fillna({}) - assert_series_equal(result, s1) + tm.assert_series_equal(result, s1) result = s1.fillna(Series(())) - assert_series_equal(result, s1) + tm.assert_series_equal(result, s1) result = s2.fillna(s1) - assert_series_equal(result, s2) + tm.assert_series_equal(result, s2) result = s1.fillna({0: 1}) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s1.fillna({1: 1}) - assert_series_equal(result, Series([np.nan])) + tm.assert_series_equal(result, Series([np.nan])) result = s1.fillna({0: 1, 1: 1}) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s1.fillna(Series({0: 1, 1: 1})) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s1.fillna(Series({0: 1, 1: 1}, index=[4, 5])) - assert_series_equal(result, s1) + tm.assert_series_equal(result, s1) s1 = Series([0, 1, 2], list("abc")) s2 = Series([0, np.nan, 2], list("bac")) result = s2.fillna(s1) expected = Series([0, 0, 2.0], list("bac")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # limit s = Series(np.nan, index=[0, 1, 2]) result = s.fillna(999, limit=1) expected = Series([999, np.nan, np.nan], index=[0, 1, 2]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.fillna(999, limit=2) expected = Series([999, 999, np.nan], index=[0, 1, 2]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH 9043 # make sure a string representation of int/float values can be filled @@ -756,17 +755,17 @@ def test_fillna(self, datetime_series): s = Series([0, 1, np.nan, np.nan, 4], dtype="float64") result = s.fillna(val) expected = Series([0, 1, val, val, 4], dtype="object") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_fillna_bug(self): x = Series([np.nan, 1.0, np.nan, 3.0, np.nan], ["z", "a", "b", "c", "d"]) filled = x.fillna(method="ffill") expected = Series([np.nan, 1.0, 1.0, 3.0, 3.0], x.index) - assert_series_equal(filled, expected) + tm.assert_series_equal(filled, expected) filled = x.fillna(method="bfill") expected = Series([1.0, 1.0, 3.0, 3.0, np.nan], x.index) - assert_series_equal(filled, expected) + tm.assert_series_equal(filled, expected) def test_fillna_inplace(self): x = Series([np.nan, 1.0, np.nan, 3.0, np.nan], ["z", "a", "b", "c", "d"]) @@ -775,7 +774,7 @@ def test_fillna_inplace(self): y.fillna(value=0, inplace=True) expected = x.fillna(value=0) - assert_series_equal(y, expected) + tm.assert_series_equal(y, expected) def test_fillna_invalid_method(self, datetime_series): try: @@ -786,18 +785,18 @@ def test_fillna_invalid_method(self, datetime_series): def test_ffill(self): ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5)) ts[2] = np.NaN - assert_series_equal(ts.ffill(), ts.fillna(method="ffill")) + tm.assert_series_equal(ts.ffill(), ts.fillna(method="ffill")) def test_ffill_mixed_dtypes_without_missing_data(self): # GH14956 series = pd.Series([datetime(2015, 1, 1, tzinfo=pytz.utc), 1]) result = series.ffill() - assert_series_equal(series, result) + tm.assert_series_equal(series, result) def test_bfill(self): ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5)) ts[2] = np.NaN - assert_series_equal(ts.bfill(), ts.fillna(method="bfill")) + tm.assert_series_equal(ts.bfill(), ts.fillna(method="bfill")) def test_timedelta64_nan(self): @@ -838,7 +837,7 @@ def test_timedelta64_nan(self): # np.random.seed(12345) # selector = -0.5 <= datetime_series <= 0.5 # expected = (datetime_series >= -0.5) & (datetime_series <= 0.5) - # assert_series_equal(selector, expected) + # tm.assert_series_equal(selector, expected) def test_dropna_empty(self): s = Series([]) @@ -903,7 +902,7 @@ def test_dropna_intervals(self): result = s.dropna() expected = s.iloc[1:] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_valid(self, datetime_series): ts = datetime_series.copy() @@ -942,7 +941,7 @@ def test_pad_nan(self): expected = Series( [np.nan, 1.0, 1.0, 3.0, 3.0], ["z", "a", "b", "c", "d"], dtype=float ) - assert_series_equal(x[1:], expected[1:]) + tm.assert_series_equal(x[1:], expected[1:]) assert np.isnan(x[0]), np.isnan(expected[0]) def test_pad_require_monotonicity(self): @@ -970,7 +969,7 @@ def test_fill_value_when_combine_const(self): exp = s.fillna(0).add(2) res = s.add(2, fill_value=0) - assert_series_equal(res, exp) + tm.assert_series_equal(res, exp) def test_series_fillna_limit(self): index = np.arange(10) @@ -981,14 +980,14 @@ def test_series_fillna_limit(self): expected = s[:2].reindex(index).fillna(method="pad") expected[-3:] = np.nan - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s[-2:].reindex(index) result = result.fillna(method="bfill", limit=5) expected = s[-2:].reindex(index).fillna(method="backfill") expected[:3] = np.nan - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_series_pad_backfill_limit(self): index = np.arange(10) @@ -998,13 +997,13 @@ def test_series_pad_backfill_limit(self): expected = s[:2].reindex(index).fillna(method="pad") expected[-3:] = np.nan - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s[-2:].reindex(index, method="backfill", limit=5) expected = s[-2:].reindex(index).fillna(method="backfill") expected[:3] = np.nan - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.fixture( @@ -1125,7 +1124,7 @@ def test_interpolate_akima(self): float ) interp_s = ser.reindex(new_index).interpolate(method="akima") - assert_series_equal(interp_s[1:3], expected) + tm.assert_series_equal(interp_s[1:3], expected) @td.skip_if_no_scipy def test_interpolate_piecewise_polynomial(self): @@ -1140,7 +1139,7 @@ def test_interpolate_piecewise_polynomial(self): float ) interp_s = ser.reindex(new_index).interpolate(method="piecewise_polynomial") - assert_series_equal(interp_s[1:3], expected) + tm.assert_series_equal(interp_s[1:3], expected) @td.skip_if_no_scipy def test_interpolate_from_derivatives(self): @@ -1155,7 +1154,7 @@ def test_interpolate_from_derivatives(self): float ) interp_s = ser.reindex(new_index).interpolate(method="from_derivatives") - assert_series_equal(interp_s[1:3], expected) + tm.assert_series_equal(interp_s[1:3], expected) @pytest.mark.parametrize( "kwargs", @@ -1168,10 +1167,10 @@ def test_interpolate_from_derivatives(self): ) def test_interpolate_corners(self, kwargs): s = Series([np.nan, np.nan]) - assert_series_equal(s.interpolate(**kwargs), s) + tm.assert_series_equal(s.interpolate(**kwargs), s) s = Series([]).interpolate() - assert_series_equal(s.interpolate(**kwargs), s) + tm.assert_series_equal(s.interpolate(**kwargs), s) def test_interpolate_index_values(self): s = Series(np.nan, index=np.sort(np.random.rand(30))) @@ -1188,13 +1187,13 @@ def test_interpolate_index_values(self): np.interp(vals[bad], vals[good], s.values[good]), index=s.index[bad] ) - assert_series_equal(result[bad], expected) + tm.assert_series_equal(result[bad], expected) # 'values' is synonymous with 'index' for the method kwarg other_result = s.interpolate(method="values") - assert_series_equal(other_result, result) - assert_series_equal(other_result[bad], expected) + tm.assert_series_equal(other_result, result) + tm.assert_series_equal(other_result[bad], expected) def test_interpolate_non_ts(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) @@ -1218,26 +1217,26 @@ def test_nan_interpolate(self, kwargs): s = Series([0, 1, np.nan, 3]) result = s.interpolate(**kwargs) expected = Series([0.0, 1.0, 2.0, 3.0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_nan_irregular_index(self): s = Series([1, 2, np.nan, 4], index=[1, 3, 5, 9]) result = s.interpolate() expected = Series([1.0, 2.0, 3.0, 4.0], index=[1, 3, 5, 9]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_nan_str_index(self): s = Series([0, 1, 2, np.nan], index=list("abcd")) result = s.interpolate() expected = Series([0.0, 1.0, 2.0, 2.0], index=list("abcd")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @td.skip_if_no_scipy def test_interp_quad(self): sq = Series([1, 4, np.nan, 16], index=[1, 2, 3, 4]) result = sq.interpolate(method="quadratic") expected = Series([1.0, 4.0, 9.0, 16.0], index=[1, 2, 3, 4]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @td.skip_if_no_scipy def test_interp_scipy_basic(self): @@ -1245,43 +1244,43 @@ def test_interp_scipy_basic(self): # slinear expected = Series([1.0, 3.0, 7.5, 12.0, 18.5, 25.0]) result = s.interpolate(method="slinear") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.interpolate(method="slinear", downcast="infer") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # nearest expected = Series([1, 3, 3, 12, 12, 25]) result = s.interpolate(method="nearest") - assert_series_equal(result, expected.astype("float")) + tm.assert_series_equal(result, expected.astype("float")) result = s.interpolate(method="nearest", downcast="infer") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # zero expected = Series([1, 3, 3, 12, 12, 25]) result = s.interpolate(method="zero") - assert_series_equal(result, expected.astype("float")) + tm.assert_series_equal(result, expected.astype("float")) result = s.interpolate(method="zero", downcast="infer") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # quadratic # GH #15662. expected = Series([1, 3.0, 6.823529, 12.0, 18.058824, 25.0]) result = s.interpolate(method="quadratic") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.interpolate(method="quadratic", downcast="infer") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # cubic expected = Series([1.0, 3.0, 6.8, 12.0, 18.2, 25.0]) result = s.interpolate(method="cubic") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interp_limit(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) expected = Series([1.0, 3.0, 5.0, 7.0, np.nan, 11.0]) result = s.interpolate(method="linear", limit=2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("limit", [-1, 0]) def test_interpolate_invalid_nonpositive_limit(self, nontemporal_method, limit): @@ -1319,25 +1318,25 @@ def test_interp_limit_forward(self): expected = Series([1.0, 3.0, 5.0, 7.0, np.nan, 11.0]) result = s.interpolate(method="linear", limit=2, limit_direction="forward") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.interpolate(method="linear", limit=2, limit_direction="FORWARD") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interp_unlimited(self): # these test are for issue #16282 default Limit=None is unlimited s = Series([np.nan, 1.0, 3.0, np.nan, np.nan, np.nan, 11.0, np.nan]) expected = Series([1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 11.0]) result = s.interpolate(method="linear", limit_direction="both") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([np.nan, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 11.0]) result = s.interpolate(method="linear", limit_direction="forward") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, np.nan]) result = s.interpolate(method="linear", limit_direction="backward") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interp_limit_bad_direction(self): s = Series([1, 3, np.nan, np.nan, np.nan, 11]) @@ -1360,7 +1359,7 @@ def test_interp_limit_area(self): expected = Series([np.nan, np.nan, 3.0, 4.0, 5.0, 6.0, 7.0, np.nan, np.nan]) result = s.interpolate(method="linear", limit_area="inside") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series( [np.nan, np.nan, 3.0, 4.0, np.nan, np.nan, 7.0, np.nan, np.nan] @@ -1371,11 +1370,11 @@ def test_interp_limit_area(self): result = s.interpolate( method="linear", limit_area="inside", limit_direction="both", limit=1 ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0]) result = s.interpolate(method="linear", limit_area="outside") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series( [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan] @@ -1386,7 +1385,7 @@ def test_interp_limit_area(self): result = s.interpolate( method="linear", limit_area="outside", limit_direction="both", limit=1 ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan]) result = s.interpolate( @@ -1404,24 +1403,24 @@ def test_interp_limit_direction(self): expected = Series([1.0, 3.0, np.nan, 7.0, 9.0, 11.0]) result = s.interpolate(method="linear", limit=2, limit_direction="backward") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([1.0, 3.0, 5.0, np.nan, 9.0, 11.0]) result = s.interpolate(method="linear", limit=1, limit_direction="both") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # Check that this works on a longer series of nans. s = Series([1, 3, np.nan, np.nan, np.nan, 7, 9, np.nan, np.nan, 12, np.nan]) expected = Series([1.0, 3.0, 4.0, 5.0, 6.0, 7.0, 9.0, 10.0, 11.0, 12.0, 12.0]) result = s.interpolate(method="linear", limit=2, limit_direction="both") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series( [1.0, 3.0, 4.0, np.nan, 6.0, 7.0, 9.0, 10.0, 11.0, 12.0, 12.0] ) result = s.interpolate(method="linear", limit=1, limit_direction="both") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interp_limit_to_ends(self): # These test are for issue #10420 -- flow back to beginning. @@ -1429,11 +1428,11 @@ def test_interp_limit_to_ends(self): expected = Series([5.0, 5.0, 5.0, 7.0, 9.0, np.nan]) result = s.interpolate(method="linear", limit=2, limit_direction="backward") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([5.0, 5.0, 5.0, 7.0, 9.0, 9.0]) result = s.interpolate(method="linear", limit=2, limit_direction="both") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interp_limit_before_ends(self): # These test are for issue #11115 -- limit ends properly. @@ -1441,25 +1440,25 @@ def test_interp_limit_before_ends(self): expected = Series([np.nan, np.nan, 5.0, 7.0, 7.0, np.nan]) result = s.interpolate(method="linear", limit=1, limit_direction="forward") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([np.nan, 5.0, 5.0, 7.0, np.nan, np.nan]) result = s.interpolate(method="linear", limit=1, limit_direction="backward") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([np.nan, 5.0, 5.0, 7.0, 7.0, np.nan]) result = s.interpolate(method="linear", limit=1, limit_direction="both") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @td.skip_if_no_scipy def test_interp_all_good(self): s = Series([1, 2, 3]) result = s.interpolate(method="polynomial", order=1) - assert_series_equal(result, s) + tm.assert_series_equal(result, s) # non-scipy result = s.interpolate() - assert_series_equal(result, s) + tm.assert_series_equal(result, s) @pytest.mark.parametrize( "check_scipy", [False, pytest.param(True, marks=td.skip_if_no_scipy)] @@ -1471,7 +1470,7 @@ def test_interp_multiIndex(self, check_scipy): expected = s.copy() expected.loc[2] = 2 result = s.interpolate() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) msg = "Only `method=linear` interpolation is supported on MultiIndexes" if check_scipy: @@ -1496,7 +1495,7 @@ def test_interp_datetime64(self, method, tz_naive_fixture): [1.0, 1.0, 3.0], index=date_range("1/1/2000", periods=3, tz=tz_naive_fixture), ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_interp_pad_datetime64tz_values(self): # GH#27628 missing.interpolate_2d should handle datetimetz values @@ -1514,7 +1513,7 @@ def test_interp_limit_no_nans(self): s = pd.Series([1.0, 2.0, 3.0]) result = s.interpolate(limit=1) expected = s - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @td.skip_if_no_scipy @pytest.mark.parametrize("method", ["polynomial", "spline"]) @@ -1538,18 +1537,18 @@ def test_spline(self): s = Series([1, 2, np.nan, 4, 5, np.nan, 7]) result = s.interpolate(method="spline", order=1) expected = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @td.skip_if_no_scipy def test_spline_extrapolate(self): s = Series([1, 2, 3, 4, np.nan, 6, np.nan]) result3 = s.interpolate(method="spline", order=1, ext=3) expected3 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 6.0]) - assert_series_equal(result3, expected3) + tm.assert_series_equal(result3, expected3) result1 = s.interpolate(method="spline", order=1, ext=0) expected1 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]) - assert_series_equal(result1, expected1) + tm.assert_series_equal(result1, expected1) @td.skip_if_no_scipy def test_spline_smooth(self): @@ -1565,20 +1564,20 @@ def test_spline_interpolation(self): s[np.random.randint(0, 9, 3)] = np.nan result1 = s.interpolate(method="spline", order=1) expected1 = s.interpolate(method="spline", order=1) - assert_series_equal(result1, expected1) + tm.assert_series_equal(result1, expected1) def test_interp_timedelta64(self): # GH 6424 df = Series([1, np.nan, 3], index=pd.to_timedelta([1, 2, 3])) result = df.interpolate(method="time") expected = Series([1.0, 2.0, 3.0], index=pd.to_timedelta([1, 2, 3])) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # test for non uniform spacing df = Series([1, np.nan, 3], index=pd.to_timedelta([1, 2, 4])) result = df.interpolate(method="time") expected = Series([1.0, 1.666667, 3.0], index=pd.to_timedelta([1, 2, 4])) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_series_interpolate_method_values(self): # #1646 @@ -1587,7 +1586,7 @@ def test_series_interpolate_method_values(self): result = ts.interpolate(method="values") exp = ts.interpolate() - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) def test_series_interpolate_intraday(self): # #1698 @@ -1629,7 +1628,7 @@ def test_interp_non_timedelta_index(self, interp_methods_ind, ind): if method == "linear": result = df[0].interpolate(**kwargs) expected = pd.Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) else: expected_error = ( "Index column must be numeric or datetime type when " @@ -1657,7 +1656,7 @@ def test_interpolate_timedelta_index(self, interp_methods_ind): if method in {"linear", "pchip"}: result = df[0].interpolate(method=method, **kwargs) expected = pd.Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) else: pytest.skip( "This interpolation method is not supported for Timedelta Index yet." diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index 4514164683015..7d212ee7cd667 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -9,12 +9,6 @@ from pandas.core import ops import pandas.core.nanops as nanops import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_index_equal, - assert_series_equal, -) class TestSeriesLogicalOps: @@ -31,7 +25,7 @@ def test_bool_operators_with_nas(self, bool_op): expected = bool_op(filled < filled[9], filled > filled[3]) expected[mask] = False - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_logical_operators_bool_dtype_with_empty(self): # GH#9016: support bitwise op for integer types @@ -43,11 +37,11 @@ def test_logical_operators_bool_dtype_with_empty(self): res = s_tft & s_empty expected = s_fff - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) res = s_tft | s_empty expected = s_tft - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) def test_logical_operators_int_dtype_with_int_dtype(self): # GH#9016: support bitwise op for integer types @@ -61,20 +55,20 @@ def test_logical_operators_int_dtype_with_int_dtype(self): res = s_0123 & s_3333 expected = Series(range(4), dtype="int64") - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) res = s_0123 | s_4444 expected = Series(range(4, 8), dtype="int64") - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) s_1111 = Series([1] * 4, dtype="int8") res = s_0123 & s_1111 expected = Series([0, 1, 0, 1], dtype="int64") - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) res = s_0123.astype(np.int16) | s_1111.astype(np.int32) expected = Series([1, 1, 3, 3], dtype="int32") - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) def test_logical_operators_int_dtype_with_int_scalar(self): # GH#9016: support bitwise op for integer types @@ -82,11 +76,11 @@ def test_logical_operators_int_dtype_with_int_scalar(self): res = s_0123 & 0 expected = Series([0] * 4) - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) res = s_0123 & 1 expected = Series([0, 1, 0, 1]) - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) def test_logical_operators_int_dtype_with_float(self): # GH#9016: support bitwise op for integer types @@ -118,17 +112,17 @@ def test_logical_operators_int_dtype_with_bool(self): expected = Series([False] * 4) result = s_0123 & False - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s_0123 & [False] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s_0123 & (False,) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s_0123 ^ False expected = Series([False, True, True, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_logical_operators_int_dtype_with_object(self): # GH#9016: support bitwise op for integer types @@ -136,7 +130,7 @@ def test_logical_operators_int_dtype_with_object(self): result = s_0123 & Series([False, np.NaN, False, False]) expected = Series([False] * 4) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s_abNd = Series(["a", "b", np.NaN, "d"]) with pytest.raises(TypeError, match="unsupported.* 'int' and 'str'"): @@ -150,11 +144,11 @@ def test_logical_operators_bool_dtype_with_int(self): res = s_tft & 0 expected = s_fff - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) res = s_tft & 1 expected = s_tft - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) def test_logical_ops_bool_dtype_with_ndarray(self): # make sure we operate on ndarray the same as Series @@ -207,21 +201,21 @@ def test_logical_operators_int_dtype_with_bool_dtype_and_reindex(self): # s_0123 will be all false now because of reindexing like s_tft expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"]) result = s_tft & s_0123 - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([False] * 7, index=[0, 1, 2, 3, "a", "b", "c"]) result = s_0123 & s_tft - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s_a0b1c0 = Series([1], list("b")) res = s_tft & s_a0b1c0 expected = s_tff.reindex(list("abc")) - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) res = s_tft | s_a0b1c0 expected = s_tft.reindex(list("abc")) - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) def test_scalar_na_logical_ops_corners(self): s = Series([2, 3, 4, 5, 6, 7, 8, 9, 10]) @@ -235,7 +229,7 @@ def test_scalar_na_logical_ops_corners(self): expected = Series(True, index=s.index) expected[::2] = False result = s & list(s) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) d = DataFrame({"A": s}) # TODO: Fix this exception - needs to be fixed! (see GH5035) @@ -272,12 +266,12 @@ def test_logical_ops_with_index(self, op): expected = Series([op(ser[n], idx1[n]) for n in range(len(ser))]) result = op(ser, idx1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([op(ser[n], idx2[n]) for n in range(len(ser))], dtype=bool) result = op(ser, idx2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_reversed_xor_with_index_returns_index(self): # GH#22092, GH#19792 @@ -287,11 +281,11 @@ def test_reversed_xor_with_index_returns_index(self): expected = Index.symmetric_difference(idx1, ser) result = idx1 ^ ser - assert_index_equal(result, expected) + tm.assert_index_equal(result, expected) expected = Index.symmetric_difference(idx2, ser) result = idx2 ^ ser - assert_index_equal(result, expected) + tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "op", @@ -322,11 +316,11 @@ def test_reversed_logical_op_with_index_returns_series(self, op): expected = pd.Series(op(idx1.values, ser.values)) result = op(ser, idx1) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = pd.Series(op(idx2.values, ser.values)) result = op(ser, idx2) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "op, expected", @@ -353,15 +347,15 @@ def test_logical_ops_label_based(self): expected = Series([False, True, False], list("abc")) result = a & b - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([True, True, False], list("abc")) result = a | b - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([True, False, False], list("abc")) result = a ^ b - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # rhs is bigger a = Series([True, False, True], list("bca")) @@ -369,31 +363,31 @@ def test_logical_ops_label_based(self): expected = Series([False, True, False, False], list("abcd")) result = a & b - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series([True, True, False, False], list("abcd")) result = a | b - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # filling # vs empty result = a & Series([]) expected = Series([False, False, False], list("bca")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = a | Series([]) expected = Series([True, False, True], list("bca")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # vs non-matching result = a & Series([1], ["z"]) expected = Series([False, False, False, False], list("abcz")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = a | Series([1], ["z"]) expected = Series([True, True, False, False], list("abcz")) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # identity # we would like s[s|e] == s to hold for any e, whether empty or not @@ -404,11 +398,11 @@ def test_logical_ops_label_based(self): Series(np.nan, a.index), ]: result = a[a | e] - assert_series_equal(result, a[a]) + tm.assert_series_equal(result, a[a]) for e in [Series(["z"])]: result = a[a | e] - assert_series_equal(result, a[a]) + tm.assert_series_equal(result, a[a]) # vs scalars index = list("bca") @@ -417,7 +411,7 @@ def test_logical_ops_label_based(self): for v in [True, 1, 2]: result = Series([True, False, True], index=index) | v expected = Series([True, True, True], index=index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) for v in [np.nan, "foo"]: with pytest.raises(TypeError): @@ -426,17 +420,17 @@ def test_logical_ops_label_based(self): for v in [False, 0]: result = Series([True, False, True], index=index) | v expected = Series([True, False, True], index=index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) for v in [True, 1]: result = Series([True, False, True], index=index) & v expected = Series([True, False, True], index=index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) for v in [False, 0]: result = Series([True, False, True], index=index) & v expected = Series([False, False, False], index=index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) for v in [np.nan]: with pytest.raises(TypeError): t & v @@ -447,44 +441,44 @@ def test_logical_ops_df_compat(self): s2 = pd.Series([True, True, False], index=list("ABD"), name="x") exp = pd.Series([True, False, False, False], index=list("ABCD"), name="x") - assert_series_equal(s1 & s2, exp) - assert_series_equal(s2 & s1, exp) + tm.assert_series_equal(s1 & s2, exp) + tm.assert_series_equal(s2 & s1, exp) # True | np.nan => True exp_or1 = pd.Series([True, True, True, False], index=list("ABCD"), name="x") - assert_series_equal(s1 | s2, exp_or1) + tm.assert_series_equal(s1 | s2, exp_or1) # np.nan | True => np.nan, filled with False exp_or = pd.Series([True, True, False, False], index=list("ABCD"), name="x") - assert_series_equal(s2 | s1, exp_or) + tm.assert_series_equal(s2 | s1, exp_or) # DataFrame doesn't fill nan with False - assert_frame_equal(s1.to_frame() & s2.to_frame(), exp.to_frame()) - assert_frame_equal(s2.to_frame() & s1.to_frame(), exp.to_frame()) + tm.assert_frame_equal(s1.to_frame() & s2.to_frame(), exp.to_frame()) + tm.assert_frame_equal(s2.to_frame() & s1.to_frame(), exp.to_frame()) exp = pd.DataFrame({"x": [True, True, np.nan, np.nan]}, index=list("ABCD")) - assert_frame_equal(s1.to_frame() | s2.to_frame(), exp_or1.to_frame()) - assert_frame_equal(s2.to_frame() | s1.to_frame(), exp_or.to_frame()) + tm.assert_frame_equal(s1.to_frame() | s2.to_frame(), exp_or1.to_frame()) + tm.assert_frame_equal(s2.to_frame() | s1.to_frame(), exp_or.to_frame()) # different length s3 = pd.Series([True, False, True], index=list("ABC"), name="x") s4 = pd.Series([True, True, True, True], index=list("ABCD"), name="x") exp = pd.Series([True, False, True, False], index=list("ABCD"), name="x") - assert_series_equal(s3 & s4, exp) - assert_series_equal(s4 & s3, exp) + tm.assert_series_equal(s3 & s4, exp) + tm.assert_series_equal(s4 & s3, exp) # np.nan | True => np.nan, filled with False exp_or1 = pd.Series([True, True, True, False], index=list("ABCD"), name="x") - assert_series_equal(s3 | s4, exp_or1) + tm.assert_series_equal(s3 | s4, exp_or1) # True | np.nan => True exp_or = pd.Series([True, True, True, True], index=list("ABCD"), name="x") - assert_series_equal(s4 | s3, exp_or) + tm.assert_series_equal(s4 | s3, exp_or) - assert_frame_equal(s3.to_frame() & s4.to_frame(), exp.to_frame()) - assert_frame_equal(s4.to_frame() & s3.to_frame(), exp.to_frame()) + tm.assert_frame_equal(s3.to_frame() & s4.to_frame(), exp.to_frame()) + tm.assert_frame_equal(s4.to_frame() & s3.to_frame(), exp.to_frame()) - assert_frame_equal(s3.to_frame() | s4.to_frame(), exp_or1.to_frame()) - assert_frame_equal(s4.to_frame() | s3.to_frame(), exp_or.to_frame()) + tm.assert_frame_equal(s3.to_frame() | s4.to_frame(), exp_or1.to_frame()) + tm.assert_frame_equal(s4.to_frame() | s3.to_frame(), exp_or.to_frame()) class TestSeriesComparisons: @@ -498,15 +492,15 @@ def test_comparisons(self): expected = (left > right).astype("O") expected[:3] = np.nan - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) s = Series(["a", "b", "c"]) s2 = Series([False, True, False]) # it works! exp = Series([False, False, False]) - assert_series_equal(s == s2, exp) - assert_series_equal(s2 == s, exp) + tm.assert_series_equal(s == s2, exp) + tm.assert_series_equal(s2 == s, exp) def test_categorical_comparisons(self): # GH 8938 @@ -570,35 +564,35 @@ def test_comparison_tuples(self): result = s == (1, 2) expected = Series([False, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s != (1, 2) expected = Series([True, False]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s == (0, 0) expected = Series([False, False]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s != (0, 0) expected = Series([True, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([(1, 1), (1, 1)]) result = s == (1, 1) expected = Series([True, True]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s != (1, 1) expected = Series([False, False]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([frozenset([1]), frozenset([1, 2])]) result = s == frozenset([1]) expected = Series([True, False]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_comparison_operators_with_nas(self): ser = Series(bdate_range("1/1/2000", periods=10), dtype=object) @@ -619,13 +613,13 @@ def test_comparison_operators_with_nas(self): else: expected = expected.fillna(False).astype(bool) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # FIXME: dont leave commented-out # fffffffuuuuuuuuuuuu # result = f(val, s) # expected = f(val, s.dropna()).reindex(s.index) - # assert_series_equal(result, expected) + # tm.assert_series_equal(result, expected) def test_unequal_categorical_comparison_raises_type_error(self): # unequal comparison should raise for unordered cats @@ -695,7 +689,7 @@ def test_compare_series_interval_keyword(self): s = Series(["IntervalA", "IntervalB", "IntervalC"]) result = s == "IntervalA" expected = Series([True, False, False]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) class TestSeriesFlexComparisonOps: @@ -704,51 +698,51 @@ def test_comparison_flex_alignment(self): right = Series([2, 2, 2], index=list("bcd")) exp = pd.Series([False, False, True, False], index=list("abcd")) - assert_series_equal(left.eq(right), exp) + tm.assert_series_equal(left.eq(right), exp) exp = pd.Series([True, True, False, True], index=list("abcd")) - assert_series_equal(left.ne(right), exp) + tm.assert_series_equal(left.ne(right), exp) exp = pd.Series([False, False, True, False], index=list("abcd")) - assert_series_equal(left.le(right), exp) + tm.assert_series_equal(left.le(right), exp) exp = pd.Series([False, False, False, False], index=list("abcd")) - assert_series_equal(left.lt(right), exp) + tm.assert_series_equal(left.lt(right), exp) exp = pd.Series([False, True, True, False], index=list("abcd")) - assert_series_equal(left.ge(right), exp) + tm.assert_series_equal(left.ge(right), exp) exp = pd.Series([False, True, False, False], index=list("abcd")) - assert_series_equal(left.gt(right), exp) + tm.assert_series_equal(left.gt(right), exp) def test_comparison_flex_alignment_fill(self): left = Series([1, 3, 2], index=list("abc")) right = Series([2, 2, 2], index=list("bcd")) exp = pd.Series([False, False, True, True], index=list("abcd")) - assert_series_equal(left.eq(right, fill_value=2), exp) + tm.assert_series_equal(left.eq(right, fill_value=2), exp) exp = pd.Series([True, True, False, False], index=list("abcd")) - assert_series_equal(left.ne(right, fill_value=2), exp) + tm.assert_series_equal(left.ne(right, fill_value=2), exp) exp = pd.Series([False, False, True, True], index=list("abcd")) - assert_series_equal(left.le(right, fill_value=0), exp) + tm.assert_series_equal(left.le(right, fill_value=0), exp) exp = pd.Series([False, False, False, True], index=list("abcd")) - assert_series_equal(left.lt(right, fill_value=0), exp) + tm.assert_series_equal(left.lt(right, fill_value=0), exp) exp = pd.Series([True, True, True, False], index=list("abcd")) - assert_series_equal(left.ge(right, fill_value=0), exp) + tm.assert_series_equal(left.ge(right, fill_value=0), exp) exp = pd.Series([True, True, False, False], index=list("abcd")) - assert_series_equal(left.gt(right, fill_value=0), exp) + tm.assert_series_equal(left.gt(right, fill_value=0), exp) class TestSeriesOperators: def test_operators_empty_int_corner(self): s1 = Series([], [], dtype=np.int32) s2 = Series({"x": 0.0}) - assert_series_equal(s1 * s2, Series([np.nan], index=["x"])) + tm.assert_series_equal(s1 * s2, Series([np.nan], index=["x"])) def test_ops_datetimelike_align(self): # GH 7500 @@ -760,11 +754,11 @@ def test_ops_datetimelike_align(self): expected = Series([timedelta(0), timedelta(0), pd.NaT]) # name is reset result = dt2 - dt - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) expected = Series(expected, name=0) result = (dt2.to_frame() - dt.to_frame())[0] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_operators_corner(self, datetime_series): empty = Series([], index=Index([])) @@ -830,14 +824,14 @@ def _check_fill(meth, op, a, b, fill_value=0): result = meth(a, b, fill_value=fill_value) expected = Series(exp_values, exp_index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) a = Series([np.nan, 1.0, 2.0, 3.0, np.nan], index=np.arange(5)) b = Series([np.nan, 1, np.nan, 3, np.nan, 4.0], index=np.arange(6)) result = op(a, b) exp = equiv_op(a, b) - assert_series_equal(result, exp) + tm.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) @@ -861,7 +855,7 @@ def test_op_duplicate_index(self): s2 = Series([10, 10], index=[1, 2]) result = s1 + s2 expected = pd.Series([11, 12, np.nan], index=[1, 1, 2]) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_divmod(self): # GH25557 @@ -870,13 +864,13 @@ def test_divmod(self): result = a.divmod(b) expected = divmod(a, b) - assert_series_equal(result[0], expected[0]) - assert_series_equal(result[1], expected[1]) + tm.assert_series_equal(result[0], expected[0]) + tm.assert_series_equal(result[1], expected[1]) result = a.rdivmod(b) expected = divmod(b, a) - assert_series_equal(result[0], expected[0]) - assert_series_equal(result[1], expected[1]) + tm.assert_series_equal(result[0], expected[0]) + tm.assert_series_equal(result[1], expected[1]) @pytest.mark.parametrize("index", [None, range(9)]) def test_series_integer_mod(self, index): @@ -896,9 +890,9 @@ class TestSeriesUnaryOps: def test_neg(self): ser = tm.makeStringSeries() ser.name = "series" - assert_series_equal(-ser, -1 * ser) + tm.assert_series_equal(-ser, -1 * ser) def test_invert(self): ser = tm.makeStringSeries() ser.name = "series" - assert_series_equal(-(ser < 0), ~(ser < 0)) + tm.assert_series_equal(-(ser < 0), ~(ser < 0)) diff --git a/pandas/tests/series/test_rank.py b/pandas/tests/series/test_rank.py index 6a79edca01c99..793e8b7da4965 100644 --- a/pandas/tests/series/test_rank.py +++ b/pandas/tests/series/test_rank.py @@ -10,7 +10,6 @@ from pandas import NaT, Series, Timestamp, date_range from pandas.api.types import CategoricalDtype import pandas.util.testing as tm -from pandas.util.testing import assert_series_equal class TestSeriesRank: @@ -34,7 +33,7 @@ def test_rank(self, datetime_series): ranks = datetime_series.rank() oranks = datetime_series.astype("O").rank() - assert_series_equal(ranks, oranks) + tm.assert_series_equal(ranks, oranks) mask = np.isnan(datetime_series) filled = datetime_series.fillna(np.inf) @@ -49,58 +48,58 @@ def test_rank(self, datetime_series): iranks = iseries.rank() exp = iseries.astype(float).rank() - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) iseries = Series(np.arange(5)) + 1.0 exp = iseries / 5.0 iranks = iseries.rank(pct=True) - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) iseries = Series(np.repeat(1, 100)) exp = Series(np.repeat(0.505, 100)) iranks = iseries.rank(pct=True) - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) iseries[1] = np.nan exp = Series(np.repeat(50.0 / 99.0, 100)) exp[1] = np.nan iranks = iseries.rank(pct=True) - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) iseries = Series(np.arange(5)) + 1.0 iseries[4] = np.nan exp = iseries / 4.0 iranks = iseries.rank(pct=True) - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) iseries = Series(np.repeat(np.nan, 100)) exp = iseries.copy() iranks = iseries.rank(pct=True) - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) iseries = Series(np.arange(5)) + 1 iseries[4] = np.nan exp = iseries / 4.0 iranks = iseries.rank(pct=True) - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) rng = date_range("1/1/1990", periods=5) iseries = Series(np.arange(5), rng) + 1 iseries.iloc[4] = np.nan exp = iseries / 4.0 iranks = iseries.rank(pct=True) - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) iseries = Series([1e-50, 1e-100, 1e-20, 1e-2, 1e-20 + 1e-30, 1e-1]) exp = Series([2, 1, 3, 5, 4, 6.0]) iranks = iseries.rank() - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) # GH 5968 iseries = Series(["3 day", "1 day 10m", "-2 day", NaT], dtype="m8[ns]") exp = Series([3, 2, 1, np.nan]) iranks = iseries.rank() - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) values = np.array( [-50, -1, -1e-20, -1e-25, -1e-50, 0, 1e-40, 1e-20, 1e-10, 2, 40], @@ -110,7 +109,7 @@ def test_rank(self, datetime_series): iseries = Series(values[random_order]) exp = Series(random_order + 1.0, dtype="float64") iranks = iseries.rank() - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) def test_rank_categorical(self): # GH issue #15420 rank incorrectly orders ordered categories @@ -126,8 +125,8 @@ def test_rank_categorical(self): ordered=True, ) ) - assert_series_equal(ordered.rank(), exp) - assert_series_equal(ordered.rank(ascending=False), exp_desc) + tm.assert_series_equal(ordered.rank(), exp) + tm.assert_series_equal(ordered.rank(ascending=False), exp_desc) # Unordered categoricals should be ranked as objects unordered = Series( @@ -140,14 +139,14 @@ def test_rank_categorical(self): ) exp_unordered = Series([2.0, 4.0, 6.0, 3.0, 1.0, 5.0]) res = unordered.rank() - assert_series_equal(res, exp_unordered) + tm.assert_series_equal(res, exp_unordered) unordered1 = Series([1, 2, 3, 4, 5, 6]).astype( CategoricalDtype([1, 2, 3, 4, 5, 6], False) ) exp_unordered1 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) res1 = unordered1.rank() - assert_series_equal(res1, exp_unordered1) + tm.assert_series_equal(res1, exp_unordered1) # Test na_option for rank data na_ser = Series( @@ -163,18 +162,20 @@ def test_rank_categorical(self): exp_bot = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]) exp_keep = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, np.NaN]) - assert_series_equal(na_ser.rank(na_option="top"), exp_top) - assert_series_equal(na_ser.rank(na_option="bottom"), exp_bot) - assert_series_equal(na_ser.rank(na_option="keep"), exp_keep) + tm.assert_series_equal(na_ser.rank(na_option="top"), exp_top) + tm.assert_series_equal(na_ser.rank(na_option="bottom"), exp_bot) + tm.assert_series_equal(na_ser.rank(na_option="keep"), exp_keep) # Test na_option for rank data with ascending False exp_top = Series([7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0]) exp_bot = Series([6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 7.0]) exp_keep = Series([6.0, 5.0, 4.0, 3.0, 2.0, 1.0, np.NaN]) - assert_series_equal(na_ser.rank(na_option="top", ascending=False), exp_top) - assert_series_equal(na_ser.rank(na_option="bottom", ascending=False), exp_bot) - assert_series_equal(na_ser.rank(na_option="keep", ascending=False), exp_keep) + tm.assert_series_equal(na_ser.rank(na_option="top", ascending=False), exp_top) + tm.assert_series_equal( + na_ser.rank(na_option="bottom", ascending=False), exp_bot + ) + tm.assert_series_equal(na_ser.rank(na_option="keep", ascending=False), exp_keep) # Test invalid values for na_option msg = "na_option must be one of 'keep', 'top', or 'bottom'" @@ -194,9 +195,9 @@ def test_rank_categorical(self): exp_bot = Series([0.2, 0.4, 0.6, 0.8, 1.0]) exp_keep = Series([0.25, 0.5, 0.75, 1.0, np.NaN]) - assert_series_equal(na_ser.rank(na_option="top", pct=True), exp_top) - assert_series_equal(na_ser.rank(na_option="bottom", pct=True), exp_bot) - assert_series_equal(na_ser.rank(na_option="keep", pct=True), exp_keep) + tm.assert_series_equal(na_ser.rank(na_option="top", pct=True), exp_top) + tm.assert_series_equal(na_ser.rank(na_option="bottom", pct=True), exp_bot) + tm.assert_series_equal(na_ser.rank(na_option="keep", pct=True), exp_keep) def test_rank_signature(self): s = Series([0, 1]) @@ -291,7 +292,7 @@ def test_rank_inf(self, contents, dtype): iseries = Series(values[random_order]) exp = Series(exp_order[random_order], dtype="float64") iranks = iseries.rank() - assert_series_equal(iranks, exp) + tm.assert_series_equal(iranks, exp) def test_rank_tie_methods(self): s = self.s @@ -394,7 +395,7 @@ def test_rank_dense_method(self): s = Series(ser).astype(dtype) result = s.rank(method="dense") expected = Series(exp).astype(result.dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_rank_descending(self): dtypes = ["O", "f8", "i8"] @@ -407,14 +408,14 @@ def test_rank_descending(self): res = s.rank(ascending=False) expected = (s.max() - s).rank() - assert_series_equal(res, expected) + tm.assert_series_equal(res, expected) if method == "first" and dtype == "O": continue expected = (s.max() - s).rank(method=method) res2 = s.rank(method=method, ascending=False) - assert_series_equal(res2, expected) + tm.assert_series_equal(res2, expected) def test_rank_int(self): s = self.s.dropna().astype("i8") @@ -423,7 +424,7 @@ def test_rank_int(self): result = s.rank(method=method) expected = Series(res).dropna() expected.index = result.index - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_rank_object_bug(self): # GH 13445 @@ -440,7 +441,7 @@ def test_rank_modify_inplace(self): s.rank() result = s - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH15630, pct should be on 100% basis when method='dense' @@ -465,7 +466,7 @@ def test_rank_dense_pct(dtype, ser, exp): s = Series(ser).astype(dtype) result = s.rank(method="dense", pct=True) expected = Series(exp).astype(result.dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("dtype", ["O", "f8", "i8"]) @@ -487,7 +488,7 @@ def test_rank_min_pct(dtype, ser, exp): s = Series(ser).astype(dtype) result = s.rank(method="min", pct=True) expected = Series(exp).astype(result.dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("dtype", ["O", "f8", "i8"]) @@ -509,7 +510,7 @@ def test_rank_max_pct(dtype, ser, exp): s = Series(ser).astype(dtype) result = s.rank(method="max", pct=True) expected = Series(exp).astype(result.dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("dtype", ["O", "f8", "i8"]) @@ -531,7 +532,7 @@ def test_rank_average_pct(dtype, ser, exp): s = Series(ser).astype(dtype) result = s.rank(method="average", pct=True) expected = Series(exp).astype(result.dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("dtype", ["f8", "i8"]) @@ -553,7 +554,7 @@ def test_rank_first_pct(dtype, ser, exp): s = Series(ser).astype(dtype) result = s.rank(method="first", pct=True) expected = Series(exp).astype(result.dtype) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) @pytest.mark.single diff --git a/pandas/tests/series/test_sorting.py b/pandas/tests/series/test_sorting.py index 192b57d2a9007..8039b133cae10 100644 --- a/pandas/tests/series/test_sorting.py +++ b/pandas/tests/series/test_sorting.py @@ -5,7 +5,6 @@ from pandas import Categorical, DataFrame, IntervalIndex, MultiIndex, Series import pandas.util.testing as tm -from pandas.util.testing import assert_almost_equal, assert_series_equal class TestSeriesSorting: @@ -38,17 +37,17 @@ def test_sort_values(self, datetime_series): # ascending=False ordered = ts.sort_values(ascending=False) expected = np.sort(ts.dropna().values)[::-1] - assert_almost_equal(expected, ordered.dropna().values) + tm.assert_almost_equal(expected, ordered.dropna().values) ordered = ts.sort_values(ascending=False, na_position="first") - assert_almost_equal(expected, ordered.dropna().values) + tm.assert_almost_equal(expected, ordered.dropna().values) # ascending=[False] should behave the same as ascending=False ordered = ts.sort_values(ascending=[False]) expected = ts.sort_values(ascending=False) - assert_series_equal(expected, ordered) + tm.assert_series_equal(expected, ordered) ordered = ts.sort_values(ascending=[False], na_position="first") expected = ts.sort_values(ascending=False, na_position="first") - assert_series_equal(expected, ordered) + tm.assert_series_equal(expected, ordered) msg = "ascending must be boolean" with pytest.raises(ValueError, match=msg): @@ -92,28 +91,28 @@ def test_sort_index(self, datetime_series): random_order = datetime_series.reindex(rindex) sorted_series = random_order.sort_index() - assert_series_equal(sorted_series, datetime_series) + tm.assert_series_equal(sorted_series, datetime_series) # descending sorted_series = random_order.sort_index(ascending=False) - assert_series_equal( + tm.assert_series_equal( sorted_series, datetime_series.reindex(datetime_series.index[::-1]) ) # compat on level sorted_series = random_order.sort_index(level=0) - assert_series_equal(sorted_series, datetime_series) + tm.assert_series_equal(sorted_series, datetime_series) # compat on axis sorted_series = random_order.sort_index(axis=0) - assert_series_equal(sorted_series, datetime_series) + tm.assert_series_equal(sorted_series, datetime_series) msg = "No axis named 1 for object type <class 'pandas.core.series.Series'>" with pytest.raises(ValueError, match=msg): random_order.sort_values(axis=1) sorted_series = random_order.sort_index(level=0, axis=0) - assert_series_equal(sorted_series, datetime_series) + tm.assert_series_equal(sorted_series, datetime_series) with pytest.raises(ValueError, match=msg): random_order.sort_index(level=0, axis=1) @@ -149,12 +148,12 @@ def test_sort_index_multiindex(self, level): # implicit sort_remaining=True res = s.sort_index(level=level) - assert_series_equal(backwards, res) + tm.assert_series_equal(backwards, res) # GH13496 # sort has no effect without remaining lvls res = s.sort_index(level=level, sort_remaining=False) - assert_series_equal(s, res) + tm.assert_series_equal(s, res) def test_sort_index_kind(self): # GH #14444 & #13589: Add support for sort algo choosing @@ -162,24 +161,24 @@ def test_sort_index_kind(self): expected_series = Series(index=[1, 2, 3, 3, 4]) index_sorted_series = series.sort_index(kind="mergesort") - assert_series_equal(expected_series, index_sorted_series) + tm.assert_series_equal(expected_series, index_sorted_series) index_sorted_series = series.sort_index(kind="quicksort") - assert_series_equal(expected_series, index_sorted_series) + tm.assert_series_equal(expected_series, index_sorted_series) index_sorted_series = series.sort_index(kind="heapsort") - assert_series_equal(expected_series, index_sorted_series) + tm.assert_series_equal(expected_series, index_sorted_series) def test_sort_index_na_position(self): series = Series(index=[3, 2, 1, 4, 3, np.nan]) expected_series_first = Series(index=[np.nan, 1, 2, 3, 3, 4]) index_sorted_series = series.sort_index(na_position="first") - assert_series_equal(expected_series_first, index_sorted_series) + tm.assert_series_equal(expected_series_first, index_sorted_series) expected_series_last = Series(index=[1, 2, 3, 3, 4, np.nan]) index_sorted_series = series.sort_index(na_position="last") - assert_series_equal(expected_series_last, index_sorted_series) + tm.assert_series_equal(expected_series_last, index_sorted_series) def test_sort_index_intervals(self): s = Series( @@ -188,13 +187,13 @@ def test_sort_index_intervals(self): result = s.sort_index() expected = s - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = s.sort_index(ascending=False) expected = Series( [3, 2, 1, np.nan], IntervalIndex.from_arrays([3, 2, 1, 0], [4, 3, 2, 1]) ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_sort_values_categorical(self): diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index f8c9c06900c3e..7154975c6c73b 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -26,11 +26,6 @@ from pandas.core.indexes.datetimes import DatetimeIndex from pandas.core.indexes.timedeltas import TimedeltaIndex import pandas.util.testing as tm -from pandas.util.testing import ( - assert_almost_equal, - assert_frame_equal, - assert_series_equal, -) from pandas.tseries.offsets import BDay, BMonthEnd @@ -61,19 +56,19 @@ def test_shift(self, datetime_series): shifted = datetime_series.shift(1, freq=offset) unshifted = shifted.shift(-1, freq=offset) - assert_series_equal(unshifted, datetime_series) + tm.assert_series_equal(unshifted, datetime_series) unshifted = datetime_series.shift(0, freq=offset) - assert_series_equal(unshifted, datetime_series) + tm.assert_series_equal(unshifted, datetime_series) shifted = datetime_series.shift(1, freq="B") unshifted = shifted.shift(-1, freq="B") - assert_series_equal(unshifted, datetime_series) + tm.assert_series_equal(unshifted, datetime_series) # corner case unshifted = datetime_series.shift(0) - assert_series_equal(unshifted, datetime_series) + tm.assert_series_equal(unshifted, datetime_series) # Shifting with PeriodIndex ps = tm.makePeriodSeries() @@ -85,8 +80,8 @@ def test_shift(self, datetime_series): shifted2 = ps.shift(1, "B") shifted3 = ps.shift(1, BDay()) - assert_series_equal(shifted2, shifted3) - assert_series_equal(ps, shifted2.shift(-1, "B")) + tm.assert_series_equal(shifted2, shifted3) + tm.assert_series_equal(ps, shifted2.shift(-1, "B")) msg = "Given freq D does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): @@ -94,10 +89,10 @@ def test_shift(self, datetime_series): # legacy support shifted4 = ps.shift(1, freq="B") - assert_series_equal(shifted2, shifted4) + tm.assert_series_equal(shifted2, shifted4) shifted5 = ps.shift(1, freq=BDay()) - assert_series_equal(shifted5, shifted4) + tm.assert_series_equal(shifted5, shifted4) # 32-bit taking # GH 8129 @@ -107,7 +102,7 @@ def test_shift(self, datetime_series): p = s1.iloc[1] result = s1.shift(periods=p) expected = Series([np.nan, 0, 1, 2, 3], index=index) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # xref 8260 # with tz @@ -117,7 +112,7 @@ def test_shift(self, datetime_series): result = s - s.shift() exp = Series(TimedeltaIndex(["NaT"] + ["1 days"] * 4), name="foo") - assert_series_equal(result, exp) + tm.assert_series_equal(result, exp) # incompat tz s2 = Series(date_range("2000-01-01 09:00:00", periods=5, tz="CET"), name="foo") @@ -215,13 +210,13 @@ def test_tshift(self, datetime_series): shifted = ps.tshift(1) unshifted = shifted.tshift(-1) - assert_series_equal(unshifted, ps) + tm.assert_series_equal(unshifted, ps) shifted2 = ps.tshift(freq="B") - assert_series_equal(shifted, shifted2) + tm.assert_series_equal(shifted, shifted2) shifted3 = ps.tshift(freq=BDay()) - assert_series_equal(shifted, shifted3) + tm.assert_series_equal(shifted, shifted3) msg = "Given freq M does not match PeriodIndex freq B" with pytest.raises(ValueError, match=msg): @@ -231,18 +226,18 @@ def test_tshift(self, datetime_series): shifted = datetime_series.tshift(1) unshifted = shifted.tshift(-1) - assert_series_equal(datetime_series, unshifted) + tm.assert_series_equal(datetime_series, unshifted) shifted2 = datetime_series.tshift(freq=datetime_series.index.freq) - assert_series_equal(shifted, shifted2) + tm.assert_series_equal(shifted, shifted2) inferred_ts = Series( datetime_series.values, Index(np.asarray(datetime_series.index)), name="ts" ) shifted = inferred_ts.tshift(1) unshifted = shifted.tshift(-1) - assert_series_equal(shifted, datetime_series.tshift(1)) - assert_series_equal(unshifted, inferred_ts) + tm.assert_series_equal(shifted, datetime_series.tshift(1)) + tm.assert_series_equal(unshifted, inferred_ts) no_freq = datetime_series[[0, 5, 7]] msg = "Freq was not given and was not set in the index" @@ -259,34 +254,34 @@ def test_truncate(self, datetime_series): # neither specified truncated = ts.truncate() - assert_series_equal(truncated, ts) + tm.assert_series_equal(truncated, ts) # both specified expected = ts[1:3] truncated = ts.truncate(start, end) - assert_series_equal(truncated, expected) + tm.assert_series_equal(truncated, expected) truncated = ts.truncate(start_missing, end_missing) - assert_series_equal(truncated, expected) + tm.assert_series_equal(truncated, expected) # start specified expected = ts[1:] truncated = ts.truncate(before=start) - assert_series_equal(truncated, expected) + tm.assert_series_equal(truncated, expected) truncated = ts.truncate(before=start_missing) - assert_series_equal(truncated, expected) + tm.assert_series_equal(truncated, expected) # end specified expected = ts[:3] truncated = ts.truncate(after=end) - assert_series_equal(truncated, expected) + tm.assert_series_equal(truncated, expected) truncated = ts.truncate(after=end_missing) - assert_series_equal(truncated, expected) + tm.assert_series_equal(truncated, expected) # corner case, empty series returned truncated = ts.truncate(after=datetime_series.index[0] - offset) @@ -359,19 +354,19 @@ def test_asfreq_datetimeindex_empty_series(self): def test_pct_change(self, datetime_series): rs = datetime_series.pct_change(fill_method=None) - assert_series_equal(rs, datetime_series / datetime_series.shift(1) - 1) + tm.assert_series_equal(rs, datetime_series / datetime_series.shift(1) - 1) rs = datetime_series.pct_change(2) filled = datetime_series.fillna(method="pad") - assert_series_equal(rs, filled / filled.shift(2) - 1) + tm.assert_series_equal(rs, filled / filled.shift(2) - 1) rs = datetime_series.pct_change(fill_method="bfill", limit=1) filled = datetime_series.fillna(method="bfill", limit=1) - assert_series_equal(rs, filled / filled.shift(1) - 1) + tm.assert_series_equal(rs, filled / filled.shift(1) - 1) rs = datetime_series.pct_change(freq="5D") filled = datetime_series.fillna(method="pad") - assert_series_equal( + tm.assert_series_equal( rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled) ) @@ -380,7 +375,7 @@ def test_pct_change_shift_over_nas(self): chg = s.pct_change() expected = Series([np.nan, 0.5, 0.0, 2.5 / 1.5 - 1, 0.2]) - assert_series_equal(chg, expected) + tm.assert_series_equal(chg, expected) @pytest.mark.parametrize( "freq, periods, fill_method, limit", @@ -403,12 +398,12 @@ def test_pct_change_periods_freq( rs_periods = datetime_series.pct_change( periods, fill_method=fill_method, limit=limit ) - assert_series_equal(rs_freq, rs_periods) + tm.assert_series_equal(rs_freq, rs_periods) empty_ts = Series(index=datetime_series.index) rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit) rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit) - assert_series_equal(rs_freq, rs_periods) + tm.assert_series_equal(rs_freq, rs_periods) def test_autocorr(self, datetime_series): # Just run the function @@ -473,7 +468,7 @@ def test_first_last_valid(self, datetime_series): def test_mpl_compat_hack(self, datetime_series): result = datetime_series[:, np.newaxis] expected = datetime_series.values[:, np.newaxis] - assert_almost_equal(result, expected) + tm.assert_almost_equal(result, expected) def test_timeseries_coercion(self): idx = tm.makeDateIndex(10000) @@ -504,14 +499,14 @@ def test_to_datetime_unit(self): expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([epoch + t for t in range(20)]).astype(float) result = to_datetime(s, unit="s") expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([epoch + t for t in range(20)] + [iNaT]) result = to_datetime(s, unit="s") @@ -519,7 +514,7 @@ def test_to_datetime_unit(self): [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + [NaT] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = Series([epoch + t for t in range(20)] + [iNaT]).astype(float) result = to_datetime(s, unit="s") @@ -527,7 +522,7 @@ def test_to_datetime_unit(self): [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + [NaT] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # GH13834 s = Series([epoch + t for t in np.arange(0, 2, 0.25)] + [iNaT]).astype(float) @@ -539,7 +534,7 @@ def test_to_datetime_unit(self): ] + [NaT] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) s = concat( [Series([epoch + t for t in range(20)]).astype(float), Series([np.nan])], @@ -550,7 +545,7 @@ def test_to_datetime_unit(self): [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + [NaT] ) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = to_datetime([1, 2, "NaT", pd.NaT, np.nan], unit="D") expected = DatetimeIndex( @@ -615,13 +610,13 @@ def test_promote_datetime_date(self): result = ts + ts2 result2 = ts2 + ts expected = ts + ts[5:] - assert_series_equal(result, expected) - assert_series_equal(result2, expected) + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, expected) # test asfreq result = ts2.asfreq("4H", method="ffill") expected = ts[5:].asfreq("4H", method="ffill") - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = rng.get_indexer(ts2.index) expected = rng.get_indexer(ts_slice.index) @@ -637,7 +632,7 @@ def test_asfreq_normalize(self): norm = date_range("1/1/2000", periods=20) expected = Series(vals, index=norm) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) vals = np.random.randn(20, 3) ts = DataFrame(vals, index=rng) @@ -645,7 +640,7 @@ def test_asfreq_normalize(self): result = ts.asfreq("D", normalize=True) expected = DataFrame(vals, index=norm) - assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_first_subset(self): ts = _simple_ts("1/1/2000", "1/1/2010", freq="12h") @@ -658,14 +653,14 @@ def test_first_subset(self): result = ts.first("3M") expected = ts[:"3/31/2000"] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.first("21D") expected = ts[:21] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts[:0].first("3M") - assert_series_equal(result, ts[:0]) + tm.assert_series_equal(result, ts[:0]) def test_first_raises(self): # GH20725 @@ -685,14 +680,14 @@ def test_last_subset(self): result = ts.last("21D") expected = ts["12/12/2009":] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts.last("21D") expected = ts[-21:] - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) result = ts[:0].last("3M") - assert_series_equal(result, ts[:0]) + tm.assert_series_equal(result, ts[:0]) def test_last_raises(self): # GH20725 @@ -717,7 +712,7 @@ def test_at_time(self): result = ts.at_time("9:30") expected = ts.at_time(time(9, 30)) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) df = DataFrame(np.random.randn(len(rng), 3), index=rng) @@ -728,7 +723,7 @@ def test_at_time(self): # expected.index = date_range('1/1/2000', '1/4/2000') - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) tm.assert_frame_equal(result_df, exp_df) chunk = df.loc["1/4/2000":] @@ -741,7 +736,7 @@ def test_at_time(self): ts = Series(np.random.randn(len(rng)), index=rng) result = ts.at_time(time(0, 0)) - assert_series_equal(result, ts) + tm.assert_series_equal(result, ts) # time doesn't exist rng = date_range("1/1/2012", freq="23Min", periods=384) @@ -762,7 +757,7 @@ def test_between(self): result = series.between(left, right) expected = (series >= left) & (series <= right) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_between_time(self): rng = date_range("1/1/2000", "1/5/2000", freq="5min") @@ -794,7 +789,7 @@ def test_between_time(self): result = ts.between_time("00:00", "01:00") expected = ts.between_time(stime, etime) - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) # across midnight rng = date_range("1/1/2000", "1/5/2000", freq="5min") @@ -891,12 +886,12 @@ def test_to_period(self): pts = ts.to_period() exp = ts.copy() exp.index = period_range("1/1/2000", "1/1/2001") - assert_series_equal(pts, exp) + tm.assert_series_equal(pts, exp) pts = ts.to_period("M") exp.index = exp.index.asfreq("M") tm.assert_index_equal(pts.index, exp.index.asfreq("M")) - assert_series_equal(pts, exp) + tm.assert_series_equal(pts, exp) # GH 7606 without freq idx = DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"]) @@ -907,16 +902,16 @@ def test_to_period(self): s = Series(np.random.randn(4), index=idx) expected = s.copy() expected.index = exp_idx - assert_series_equal(s.to_period(), expected) + tm.assert_series_equal(s.to_period(), expected) df = DataFrame(np.random.randn(4, 4), index=idx, columns=idx) expected = df.copy() expected.index = exp_idx - assert_frame_equal(df.to_period(), expected) + tm.assert_frame_equal(df.to_period(), expected) expected = df.copy() expected.columns = exp_idx - assert_frame_equal(df.to_period(axis=1), expected) + tm.assert_frame_equal(df.to_period(axis=1), expected) def test_groupby_count_dateparseerror(self): dr = date_range(start="1/1/2012", freq="5min", periods=10) @@ -930,7 +925,7 @@ def test_groupby_count_dateparseerror(self): grouped = s.groupby(lambda x: x[0] % 2 == 0) expected = grouped.count() - assert_series_equal(result, expected) + tm.assert_series_equal(result, expected) def test_to_csv_numpy_16_bug(self): frame = DataFrame({"a": date_range("1/1/2000", periods=10)})
Part of #29272 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29273
2019-10-29T21:22:07Z
2019-10-29T23:12:03Z
2019-10-29T23:12:03Z
2019-10-29T23:12:11Z
BLD: fix some build warnings
diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in index 0ae8094769f46..c3b0a84067f92 100644 --- a/pandas/_libs/algos_common_helper.pxi.in +++ b/pandas/_libs/algos_common_helper.pxi.in @@ -22,54 +22,55 @@ ctypedef fused out_t: def diff_2d(ndarray[diff_t, ndim=2] arr, ndarray[out_t, ndim=2] out, Py_ssize_t periods, int axis): + cdef: + Py_ssize_t i, j, sx, sy # Disable for unsupported dtype combinations, # see https://github.com/cython/cython/issues/2646 - if out_t is float32_t: - if not (diff_t is float32_t or diff_t is int8_t or diff_t is int16_t): - raise NotImplementedError + if (out_t is float32_t + and not (diff_t is float32_t or diff_t is int8_t or diff_t is int16_t)): + raise NotImplementedError + elif (out_t is float64_t + and (diff_t is float32_t or diff_t is int8_t or diff_t is int16_t)): + raise NotImplementedError else: - if (diff_t is float32_t or diff_t is int8_t or diff_t is int16_t): - raise NotImplementedError - - cdef: - Py_ssize_t i, j, sx, sy - - sx, sy = (<object>arr).shape - if arr.flags.f_contiguous: - if axis == 0: - if periods >= 0: - start, stop = periods, sx + # We put this inside an indented else block to avoid cython build + # warnings about unreachable code + sx, sy = (<object>arr).shape + if arr.flags.f_contiguous: + if axis == 0: + if periods >= 0: + start, stop = periods, sx + else: + start, stop = 0, sx + periods + for j in range(sy): + for i in range(start, stop): + out[i, j] = arr[i, j] - arr[i - periods, j] else: - start, stop = 0, sx + periods - for j in range(sy): - for i in range(start, stop): - out[i, j] = arr[i, j] - arr[i - periods, j] + if periods >= 0: + start, stop = periods, sy + else: + start, stop = 0, sy + periods + for j in range(start, stop): + for i in range(sx): + out[i, j] = arr[i, j] - arr[i, j - periods] else: - if periods >= 0: - start, stop = periods, sy + if axis == 0: + if periods >= 0: + start, stop = periods, sx + else: + start, stop = 0, sx + periods + for i in range(start, stop): + for j in range(sy): + out[i, j] = arr[i, j] - arr[i - periods, j] else: - start, stop = 0, sy + periods - for j in range(start, stop): + if periods >= 0: + start, stop = periods, sy + else: + start, stop = 0, sy + periods for i in range(sx): - out[i, j] = arr[i, j] - arr[i, j - periods] - else: - if axis == 0: - if periods >= 0: - start, stop = periods, sx - else: - start, stop = 0, sx + periods - for i in range(start, stop): - for j in range(sy): - out[i, j] = arr[i, j] - arr[i - periods, j] - else: - if periods >= 0: - start, stop = periods, sy - else: - start, stop = 0, sy + periods - for i in range(sx): - for j in range(start, stop): - out[i, j] = arr[i, j] - arr[i, j - periods] + for j in range(start, stop): + out[i, j] = arr[i, j] - arr[i, j - periods] # ---------------------------------------------------------------------- diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 6efe5e90f522f..71de80da699e9 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -833,6 +833,9 @@ cdef inline bint _treat_as_na(rank_t val, bint is_datetimelike) nogil: elif rank_t is int64_t: return is_datetimelike and val == NPY_NAT + elif rank_t is uint64_t: + # There is no NA value for uint64 + return False else: return val != val @@ -1278,7 +1281,8 @@ def group_max(groupby_t[:, :] out, if groupby_t is uint64_t: runtime_error = True break - out[i, j] = nan_val + else: + out[i, j] = nan_val else: out[i, j] = maxx[i, j] @@ -1349,7 +1353,8 @@ def group_min(groupby_t[:, :] out, if groupby_t is uint64_t: runtime_error = True break - out[i, j] = nan_val + else: + out[i, j] = nan_val else: out[i, j] = minx[i, j] diff --git a/pandas/io/msgpack/_packer.pyx b/pandas/io/msgpack/_packer.pyx index aa71c5cc39667..7c7c8f7b61e60 100644 --- a/pandas/io/msgpack/_packer.pyx +++ b/pandas/io/msgpack/_packer.pyx @@ -235,7 +235,8 @@ cdef class Packer: continue else: raise TypeError("can't serialize {thing!r}".format(thing=o)) - return ret + break + return ret cpdef pack(self, object obj): cdef int ret
https://api.github.com/repos/pandas-dev/pandas/pulls/29271
2019-10-29T20:04:21Z
2019-10-30T11:53:03Z
2019-10-30T11:53:03Z
2019-10-30T14:28:45Z
Add simple test for GH 28448
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index e70e4f2fe501b..528053aa8c7f1 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -223,6 +223,26 @@ def test_cast_category_to_extension_dtype(self, expected): tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "dtype, expected", + [ + ( + "datetime64[ns]", + np.array(["2015-01-01T00:00:00.000000000"], dtype="datetime64[ns]"), + ), + ( + "datetime64[ns, MET]", + pd.DatetimeIndex( + [pd.Timestamp("2015-01-01 00:00:00+0100", tz="MET")] + ).array, + ), + ], + ) + def test_consistent_casting(self, dtype, expected): + # GH 28448 + result = pd.Categorical("2015-01-01").astype(dtype) + assert result == expected + class TestArithmeticOps(base.BaseArithmeticOpsTests): def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
- [x] closes #28448 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29269
2019-10-29T16:07:49Z
2019-10-31T15:56:19Z
2019-10-31T15:56:19Z
2019-10-31T16:03:28Z
Fix SS06 formatting errors
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d7043a8cda7b2..5a248838810e9 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5251,8 +5251,7 @@ def swaplevel(self, i=-2, j=-1, axis=0): def reorder_levels(self, order, axis=0): """ - Rearrange index levels using input order. May not drop or - duplicate levels. + Rearrange index levels using input order. May not drop or duplicate levels. Parameters ---------- @@ -5854,9 +5853,10 @@ def pivot(self, index=None, columns=None, values=None): _shared_docs[ "pivot_table" ] = """ - Create a spreadsheet-style pivot table as a DataFrame. The levels in - the pivot table will be stored in MultiIndex objects (hierarchical - indexes) on the index and columns of the result DataFrame. + Create a spreadsheet-style pivot table as a DataFrame. + + The levels in the pivot table will be stored in MultiIndex objects + (hierarchical indexes) on the index and columns of the result DataFrame. Parameters ----------%s @@ -6249,8 +6249,9 @@ def explode(self, column: Union[str, Tuple]) -> "DataFrame": def unstack(self, level=-1, fill_value=None): """ - Pivot a level of the (necessarily hierarchical) index labels, returning - a DataFrame having a new level of column labels whose inner-most level + Pivot a level of the (necessarily hierarchical) index labels. + + Returns a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels. If the index is not a MultiIndex, the output will be a Series @@ -6312,8 +6313,7 @@ def unstack(self, level=-1, fill_value=None): _shared_docs[ "melt" ] = """ - Unpivot a DataFrame from wide format to long format, optionally - leaving identifier variables set. + Unpivot a DataFrame from wide to long format, optionally leaving identifiers set. This function is useful to massage a DataFrame into a format where one or more columns are identifier variables (`id_vars`), while all other @@ -7908,6 +7908,7 @@ def nunique(self, axis=0, dropna=True): def idxmin(self, axis=0, skipna=True): """ Return index of first occurrence of minimum over requested axis. + NA/null values are excluded. Parameters @@ -7945,6 +7946,7 @@ def idxmin(self, axis=0, skipna=True): def idxmax(self, axis=0, skipna=True): """ Return index of first occurrence of maximum over requested axis. + NA/null values are excluded. Parameters diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 81742b5337e47..e15332a5277b9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4353,8 +4353,9 @@ def sort_index( def reindex(self, *args, **kwargs): """ - Conform %(klass)s to new index with optional filling logic, placing - NA/NaN in locations having no value in the previous index. A new object + Conform %(klass)s to new index with optional filling logic. + + Places NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and ``copy=False``. @@ -4669,8 +4670,7 @@ def _reindex_with_indexers( def filter(self, items=None, like=None, regex=None, axis=None): """ - Subset rows or columns of dataframe according to labels in - the specified index. + Subset the dataframe rows or columns according to the specified index labels. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index. @@ -8497,8 +8497,7 @@ def resample( def first(self, offset): """ - Convenience method for subsetting initial periods of time series data - based on a date offset. + Method to subset initial periods of time series data based on a date offset. Parameters ---------- @@ -8560,8 +8559,7 @@ def first(self, offset): def last(self, offset): """ - Convenience method for subsetting final periods of time series data - based on a date offset. + Method to subset final periods of time series data based on a date offset. Parameters ----------
Errors resolved (from list in #29254): pandas.DataFrame.filter pandas.DataFrame.first pandas.DataFrame.idxmax pandas.DataFrame.idxmin pandas.DataFrame.last pandas.DataFrame.reindex pandas.DataFrame.pivot_table pandas.DataFrame.reorder_levels pandas.DataFrame.unstack pandas.DataFrame.melt Validated with `python scripts/validate_docstrings.py` Referencing issue: #27977
https://api.github.com/repos/pandas-dev/pandas/pulls/29263
2019-10-29T09:27:58Z
2019-10-29T16:57:57Z
2019-10-29T16:57:57Z
2021-05-09T00:48:47Z
TST: Test named aggregations with functions
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index aa80c461a00e7..b56da5fba6f80 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -495,6 +495,33 @@ def test_mangled(self): tm.assert_frame_equal(result, expected) +def myfunc(s): + return np.percentile(s, q=0.90) + + +@pytest.mark.parametrize("func", [lambda s: np.percentile(s, q=0.90), myfunc]) +def test_lambda_named_agg(func): + # see gh-28467 + animals = DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + + result = animals.groupby("kind").agg( + mean_height=("height", "mean"), perc90=("height", func) + ) + expected = DataFrame( + [[9.3, 9.1036], [20.0, 6.252]], + columns=["mean_height", "perc90"], + index=Index(["cat", "dog"], name="kind"), + ) + + tm.assert_frame_equal(result, expected) + + class TestLambdaMangling: def test_maybe_mangle_lambdas_passthrough(self): assert _maybe_mangle_lambdas("mean") == "mean"
Closes https://github.com/pandas-dev/pandas/issues/28467
https://api.github.com/repos/pandas-dev/pandas/pulls/29262
2019-10-29T04:48:49Z
2019-10-29T13:09:06Z
2019-10-29T13:09:05Z
2019-10-29T15:44:08Z
REF: Pre-empt TypeError in groupby
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 707c0c3571eac..8d13c37270d7a 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -140,15 +140,20 @@ def apply(self, f, data, axis=0): group_keys = self._get_group_keys() result_values = None - # oh boy - f_name = com.get_callable_name(f) - if ( - f_name not in base.plotting_methods + sdata = splitter._get_sorted_data() + if sdata.ndim == 2 and np.any(sdata.dtypes.apply(is_extension_array_dtype)): + # calling splitter.fast_apply will raise TypeError via apply_frame_axis0 + # if we pass EA instead of ndarray + # TODO: can we have a workaround for EAs backed by ndarray? + pass + + elif ( + com.get_callable_name(f) not in base.plotting_methods and hasattr(splitter, "fast_apply") and axis == 0 # with MultiIndex, apply_frame_axis0 would raise InvalidApply # TODO: can we make this check prettier? - and not splitter._get_sorted_data().index._has_complex_internals + and not sdata.index._has_complex_internals ): try: result_values, mutated = splitter.fast_apply(f, group_keys) @@ -166,12 +171,6 @@ def apply(self, f, data, axis=0): # TODO: can we infer anything about whether this is # worth-retrying in pure-python? raise - except TypeError as err: - if "Cannot convert" in str(err): - # via apply_frame_axis0 if we pass a non-ndarray - pass - else: - raise for key, (i, group) in zip(group_keys, splitter): object.__setattr__(group, "name", key)
cc @WillAyd @jreback, should be orthogonal to #29228.
https://api.github.com/repos/pandas-dev/pandas/pulls/29261
2019-10-29T02:03:25Z
2019-11-02T19:18:16Z
2019-11-02T19:18:16Z
2019-11-02T21:07:09Z
Multiindex recurse error fix
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index efea1fc1f525f..6804cc08a0638 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -946,6 +946,7 @@ Reshaping - :func:`qcut` and :func:`cut` now handle boolean input (:issue:`20303`) - Fix to ensure all int dtypes can be used in :func:`merge_asof` when using a tolerance value. Previously every non-int64 type would raise an erroneous ``MergeError`` (:issue:`28870`). - Better error message in :func:`get_dummies` when `columns` isn't a list-like value (:issue:`28383`) +- Bug in :meth:`Index.join` that caused infinite recursion error for mismatched ``MultiIndex`` name orders. (:issue:`25760`, :issue:`28956`) - Bug :meth:`Series.pct_change` where supplying an anchored frequency would throw a ValueError (:issue:`28664`) - Bug where :meth:`DataFrame.equals` returned True incorrectly in some cases when two DataFrames had the same columns in different orders (:issue:`28839`) - Bug in :meth:`DataFrame.replace` that caused non-numeric replacer's dtype not respected (:issue:`26632`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e9e3a5ef94a1f..28e144a957d1c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3368,8 +3368,13 @@ def _join_multi(self, other, how, return_indexers=True): ldrop_names = list(self_names - overlap) rdrop_names = list(other_names - overlap) - self_jnlevels = self.droplevel(ldrop_names) - other_jnlevels = other.droplevel(rdrop_names) + # if only the order differs + if not len(ldrop_names + rdrop_names): + self_jnlevels = self + other_jnlevels = other.reorder_levels(self.names) + else: + self_jnlevels = self.droplevel(ldrop_names) + other_jnlevels = other.droplevel(rdrop_names) # Join left and right # Join on same leveled multi-index frames is supported diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py index 42d8cf761842e..31ab521958342 100644 --- a/pandas/tests/indexes/multi/test_join.py +++ b/pandas/tests/indexes/multi/test_join.py @@ -87,3 +87,19 @@ def test_join_self_unique(idx, join_type): if idx.is_unique: joined = idx.join(idx, how=join_type) assert (idx == joined).all() + + +def test_join_multi_wrong_order(): + # GH 25760 + # GH 28956 + + midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) + midx2 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["b", "a"]) + + join_idx, lidx, ridx = midx1.join(midx2, return_indexers=False) + + exp_ridx = np.array([-1, -1, -1, -1], dtype=np.intp) + + tm.assert_index_equal(midx1, join_idx) + assert lidx is None + tm.assert_numpy_array_equal(ridx, exp_ridx) diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index bce62571d55ec..d269196401554 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -828,3 +828,22 @@ def test_single_common_level(self): ).set_index(["key", "X", "Y"]) tm.assert_frame_equal(result, expected) + + def test_join_multi_wrong_order(self): + # GH 25760 + # GH 28956 + + midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) + midx3 = pd.MultiIndex.from_tuples([(4, 1), (3, 2), (3, 1)], names=["b", "a"]) + + left = pd.DataFrame(index=midx1, data={"x": [10, 20, 30, 40]}) + right = pd.DataFrame(index=midx3, data={"y": ["foo", "bar", "fing"]}) + + result = left.join(right) + + expected = pd.DataFrame( + index=midx1, + data={"x": [10, 20, 30, 40], "y": ["fing", "foo", "bar", np.nan]}, + ) + + tm.assert_frame_equal(result, expected)
test and 3 line fix for a small bug mentioned in 2 issues (1 closed). test might be expanded, I only checked for the error disappearing - [x] closes #25760 (and #28956 ) - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29260
2019-10-28T22:43:15Z
2020-01-01T20:46:46Z
2020-01-01T20:46:46Z
2020-01-01T20:46:53Z
DOC: use new logo in the sphinx theme as well
diff --git a/doc/source/conf.py b/doc/source/conf.py index 13d3324caf249..b4f719b6e64b2 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -218,7 +218,7 @@ # The name of an image file (relative to this directory) to place at the top # of the sidebar. -# html_logo = None +html_logo = "../../web/pandas/static/img/pandas.svg" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files,
With this change (https://github.com/pandas-dev/pandas-sphinx-theme/commit/84134e0804325538918324246f449e694466929b) in the theme, that should work. However, locally, I am running into the problem that sphinx/html doesn't seem to like the svg logo's .. For local testing I added a converted png which works, but just replacing `.png` with `.svg` makes that the html does not include the image (at least in firefox). cc @datapythonista
https://api.github.com/repos/pandas-dev/pandas/pulls/29259
2019-10-28T21:07:03Z
2019-10-29T09:00:40Z
2019-10-29T09:00:40Z
2019-10-29T09:00:40Z
CLN: catch specific exceptions in frame.py
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2208a0b878144..620e565aa55c8 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1666,11 +1666,12 @@ def from_records( else: try: index_data = [arrays[arr_columns.get_loc(field)] for field in index] + except (KeyError, TypeError): + # raised by get_loc, see GH#29258 + result_index = index + else: result_index = ensure_index_from_sequences(index_data, names=index) - exclude.update(index) - except Exception: - result_index = index if any(exclude): arr_exclude = [x for x in exclude if x in arr_columns] @@ -3625,11 +3626,11 @@ def reindexer(value): # GH 4107 try: value = value.reindex(self.index)._values - except Exception as e: - - # duplicate axis + except ValueError as err: + # raised in MultiIndex.from_tuples, see test_insert_error_msmgs if not value.index.is_unique: - raise e + # duplicate axis + raise err # other raise TypeError( @@ -7796,7 +7797,8 @@ def f(x): # TODO: combine with hasattr(result, 'dtype') further down # hard since we don't have `values` down there. result = np.bool_(result) - except Exception as e: + except TypeError as err: + # e.g. in nanops trying to convert strs to float # try by-column first if filter_type is None and axis == 0: @@ -7826,7 +7828,7 @@ def f(x): raise NotImplementedError( "Handling exception with filter_type {f} not" "implemented.".format(f=filter_type) - ) from e + ) from err with np.errstate(all="ignore"): result = f(data.values) labels = data._get_agg_axis(axis)
https://api.github.com/repos/pandas-dev/pandas/pulls/29258
2019-10-28T20:58:08Z
2019-10-29T16:08:29Z
2019-10-29T16:08:29Z
2019-10-29T16:22:19Z
Timedelta index 29236
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 84a4cbbc0a447..7a6f28a86dee0 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1457,15 +1457,16 @@ def mean(self, skipna=True): Parameters ---------- skipna : bool, default True - Whether to ignore any NaT elements + Whether to ignore any NaT elements. Returns ------- - scalar (Timestamp or Timedelta) + scalar + Timestamp or Timedelta. See Also -------- - numpy.ndarray.mean + numpy.ndarray.mean : Returns the average of array elements along a given axis. Series.mean : Return the mean value in a Series. Notes diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 4c15e4b26ed46..79d97a13e37ca 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1169,20 +1169,22 @@ def to_flat_index(self): def to_series(self, index=None, name=None): """ - Create a Series with both index and values equal to the index keys - useful with map for returning an indexer based on an index. + Create a Series with both index and values equal to the index keys. + + Useful with map for returning an indexer based on an index. Parameters ---------- index : Index, optional - index of resulting Series. If None, defaults to original index + Index of resulting Series. If None, defaults to original index. name : str, optional - name of resulting Series. If None, defaults to name of original - index + Dame of resulting Series. If None, defaults to name of original + index. Returns ------- - Series : dtype will be based on the type of the Index values. + Series + The dtype will be based on the type of the Index values. """ from pandas import Series
- [ ] closes #29236 only remaining docstring errors are for `TimedeltaIndex.mean` Parameters {*args, **kwargs} not documented Unknown parameters {skipna}
https://api.github.com/repos/pandas-dev/pandas/pulls/29257
2019-10-28T20:11:15Z
2019-10-29T03:16:23Z
2019-10-29T03:16:23Z
2020-01-06T16:47:22Z
DOC: Added whatsnew for GH-29174
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index f4761c5663c9f..f704a1018c926 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -171,10 +171,6 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -R --include="*.py" --include="*.pyx" --include="*.rst" -E "\.\. (autosummary|contents|currentmodule|deprecated|function|image|important|include|ipython|literalinclude|math|module|note|raw|seealso|toctree|versionadded|versionchanged|warning):[^:]" ./pandas ./doc/source RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Check that the deprecated `assert_raises_regex` is not used (`pytest.raises(match=pattern)` should be used instead)' ; echo $MSG - invgrep -R --exclude=*.pyc --exclude=testing.py --exclude=test_util.py assert_raises_regex pandas - RET=$(($RET + $?)) ; echo $MSG "DONE" - # Check for the following code in testing: `unittest.mock`, `mock.Mock()` or `mock.patch` MSG='Check that unittest.mock is not used (pytest builtin monkeypatch fixture should be used instead)' ; echo $MSG invgrep -r -E --include '*.py' '(unittest(\.| import )mock|mock\.Mock\(\)|mock\.patch)' pandas/tests/ diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 4007ecd5a9412..5e16cee1de89c 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -255,6 +255,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - Removed the previously deprecated ``IntervalIndex.from_intervals`` in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) - Ability to read pickles containing :class:`Categorical` instances created with pre-0.16 version of pandas has been removed (:issue:`27538`) - Removed the previously deprecated ``reduce`` and ``broadcast`` arguments from :meth:`DataFrame.apply` (:issue:`18577`) +- Removed the previously deprecated ``assert_raises_regex`` function in ``pandas.util.testing`` (:issue:`29174`) - .. _whatsnew_1000.performance:
follow up to #29174
https://api.github.com/repos/pandas-dev/pandas/pulls/29256
2019-10-28T19:44:16Z
2019-10-30T07:34:30Z
2019-10-30T07:34:29Z
2020-01-16T00:33:41Z
Fix SS06 formatting errors
diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py index 57fd6d284af31..595af6dc08733 100644 --- a/pandas/core/arrays/sparse/accessor.py +++ b/pandas/core/arrays/sparse/accessor.py @@ -308,8 +308,7 @@ def to_coo(self): @property def density(self) -> float: """ - Ratio of non-sparse points to total (dense) data points - represented in the DataFrame. + Ratio of non-sparse points to total (dense) data points. """ return np.mean([column.array.density for _, column in self._parent.items()]) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 23611055d6f01..d7043a8cda7b2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -814,8 +814,10 @@ def to_string( @property def style(self): """ - Property returning a Styler object containing methods for - building a styled HTML representation fo the DataFrame. + Returns a Styler object. + + Contains methods for building a styled HTML representation of the DataFrame. + a styled HTML representation fo the DataFrame. See Also -------- @@ -8207,6 +8209,8 @@ def to_timestamp(self, freq=None, how="start", axis=0, copy=True): def to_period(self, freq=None, axis=0, copy=True): """ + Convert DataFrame from DatetimeIndex to PeriodIndex. + Convert DataFrame from DatetimeIndex to PeriodIndex with desired frequency (inferred from index if not passed). diff --git a/pandas/core/generic.py b/pandas/core/generic.py index fe0923f096493..81742b5337e47 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5766,8 +5766,7 @@ def ftypes(self): def as_blocks(self, copy=True): """ - Convert the frame to a dict of dtype -> Constructor Types that each has - a homogeneous dtype. + Convert the frame to a dict of dtype -> Constructor Types. .. deprecated:: 0.21.0 @@ -9428,9 +9427,10 @@ def shift(self, periods=1, freq=None, axis=0, fill_value=None): def slice_shift(self, periods=1, axis=0): """ - Equivalent to `shift` without copying data. The shifted data will - not include the dropped periods and the shifted axis will be smaller - than the original. + Equivalent to `shift` without copying data. + + The shifted data will not include the dropped periods and the + shifted axis will be smaller than the original. Parameters ---------- @@ -10739,10 +10739,11 @@ def nanptp(values, axis=0, skipna=True): name, name2, axis_descr, - """Return the difference between the maximum value and the + """Return the difference between the min and max value. + \n.. deprecated:: 0.24.0 Use numpy.ptp instead + \nReturn the difference between the maximum value and the minimum value in the object. This is the equivalent of the - ``numpy.ndarray`` method ``ptp``.\n\n.. deprecated:: 0.24.0 - Use numpy.ptp instead""", + ``numpy.ndarray`` method ``ptp``.""", nanptp, ) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 45cb037600fd7..44c786f003369 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1291,8 +1291,7 @@ def _get_slice_axis(self, slice_obj: slice, axis: int): class _IXIndexer(_NDFrameIndexer): """ - A primarily label-location based indexer, with integer position - fallback. + A primarily label-location based indexer, with integer position fallback. Warning: Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers. diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 127fdffafcf36..c11d94c381d6d 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -496,7 +496,9 @@ def boxplot_frame_groupby( class PlotAccessor(PandasObject): """ - Make plots of Series or DataFrame using the backend specified by the + Make plots of Series or DataFrame. + + Uses the backend specified by the option ``plotting.backend``. By default, matplotlib is used. Parameters
SS06 (Summary should fit in a single line) errors fixed (#29254) for the following: ``` pandas.DataFrame.slice_shift pandas.DataFrame.to_period pandas.DataFrame.plot pandas.DataFrame.sparse.density pandas.DataFrame.style pandas.Series.as_blocks pandas.Series.ix pandas.Series.ptp pandas.DataFrame.as_blocks pandas.DataFrame.ix ``` Validated with `python scripts/validate_docstrings.py` Also referencing issue: #27977
https://api.github.com/repos/pandas-dev/pandas/pulls/29255
2019-10-28T17:10:48Z
2019-10-29T03:14:34Z
2019-10-29T03:14:34Z
2019-10-30T16:17:55Z
CLN: remove algorithms.match
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 8f72245b1f4eb..5139fdfeeb916 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -226,9 +226,8 @@ def _get_hashtable_algo(values): ------- htable : HashTable subclass values : ndarray - dtype : str or dtype """ - values, dtype, ndtype = _ensure_data(values) + values, _, ndtype = _ensure_data(values) if ndtype == "object": @@ -239,7 +238,7 @@ def _get_hashtable_algo(values): ndtype = "string" htable = _hashtables[ndtype] - return htable, values, dtype + return htable, values def _get_values_for_rank(values): @@ -271,44 +270,6 @@ def _get_data_algo(values): # --------------- # -def match(to_match, values, na_sentinel=-1): - """ - Compute locations of to_match into values - - Parameters - ---------- - to_match : array-like - values to find positions of - values : array-like - Unique set of values - na_sentinel : int, default -1 - Value to mark "not found" - - Examples - -------- - - Returns - ------- - match : ndarray of integers - """ - values = com.asarray_tuplesafe(values) - htable, values, dtype = _get_hashtable_algo(values) - to_match, _, _ = _ensure_data(to_match, dtype) - table = htable(min(len(to_match), 1000000)) - table.map_locations(values) - result = table.lookup(to_match) - - if na_sentinel != -1: - # replace but return a numpy array - # use a Series because it handles dtype conversions properly - from pandas import Series - - result = Series(result.ravel()).replace(-1, na_sentinel) - result = result.values.reshape(result.shape) - - return result - - def unique(values): """ Hash table-based unique. Uniques are returned in order @@ -395,7 +356,7 @@ def unique(values): return values.unique() original = values - htable, values, _ = _get_hashtable_algo(values) + htable, values = _get_hashtable_algo(values) table = htable(len(values)) uniques = table.unique(values) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 48cfc06f42e91..738afaea4b532 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -31,41 +31,6 @@ from pandas.util.testing import assert_almost_equal -class TestMatch: - def test_ints(self): - values = np.array([0, 2, 1]) - to_match = np.array([0, 1, 2, 2, 0, 1, 3, 0]) - - result = algos.match(to_match, values) - expected = np.array([0, 2, 1, 1, 0, 2, -1, 0], dtype=np.int64) - tm.assert_numpy_array_equal(result, expected) - - result = Series(algos.match(to_match, values, np.nan)) - expected = Series(np.array([0, 2, 1, 1, 0, 2, np.nan, 0])) - tm.assert_series_equal(result, expected) - - s = Series(np.arange(5), dtype=np.float32) - result = algos.match(s, [2, 4]) - expected = np.array([-1, -1, 0, -1, 1], dtype=np.int64) - tm.assert_numpy_array_equal(result, expected) - - result = Series(algos.match(s, [2, 4], np.nan)) - expected = Series(np.array([np.nan, np.nan, 0, np.nan, 1])) - tm.assert_series_equal(result, expected) - - def test_strings(self): - values = ["foo", "bar", "baz"] - to_match = ["bar", "foo", "qux", "foo", "bar", "baz", "qux"] - - result = algos.match(to_match, values) - expected = np.array([1, 0, -1, 0, 1, 2, -1], dtype=np.int64) - tm.assert_numpy_array_equal(result, expected) - - result = Series(algos.match(to_match, values, np.nan)) - expected = Series(np.array([1, 0, np.nan, 0, 1, 2, np.nan])) - tm.assert_series_equal(result, expected) - - class TestFactorize: def test_basic(self):
Appears to be dead code, allows for simplification of _get_hashtable_algo.
https://api.github.com/repos/pandas-dev/pandas/pulls/29249
2019-10-27T23:02:56Z
2019-10-28T18:40:57Z
2019-10-28T18:40:57Z
2020-02-09T17:05:17Z
REF: Simplify _cython_functions lookup
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index b4300c162156f..49a335218db96 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -937,7 +937,7 @@ def group_last(rank_t[:, :] out, def group_nth(rank_t[:, :] out, int64_t[:] counts, rank_t[:, :] values, - const int64_t[:] labels, int64_t rank, + const int64_t[:] labels, int64_t rank=1, Py_ssize_t min_count=-1): """ Only aggregates on axis=0 @@ -1028,8 +1028,9 @@ def group_nth(rank_t[:, :] out, def group_rank(float64_t[:, :] out, rank_t[:, :] values, const int64_t[:] labels, - bint is_datetimelike, object ties_method, - bint ascending, bint pct, object na_option): + int ngroups, + bint is_datetimelike, object ties_method="average", + bint ascending=True, bint pct=False, object na_option="keep"): """ Provides the rank of values within each group. @@ -1039,6 +1040,9 @@ def group_rank(float64_t[:, :] out, values : array of rank_t values to be ranked labels : array containing unique label for each group, with its ordering matching up to the corresponding record in `values` + ngroups : int + This parameter is not used, is needed to match signatures of other + groupby functions. is_datetimelike : bool, default False unused in this method but provided for call compatibility with other Cython transformations diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 3aae31d02bc0d..2a7fd079679a4 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -319,12 +319,9 @@ def get_group_levels(self): "min": "group_min", "max": "group_max", "mean": "group_mean", - "median": {"name": "group_median"}, + "median": "group_median", "var": "group_var", - "first": { - "name": "group_nth", - "f": lambda func, a, b, c, d, e: func(a, b, c, d, 1, -1), - }, + "first": "group_nth", "last": "group_last", "ohlc": "group_ohlc", }, @@ -333,19 +330,7 @@ def get_group_levels(self): "cumsum": "group_cumsum", "cummin": "group_cummin", "cummax": "group_cummax", - "rank": { - "name": "group_rank", - "f": lambda func, a, b, c, d, e, **kwargs: func( - a, - b, - c, - e, - kwargs.get("ties_method", "average"), - kwargs.get("ascending", True), - kwargs.get("pct", False), - kwargs.get("na_option", "keep"), - ), - }, + "rank": "group_rank", }, } @@ -391,21 +376,7 @@ def get_func(fname): ftype = self._cython_functions[kind][how] - if isinstance(ftype, dict): - func = afunc = get_func(ftype["name"]) - - # a sub-function - f = ftype.get("f") - if f is not None: - - def wrapper(*args, **kwargs): - return f(afunc, *args, **kwargs) - - # need to curry our sub-function - func = wrapper - - else: - func = get_func(ftype) + func = get_func(ftype) if func is None: raise NotImplementedError( @@ -517,14 +488,7 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): ) counts = np.zeros(self.ngroups, dtype=np.int64) result = self._aggregate( - result, - counts, - values, - labels, - func, - is_numeric, - is_datetimelike, - min_count, + result, counts, values, labels, func, is_datetimelike, min_count ) elif kind == "transform": result = _maybe_fill( @@ -533,7 +497,7 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): # TODO: min_count result = self._transform( - result, values, labels, func, is_numeric, is_datetimelike, **kwargs + result, values, labels, func, is_datetimelike, **kwargs ) if is_integer_dtype(result) and not is_datetimelike: @@ -574,33 +538,22 @@ def transform(self, values, how, axis=0, **kwargs): return self._cython_operation("transform", values, how, axis, **kwargs) def _aggregate( - self, - result, - counts, - values, - comp_ids, - agg_func, - is_numeric, - is_datetimelike, - min_count=-1, + self, result, counts, values, comp_ids, agg_func, is_datetimelike, min_count=-1 ): if values.ndim > 2: # punting for now raise NotImplementedError("number of dimensions is currently limited to 2") + elif agg_func is libgroupby.group_nth: + # different signature from the others + # TODO: should we be using min_count instead of hard-coding it? + agg_func(result, counts, values, comp_ids, rank=1, min_count=-1) else: agg_func(result, counts, values, comp_ids, min_count) return result def _transform( - self, - result, - values, - comp_ids, - transform_func, - is_numeric, - is_datetimelike, - **kwargs + self, result, values, comp_ids, transform_func, is_datetimelike, **kwargs ): comp_ids, _, ngroups = self.group_info
The remaining two non-trivial cases are ("aggregate", "first") and ("aggregate", "median"). The "first" case I think is straightforward. The "median" case I'm reticent to change because it isn't clear to me why it is a dict at all (cc @WillAyd if you have any ideas)
https://api.github.com/repos/pandas-dev/pandas/pulls/29246
2019-10-27T18:05:54Z
2019-10-31T17:10:31Z
2019-10-31T17:10:31Z
2019-10-31T17:13:44Z
ENH: Styler.background_gradient to accept vmin vmax and dtype Int64
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index fa1669b1f3343..32602a1ccd24d 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -112,6 +112,7 @@ Other enhancements - :meth:`read_stata` can read Stata 119 dta files. (:issue:`28250`) - Added ``encoding`` argument to :meth:`DataFrame.to_string` for non-ascii text (:issue:`28766`) - Added ``encoding`` argument to :func:`DataFrame.to_html` for non-ascii text (:issue:`28663`) +- :meth:`Styler.background_gradient` now accepts ``vmin`` and ``vmax`` arguments (:issue:`12145`) Build Changes ^^^^^^^^^^^^^ @@ -386,6 +387,7 @@ I/O - Bug in :meth:`DataFrame.read_excel` with ``engine='ods'`` when ``sheet_name`` argument references a non-existent sheet (:issue:`27676`) - Bug in :meth:`pandas.io.formats.style.Styler` formatting for floating values not displaying decimals correctly (:issue:`13257`) - Bug in :meth:`DataFrame.to_html` when using ``formatters=<list>`` and ``max_cols`` together. (:issue:`25955`) +- Bug in :meth:`Styler.background_gradient` not able to work with dtype ``Int64`` (:issue:`28869`) Plotting ^^^^^^^^ diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 545d6a674411a..9865087a26ae3 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -8,6 +8,7 @@ import copy from functools import partial from itertools import product +from typing import Optional from uuid import uuid1 import numpy as np @@ -18,7 +19,6 @@ from pandas.util._decorators import Appender from pandas.core.dtypes.common import is_float, is_string_like -from pandas.core.dtypes.generic import ABCSeries import pandas as pd from pandas.api.types import is_dict_like, is_list_like @@ -963,6 +963,8 @@ def background_gradient( axis=0, subset=None, text_color_threshold=0.408, + vmin: Optional[float] = None, + vmax: Optional[float] = None, ): """ Color the background in a gradient style. @@ -991,6 +993,18 @@ def background_gradient( .. versionadded:: 0.24.0 + vmin : float, optional + Minimum data value that corresponds to colormap minimum value. + When None (default): the minimum value of the data will be used. + + .. versionadded:: 1.0.0 + + vmax : float, optional + Maximum data value that corresponds to colormap maximum value. + When None (default): the maximum value of the data will be used. + + .. versionadded:: 1.0.0 + Returns ------- self : Styler @@ -1017,11 +1031,21 @@ def background_gradient( low=low, high=high, text_color_threshold=text_color_threshold, + vmin=vmin, + vmax=vmax, ) return self @staticmethod - def _background_gradient(s, cmap="PuBu", low=0, high=0, text_color_threshold=0.408): + def _background_gradient( + s, + cmap="PuBu", + low=0, + high=0, + text_color_threshold=0.408, + vmin: Optional[float] = None, + vmax: Optional[float] = None, + ): """ Color background in a range according to the data. """ @@ -1033,14 +1057,14 @@ def _background_gradient(s, cmap="PuBu", low=0, high=0, text_color_threshold=0.4 raise ValueError(msg) with _mpl(Styler.background_gradient) as (plt, colors): - smin = s.values.min() - smax = s.values.max() + smin = np.nanmin(s.to_numpy()) if vmin is None else vmin + smax = np.nanmax(s.to_numpy()) if vmax is None else vmax rng = smax - smin # extend lower / upper bounds, compresses color range norm = colors.Normalize(smin - (rng * low), smax + (rng * high)) # matplotlib colors.Normalize modifies inplace? # https://github.com/matplotlib/matplotlib/issues/5427 - rgbas = plt.cm.get_cmap(cmap)(norm(s.values)) + rgbas = plt.cm.get_cmap(cmap)(norm(s.to_numpy(dtype=float))) def relative_luminance(rgba): """ @@ -1111,12 +1135,8 @@ def _bar(s, align, colors, width=100, vmin=None, vmax=None): Draw bar chart in dataframe cells. """ # Get input value range. - smin = s.min() if vmin is None else vmin - if isinstance(smin, ABCSeries): - smin = smin.min() - smax = s.max() if vmax is None else vmax - if isinstance(smax, ABCSeries): - smax = smax.max() + smin = np.nanmin(s.to_numpy()) if vmin is None else vmin + smax = np.nanmax(s.to_numpy()) if vmax is None else vmax if align == "mid": smin = min(0, smin) smax = max(0, smax) @@ -1125,7 +1145,7 @@ def _bar(s, align, colors, width=100, vmin=None, vmax=None): smax = max(abs(smin), abs(smax)) smin = -smax # Transform to percent-range of linear-gradient - normed = width * (s.values - smin) / (smax - smin + 1e-12) + normed = width * (s.to_numpy(dtype=float) - smin) / (smax - smin + 1e-12) zero = -width * smin / (smax - smin + 1e-12) def css_bar(start, end, color): @@ -1304,17 +1324,15 @@ def _highlight_extrema(data, color="yellow", max_=True): Highlight the min or max in a Series or DataFrame. """ attr = "background-color: {0}".format(color) + + if max_: + extrema = data == np.nanmax(data.to_numpy()) + else: + extrema = data == np.nanmin(data.to_numpy()) + if data.ndim == 1: # Series from .apply - if max_: - extrema = data == data.max() - else: - extrema = data == data.min() return [attr if v else "" for v in extrema] else: # DataFrame from .tee - if max_: - extrema = data == data.max().max() - else: - extrema = data == data.min().min() return pd.DataFrame( np.where(extrema, attr, ""), index=data.index, columns=data.columns ) diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 0f1402d7da389..fa725ccae66f9 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -1648,6 +1648,23 @@ def test_background_gradient_axis(self): assert result[(1, 0)] == mid assert result[(1, 1)] == high + def test_background_gradient_vmin_vmax(self): + # GH 12145 + df = pd.DataFrame(range(5)) + ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx + assert ctx[(0, 0)] == ctx[(1, 0)] + assert ctx[(4, 0)] == ctx[(3, 0)] + + def test_background_gradient_int64(self): + # GH 28869 + df1 = pd.Series(range(3)).to_frame() + df2 = pd.Series(range(3), dtype="Int64").to_frame() + ctx1 = df1.style.background_gradient()._compute().ctx + ctx2 = df2.style.background_gradient()._compute().ctx + assert ctx2[(0, 0)] == ctx1[(0, 0)] + assert ctx2[(1, 0)] == ctx1[(1, 0)] + assert ctx2[(2, 0)] == ctx1[(2, 0)] + def test_block_names(): # catch accidental removal of a block
For `vmin` `vmax` use the same implementation as `Styler.bar` For dtype `Int64` issue, deprecated `.values` and use `.to_numpy` instead Here explicitly assign the dtype to float since we are doing normalize - [x] closes #12145 and #28869 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29245
2019-10-27T18:01:55Z
2019-11-03T12:59:56Z
2019-11-03T12:59:56Z
2019-11-03T13:00:00Z
Follow up PR: #28097 Simplify branch statement
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index f94d012b3aa03..ea4d95f848ce8 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1266,10 +1266,10 @@ def _get_grouper_for_level(self, mapper, level): # Remove unobserved levels from level_index level_index = level_index.take(uniques) - if len(level_index): - grouper = level_index.take(codes) - else: + if level_index._can_hold_na: grouper = level_index.take(codes, fill_value=True) + else: + grouper = level_index.take(codes) return grouper, codes, level_index
xref #28097 This is follow up pr. eliminate branch statement. "grouper" variable is assigned when handle NAs.
https://api.github.com/repos/pandas-dev/pandas/pulls/29243
2019-10-27T17:15:37Z
2020-01-26T01:35:52Z
2020-01-26T01:35:52Z
2020-02-05T08:47:25Z
BENCH: Improve perf of rolling.Apply.time_rolling
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index 493f96d46d5e7..7a72622fd5fe3 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -28,15 +28,15 @@ def peakmem_rolling(self, constructor, window, dtype, method): class Apply: params = ( ["DataFrame", "Series"], - [10, 1000], + [3, 300], ["int", "float"], [sum, np.sum, lambda x: np.sum(x) + 5], [True, False], ) - param_names = ["contructor", "window", "dtype", "function", "raw"] + param_names = ["constructor", "window", "dtype", "function", "raw"] def setup(self, constructor, window, dtype, function, raw): - N = 10 ** 5 + N = 10 ** 3 arr = (100 * np.random.random(N)).astype(dtype) self.roll = getattr(pd, constructor)(arr).rolling(window)
Per discussion in #29165, this PR significantly reduces the run time of the `rolling.Apply.time_rolling` benchmark from 8 minutes minimum. ``` $ asv dev -b rolling.Apply.time_rolling · Discovering benchmarks · Running 1 total benchmarks (1 commits * 1 environments * 1 benchmarks) [ 0.00%] ·· Benchmarking existing-py_home_chris_anaconda3_bin_python [ 50.00%] ··· Running (rolling.Apply.time_rolling--). [100.00%] ··· rolling.Apply.time_rolling ok [100.00%] ··· ============= ======== ======= =========================== ============= ============ -- raw ---------------------------------------------------------- -------------------------- constructor window dtype function True False ============= ======== ======= =========================== ============= ============ DataFrame 3 int <built-in function sum> 1.87±0.1ms 44.8±2ms DataFrame 3 int <function sum> 3.53±0.2ms 126±3ms DataFrame 3 int <function Apply.<lambda>> 4.20±0.2ms 126±7ms DataFrame 3 float <built-in function sum> 1.86±0.07ms 45.1±1ms DataFrame 3 float <function sum> 3.42±0.03ms 129±5ms DataFrame 3 float <function Apply.<lambda>> 4.34±0.5ms 133±9ms DataFrame 300 int <built-in function sum> 31.8±3ms 44.1±2ms DataFrame 300 int <function sum> 2.90±0.2ms 92.6±10ms DataFrame 300 int <function Apply.<lambda>> 3.24±0.2ms 93.9±4ms DataFrame 300 float <built-in function sum> 33.3±20ms 85.4±40ms DataFrame 300 float <function sum> 3.06±0.3ms 91.0±3ms DataFrame 300 float <function Apply.<lambda>> 3.19±0.2ms 91.5±4ms Series 3 int <built-in function sum> 1.42±0.03ms 43.6±1ms Series 3 int <function sum> 3.08±0.06ms 127±2ms Series 3 int <function Apply.<lambda>> 3.67±0.2ms 127±20ms Series 3 float <built-in function sum> 1.41±0.03ms 43.5±0.5ms Series 3 float <function sum> 3.08±0.1ms 123±3ms Series 3 float <function Apply.<lambda>> 3.65±0.1ms 129±6ms Series 300 int <built-in function sum> 31.2±2ms 43.8±3ms Series 300 int <function sum> 2.35±0.1ms 90.4±4ms Series 300 int <function Apply.<lambda>> 2.74±0.2ms 93.2±6ms Series 300 float <built-in function sum> 31.7±0.8ms 45.6±1ms Series 300 float <function sum> 2.36±0.1ms 108±20ms Series 300 float <function Apply.<lambda>> 2.82±0.09ms 99.4±2ms ============= ======== ======= =========================== ============= ============ ``` - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29239
2019-10-26T21:06:21Z
2019-10-28T18:40:13Z
2019-10-28T18:40:13Z
2019-10-28T19:36:39Z
Replace _has_complex_internals #29227
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 6302499b6d153..94b7c59b93563 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -13,7 +13,7 @@ is_list_like, is_sequence, ) -from pandas.core.dtypes.generic import ABCSeries +from pandas.core.dtypes.generic import ABCMultiIndex, ABCSeries if TYPE_CHECKING: from pandas import DataFrame, Series, Index @@ -281,7 +281,7 @@ def apply_standard(self): and not self.dtypes.apply(is_extension_array_dtype).any() # Disallow complex_internals since libreduction shortcut # cannot handle MultiIndex - and not self.agg_axis._has_complex_internals + and not isinstance(self.agg_axis, ABCMultiIndex) ): values = self.values diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 20ca176f4a456..5ac361a83abd0 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4086,11 +4086,6 @@ def _assert_can_do_op(self, value): msg = "'value' must be a scalar, passed: {0}" raise TypeError(msg.format(type(value).__name__)) - @property - def _has_complex_internals(self): - # to disable groupby tricks in MultiIndex - return False - def _is_memory_usage_qualified(self): """ Return a boolean if we need a qualified .info display. diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index a83fd6bf59f05..e768a5b6dd23c 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1396,11 +1396,6 @@ def values(self): self._tuples = lib.fast_zip(values) return self._tuples - @property - def _has_complex_internals(self): - # to disable groupby tricks - return True - @cache_readonly def is_monotonic_increasing(self): """
closes #29227 Hi, it my first issues within hacktoberfest. I replaced _has_complex_internals with isinstance/ Is it possible to import ABCMultiIndex?
https://api.github.com/repos/pandas-dev/pandas/pulls/29237
2019-10-26T13:49:24Z
2019-11-14T18:06:09Z
2019-11-14T18:06:08Z
2019-11-14T18:06:17Z
CLN: assorted cleanups
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index b2ffbb3ecb4f2..6efe5e90f522f 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -146,7 +146,8 @@ def group_cumprod_float64(float64_t[:, :] out, int ngroups, bint is_datetimelike, bint skipna=True): - """Cumulative product of columns of `values`, in row groups `labels`. + """ + Cumulative product of columns of `values`, in row groups `labels`. Parameters ---------- @@ -203,7 +204,8 @@ def group_cumsum(numeric[:, :] out, int ngroups, is_datetimelike, bint skipna=True): - """Cumulative sum of columns of `values`, in row groups `labels`. + """ + Cumulative sum of columns of `values`, in row groups `labels`. Parameters ---------- @@ -314,7 +316,8 @@ def group_shift_indexer(int64_t[:] out, const int64_t[:] labels, def group_fillna_indexer(ndarray[int64_t] out, ndarray[int64_t] labels, ndarray[uint8_t] mask, object direction, int64_t limit): - """Indexes how to fill values forwards or backwards within a group + """ + Indexes how to fill values forwards or backwards within a group. Parameters ---------- diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index d9bde2a471e06..cc114b48a5b53 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -227,7 +227,7 @@ cdef class IndexEngine: cdef _get_index_values(self): return self.vgetter() - def _call_monotonic(self, values): + cdef _call_monotonic(self, values): return algos.is_monotonic(values, timelike=False) def get_backfill_indexer(self, other, limit=None): @@ -236,7 +236,7 @@ cdef class IndexEngine: def get_pad_indexer(self, other, limit=None): return algos.pad(self._get_index_values(), other, limit=limit) - cdef _make_hash_table(self, n): + cdef _make_hash_table(self, Py_ssize_t n): raise NotImplementedError cdef _check_type(self, object val): @@ -262,7 +262,7 @@ cdef class IndexEngine: self.need_unique_check = 0 - cpdef _call_map_locations(self, values): + cdef void _call_map_locations(self, values): self.mapping.map_locations(values) def clear_mapping(self): @@ -391,7 +391,7 @@ cdef class ObjectEngine(IndexEngine): """ Index Engine for use with object-dtype Index, namely the base class Index """ - cdef _make_hash_table(self, n): + cdef _make_hash_table(self, Py_ssize_t n): return _hash.PyObjectHashTable(n) @@ -418,7 +418,7 @@ cdef class DatetimeEngine(Int64Engine): cdef _get_index_values(self): return self.vgetter().view('i8') - def _call_monotonic(self, values): + cdef _call_monotonic(self, values): return algos.is_monotonic(values, timelike=True) cpdef get_loc(self, object val): @@ -500,11 +500,13 @@ cdef class PeriodEngine(Int64Engine): cdef _get_index_values(self): return super(PeriodEngine, self).vgetter() - cpdef _call_map_locations(self, values): - super(PeriodEngine, self)._call_map_locations(values.view('i8')) + cdef void _call_map_locations(self, values): + # super(...) pattern doesn't seem to work with `cdef` + Int64Engine._call_map_locations(self, values.view('i8')) - def _call_monotonic(self, values): - return super(PeriodEngine, self)._call_monotonic(values.view('i8')) + cdef _call_monotonic(self, values): + # super(...) pattern doesn't seem to work with `cdef` + return Int64Engine._call_monotonic(self, values.view('i8')) def get_indexer(self, values): cdef ndarray[int64_t, ndim=1] ordinals diff --git a/pandas/_libs/index_class_helper.pxi.in b/pandas/_libs/index_class_helper.pxi.in index 4db048eeb0383..093cca4fe7ed5 100644 --- a/pandas/_libs/index_class_helper.pxi.in +++ b/pandas/_libs/index_class_helper.pxi.in @@ -29,7 +29,7 @@ dtypes = [('Float64', 'float64', 'float64_t', 'Float64', 'float64'), cdef class {{name}}Engine(IndexEngine): - cdef _make_hash_table(self, n): + cdef _make_hash_table(self, Py_ssize_t n): return _hash.{{hashtable_name}}HashTable(n) {{if name not in {'Float64', 'Float32'} }} @@ -38,7 +38,7 @@ cdef class {{name}}Engine(IndexEngine): raise KeyError(val) {{endif}} - cpdef _call_map_locations(self, values): + cdef void _call_map_locations(self, values): # self.mapping is of type {{hashtable_name}}HashTable, # so convert dtype of values self.mapping.map_locations(algos.ensure_{{hashtable_dtype}}(values)) diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index 48190d123f4a9..ff143fea892ae 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -319,7 +319,7 @@ cdef slice_getitem(slice slc, ind): @cython.boundscheck(False) @cython.wraparound(False) -cpdef slice indexer_as_slice(int64_t[:] vals): +cdef slice indexer_as_slice(int64_t[:] vals): cdef: Py_ssize_t i, n, start, stop int64_t d diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 7fc4fede1996b..eddc0beae7b8b 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -2168,8 +2168,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=0, @cython.boundscheck(False) @cython.wraparound(False) -def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, - bint convert=1): +def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=1): """ Substitute for np.vectorize with pandas-friendly dtype inference diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index 7ed131e1c7608..f505c0479e944 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -105,7 +105,7 @@ cdef class Reducer: flatiter it bint has_labels, has_ndarray_labels object res, name, labels, index - object cached_typ=None + object cached_typ = None arr = self.arr chunk = self.dummy @@ -248,7 +248,7 @@ cdef class SeriesBinGrouper: object res bint initialized = 0 Slider vslider, islider - object name, cached_typ=None, cached_ityp=None + object name, cached_typ = None, cached_ityp = None counts = np.zeros(self.ngroups, dtype=np.int64) diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 796d1400194fd..27abedcda5adf 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -581,7 +581,7 @@ def try_parse_dates(object[:] values, parser=None, else: result[i] = parse_date(values[i]) except Exception: - # Since parser is user-defined, we can't guess what it migh raise + # Since parser is user-defined, we can't guess what it might raise return values else: parse_date = parser diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 5139fdfeeb916..ca36546b8937a 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -260,9 +260,9 @@ def _get_data_algo(values): if lib.infer_dtype(values, skipna=False) in ["string"]: ndtype = "string" - f = _hashtables.get(ndtype, _hashtables["object"]) + htable = _hashtables.get(ndtype, _hashtables["object"]) - return f, values + return htable, values # --------------- # diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py index 3cc34ea1f4ed7..dc6378e83d229 100644 --- a/pandas/core/computation/engines.py +++ b/pandas/core/computation/engines.py @@ -29,7 +29,7 @@ def _check_ne_builtin_clash(expr): overlap = names & _ne_builtins if overlap: - s = ", ".join(map(repr, overlap)) + s = ", ".join(repr(x) for x in overlap) raise NumExprClobberingError( 'Variables in expression "{expr}" ' "overlap with builtins: ({s})".format(expr=expr, s=s) diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 28b6aef693bfe..dc0f381414970 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -4,7 +4,7 @@ from datetime import datetime from distutils.version import LooseVersion from functools import partial -import operator as op +import operator import numpy as np @@ -18,7 +18,7 @@ from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded -_reductions = "sum", "prod" +_reductions = ("sum", "prod") _unary_math_ops = ( "sin", @@ -273,20 +273,37 @@ def _not_in(x, y): return x not in y -_cmp_ops_syms = ">", "<", ">=", "<=", "==", "!=", "in", "not in" -_cmp_ops_funcs = op.gt, op.lt, op.ge, op.le, op.eq, op.ne, _in, _not_in +_cmp_ops_syms = (">", "<", ">=", "<=", "==", "!=", "in", "not in") +_cmp_ops_funcs = ( + operator.gt, + operator.lt, + operator.ge, + operator.le, + operator.eq, + operator.ne, + _in, + _not_in, +) _cmp_ops_dict = dict(zip(_cmp_ops_syms, _cmp_ops_funcs)) -_bool_ops_syms = "&", "|", "and", "or" -_bool_ops_funcs = op.and_, op.or_, op.and_, op.or_ +_bool_ops_syms = ("&", "|", "and", "or") +_bool_ops_funcs = (operator.and_, operator.or_, operator.and_, operator.or_) _bool_ops_dict = dict(zip(_bool_ops_syms, _bool_ops_funcs)) -_arith_ops_syms = "+", "-", "*", "/", "**", "//", "%" -_arith_ops_funcs = (op.add, op.sub, op.mul, op.truediv, op.pow, op.floordiv, op.mod) +_arith_ops_syms = ("+", "-", "*", "/", "**", "//", "%") +_arith_ops_funcs = ( + operator.add, + operator.sub, + operator.mul, + operator.truediv, + operator.pow, + operator.floordiv, + operator.mod, +) _arith_ops_dict = dict(zip(_arith_ops_syms, _arith_ops_funcs)) -_special_case_arith_ops_syms = "**", "//", "%" -_special_case_arith_ops_funcs = op.pow, op.floordiv, op.mod +_special_case_arith_ops_syms = ("**", "//", "%") +_special_case_arith_ops_funcs = (operator.pow, operator.floordiv, operator.mod) _special_case_arith_ops_dict = dict( zip(_special_case_arith_ops_syms, _special_case_arith_ops_funcs) ) @@ -371,7 +388,7 @@ def __call__(self, env): """ # handle truediv if self.op == "/" and env.scope["truediv"]: - self.func = op.truediv + self.func = operator.truediv # recurse over the left/right nodes left = self.lhs(env) @@ -502,8 +519,8 @@ def __init__(self, lhs, rhs, truediv, *args, **kwargs): _cast_inplace(com.flatten(self), acceptable_dtypes, np.float_) -_unary_ops_syms = "+", "-", "~", "not" -_unary_ops_funcs = op.pos, op.neg, op.invert, op.invert +_unary_ops_syms = ("+", "-", "~", "not") +_unary_ops_funcs = (operator.pos, operator.neg, operator.invert, operator.invert) _unary_ops_dict = dict(zip(_unary_ops_syms, _unary_ops_funcs)) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index d8b4e4127acd1..c47aaf7c773c4 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -432,7 +432,7 @@ def apply( b_items = self.items[b.mgr_locs.indexer] for k, obj in aligned_args.items(): - axis = getattr(obj, "_info_axis_number", 0) + axis = obj._info_axis_number kwargs[k] = obj.reindex(b_items, axis=axis, copy=align_copy) applied = getattr(b, f)(**kwargs) diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 5dd4cc946572c..b9267db76e1a8 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -237,7 +237,8 @@ def _get_values( fill_value_typ: Optional[str] = None, mask: Optional[np.ndarray] = None, ) -> Tuple[np.ndarray, Optional[np.ndarray], np.dtype, np.dtype, Any]: - """ Utility to get the values view, mask, dtype, dtype_max, and fill_value. + """ + Utility to get the values view, mask, dtype, dtype_max, and fill_value. If both mask and fill_value/fill_value_typ are not None and skipna is True, the values array will be copied. diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 13b994d116c76..bcbd13cdcf017 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -989,13 +989,12 @@ def test_query_with_nested_special_character(self, parser, engine): assert_frame_equal(res, expec) def test_query_lex_compare_strings(self, parser, engine): - import operator as opr a = Series(np.random.choice(list("abcde"), 20)) b = Series(np.arange(a.size)) df = DataFrame({"X": a, "Y": b}) - ops = {"<": opr.lt, ">": opr.gt, "<=": opr.le, ">=": opr.ge} + ops = {"<": operator.lt, ">": operator.gt, "<=": operator.le, ">=": operator.ge} for op, func in ops.items(): res = df.query('X %s "d"' % op, engine=engine, parser=parser) diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index 5660fa5ffed80..32e2a72fcef36 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -1,7 +1,7 @@ """ test partial slicing on Series/Frame """ from datetime import datetime -import operator as op +import operator import numpy as np import pytest @@ -408,10 +408,10 @@ def test_loc_datetime_length_one(self): @pytest.mark.parametrize( "op,expected", [ - (op.lt, [True, False, False, False]), - (op.le, [True, True, False, False]), - (op.eq, [False, True, False, False]), - (op.gt, [False, False, False, True]), + (operator.lt, [True, False, False, False]), + (operator.le, [True, True, False, False]), + (operator.eq, [False, True, False, False]), + (operator.gt, [False, False, False, True]), ], ) def test_selection_by_datetimelike(self, datetimelike, op, expected):
https://api.github.com/repos/pandas-dev/pandas/pulls/29232
2019-10-26T01:21:52Z
2019-10-29T16:06:50Z
2019-10-29T16:06:50Z
2020-04-05T17:44:57Z
Refresh Aptitude Package Lists in CI
diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 62c46b6970969..6fb8241d6d600 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -33,6 +33,7 @@ jobs: condition: true - script: | + sudo apt-get update sudo apt-get install -y libc6-dev-i386 ci/setup_env.sh displayName: 'Setup environment and build pandas'
This might fix the intermittent build failures by updating the package lists before trying to install anything via aptitude
https://api.github.com/repos/pandas-dev/pandas/pulls/29230
2019-10-25T20:41:52Z
2019-10-25T21:25:54Z
2019-10-25T21:25:54Z
2019-10-25T21:25:58Z
API/DOC: an ExtensionDtype.__from_arrow__ method to convert pyarrow.Array into ExtensionArray
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index 59ef17e3d121f..cd5064522bf4a 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -63,6 +63,18 @@ class property**. Added ``_metadata``, ``__hash__``, and changed the default definition of ``__eq__``. + For interaction with Apache Arrow (pyarrow), a ``__from_arrow__`` method + can be implemented: this method receives a pyarrow Array or ChunkedArray + as only argument and is expected to return the appropriate pandas + ExtensionArray for this dtype and the passed values:: + + class ExtensionDtype: + + def __from_arrow__( + self, array: pyarrow.Array/ChunkedArray + ) -> ExtensionArray: + ... + This class does not inherit from 'abc.ABCMeta' for performance reasons. Methods and properties required by the interface raise ``pandas.errors.AbstractMethodError`` and no ``register`` method is
xref the discussion in https://github.com/pandas-dev/pandas/issues/20612, and a companion to my PR in Arrow: https://github.com/apache/arrow/pull/5512 Summary: to support ExtensionArrays in the conversion of an arrow table into a pandas DataFrame, we need some way to convert pyarrow Arrays into pandas ExtensionArrays, given a certain pandas dtype (in pyarrow, we can for example know the resulting dtype from the stored metadata). For that, I propose to add the `ExtensionDtype.__from_arrow__` method, with the following signature: ``` class ExtensionDtype: def __from_arrow__(self, array: pyarrow.Array) -> pandas.ExtensionArray: ... ``` Note: I only added documentation about it (which should still be expanded) for now, and not a method in the base class (eg a NotImplementedError), because in pyarrow we use `hasattr` to see if this is supported (see the linked arrow PR).
https://api.github.com/repos/pandas-dev/pandas/pulls/29229
2019-10-25T19:21:18Z
2019-11-08T14:05:49Z
2019-11-08T14:05:49Z
2019-11-08T14:05:54Z
CLN: prevent libreduction TypeError
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 647eb5a2daa28..f4c3ac970a3ca 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1104,6 +1104,7 @@ def _aggregate_item_by_item(self, func, *args, **kwargs): # raised in _aggregate_named, handle at higher level # see test_apply_with_mutated_index raise + # otherwise we get here from an AttributeError in _make_wrapper cannot_agg.append(item) continue @@ -1466,7 +1467,8 @@ def _transform_item_by_item(self, obj, wrapper): output[col] = self[col].transform(wrapper) except AssertionError: raise - except Exception: + except TypeError: + # e.g. trying to call nanmean with string values pass else: inds.append(i) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 7d1c74e415658..e53e7ffdbf72f 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -641,12 +641,15 @@ def curried(x): # if we don't have this method to indicated to aggregate to # mark this column as an error try: - return self._aggregate_item_by_item(name, *args, **kwargs) + result = self._aggregate_item_by_item(name, *args, **kwargs) + assert self.obj.ndim == 2 + return result except AttributeError: # e.g. SparseArray has no flags attr # FIXME: 'SeriesGroupBy' has no attribute '_aggregate_item_by_item' # occurs in idxmax() case # in tests.groupby.test_function.test_non_cython_api + assert self.obj.ndim == 1 raise ValueError wrapper.__name__ = name diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 79b51ef57cd37..a34e002e7a144 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -669,13 +669,16 @@ def agg_series(self, obj, func): if is_extension_array_dtype(obj.dtype) and obj.dtype.kind != "M": # _aggregate_series_fast would raise TypeError when # calling libreduction.Slider + # TODO: can we get a performant workaround for EAs backed by ndarray? # TODO: is the datetime64tz case supposed to go through here? return self._aggregate_series_pure_python(obj, func) + elif obj.index._has_complex_internals: + # MultiIndex; Pre-empt TypeError in _aggregate_series_fast + return self._aggregate_series_pure_python(obj, func) + try: return self._aggregate_series_fast(obj, func) - except AssertionError: - raise except ValueError as err: if "No result." in str(err): # raised in libreduction @@ -685,12 +688,6 @@ def agg_series(self, obj, func): pass else: raise - except TypeError as err: - if "ndarray" in str(err): - # raised in libreduction if obj's values is no ndarray - pass - else: - raise return self._aggregate_series_pure_python(obj, func) def _aggregate_series_fast(self, obj, func):
cc @jreback @WillAyd
https://api.github.com/repos/pandas-dev/pandas/pulls/29228
2019-10-25T18:03:35Z
2019-10-29T16:09:38Z
2019-10-29T16:09:37Z
2019-10-29T16:18:40Z
Remove TestData in frame tests in multiple files - part 3
diff --git a/pandas/tests/frame/common.py b/pandas/tests/frame/common.py index 281028b971d1e..463a140972ab5 100644 --- a/pandas/tests/frame/common.py +++ b/pandas/tests/frame/common.py @@ -1,127 +1,3 @@ -import numpy as np - -from pandas.util._decorators import cache_readonly - -import pandas as pd -import pandas.util.testing as tm - -_seriesd = tm.getSeriesData() -_tsd = tm.getTimeSeriesData() - -_frame = pd.DataFrame(_seriesd) -_frame2 = pd.DataFrame(_seriesd, columns=["D", "C", "B", "A"]) -_intframe = pd.DataFrame({k: v.astype(int) for k, v in _seriesd.items()}) - -_tsframe = pd.DataFrame(_tsd) - -_mixed_frame = _frame.copy() -_mixed_frame["foo"] = "bar" - - -class TestData: - @cache_readonly - def frame(self): - return _frame.copy() - - @cache_readonly - def frame2(self): - return _frame2.copy() - - @cache_readonly - def intframe(self): - # force these all to int64 to avoid platform testing issues - return pd.DataFrame({c: s for c, s in _intframe.items()}, dtype=np.int64) - - @cache_readonly - def tsframe(self): - return _tsframe.copy() - - @cache_readonly - def mixed_frame(self): - return _mixed_frame.copy() - - @cache_readonly - def mixed_float(self): - return pd.DataFrame( - { - "A": _frame["A"].copy().astype("float32"), - "B": _frame["B"].copy().astype("float32"), - "C": _frame["C"].copy().astype("float16"), - "D": _frame["D"].copy().astype("float64"), - } - ) - - @cache_readonly - def mixed_float2(self): - return pd.DataFrame( - { - "A": _frame2["A"].copy().astype("float32"), - "B": _frame2["B"].copy().astype("float32"), - "C": _frame2["C"].copy().astype("float16"), - "D": _frame2["D"].copy().astype("float64"), - } - ) - - @cache_readonly - def mixed_int(self): - return pd.DataFrame( - { - "A": _intframe["A"].copy().astype("int32"), - "B": np.ones(len(_intframe["B"]), dtype="uint64"), - "C": _intframe["C"].copy().astype("uint8"), - "D": _intframe["D"].copy().astype("int64"), - } - ) - - @cache_readonly - def all_mixed(self): - return pd.DataFrame( - { - "a": 1.0, - "b": 2, - "c": "foo", - "float32": np.array([1.0] * 10, dtype="float32"), - "int32": np.array([1] * 10, dtype="int32"), - }, - index=np.arange(10), - ) - - @cache_readonly - def tzframe(self): - result = pd.DataFrame( - { - "A": pd.date_range("20130101", periods=3), - "B": pd.date_range("20130101", periods=3, tz="US/Eastern"), - "C": pd.date_range("20130101", periods=3, tz="CET"), - } - ) - result.iloc[1, 1] = pd.NaT - result.iloc[1, 2] = pd.NaT - return result - - @cache_readonly - def empty(self): - return pd.DataFrame() - - @cache_readonly - def ts1(self): - return tm.makeTimeSeries(nper=30) - - @cache_readonly - def ts2(self): - return tm.makeTimeSeries(nper=30)[5:] - - @cache_readonly - def simple(self): - arr = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) - - return pd.DataFrame(arr, columns=["one", "two", "three"], index=["a", "b", "c"]) - - -# self.ts3 = tm.makeTimeSeries()[-5:] -# self.ts4 = tm.makeTimeSeries()[1:-1] - - 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") diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 6d239e96cd167..5f99d98c705cb 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -25,7 +25,6 @@ ) import pandas.core.common as com from pandas.core.indexing import IndexingError -from pandas.tests.frame.common import TestData import pandas.util.testing as tm from pandas.util.testing import ( assert_almost_equal, @@ -36,7 +35,7 @@ from pandas.tseries.offsets import BDay -class TestDataFrameIndexing(TestData): +class TestDataFrameIndexing: def test_getitem(self, float_frame): # Slicing sl = float_frame[:20] @@ -1167,8 +1166,8 @@ def test_setitem_fancy_mixed_2d(self, float_string_frame): with catch_warnings(record=True): simplefilter("ignore", FutureWarning) - self.mixed_frame.ix[:5, ["C", "B", "A"]] = 5 - result = self.mixed_frame.ix[:5, ["C", "B", "A"]] + float_string_frame.ix[:5, ["C", "B", "A"]] = 5 + result = float_string_frame.ix[:5, ["C", "B", "A"]] assert (result.values == 5).all() float_string_frame.ix[5] = np.nan @@ -3402,7 +3401,7 @@ def test_interval_index(self): assert_series_equal(result, expected) -class TestDataFrameIndexingDatetimeWithTZ(TestData): +class TestDataFrameIndexingDatetimeWithTZ: def test_setitem(self, timezone_frame): df = timezone_frame @@ -3461,7 +3460,7 @@ def test_scalar_assignment(self): tm.assert_frame_equal(df, expected) -class TestDataFrameIndexingUInt64(TestData): +class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame): df = uint64_frame diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 13b994d116c76..abedc2b9375b7 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -9,7 +9,6 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, date_range from pandas.core.computation.check import _NUMEXPR_INSTALLED -from pandas.tests.frame.common import TestData from pandas.util.testing import ( assert_frame_equal, assert_series_equal, @@ -704,7 +703,6 @@ def setup_class(cls): super().setup_class() cls.engine = "numexpr" cls.parser = "python" - cls.frame = TestData().frame def test_date_query_no_attribute_access(self): engine, parser = self.engine, self.parser @@ -808,7 +806,6 @@ def setup_class(cls): super().setup_class() cls.engine = "python" cls.parser = "pandas" - cls.frame = TestData().frame def test_query_builtin(self): engine, parser = self.engine, self.parser @@ -827,7 +824,6 @@ class TestDataFrameQueryPythonPython(TestDataFrameQueryNumExprPython): def setup_class(cls): super().setup_class() cls.engine = cls.parser = "python" - cls.frame = TestData().frame def test_query_builtin(self): engine, parser = self.engine, self.parser
Part of #22471 This is removing/replacing TestData usage in the following files: * `test_query_eval.py` * `test_indexing.py` Also removes `TestData` from `pandas/tests/frame/common.py` -------- - [x] closes #22471 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29226
2019-10-25T16:10:22Z
2019-10-29T16:16:45Z
2019-10-29T16:16:44Z
2019-10-29T16:16:52Z
TST: Add test for nested JSON normalization
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 3ceddfc3c1db4..aa4f522ef45ba 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -457,6 +457,14 @@ def test_max_level_with_records_path(self, max_level, expected): expected_df = DataFrame(data=expected, columns=result.columns.values) tm.assert_equal(expected_df, result) + def test_nested_flattening_consistent(self): + # see gh-21537 + df1 = json_normalize([{"A": {"B": 1}}]) + df2 = json_normalize({"dummy": [{"A": {"B": 1}}]}, "dummy") + + # They should be the same. + tm.assert_frame_equal(df1, df2) + class TestNestedToRecord: def test_flat_stays_flat(self):
Closes https://github.com/pandas-dev/pandas/issues/21537
https://api.github.com/repos/pandas-dev/pandas/pulls/29225
2019-10-25T15:47:28Z
2019-10-25T16:54:35Z
2019-10-25T16:54:35Z
2019-10-25T17:25:54Z
Remove TestData in frame tests in multiple files - part2
diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index eb654be3f12e6..5ce811712b989 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -6,12 +6,11 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Period, Series, Timedelta, date_range -from pandas.tests.frame.common import TestData import pandas.util.testing as tm from pandas.util.testing import assert_frame_equal, assert_series_equal -class TestDataFrameReshape(TestData): +class TestDataFrameReshape: def test_pivot(self): data = { "index": ["A", "B", "C", "C", "B", "A"], @@ -101,8 +100,8 @@ def test_pivot_index_none(self): expected.columns.name = "columns" tm.assert_frame_equal(result, expected) - def test_stack_unstack(self): - df = self.frame.copy() + def test_stack_unstack(self, float_frame): + df = float_frame.copy() df[:] = np.arange(np.prod(df.shape)).reshape(df.shape) stacked = df.stack() @@ -515,13 +514,13 @@ def test_unstack_level_binding(self): assert_frame_equal(result, expected) - def test_unstack_to_series(self): + def test_unstack_to_series(self, float_frame): # check reversibility - data = self.frame.unstack() + data = float_frame.unstack() assert isinstance(data, Series) undo = data.unstack().T - assert_frame_equal(undo, self.frame) + assert_frame_equal(undo, float_frame) # check NA handling data = DataFrame({"x": [1, 2, np.NaN], "y": [3.0, 4, np.NaN]}) diff --git a/pandas/tests/frame/test_sorting.py b/pandas/tests/frame/test_sorting.py index 24833f8c02df0..2b4b20d318adf 100644 --- a/pandas/tests/frame/test_sorting.py +++ b/pandas/tests/frame/test_sorting.py @@ -15,12 +15,11 @@ date_range, ) from pandas.api.types import CategoricalDtype -from pandas.tests.frame.common import TestData import pandas.util.testing as tm from pandas.util.testing import assert_frame_equal, assert_series_equal -class TestDataFrameSorting(TestData): +class TestDataFrameSorting: def test_sort_values(self): frame = DataFrame( [[1, 1, 2], [3, 1, 0], [4, 5, 6]], index=[1, 2, 3], columns=list("ABC") @@ -295,8 +294,8 @@ def test_sort_datetimes(self): df2 = df.sort_values(by=["C", "B"]) assert_frame_equal(df1, df2) - def test_frame_column_inplace_sort_exception(self): - s = self.frame["A"] + def test_frame_column_inplace_sort_exception(self, float_frame): + s = float_frame["A"] with pytest.raises(ValueError, match="This Series is a view"): s.sort_values(inplace=True) @@ -379,7 +378,7 @@ def test_sort_nat(self): tm.assert_frame_equal(sorted_df, expected) -class TestDataFrameSortIndexKinds(TestData): +class TestDataFrameSortIndexKinds: def test_sort_index_multicolumn(self): A = np.arange(5).repeat(20) B = np.tile(np.arange(5), 20) diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index 649a78b785d21..e1e546256f7cd 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -3,11 +3,10 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series -from pandas.tests.frame.common import TestData import pandas.util.testing as tm -class TestDataFrameSubclassing(TestData): +class TestDataFrameSubclassing: def test_frame_subclassing_and_slicing(self): # Subclass frame and ensure it returns the right class on slicing it # In reference to PR 9632 diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index b8708e6ca1871..3355d6e746db2 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -17,7 +17,6 @@ period_range, to_datetime, ) -from pandas.tests.frame.common import TestData import pandas.util.testing as tm from pandas.util.testing import ( assert_frame_equal, @@ -33,12 +32,12 @@ def close_open_fixture(request): return request.param -class TestDataFrameTimeSeriesMethods(TestData): - def test_diff(self): - the_diff = self.tsframe.diff(1) +class TestDataFrameTimeSeriesMethods: + def test_diff(self, datetime_frame): + the_diff = datetime_frame.diff(1) assert_series_equal( - the_diff["A"], self.tsframe["A"] - self.tsframe["A"].shift(1) + the_diff["A"], datetime_frame["A"] - datetime_frame["A"].shift(1) ) # int dtype @@ -50,7 +49,7 @@ def test_diff(self): assert rs.s[1] == 1 # mixed numeric - tf = self.tsframe.astype("float32") + tf = datetime_frame.astype("float32") the_diff = tf.diff(1) assert_series_equal(the_diff["A"], tf["A"] - tf["A"].shift(1)) @@ -126,14 +125,14 @@ def test_diff_mixed_dtype(self): result = df.diff() assert result[0].dtype == np.float64 - def test_diff_neg_n(self): - rs = self.tsframe.diff(-1) - xp = self.tsframe - self.tsframe.shift(-1) + def test_diff_neg_n(self, datetime_frame): + rs = datetime_frame.diff(-1) + xp = datetime_frame - datetime_frame.shift(-1) assert_frame_equal(rs, xp) - def test_diff_float_n(self): - rs = self.tsframe.diff(1.0) - xp = self.tsframe.diff(1) + def test_diff_float_n(self, datetime_frame): + rs = datetime_frame.diff(1.0) + xp = datetime_frame.diff(1) assert_frame_equal(rs, xp) def test_diff_axis(self): @@ -142,20 +141,20 @@ def test_diff_axis(self): assert_frame_equal(df.diff(axis=1), DataFrame([[np.nan, 1.0], [np.nan, 1.0]])) assert_frame_equal(df.diff(axis=0), DataFrame([[np.nan, np.nan], [2.0, 2.0]])) - def test_pct_change(self): - rs = self.tsframe.pct_change(fill_method=None) - assert_frame_equal(rs, self.tsframe / self.tsframe.shift(1) - 1) + def test_pct_change(self, datetime_frame): + rs = datetime_frame.pct_change(fill_method=None) + assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1) - rs = self.tsframe.pct_change(2) - filled = self.tsframe.fillna(method="pad") + rs = datetime_frame.pct_change(2) + filled = datetime_frame.fillna(method="pad") assert_frame_equal(rs, filled / filled.shift(2) - 1) - rs = self.tsframe.pct_change(fill_method="bfill", limit=1) - filled = self.tsframe.fillna(method="bfill", limit=1) + rs = datetime_frame.pct_change(fill_method="bfill", limit=1) + filled = datetime_frame.fillna(method="bfill", limit=1) assert_frame_equal(rs, filled / filled.shift(1) - 1) - rs = self.tsframe.pct_change(freq="5D") - filled = self.tsframe.fillna(method="pad") + rs = datetime_frame.pct_change(freq="5D") + filled = datetime_frame.fillna(method="pad") assert_frame_equal( rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled) ) @@ -181,17 +180,19 @@ def test_pct_change_shift_over_nas(self): ("14B", 14, None, None), ], ) - def test_pct_change_periods_freq(self, freq, periods, fill_method, limit): + def test_pct_change_periods_freq( + self, datetime_frame, freq, periods, fill_method, limit + ): # GH 7292 - rs_freq = self.tsframe.pct_change( + rs_freq = datetime_frame.pct_change( freq=freq, fill_method=fill_method, limit=limit ) - rs_periods = self.tsframe.pct_change( + rs_periods = datetime_frame.pct_change( periods, fill_method=fill_method, limit=limit ) assert_frame_equal(rs_freq, rs_periods) - empty_ts = DataFrame(index=self.tsframe.index, columns=self.tsframe.columns) + empty_ts = DataFrame(index=datetime_frame.index, columns=datetime_frame.columns) rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit) rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit) assert_frame_equal(rs_freq, rs_periods) @@ -249,39 +250,39 @@ def test_frame_append_datetime64_col_other_units(self): assert (tmp["dates"].values == ex_vals).all() - def test_shift(self): + def test_shift(self, datetime_frame, int_frame): # naive shift - shiftedFrame = self.tsframe.shift(5) - tm.assert_index_equal(shiftedFrame.index, self.tsframe.index) + shiftedFrame = datetime_frame.shift(5) + tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) - shiftedSeries = self.tsframe["A"].shift(5) + shiftedSeries = datetime_frame["A"].shift(5) assert_series_equal(shiftedFrame["A"], shiftedSeries) - shiftedFrame = self.tsframe.shift(-5) - tm.assert_index_equal(shiftedFrame.index, self.tsframe.index) + shiftedFrame = datetime_frame.shift(-5) + tm.assert_index_equal(shiftedFrame.index, datetime_frame.index) - shiftedSeries = self.tsframe["A"].shift(-5) + shiftedSeries = datetime_frame["A"].shift(-5) assert_series_equal(shiftedFrame["A"], shiftedSeries) # shift by 0 - unshifted = self.tsframe.shift(0) - assert_frame_equal(unshifted, self.tsframe) + unshifted = datetime_frame.shift(0) + assert_frame_equal(unshifted, datetime_frame) # shift by DateOffset - shiftedFrame = self.tsframe.shift(5, freq=offsets.BDay()) - assert len(shiftedFrame) == len(self.tsframe) + shiftedFrame = datetime_frame.shift(5, freq=offsets.BDay()) + assert len(shiftedFrame) == len(datetime_frame) - shiftedFrame2 = self.tsframe.shift(5, freq="B") + shiftedFrame2 = datetime_frame.shift(5, freq="B") assert_frame_equal(shiftedFrame, shiftedFrame2) - d = self.tsframe.index[0] + d = datetime_frame.index[0] shifted_d = d + offsets.BDay(5) assert_series_equal( - self.tsframe.xs(d), shiftedFrame.xs(shifted_d), check_names=False + datetime_frame.xs(d), shiftedFrame.xs(shifted_d), check_names=False ) # shift int frame - int_shifted = self.intframe.shift(1) # noqa + int_shifted = int_frame.shift(1) # noqa # Shifting with PeriodIndex ps = tm.makePeriodFrame() @@ -387,7 +388,7 @@ def test_shift_duplicate_columns(self): assert_frame_equal(shifted[0], shifted[1]) assert_frame_equal(shifted[0], shifted[2]) - def test_tshift(self): + def test_tshift(self, datetime_frame): # PeriodIndex ps = tm.makePeriodFrame() shifted = ps.tshift(1) @@ -405,36 +406,36 @@ def test_tshift(self): ps.tshift(freq="M") # DatetimeIndex - shifted = self.tsframe.tshift(1) + shifted = datetime_frame.tshift(1) unshifted = shifted.tshift(-1) - assert_frame_equal(self.tsframe, unshifted) + assert_frame_equal(datetime_frame, unshifted) - shifted2 = self.tsframe.tshift(freq=self.tsframe.index.freq) + shifted2 = datetime_frame.tshift(freq=datetime_frame.index.freq) assert_frame_equal(shifted, shifted2) inferred_ts = DataFrame( - self.tsframe.values, - Index(np.asarray(self.tsframe.index)), - columns=self.tsframe.columns, + datetime_frame.values, + Index(np.asarray(datetime_frame.index)), + columns=datetime_frame.columns, ) shifted = inferred_ts.tshift(1) unshifted = shifted.tshift(-1) - assert_frame_equal(shifted, self.tsframe.tshift(1)) + assert_frame_equal(shifted, datetime_frame.tshift(1)) assert_frame_equal(unshifted, inferred_ts) - no_freq = self.tsframe.iloc[[0, 5, 7], :] + no_freq = datetime_frame.iloc[[0, 5, 7], :] msg = "Freq was not given and was not set in the index" with pytest.raises(ValueError, match=msg): no_freq.tshift() - def test_truncate(self): - ts = self.tsframe[::3] + def test_truncate(self, datetime_frame): + ts = datetime_frame[::3] - start, end = self.tsframe.index[3], self.tsframe.index[6] + start, end = datetime_frame.index[3], datetime_frame.index[6] - start_missing = self.tsframe.index[2] - end_missing = self.tsframe.index[7] + start_missing = datetime_frame.index[2] + end_missing = datetime_frame.index[7] # neither specified truncated = ts.truncate() @@ -473,11 +474,11 @@ def test_truncate(self): before=ts.index[-1] - ts.index.freq, after=ts.index[0] + ts.index.freq ) - def test_truncate_copy(self): - index = self.tsframe.index - truncated = self.tsframe.truncate(index[5], index[10]) + def test_truncate_copy(self, datetime_frame): + index = datetime_frame.index + truncated = datetime_frame.truncate(index[5], index[10]) truncated.values[:] = 5.0 - assert not (self.tsframe.values[5:11] == 5).any() + assert not (datetime_frame.values[5:11] == 5).any() def test_truncate_nonsortedindex(self): # GH 17935 @@ -510,9 +511,9 @@ def test_truncate_nonsortedindex(self): with pytest.raises(ValueError, match=msg): df.truncate(before=2, after=20, axis=1) - def test_asfreq(self): - offset_monthly = self.tsframe.asfreq(offsets.BMonthEnd()) - rule_monthly = self.tsframe.asfreq("BM") + def test_asfreq(self, datetime_frame): + offset_monthly = datetime_frame.asfreq(offsets.BMonthEnd()) + rule_monthly = datetime_frame.asfreq("BM") tm.assert_almost_equal(offset_monthly["A"], rule_monthly["A"]) @@ -523,7 +524,7 @@ def test_asfreq(self): filled_dep = rule_monthly.asfreq("B", method="pad") # noqa # test does not blow up on length-0 DataFrame - zero_length = self.tsframe.reindex([]) + zero_length = datetime_frame.reindex([]) result = zero_length.asfreq("BM") assert result is not zero_length @@ -569,13 +570,15 @@ def test_asfreq_fillvalue(self): ({"A": [1, np.nan, 3]}, [1, 2, 2], 1, 2), ], ) - def test_first_last_valid(self, data, idx, expected_first, expected_last): - N = len(self.frame.index) + def test_first_last_valid( + self, float_frame, data, idx, expected_first, expected_last + ): + N = len(float_frame.index) mat = np.random.randn(N) mat[:5] = np.nan mat[-5:] = np.nan - frame = DataFrame({"foo": mat}, index=self.frame.index) + frame = DataFrame({"foo": mat}, index=float_frame.index) index = frame.first_valid_index() assert index == frame.index[5] diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index 8fb028a0f0326..67c748227a43d 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -19,7 +19,6 @@ to_datetime, ) import pandas.core.common as com -from pandas.tests.frame.common import TestData import pandas.util.testing as tm from pandas.util.testing import ( assert_almost_equal, @@ -44,37 +43,37 @@ ] -class TestDataFrameToCSV(TestData): +class TestDataFrameToCSV: def read_csv(self, path, **kwargs): params = dict(index_col=0, parse_dates=True) params.update(**kwargs) return pd.read_csv(path, **params) - def test_to_csv_from_csv1(self): + def test_to_csv_from_csv1(self, float_frame, datetime_frame): with ensure_clean("__tmp_to_csv_from_csv1__") as path: - self.frame["A"][:5] = np.nan + float_frame["A"][:5] = np.nan - self.frame.to_csv(path) - self.frame.to_csv(path, columns=["A", "B"]) - self.frame.to_csv(path, header=False) - self.frame.to_csv(path, index=False) + float_frame.to_csv(path) + float_frame.to_csv(path, columns=["A", "B"]) + float_frame.to_csv(path, header=False) + float_frame.to_csv(path, index=False) # test roundtrip - self.tsframe.to_csv(path) + datetime_frame.to_csv(path) recons = self.read_csv(path) - assert_frame_equal(self.tsframe, recons) + assert_frame_equal(datetime_frame, recons) - self.tsframe.to_csv(path, index_label="index") + datetime_frame.to_csv(path, index_label="index") recons = self.read_csv(path, index_col=None) - assert len(recons.columns) == len(self.tsframe.columns) + 1 + assert len(recons.columns) == len(datetime_frame.columns) + 1 # no index - self.tsframe.to_csv(path, index=False) + datetime_frame.to_csv(path, index=False) recons = self.read_csv(path, index_col=None) - assert_almost_equal(self.tsframe.values, recons.values) + assert_almost_equal(datetime_frame.values, recons.values) # corner case dm = DataFrame( @@ -88,7 +87,7 @@ def test_to_csv_from_csv1(self): recons = self.read_csv(path) assert_frame_equal(dm, recons) - def test_to_csv_from_csv2(self): + def test_to_csv_from_csv2(self, float_frame): with ensure_clean("__tmp_to_csv_from_csv2__") as path: @@ -109,16 +108,16 @@ def test_to_csv_from_csv2(self): # column aliases col_aliases = Index(["AA", "X", "Y", "Z"]) - self.frame2.to_csv(path, header=col_aliases) + float_frame.to_csv(path, header=col_aliases) rs = self.read_csv(path) - xp = self.frame2.copy() + xp = float_frame.copy() xp.columns = col_aliases assert_frame_equal(xp, rs) msg = "Writing 4 cols but got 2 aliases" with pytest.raises(ValueError, match=msg): - self.frame2.to_csv(path, header=["AA", "X"]) + float_frame.to_csv(path, header=["AA", "X"]) def test_to_csv_from_csv3(self): @@ -153,22 +152,22 @@ def test_to_csv_from_csv4(self): assert_frame_equal(df, result, check_index_type=True) - def test_to_csv_from_csv5(self): + def test_to_csv_from_csv5(self, timezone_frame): # tz, 8260 with ensure_clean("__tmp_to_csv_from_csv5__") as path: - self.tzframe.to_csv(path) + timezone_frame.to_csv(path) result = pd.read_csv(path, index_col=0, parse_dates=["A"]) converter = ( lambda c: to_datetime(result[c]) .dt.tz_convert("UTC") - .dt.tz_convert(self.tzframe[c].dt.tz) + .dt.tz_convert(timezone_frame[c].dt.tz) ) result["B"] = converter("B") result["C"] = converter("C") - assert_frame_equal(result, self.tzframe) + assert_frame_equal(result, timezone_frame) def test_to_csv_cols_reordering(self): # GH3454 @@ -493,37 +492,37 @@ def _to_uni(x): cnlvl=2, ) - def test_to_csv_from_csv_w_some_infs(self): + def test_to_csv_from_csv_w_some_infs(self, float_frame): # test roundtrip with inf, -inf, nan, as full columns and mix - self.frame["G"] = np.nan + float_frame["G"] = np.nan f = lambda x: [np.inf, np.nan][np.random.rand() < 0.5] - self.frame["H"] = self.frame.index.map(f) + float_frame["H"] = float_frame.index.map(f) with ensure_clean() as path: - self.frame.to_csv(path) + float_frame.to_csv(path) recons = self.read_csv(path) # TODO to_csv drops column name - assert_frame_equal(self.frame, recons, check_names=False) + assert_frame_equal(float_frame, recons, check_names=False) assert_frame_equal( - np.isinf(self.frame), np.isinf(recons), check_names=False + np.isinf(float_frame), np.isinf(recons), check_names=False ) - def test_to_csv_from_csv_w_all_infs(self): + def test_to_csv_from_csv_w_all_infs(self, float_frame): # test roundtrip with inf, -inf, nan, as full columns and mix - self.frame["E"] = np.inf - self.frame["F"] = -np.inf + float_frame["E"] = np.inf + float_frame["F"] = -np.inf with ensure_clean() as path: - self.frame.to_csv(path) + float_frame.to_csv(path) recons = self.read_csv(path) # TODO to_csv drops column name - assert_frame_equal(self.frame, recons, check_names=False) + assert_frame_equal(float_frame, recons, check_names=False) assert_frame_equal( - np.isinf(self.frame), np.isinf(recons), check_names=False + np.isinf(float_frame), np.isinf(recons), check_names=False ) def test_to_csv_no_index(self): @@ -563,9 +562,9 @@ def test_to_csv_headers(self): recons.reset_index(inplace=True) assert_frame_equal(to_df, recons) - def test_to_csv_multiindex(self): + def test_to_csv_multiindex(self, float_frame, datetime_frame): - frame = self.frame + frame = float_frame old_index = frame.index arrays = np.arange(len(old_index) * 2).reshape(2, -1) new_index = MultiIndex.from_arrays(arrays, names=["first", "second"]) @@ -586,10 +585,10 @@ def test_to_csv_multiindex(self): assert frame.index.names == df.index.names # needed if setUp becomes a class method - self.frame.index = old_index + float_frame.index = old_index # try multiindex with dates - tsframe = self.tsframe + tsframe = datetime_frame old_index = tsframe.index new_index = [old_index, np.arange(len(old_index))] tsframe.index = MultiIndex.from_arrays(new_index) @@ -608,10 +607,10 @@ def test_to_csv_multiindex(self): # no index tsframe.to_csv(path, index=False) recons = self.read_csv(path, index_col=None) - assert_almost_equal(recons.values, self.tsframe.values) + assert_almost_equal(recons.values, datetime_frame.values) # needed if setUp becomes class method - self.tsframe.index = old_index + datetime_frame.index = old_index with ensure_clean("__tmp_to_csv_multiindex__") as path: # GH3571, GH1651, GH3141 @@ -889,13 +888,13 @@ def test_to_csv_unicode_index_col(self): df2 = read_csv(buf, index_col=0, encoding="UTF-8") assert_frame_equal(df, df2) - def test_to_csv_stringio(self): + def test_to_csv_stringio(self, float_frame): buf = StringIO() - self.frame.to_csv(buf) + float_frame.to_csv(buf) buf.seek(0) recons = read_csv(buf, index_col=0) # TODO to_csv drops column name - assert_frame_equal(recons, self.frame, check_names=False) + assert_frame_equal(recons, float_frame, check_names=False) def test_to_csv_float_format(self): @@ -1013,14 +1012,14 @@ def test_to_csv_from_csv_categorical(self): assert res.getvalue() == exp.getvalue() - def test_to_csv_path_is_none(self): + def test_to_csv_path_is_none(self, float_frame): # GH 8215 # Make sure we return string for consistency with # Series.to_csv() - csv_str = self.frame.to_csv(path_or_buf=None) + csv_str = float_frame.to_csv(path_or_buf=None) assert isinstance(csv_str, str) recons = pd.read_csv(StringIO(csv_str), index_col=0) - assert_frame_equal(self.frame, recons) + assert_frame_equal(float_frame, recons) @pytest.mark.parametrize( "df,encoding", @@ -1077,9 +1076,9 @@ def test_to_csv_compression(self, df, encoding, compression): with tm.decompress_file(filename, compression) as fh: assert_frame_equal(df, read_csv(fh, index_col=0, encoding=encoding)) - def test_to_csv_date_format(self): + def test_to_csv_date_format(self, datetime_frame): with ensure_clean("__tmp_to_csv_date_format__") as path: - dt_index = self.tsframe.index + dt_index = datetime_frame.index datetime_frame = DataFrame( {"A": dt_index, "B": dt_index.shift(1)}, index=dt_index )
Part of #22471 This is removing/replacing TestData usage in the following files: * `test_reshape.py` * `test_sorting.py` * `test_subclass.py` * `test_timeseries.py` * `test_to_csv.py` -------- - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29222
2019-10-25T12:01:46Z
2019-10-25T12:41:36Z
2019-10-25T12:41:36Z
2019-10-25T12:41:39Z
Remove TestData in series tests indexing
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 54c931cd60d20..ba7e3c9d38861 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -14,7 +14,6 @@ import pandas as pd from pandas import DatetimeIndex, Timestamp, bdate_range, date_range, offsets -from pandas.tests.series.common import TestData import pandas.util.testing as tm from pandas.tseries.offsets import ( @@ -82,7 +81,7 @@ def test_date_range_timestamp_equiv_preserve_frequency(self): assert timestamp_instance == ts -class TestDateRanges(TestData): +class TestDateRanges: def test_date_range_nat(self): # GH#11587 msg = "Neither `start` nor `end` can be NaT" diff --git a/pandas/tests/series/common.py b/pandas/tests/series/common.py deleted file mode 100644 index 38c62e89f1873..0000000000000 --- a/pandas/tests/series/common.py +++ /dev/null @@ -1,30 +0,0 @@ -from pandas.util._decorators import cache_readonly - -import pandas as pd -import pandas.util.testing as tm - -_ts = tm.makeTimeSeries() - - -class TestData: - @cache_readonly - def ts(self): - ts = _ts.copy() - ts.name = "ts" - return ts - - @cache_readonly - def series(self): - series = tm.makeStringSeries() - series.name = "series" - return series - - @cache_readonly - def objSeries(self): - objSeries = tm.makeObjectSeries() - objSeries.name = "objects" - return objSeries - - @cache_readonly - def empty(self): - return pd.Series([], index=[]) diff --git a/pandas/tests/series/indexing/conftest.py b/pandas/tests/series/indexing/conftest.py deleted file mode 100644 index 9c7103c196d60..0000000000000 --- a/pandas/tests/series/indexing/conftest.py +++ /dev/null @@ -1,8 +0,0 @@ -import pytest - -from pandas.tests.series.common import TestData - - -@pytest.fixture(scope="module") -def test_data(): - return TestData() diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py index b25fee0435da0..331747b6cd056 100644 --- a/pandas/tests/series/indexing/test_alter_index.py +++ b/pandas/tests/series/indexing/test_alter_index.py @@ -19,9 +19,9 @@ ], ) @pytest.mark.parametrize("fill", [None, -1]) -def test_align(test_data, first_slice, second_slice, join_type, fill): - a = test_data.ts[slice(*first_slice)] - b = test_data.ts[slice(*second_slice)] +def test_align(datetime_series, first_slice, second_slice, join_type, fill): + a = datetime_series[slice(*first_slice)] + b = datetime_series[slice(*second_slice)] aa, ab = a.align(b, join=join_type, fill_value=fill) @@ -61,10 +61,10 @@ def test_align(test_data, first_slice, second_slice, join_type, fill): @pytest.mark.parametrize("method", ["pad", "bfill"]) @pytest.mark.parametrize("limit", [None, 1]) def test_align_fill_method( - test_data, first_slice, second_slice, join_type, method, limit + datetime_series, first_slice, second_slice, join_type, method, limit ): - a = test_data.ts[slice(*first_slice)] - b = test_data.ts[slice(*second_slice)] + a = datetime_series[slice(*first_slice)] + b = datetime_series[slice(*second_slice)] aa, ab = a.align(b, join=join_type, method=method, limit=limit) @@ -79,44 +79,44 @@ def test_align_fill_method( assert_series_equal(ab, eb) -def test_align_nocopy(test_data): - b = test_data.ts[:5].copy() +def test_align_nocopy(datetime_series): + b = datetime_series[:5].copy() # do copy - a = test_data.ts.copy() + a = datetime_series.copy() ra, _ = a.align(b, join="left") ra[:5] = 5 assert not (a[:5] == 5).any() # do not copy - a = test_data.ts.copy() + a = datetime_series.copy() ra, _ = a.align(b, join="left", copy=False) ra[:5] = 5 assert (a[:5] == 5).all() # do copy - a = test_data.ts.copy() - b = test_data.ts[:5].copy() + a = datetime_series.copy() + b = datetime_series[:5].copy() _, rb = a.align(b, join="right") rb[:3] = 5 assert not (b[:3] == 5).any() # do not copy - a = test_data.ts.copy() - b = test_data.ts[:5].copy() + a = datetime_series.copy() + b = datetime_series[:5].copy() _, rb = a.align(b, join="right", copy=False) rb[:2] = 5 assert (b[:2] == 5).all() -def test_align_same_index(test_data): - a, b = test_data.ts.align(test_data.ts, copy=False) - assert a.index is test_data.ts.index - assert b.index is test_data.ts.index +def test_align_same_index(datetime_series): + a, b = datetime_series.align(datetime_series, copy=False) + assert a.index is datetime_series.index + assert b.index is datetime_series.index - a, b = test_data.ts.align(test_data.ts, copy=True) - assert a.index is not test_data.ts.index - assert b.index is not test_data.ts.index + a, b = datetime_series.align(datetime_series, copy=True) + assert a.index is not datetime_series.index + assert b.index is not datetime_series.index def test_align_multiindex(): @@ -154,43 +154,43 @@ def test_align_multiindex(): tm.assert_series_equal(expr, res2l) -def test_reindex(test_data): - identity = test_data.series.reindex(test_data.series.index) +def test_reindex(datetime_series, string_series): + identity = string_series.reindex(string_series.index) # __array_interface__ is not defined for older numpies # and on some pythons try: - assert np.may_share_memory(test_data.series.index, identity.index) + assert np.may_share_memory(string_series.index, identity.index) except AttributeError: pass - assert identity.index.is_(test_data.series.index) - assert identity.index.identical(test_data.series.index) + assert identity.index.is_(string_series.index) + assert identity.index.identical(string_series.index) - subIndex = test_data.series.index[10:20] - subSeries = test_data.series.reindex(subIndex) + subIndex = string_series.index[10:20] + subSeries = string_series.reindex(subIndex) for idx, val in subSeries.items(): - assert val == test_data.series[idx] + assert val == string_series[idx] - subIndex2 = test_data.ts.index[10:20] - subTS = test_data.ts.reindex(subIndex2) + subIndex2 = datetime_series.index[10:20] + subTS = datetime_series.reindex(subIndex2) for idx, val in subTS.items(): - assert val == test_data.ts[idx] - stuffSeries = test_data.ts.reindex(subIndex) + assert val == datetime_series[idx] + stuffSeries = datetime_series.reindex(subIndex) assert np.isnan(stuffSeries).all() # This is extremely important for the Cython code to not screw up - nonContigIndex = test_data.ts.index[::2] - subNonContig = test_data.ts.reindex(nonContigIndex) + nonContigIndex = datetime_series.index[::2] + subNonContig = datetime_series.reindex(nonContigIndex) for idx, val in subNonContig.items(): - assert val == test_data.ts[idx] + assert val == datetime_series[idx] # return a copy the same index here - result = test_data.ts.reindex() - assert not (result is test_data.ts) + result = datetime_series.reindex() + assert not (result is datetime_series) def test_reindex_nan(): @@ -229,25 +229,26 @@ def test_reindex_with_datetimes(): tm.assert_series_equal(result, expected) -def test_reindex_corner(test_data): +def test_reindex_corner(datetime_series): # (don't forget to fix this) I think it's fixed - test_data.empty.reindex(test_data.ts.index, method="pad") # it works + empty = Series() + empty.reindex(datetime_series.index, method="pad") # it works # corner case: pad empty series - reindexed = test_data.empty.reindex(test_data.ts.index, method="pad") + reindexed = empty.reindex(datetime_series.index, method="pad") # pass non-Index - reindexed = test_data.ts.reindex(list(test_data.ts.index)) - assert_series_equal(test_data.ts, reindexed) + reindexed = datetime_series.reindex(list(datetime_series.index)) + assert_series_equal(datetime_series, reindexed) # bad fill method - ts = test_data.ts[::2] + ts = datetime_series[::2] msg = ( r"Invalid fill method\. Expecting pad \(ffill\), backfill" r" \(bfill\) or nearest\. Got foo" ) with pytest.raises(ValueError, match=msg): - ts.reindex(test_data.ts.index, method="foo") + ts.reindex(datetime_series.index, method="foo") def test_reindex_pad(): @@ -319,12 +320,12 @@ def test_reindex_backfill(): pass -def test_reindex_int(test_data): - ts = test_data.ts[::2] +def test_reindex_int(datetime_series): + ts = datetime_series[::2] int_ts = Series(np.zeros(len(ts), dtype=int), index=ts.index) # this should work fine - reindexed_int = int_ts.reindex(test_data.ts.index) + reindexed_int = int_ts.reindex(datetime_series.index) # if NaNs introduced assert reindexed_int.dtype == np.float_ @@ -334,13 +335,13 @@ def test_reindex_int(test_data): assert reindexed_int.dtype == np.int_ -def test_reindex_bool(test_data): +def test_reindex_bool(datetime_series): # A series other than float, int, string, or object - ts = test_data.ts[::2] + ts = datetime_series[::2] bool_ts = Series(np.zeros(len(ts), dtype=bool), index=ts.index) # this should work fine - reindexed_bool = bool_ts.reindex(test_data.ts.index) + reindexed_bool = bool_ts.reindex(datetime_series.index) # if NaNs introduced assert reindexed_bool.dtype == np.object_ @@ -350,11 +351,11 @@ def test_reindex_bool(test_data): assert reindexed_bool.dtype == np.bool_ -def test_reindex_bool_pad(test_data): +def test_reindex_bool_pad(datetime_series): # fail - ts = test_data.ts[5:] + ts = datetime_series[5:] bool_ts = Series(np.zeros(len(ts), dtype=bool), index=ts.index) - filled_bool = bool_ts.reindex(test_data.ts.index, method="pad") + filled_bool = bool_ts.reindex(datetime_series.index, method="pad") assert isna(filled_bool[:5]).all() @@ -382,10 +383,10 @@ def test_reindex_categorical(): tm.assert_series_equal(result, expected) -def test_reindex_like(test_data): - other = test_data.ts[::2] +def test_reindex_like(datetime_series): + other = datetime_series[::2] assert_series_equal( - test_data.ts.reindex(other.index), test_data.ts.reindex_like(other) + datetime_series.reindex(other.index), datetime_series.reindex_like(other) ) # GH 7179 diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py index 01b4a3c84a565..bcbb162697e50 100644 --- a/pandas/tests/series/indexing/test_boolean.py +++ b/pandas/tests/series/indexing/test_boolean.py @@ -12,8 +12,8 @@ from pandas.tseries.offsets import BDay -def test_getitem_boolean(test_data): - s = test_data.series +def test_getitem_boolean(string_series): + s = string_series mask = s > s.median() # passing list is OK @@ -55,10 +55,10 @@ def test_getitem_boolean_empty(): s[Series([True], dtype=bool)] -def test_getitem_boolean_object(test_data): +def test_getitem_boolean_object(string_series): # using column from DataFrame - s = test_data.series + s = string_series mask = s > s.median() omask = mask.astype(object) @@ -83,8 +83,8 @@ def test_getitem_boolean_object(test_data): s[omask] = 5 -def test_getitem_setitem_boolean_corner(test_data): - ts = test_data.ts +def test_getitem_setitem_boolean_corner(datetime_series): + ts = datetime_series mask_shifted = ts.shift(1, freq=BDay()) > ts.median() # these used to raise...?? @@ -104,38 +104,38 @@ def test_getitem_setitem_boolean_corner(test_data): ts.loc[mask_shifted] = 1 -def test_setitem_boolean(test_data): - mask = test_data.series > test_data.series.median() +def test_setitem_boolean(string_series): + mask = string_series > string_series.median() # similar indexed series - result = test_data.series.copy() - result[mask] = test_data.series * 2 - expected = test_data.series * 2 + result = string_series.copy() + result[mask] = string_series * 2 + expected = string_series * 2 assert_series_equal(result[mask], expected[mask]) # needs alignment - result = test_data.series.copy() - result[mask] = (test_data.series * 2)[0:5] - expected = (test_data.series * 2)[0:5].reindex_like(test_data.series) - expected[-mask] = test_data.series[mask] + result = string_series.copy() + result[mask] = (string_series * 2)[0:5] + expected = (string_series * 2)[0:5].reindex_like(string_series) + expected[-mask] = string_series[mask] assert_series_equal(result[mask], expected[mask]) -def test_get_set_boolean_different_order(test_data): - ordered = test_data.series.sort_values() +def test_get_set_boolean_different_order(string_series): + ordered = string_series.sort_values() # setting - copy = test_data.series.copy() + copy = string_series.copy() copy[ordered > 0] = 0 - expected = test_data.series.copy() + expected = string_series.copy() expected[expected > 0] = 0 assert_series_equal(copy, expected) # getting - sel = test_data.series[ordered > 0] - exp = test_data.series[test_data.series > 0] + sel = string_series[ordered > 0] + exp = string_series[string_series > 0] assert_series_equal(sel, exp) diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 19d3e76f52adf..d1c93990e9167 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -38,15 +38,15 @@ def test_basic_indexing(): s[5] = 0 -def test_basic_getitem_with_labels(test_data): - indices = test_data.ts.index[[5, 10, 15]] +def test_basic_getitem_with_labels(datetime_series): + indices = datetime_series.index[[5, 10, 15]] - result = test_data.ts[indices] - expected = test_data.ts.reindex(indices) + result = datetime_series[indices] + expected = datetime_series.reindex(indices) assert_series_equal(result, expected) - result = test_data.ts[indices[0] : indices[2]] - expected = test_data.ts.loc[indices[0] : indices[2]] + result = datetime_series[indices[0] : indices[2]] + expected = datetime_series.loc[indices[0] : indices[2]] assert_series_equal(result, expected) # integer indexes, be careful @@ -89,27 +89,24 @@ def test_getitem_setitem_ellipsis(): assert (result == 5).all() -def test_getitem_get(test_data): - test_series = test_data.series - test_obj_series = test_data.objSeries +def test_getitem_get(datetime_series, string_series, object_series): + idx1 = string_series.index[5] + idx2 = object_series.index[5] - idx1 = test_series.index[5] - idx2 = test_obj_series.index[5] + assert string_series[idx1] == string_series.get(idx1) + assert object_series[idx2] == object_series.get(idx2) - assert test_series[idx1] == test_series.get(idx1) - assert test_obj_series[idx2] == test_obj_series.get(idx2) + assert string_series[idx1] == string_series[5] + assert object_series[idx2] == object_series[5] - assert test_series[idx1] == test_series[5] - assert test_obj_series[idx2] == test_obj_series[5] - - assert test_series.get(-1) == test_series.get(test_series.index[-1]) - assert test_series[5] == test_series.get(test_series.index[5]) + assert string_series.get(-1) == string_series.get(string_series.index[-1]) + assert string_series[5] == string_series.get(string_series.index[5]) # missing - d = test_data.ts.index[0] - BDay() + d = datetime_series.index[0] - BDay() msg = r"Timestamp\('1999-12-31 00:00:00', freq='B'\)" with pytest.raises(KeyError, match=msg): - test_data.ts[d] + datetime_series[d] # None # GH 5652 @@ -118,20 +115,20 @@ def test_getitem_get(test_data): assert result is None -def test_getitem_fancy(test_data): - slice1 = test_data.series[[1, 2, 3]] - slice2 = test_data.objSeries[[1, 2, 3]] - assert test_data.series.index[2] == slice1.index[1] - assert test_data.objSeries.index[2] == slice2.index[1] - assert test_data.series[2] == slice1[1] - assert test_data.objSeries[2] == slice2[1] +def test_getitem_fancy(string_series, object_series): + slice1 = string_series[[1, 2, 3]] + slice2 = object_series[[1, 2, 3]] + assert string_series.index[2] == slice1.index[1] + assert object_series.index[2] == slice2.index[1] + assert string_series[2] == slice1[1] + assert object_series[2] == slice2[1] -def test_getitem_generator(test_data): - gen = (x > 0 for x in test_data.series) - result = test_data.series[gen] - result2 = test_data.series[iter(test_data.series > 0)] - expected = test_data.series[test_data.series > 0] +def test_getitem_generator(string_series): + gen = (x > 0 for x in string_series) + result = string_series[gen] + result2 = string_series[iter(string_series > 0)] + expected = string_series[string_series > 0] assert_series_equal(result, expected) assert_series_equal(result2, expected) @@ -169,11 +166,11 @@ def test_getitem_with_duplicates_indices(result_1, duplicate_item, expected_1): assert result[2] == result_1[2] -def test_getitem_out_of_bounds(test_data): +def test_getitem_out_of_bounds(datetime_series): # don't segfault, GH #495 msg = "index out of bounds" with pytest.raises(IndexError, match=msg): - test_data.ts[len(test_data.ts)] + datetime_series[len(datetime_series)] # GH #917 s = Series([]) @@ -190,8 +187,8 @@ def test_getitem_setitem_integers(): tm.assert_almost_equal(s["a"], 5) -def test_getitem_box_float64(test_data): - value = test_data.ts[5] +def test_getitem_box_float64(datetime_series): + value = datetime_series[5] assert isinstance(value, np.float64) @@ -308,14 +305,14 @@ def test_getitem_dataframe(): s[df > 5] -def test_setitem(test_data): - test_data.ts[test_data.ts.index[5]] = np.NaN - test_data.ts[[1, 2, 17]] = np.NaN - test_data.ts[6] = np.NaN - assert np.isnan(test_data.ts[6]) - assert np.isnan(test_data.ts[2]) - test_data.ts[np.isnan(test_data.ts)] = 5 - assert not np.isnan(test_data.ts[2]) +def test_setitem(datetime_series, string_series): + datetime_series[datetime_series.index[5]] = np.NaN + datetime_series[[1, 2, 17]] = np.NaN + datetime_series[6] = np.NaN + assert np.isnan(datetime_series[6]) + assert np.isnan(datetime_series[2]) + datetime_series[np.isnan(datetime_series)] = 5 + assert not np.isnan(datetime_series[2]) # caught this bug when writing tests series = Series(tm.makeIntIndex(20).astype(float), index=tm.makeIntIndex(20)) @@ -324,11 +321,11 @@ def test_setitem(test_data): assert (series[::2] == 0).all() # set item that's not contained - s = test_data.series.copy() + s = string_series.copy() s["foobar"] = 1 app = Series([1], index=["foobar"], name="series") - expected = test_data.series.append(app) + expected = string_series.append(app) assert_series_equal(s, expected) # Test for issue #10193 @@ -370,52 +367,52 @@ def test_setitem_dtypes(): assert_series_equal(s, Series([np.nan, 1.0])) -def test_set_value(test_data): - idx = test_data.ts.index[10] - res = test_data.ts._set_value(idx, 0) - assert res is test_data.ts - assert test_data.ts[idx] == 0 +def test_set_value(datetime_series, string_series): + idx = datetime_series.index[10] + res = datetime_series._set_value(idx, 0) + assert res is datetime_series + assert datetime_series[idx] == 0 # equiv - s = test_data.series.copy() + s = string_series.copy() res = s._set_value("foobar", 0) assert res is s assert res.index[-1] == "foobar" assert res["foobar"] == 0 - s = test_data.series.copy() + s = string_series.copy() s.loc["foobar"] = 0 assert s.index[-1] == "foobar" assert s["foobar"] == 0 -def test_setslice(test_data): - sl = test_data.ts[5:20] +def test_setslice(datetime_series): + sl = datetime_series[5:20] assert len(sl) == len(sl.index) assert sl.index.is_unique is True # FutureWarning from NumPy about [slice(None, 5). @pytest.mark.filterwarnings("ignore:Using a non-tuple:FutureWarning") -def test_basic_getitem_setitem_corner(test_data): +def test_basic_getitem_setitem_corner(datetime_series): # invalid tuples, e.g. td.ts[:, None] vs. td.ts[:, 2] msg = "Can only tuple-index with a MultiIndex" with pytest.raises(ValueError, match=msg): - test_data.ts[:, 2] + datetime_series[:, 2] with pytest.raises(ValueError, match=msg): - test_data.ts[:, 2] = 2 + datetime_series[:, 2] = 2 # weird lists. [slice(0, 5)] will work but not two slices - result = test_data.ts[[slice(None, 5)]] - expected = test_data.ts[:5] + result = datetime_series[[slice(None, 5)]] + expected = datetime_series[:5] assert_series_equal(result, expected) # OK msg = r"unhashable type(: 'slice')?" with pytest.raises(TypeError, match=msg): - test_data.ts[[5, slice(None, None)]] + datetime_series[[5, slice(None, None)]] with pytest.raises(TypeError, match=msg): - test_data.ts[[5, slice(None, None)]] = 2 + datetime_series[[5, slice(None, None)]] = 2 @pytest.mark.parametrize("tz", ["US/Eastern", "UTC", "Asia/Tokyo"]) @@ -556,25 +553,25 @@ def test_categorical_assigning_ops(): tm.assert_series_equal(s, exp) -def test_slice(test_data): - numSlice = test_data.series[10:20] - numSliceEnd = test_data.series[-10:] - objSlice = test_data.objSeries[10:20] +def test_slice(string_series, object_series): + numSlice = string_series[10:20] + numSliceEnd = string_series[-10:] + objSlice = object_series[10:20] - assert test_data.series.index[9] not in numSlice.index - assert test_data.objSeries.index[9] not in objSlice.index + assert string_series.index[9] not in numSlice.index + assert object_series.index[9] not in objSlice.index assert len(numSlice) == len(numSlice.index) - assert test_data.series[numSlice.index[0]] == numSlice[numSlice.index[0]] + assert string_series[numSlice.index[0]] == numSlice[numSlice.index[0]] - assert numSlice.index[1] == test_data.series.index[11] - assert tm.equalContents(numSliceEnd, np.array(test_data.series)[-10:]) + assert numSlice.index[1] == string_series.index[11] + assert tm.equalContents(numSliceEnd, np.array(string_series)[-10:]) # Test return view. - sl = test_data.series[10:20] + sl = string_series[10:20] sl[:] = 0 - assert (test_data.series[10:20] == 0).all() + assert (string_series[10:20] == 0).all() def test_slice_can_reorder_not_uniquely_indexed(): @@ -582,13 +579,13 @@ def test_slice_can_reorder_not_uniquely_indexed(): s[::-1] # it works! -def test_loc_setitem(test_data): - inds = test_data.series.index[[3, 4, 7]] +def test_loc_setitem(string_series): + inds = string_series.index[[3, 4, 7]] - result = test_data.series.copy() + result = string_series.copy() result.loc[inds] = 5 - expected = test_data.series.copy() + expected = string_series.copy() expected[[3, 4, 7]] = 5 assert_series_equal(result, expected) @@ -597,16 +594,16 @@ def test_loc_setitem(test_data): assert_series_equal(result, expected) # set slice with indices - d1, d2 = test_data.series.index[[5, 15]] + d1, d2 = string_series.index[[5, 15]] result.loc[d1:d2] = 6 expected[5:16] = 6 # because it's inclusive assert_series_equal(result, expected) # set index value - test_data.series.loc[d1] = 4 - test_data.series.loc[d2] = 6 - assert test_data.series[d1] == 4 - assert test_data.series[d2] == 6 + string_series.loc[d1] = 4 + string_series.loc[d2] = 6 + assert string_series[d1] == 4 + assert string_series[d2] == 6 def test_setitem_na(): @@ -776,10 +773,10 @@ def test_underlying_data_conversion(): tm.assert_frame_equal(df, expected) -def test_preserve_refs(test_data): - seq = test_data.ts[[5, 10, 15]] +def test_preserve_refs(datetime_series): + seq = datetime_series[[5, 10, 15]] seq[1] = np.NaN - assert not np.isnan(test_data.ts[10]) + assert not np.isnan(datetime_series[10]) def test_cast_on_putmask(): @@ -902,11 +899,11 @@ def test_take_categorical(): assert_series_equal(result, expected) -def test_head_tail(test_data): - assert_series_equal(test_data.series.head(), test_data.series[:5]) - assert_series_equal(test_data.series.head(0), test_data.series[0:0]) - assert_series_equal(test_data.series.tail(), test_data.series[-5:]) - assert_series_equal(test_data.series.tail(0), test_data.series[0:0]) +def test_head_tail(string_series): + assert_series_equal(string_series.head(), string_series[:5]) + assert_series_equal(string_series.head(0), string_series[0:0]) + assert_series_equal(string_series.tail(), string_series[-5:]) + assert_series_equal(string_series.tail(0), string_series[0:0]) def test_uint_drop(any_int_dtype): diff --git a/pandas/tests/series/indexing/test_loc.py b/pandas/tests/series/indexing/test_loc.py index 2f7807526a29d..d3402725130fb 100644 --- a/pandas/tests/series/indexing/test_loc.py +++ b/pandas/tests/series/indexing/test_loc.py @@ -13,30 +13,30 @@ def test_loc_uint64(val, expected): assert s.loc[val] == expected -def test_loc_getitem(test_data): - inds = test_data.series.index[[3, 4, 7]] - assert_series_equal(test_data.series.loc[inds], test_data.series.reindex(inds)) - assert_series_equal(test_data.series.iloc[5::2], test_data.series[5::2]) +def test_loc_getitem(string_series, datetime_series): + inds = string_series.index[[3, 4, 7]] + assert_series_equal(string_series.loc[inds], string_series.reindex(inds)) + assert_series_equal(string_series.iloc[5::2], string_series[5::2]) # slice with indices - d1, d2 = test_data.ts.index[[5, 15]] - result = test_data.ts.loc[d1:d2] - expected = test_data.ts.truncate(d1, d2) + d1, d2 = datetime_series.index[[5, 15]] + result = datetime_series.loc[d1:d2] + expected = datetime_series.truncate(d1, d2) assert_series_equal(result, expected) # boolean - mask = test_data.series > test_data.series.median() - assert_series_equal(test_data.series.loc[mask], test_data.series[mask]) + mask = string_series > string_series.median() + assert_series_equal(string_series.loc[mask], string_series[mask]) # ask for index value - assert test_data.ts.loc[d1] == test_data.ts[d1] - assert test_data.ts.loc[d2] == test_data.ts[d2] + assert datetime_series.loc[d1] == datetime_series[d1] + assert datetime_series.loc[d2] == datetime_series[d2] -def test_loc_getitem_not_monotonic(test_data): - d1, d2 = test_data.ts.index[[5, 15]] +def test_loc_getitem_not_monotonic(datetime_series): + d1, d2 = datetime_series.index[[5, 15]] - ts2 = test_data.ts[::2][[1, 2, 0]] + ts2 = datetime_series[::2][[1, 2, 0]] msg = r"Timestamp\('2000-01-10 00:00:00'\)" with pytest.raises(KeyError, match=msg): @@ -73,41 +73,41 @@ def test_loc_getitem_setitem_integer_slice_keyerrors(): s2.loc[3:11] = 0 -def test_loc_getitem_iterator(test_data): - idx = iter(test_data.series.index[:10]) - result = test_data.series.loc[idx] - assert_series_equal(result, test_data.series[:10]) +def test_loc_getitem_iterator(string_series): + idx = iter(string_series.index[:10]) + result = string_series.loc[idx] + assert_series_equal(result, string_series[:10]) -def test_loc_setitem_boolean(test_data): - mask = test_data.series > test_data.series.median() +def test_loc_setitem_boolean(string_series): + mask = string_series > string_series.median() - result = test_data.series.copy() + result = string_series.copy() result.loc[mask] = 0 - expected = test_data.series + expected = string_series expected[mask] = 0 assert_series_equal(result, expected) -def test_loc_setitem_corner(test_data): - inds = list(test_data.series.index[[5, 8, 12]]) - test_data.series.loc[inds] = 5 +def test_loc_setitem_corner(string_series): + inds = list(string_series.index[[5, 8, 12]]) + string_series.loc[inds] = 5 msg = r"\['foo'\] not in index" with pytest.raises(KeyError, match=msg): - test_data.series.loc[inds + ["foo"]] = 5 + string_series.loc[inds + ["foo"]] = 5 -def test_basic_setitem_with_labels(test_data): - indices = test_data.ts.index[[5, 10, 15]] +def test_basic_setitem_with_labels(datetime_series): + indices = datetime_series.index[[5, 10, 15]] - cp = test_data.ts.copy() - exp = test_data.ts.copy() + cp = datetime_series.copy() + exp = datetime_series.copy() cp[indices] = 0 exp.loc[indices] = 0 assert_series_equal(cp, exp) - cp = test_data.ts.copy() - exp = test_data.ts.copy() + cp = datetime_series.copy() + exp = datetime_series.copy() cp[indices[0] : indices[2]] = 0 exp.loc[indices[0] : indices[2]] = 0 assert_series_equal(cp, exp) diff --git a/pandas/tests/series/indexing/test_numeric.py b/pandas/tests/series/indexing/test_numeric.py index b4996575b0a05..083324101f437 100644 --- a/pandas/tests/series/indexing/test_numeric.py +++ b/pandas/tests/series/indexing/test_numeric.py @@ -262,22 +262,22 @@ def test_setitem_float_labels(): assert_series_equal(s, tmp) -def test_slice_float_get_set(test_data): +def test_slice_float_get_set(datetime_series): msg = ( r"cannot do slice indexing on <class 'pandas\.core\.indexes" r"\.datetimes\.DatetimeIndex'> with these indexers \[{key}\]" r" of <class 'float'>" ) with pytest.raises(TypeError, match=msg.format(key=r"4\.0")): - test_data.ts[4.0:10.0] + datetime_series[4.0:10.0] with pytest.raises(TypeError, match=msg.format(key=r"4\.0")): - test_data.ts[4.0:10.0] = 0 + datetime_series[4.0:10.0] = 0 with pytest.raises(TypeError, match=msg.format(key=r"4\.5")): - test_data.ts[4.5:10.0] + datetime_series[4.5:10.0] with pytest.raises(TypeError, match=msg.format(key=r"4\.5")): - test_data.ts[4.5:10.0] = 0 + datetime_series[4.5:10.0] = 0 def test_slice_floats2(): @@ -312,6 +312,6 @@ def test_int_indexing(): s["c"] -def test_getitem_int64(test_data): +def test_getitem_int64(datetime_series): idx = np.int64(5) - assert test_data.ts[idx] == test_data.ts[5] + assert datetime_series[idx] == datetime_series[5]
Part of #22550 * Replaced test_data fixture in `pandas/tests/series/indexing/` with more granular fixtures * Removed pandas/tests/series/indexing/conftest.py as the test_data fixture is not needed anymore * Removed pandas/tests/series/common.py as TestData isn't used anymore - [x] closes #22550 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/29220
2019-10-25T09:27:14Z
2019-10-29T16:18:24Z
2019-10-29T16:18:24Z
2019-10-29T16:18:29Z
ENH: Show column name in assert_frame_equal
diff --git a/pandas/_testing.py b/pandas/_testing.py index 8febcfc574d75..2050a18cb48bf 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -1287,7 +1287,7 @@ def assert_frame_equal( >>> assert_frame_equal(df1, df2) Traceback (most recent call last): ... - AssertionError: Attributes of DataFrame.iloc[:, 1] are different + AssertionError: Attributes of DataFrame.iloc[:, 1] (column name="b") are different Attribute "dtype" are different [left]: int64 @@ -1366,7 +1366,7 @@ def assert_frame_equal( check_names=check_names, check_datetimelike_compat=check_datetimelike_compat, check_categorical=check_categorical, - obj=f"{obj}.iloc[:, {i}]", + obj=f'{obj}.iloc[:, {i}] (column name="{col}")', ) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index 0aa450f5f96d1..dcb3859c5f166 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -181,9 +181,9 @@ def test_frame_equal_columns_mismatch(obj_fixture): def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): - msg = """{obj}\\.iloc\\[:, 1\\] are different + msg = """{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) are different -{obj}\\.iloc\\[:, 1\\] values are different \\(33\\.33333 %\\) +{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) values are different \\(33\\.33333 %\\) \\[left\\]: \\[4, 5, 6\\] \\[right\\]: \\[4, 5, 7\\]""".format( obj=obj_fixture @@ -202,18 +202,18 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "e̊"]}), - """{obj}\\.iloc\\[:, 1\\] are different + """{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) are different -{obj}\\.iloc\\[:, 1\\] values are different \\(33\\.33333 %\\) +{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) values are different \\(33\\.33333 %\\) \\[left\\]: \\[é, è, ë\\] \\[right\\]: \\[é, è, e̊\\]""", ), ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["a", "a", "a"], "E": ["e", "e", "e"]}), - """{obj}\\.iloc\\[:, 0\\] are different + """{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) are different -{obj}\\.iloc\\[:, 0\\] values are different \\(100\\.0 %\\) +{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) values are different \\(100\\.0 %\\) \\[left\\]: \\[á, à, ä\\] \\[right\\]: \\[a, a, a\\]""", ),
The output of the AssertionError raised by assert_frame_equal is changed: - old: `AssertionError: Attributes of DataFrame.iloc[:, 1] are different` - new: `AssertionError: Attributes of DataFrame.loc[:, 'b'] are different` - [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/29218
2019-10-25T07:17:34Z
2020-01-07T07:05:19Z
2020-01-07T07:05:19Z
2020-01-09T12:59:57Z
Changing logo in README and removing old logo
diff --git a/README.md b/README.md index 7786eeb0ec5c7..c299241722b7e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ <div align="center"> - <img src="https://github.com/pandas-dev/pandas/blob/master/doc/logo/pandas_logo.png"><br> + <img src="https://dev.pandas.io/static/img/pandas.svg"><br> </div> ----------------- diff --git a/doc/logo/pandas_logo.png b/doc/logo/pandas_logo.png deleted file mode 100644 index 065ee4e4856a6..0000000000000 Binary files a/doc/logo/pandas_logo.png and /dev/null differ diff --git a/doc/logo/pandas_logo.py b/doc/logo/pandas_logo.py deleted file mode 100644 index 89410e3847bef..0000000000000 --- a/doc/logo/pandas_logo.py +++ /dev/null @@ -1,47 +0,0 @@ -# script to generate the pandas logo - -from matplotlib import pyplot as plt, rcParams -import numpy as np - -rcParams["mathtext.fontset"] = "cm" - - -def fnx(): - return np.random.randint(5, 50, 10) - - -fig = plt.figure(figsize=(6, 1.25)) - -ax = fig.add_axes((0.45, 0.1, 0.16, 0.8)) -bar_data = [2.1, -00.8, 1.1, 2.5, -2.1, -0.5, -2.0, 1.5] -ax.set_ylim(-3, 3) -ax.set_xticks([]) -ax.set_yticks([]) -ax.bar(np.arange(len(bar_data)), bar_data) - -ax = fig.add_axes((0.63, 0.1, 0.16, 0.8)) -for i in range(4): - ax.plot(np.random.rand(8)) -ax.set_xticks([]) -ax.set_yticks([]) - -ax = fig.add_axes((0.63 + 0.18, 0.1, 0.16, 0.8)) -y = np.row_stack((fnx(), fnx(), fnx())) -x = np.arange(10) -y1, y2, y3 = fnx(), fnx(), fnx() -ax.stackplot(x, y1, y2, y3) -ax.set_xticks([]) -ax.set_yticks([]) - -plt.figtext(0.05, 0.5, "pandas", size=40) - -plt.figtext( - 0.05, - 0.2, - r"$y_{it} = \beta^{\prime} x_{it} + \mu_{i} + \epsilon_{it}$", - size=16, - color="#5a89a4", -) - -fig.savefig("pandas_logo.svg") -fig.savefig("pandas_logo.png") diff --git a/doc/logo/pandas_logo.svg b/doc/logo/pandas_logo.svg deleted file mode 100644 index b165f9635bf51..0000000000000 --- a/doc/logo/pandas_logo.svg +++ /dev/null @@ -1,879 +0,0 @@ -<?xml version="1.0" encoding="utf-8" standalone="no"?> -<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" - "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> -<!-- Created with matplotlib (http://matplotlib.org/) --> -<svg height="90pt" version="1.1" viewBox="0 0 432 90" width="432pt" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> - <defs> - <style type="text/css"> -*{stroke-linecap:butt;stroke-linejoin:round;} - </style> - </defs> - <g id="figure_1"> - <g id="patch_1"> - <path d="M 0 90 -L 432 90 -L 432 0 -L 0 0 -z -" style="fill:#ffffff;"/> - </g> - <g id="axes_1"> - <g id="patch_2"> - <path d="M 194.4 81 -L 263.52 81 -L 263.52 9 -L 194.4 9 -z -" style="fill:#ffffff;"/> - </g> - <g id="patch_3"> - <path clip-path="url(#p65e1c8b035)" d="M 197.541818 45 -L 203.986573 45 -L 203.986573 19.8 -L 197.541818 19.8 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_4"> - <path clip-path="url(#p65e1c8b035)" d="M 205.597762 54.6 -L 212.042517 54.6 -L 212.042517 45 -L 205.597762 45 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_5"> - <path clip-path="url(#p65e1c8b035)" d="M 213.653706 45 -L 220.098462 45 -L 220.098462 31.8 -L 213.653706 31.8 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_6"> - <path clip-path="url(#p65e1c8b035)" d="M 221.70965 45 -L 228.154406 45 -L 228.154406 15 -L 221.70965 15 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_7"> - <path clip-path="url(#p65e1c8b035)" d="M 229.765594 70.2 -L 236.21035 70.2 -L 236.21035 45 -L 229.765594 45 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_8"> - <path clip-path="url(#p65e1c8b035)" d="M 237.821538 51 -L 244.266294 51 -L 244.266294 45 -L 237.821538 45 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_9"> - <path clip-path="url(#p65e1c8b035)" d="M 245.877483 69 -L 252.322238 69 -L 252.322238 45 -L 245.877483 45 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_10"> - <path clip-path="url(#p65e1c8b035)" d="M 253.933427 45 -L 260.378182 45 -L 260.378182 27 -L 253.933427 27 -z -" style="fill:#1f77b4;"/> - </g> - <g id="patch_11"> - <path d="M 194.4 81 -L 194.4 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_12"> - <path d="M 263.52 81 -L 263.52 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_13"> - <path d="M 194.4 81 -L 263.52 81 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_14"> - <path d="M 194.4 9 -L 263.52 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="matplotlib.axis_1"/> - <g id="matplotlib.axis_2"/> - </g> - <g id="axes_2"> - <g id="patch_15"> - <path d="M 272.16 81 -L 341.28 81 -L 341.28 9 -L 272.16 9 -z -" style="fill:#ffffff;"/> - </g> - <g id="line2d_1"> - <path clip-path="url(#p4dc94feb3b)" d="M 275.301818 28.25879 -L 284.278442 12.272727 -L 293.255065 77.727273 -L 302.231688 74.001976 -L 311.208312 75.463299 -L 320.184935 22.132305 -L 329.161558 55.957655 -L 338.138182 61.29857 -" style="fill:none;stroke:#1f77b4;stroke-linecap:square;stroke-width:1.5;"/> - </g> - <g id="line2d_2"> - <path clip-path="url(#p4dc94feb3b)" d="M 275.301818 61.597884 -L 284.278442 64.880819 -L 293.255065 72.804377 -L 302.231688 45.091884 -L 311.208312 52.559951 -L 320.184935 68.827589 -L 329.161558 20.701624 -L 338.138182 33.377345 -" style="fill:none;stroke:#ff7f0e;stroke-linecap:square;stroke-width:1.5;"/> - </g> - <g id="line2d_3"> - <path clip-path="url(#p4dc94feb3b)" d="M 275.301818 61.030555 -L 284.278442 53.336965 -L 293.255065 70.575237 -L 302.231688 25.312123 -L 311.208312 59.636378 -L 320.184935 15.516067 -L 329.161558 18.278268 -L 338.138182 15.705298 -" style="fill:none;stroke:#2ca02c;stroke-linecap:square;stroke-width:1.5;"/> - </g> - <g id="line2d_4"> - <path clip-path="url(#p4dc94feb3b)" d="M 275.301818 24.671958 -L 284.278442 24.751621 -L 293.255065 54.365292 -L 302.231688 22.746952 -L 311.208312 43.129804 -L 320.184935 56.792715 -L 329.161558 36.348113 -L 338.138182 22.434164 -" style="fill:none;stroke:#d62728;stroke-linecap:square;stroke-width:1.5;"/> - </g> - <g id="patch_16"> - <path d="M 272.16 81 -L 272.16 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_17"> - <path d="M 341.28 81 -L 341.28 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_18"> - <path d="M 272.16 81 -L 341.28 81 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_19"> - <path d="M 272.16 9 -L 341.28 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="matplotlib.axis_3"/> - <g id="matplotlib.axis_4"/> - </g> - <g id="axes_3"> - <g id="patch_20"> - <path d="M 349.92 81 -L 419.04 81 -L 419.04 9 -L 349.92 9 -z -" style="fill:#ffffff;"/> - </g> - <g id="PolyCollection_1"> - <defs> - <path d="M 353.061818 -31.491429 -L 353.061818 -9 -L 360.043636 -9 -L 367.025455 -9 -L 374.007273 -9 -L 380.989091 -9 -L 387.970909 -9 -L 394.952727 -9 -L 401.934545 -9 -L 408.916364 -9 -L 415.898182 -9 -L 415.898182 -22.165714 -L 415.898182 -22.165714 -L 408.916364 -29.297143 -L 401.934545 -15.034286 -L 394.952727 -25.457143 -L 387.970909 -19.422857 -L 380.989091 -29.297143 -L 374.007273 -24.908571 -L 367.025455 -35.88 -L 360.043636 -17.777143 -L 353.061818 -31.491429 -z -" id="m81de97919c"/> - </defs> - <g clip-path="url(#pfceed726e3)"> - <use style="fill:#1f77b4;" x="0" xlink:href="#m81de97919c" y="90"/> - </g> - </g> - <g id="PolyCollection_2"> - <defs> - <path d="M 353.061818 -56.725714 -L 353.061818 -31.491429 -L 360.043636 -17.777143 -L 367.025455 -35.88 -L 374.007273 -24.908571 -L 380.989091 -29.297143 -L 387.970909 -19.422857 -L 394.952727 -25.457143 -L 401.934545 -15.034286 -L 408.916364 -29.297143 -L 415.898182 -22.165714 -L 415.898182 -41.365714 -L 415.898182 -41.365714 -L 408.916364 -44.657143 -L 401.934545 -36.977143 -L 394.952727 -32.04 -L 387.970909 -32.588571 -L 380.989091 -47.4 -L 374.007273 -37.525714 -L 367.025455 -41.365714 -L 360.043636 -34.782857 -L 353.061818 -56.725714 -z -" id="maaf380e772"/> - </defs> - <g clip-path="url(#pfceed726e3)"> - <use style="fill:#ff7f0e;" x="0" xlink:href="#maaf380e772" y="90"/> - </g> - </g> - <g id="PolyCollection_3"> - <defs> - <path d="M 353.061818 -77.571429 -L 353.061818 -56.725714 -L 360.043636 -34.782857 -L 367.025455 -41.365714 -L 374.007273 -37.525714 -L 380.989091 -47.4 -L 387.970909 -32.588571 -L 394.952727 -32.04 -L 401.934545 -36.977143 -L 408.916364 -44.657143 -L 415.898182 -41.365714 -L 415.898182 -58.92 -L 415.898182 -58.92 -L 408.916364 -64.405714 -L 401.934545 -49.594286 -L 394.952727 -40.817143 -L 387.970909 -39.171429 -L 380.989091 -50.691429 -L 374.007273 -49.594286 -L 367.025455 -57.822857 -L 360.043636 -56.177143 -L 353.061818 -77.571429 -z -" id="m31c02dcfcb"/> - </defs> - <g clip-path="url(#pfceed726e3)"> - <use style="fill:#2ca02c;" x="0" xlink:href="#m31c02dcfcb" y="90"/> - </g> - </g> - <g id="patch_21"> - <path d="M 349.92 81 -L 349.92 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_22"> - <path d="M 419.04 81 -L 419.04 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_23"> - <path d="M 349.92 81 -L 419.04 81 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="patch_24"> - <path d="M 349.92 9 -L 419.04 9 -" style="fill:none;stroke:#000000;stroke-linecap:square;stroke-linejoin:miter;"/> - </g> - <g id="matplotlib.axis_5"/> - <g id="matplotlib.axis_6"/> - </g> - <g id="text_1"> - <!-- pandas --> - <defs> - <path d="M 18.109375 8.203125 -L 18.109375 -20.796875 -L 9.078125 -20.796875 -L 9.078125 54.6875 -L 18.109375 54.6875 -L 18.109375 46.390625 -Q 20.953125 51.265625 25.265625 53.625 -Q 29.59375 56 35.59375 56 -Q 45.5625 56 51.78125 48.09375 -Q 58.015625 40.1875 58.015625 27.296875 -Q 58.015625 14.40625 51.78125 6.484375 -Q 45.5625 -1.421875 35.59375 -1.421875 -Q 29.59375 -1.421875 25.265625 0.953125 -Q 20.953125 3.328125 18.109375 8.203125 -M 48.6875 27.296875 -Q 48.6875 37.203125 44.609375 42.84375 -Q 40.53125 48.484375 33.40625 48.484375 -Q 26.265625 48.484375 22.1875 42.84375 -Q 18.109375 37.203125 18.109375 27.296875 -Q 18.109375 17.390625 22.1875 11.75 -Q 26.265625 6.109375 33.40625 6.109375 -Q 40.53125 6.109375 44.609375 11.75 -Q 48.6875 17.390625 48.6875 27.296875 -" id="DejaVuSans-70"/> - <path d="M 34.28125 27.484375 -Q 23.390625 27.484375 19.1875 25 -Q 14.984375 22.515625 14.984375 16.5 -Q 14.984375 11.71875 18.140625 8.90625 -Q 21.296875 6.109375 26.703125 6.109375 -Q 34.1875 6.109375 38.703125 11.40625 -Q 43.21875 16.703125 43.21875 25.484375 -L 43.21875 27.484375 -z -M 52.203125 31.203125 -L 52.203125 0 -L 43.21875 0 -L 43.21875 8.296875 -Q 40.140625 3.328125 35.546875 0.953125 -Q 30.953125 -1.421875 24.3125 -1.421875 -Q 15.921875 -1.421875 10.953125 3.296875 -Q 6 8.015625 6 15.921875 -Q 6 25.140625 12.171875 29.828125 -Q 18.359375 34.515625 30.609375 34.515625 -L 43.21875 34.515625 -L 43.21875 35.40625 -Q 43.21875 41.609375 39.140625 45 -Q 35.0625 48.390625 27.6875 48.390625 -Q 23 48.390625 18.546875 47.265625 -Q 14.109375 46.140625 10.015625 43.890625 -L 10.015625 52.203125 -Q 14.9375 54.109375 19.578125 55.046875 -Q 24.21875 56 28.609375 56 -Q 40.484375 56 46.34375 49.84375 -Q 52.203125 43.703125 52.203125 31.203125 -" id="DejaVuSans-61"/> - <path d="M 54.890625 33.015625 -L 54.890625 0 -L 45.90625 0 -L 45.90625 32.71875 -Q 45.90625 40.484375 42.875 44.328125 -Q 39.84375 48.1875 33.796875 48.1875 -Q 26.515625 48.1875 22.3125 43.546875 -Q 18.109375 38.921875 18.109375 30.90625 -L 18.109375 0 -L 9.078125 0 -L 9.078125 54.6875 -L 18.109375 54.6875 -L 18.109375 46.1875 -Q 21.34375 51.125 25.703125 53.5625 -Q 30.078125 56 35.796875 56 -Q 45.21875 56 50.046875 50.171875 -Q 54.890625 44.34375 54.890625 33.015625 -" id="DejaVuSans-6e"/> - <path d="M 45.40625 46.390625 -L 45.40625 75.984375 -L 54.390625 75.984375 -L 54.390625 0 -L 45.40625 0 -L 45.40625 8.203125 -Q 42.578125 3.328125 38.25 0.953125 -Q 33.9375 -1.421875 27.875 -1.421875 -Q 17.96875 -1.421875 11.734375 6.484375 -Q 5.515625 14.40625 5.515625 27.296875 -Q 5.515625 40.1875 11.734375 48.09375 -Q 17.96875 56 27.875 56 -Q 33.9375 56 38.25 53.625 -Q 42.578125 51.265625 45.40625 46.390625 -M 14.796875 27.296875 -Q 14.796875 17.390625 18.875 11.75 -Q 22.953125 6.109375 30.078125 6.109375 -Q 37.203125 6.109375 41.296875 11.75 -Q 45.40625 17.390625 45.40625 27.296875 -Q 45.40625 37.203125 41.296875 42.84375 -Q 37.203125 48.484375 30.078125 48.484375 -Q 22.953125 48.484375 18.875 42.84375 -Q 14.796875 37.203125 14.796875 27.296875 -" id="DejaVuSans-64"/> - <path d="M 44.28125 53.078125 -L 44.28125 44.578125 -Q 40.484375 46.53125 36.375 47.5 -Q 32.28125 48.484375 27.875 48.484375 -Q 21.1875 48.484375 17.84375 46.4375 -Q 14.5 44.390625 14.5 40.28125 -Q 14.5 37.15625 16.890625 35.375 -Q 19.28125 33.59375 26.515625 31.984375 -L 29.59375 31.296875 -Q 39.15625 29.25 43.1875 25.515625 -Q 47.21875 21.78125 47.21875 15.09375 -Q 47.21875 7.46875 41.1875 3.015625 -Q 35.15625 -1.421875 24.609375 -1.421875 -Q 20.21875 -1.421875 15.453125 -0.5625 -Q 10.6875 0.296875 5.421875 2 -L 5.421875 11.28125 -Q 10.40625 8.6875 15.234375 7.390625 -Q 20.0625 6.109375 24.8125 6.109375 -Q 31.15625 6.109375 34.5625 8.28125 -Q 37.984375 10.453125 37.984375 14.40625 -Q 37.984375 18.0625 35.515625 20.015625 -Q 33.0625 21.96875 24.703125 23.78125 -L 21.578125 24.515625 -Q 13.234375 26.265625 9.515625 29.90625 -Q 5.8125 33.546875 5.8125 39.890625 -Q 5.8125 47.609375 11.28125 51.796875 -Q 16.75 56 26.8125 56 -Q 31.78125 56 36.171875 55.265625 -Q 40.578125 54.546875 44.28125 53.078125 -" id="DejaVuSans-73"/> - </defs> - <g transform="translate(21.6 45)scale(0.4 -0.4)"> - <use xlink:href="#DejaVuSans-70"/> - <use x="63.476562" xlink:href="#DejaVuSans-61"/> - <use x="124.755859" xlink:href="#DejaVuSans-6e"/> - <use x="188.134766" xlink:href="#DejaVuSans-64"/> - <use x="251.611328" xlink:href="#DejaVuSans-61"/> - <use x="312.890625" xlink:href="#DejaVuSans-73"/> - </g> - </g> - <g id="text_2"> - <!-- $y_{it} = \beta^{\prime} x_{it} + \mu_{i} + \epsilon_{it}$ --> - <defs> - <path d="M 8.40625 -14.3125 -Q 10.5 -17.921875 15.71875 -17.921875 -Q 20.453125 -17.921875 23.921875 -14.59375 -Q 27.390625 -11.28125 29.515625 -6.5625 -Q 31.640625 -1.859375 32.8125 3.078125 -Q 28.375 -1.125 23.1875 -1.125 -Q 19.234375 -1.125 16.453125 0.234375 -Q 13.671875 1.609375 12.125 4.3125 -Q 10.59375 7.03125 10.59375 10.890625 -Q 10.59375 14.15625 11.46875 17.59375 -Q 12.359375 21.046875 13.9375 25.265625 -Q 15.53125 29.5 16.703125 32.625 -Q 18.015625 36.28125 18.015625 38.625 -Q 18.015625 41.609375 15.828125 41.609375 -Q 11.859375 41.609375 9.296875 37.53125 -Q 6.734375 33.453125 5.515625 28.421875 -Q 5.328125 27.78125 4.6875 27.78125 -L 3.515625 27.78125 -Q 2.6875 27.78125 2.6875 28.71875 -L 2.6875 29 -Q 4.296875 34.96875 7.609375 39.578125 -Q 10.9375 44.1875 16.015625 44.1875 -Q 19.578125 44.1875 22.046875 41.84375 -Q 24.515625 39.5 24.515625 35.890625 -Q 24.515625 34.03125 23.6875 31.984375 -Q 23.25 30.765625 21.6875 26.65625 -Q 20.125 22.5625 19.28125 19.875 -Q 18.453125 17.1875 17.921875 14.59375 -Q 17.390625 12.015625 17.390625 9.421875 -Q 17.390625 6.109375 18.796875 3.8125 -Q 20.21875 1.515625 23.296875 1.515625 -Q 29.5 1.515625 34.421875 9.078125 -L 42 39.890625 -Q 42.328125 41.21875 43.546875 42.15625 -Q 44.78125 43.109375 46.1875 43.109375 -Q 47.40625 43.109375 48.3125 42.328125 -Q 49.21875 41.546875 49.21875 40.28125 -Q 49.21875 39.703125 49.125 39.5 -L 39.203125 -0.296875 -Q 37.890625 -5.421875 34.375 -10.109375 -Q 30.859375 -14.796875 25.90625 -17.65625 -Q 20.953125 -20.515625 15.578125 -20.515625 -Q 12.984375 -20.515625 10.4375 -19.5 -Q 7.90625 -18.5 6.34375 -16.5 -Q 4.78125 -14.5 4.78125 -11.8125 -Q 4.78125 -9.078125 6.390625 -7.078125 -Q 8.015625 -5.078125 10.6875 -5.078125 -Q 12.3125 -5.078125 13.40625 -6.078125 -Q 14.5 -7.078125 14.5 -8.6875 -Q 14.5 -10.984375 12.78125 -12.6875 -Q 11.078125 -14.40625 8.796875 -14.40625 -Q 8.6875 -14.359375 8.59375 -14.328125 -Q 8.5 -14.3125 8.40625 -14.3125 -" id="Cmmi10-79"/> - <path d="M 7.8125 7.171875 -Q 7.8125 9.03125 8.59375 11.078125 -L 16.703125 32.625 -Q 18.015625 36.28125 18.015625 38.625 -Q 18.015625 41.609375 15.828125 41.609375 -Q 11.859375 41.609375 9.296875 37.53125 -Q 6.734375 33.453125 5.515625 28.421875 -Q 5.328125 27.78125 4.6875 27.78125 -L 3.515625 27.78125 -Q 2.6875 27.78125 2.6875 28.71875 -L 2.6875 29 -Q 4.296875 34.96875 7.609375 39.578125 -Q 10.9375 44.1875 16.015625 44.1875 -Q 19.578125 44.1875 22.046875 41.84375 -Q 24.515625 39.5 24.515625 35.890625 -Q 24.515625 34.03125 23.6875 31.984375 -L 15.578125 10.5 -Q 14.203125 7.171875 14.203125 4.5 -Q 14.203125 1.515625 16.5 1.515625 -Q 20.40625 1.515625 23.015625 5.6875 -Q 25.640625 9.859375 26.703125 14.703125 -Q 26.90625 15.28125 27.484375 15.28125 -L 28.71875 15.28125 -Q 29.109375 15.28125 29.34375 15.015625 -Q 29.59375 14.75 29.59375 14.40625 -Q 29.59375 14.3125 29.5 14.109375 -Q 28.125 8.453125 24.734375 3.65625 -Q 21.34375 -1.125 16.3125 -1.125 -Q 12.796875 -1.125 10.296875 1.296875 -Q 7.8125 3.71875 7.8125 7.171875 -M 19.09375 60.59375 -Q 19.09375 62.703125 20.84375 64.40625 -Q 22.609375 66.109375 24.703125 66.109375 -Q 26.421875 66.109375 27.515625 65.0625 -Q 28.609375 64.015625 28.609375 62.40625 -Q 28.609375 60.15625 26.828125 58.46875 -Q 25.046875 56.78125 22.90625 56.78125 -Q 21.296875 56.78125 20.1875 57.875 -Q 19.09375 58.984375 19.09375 60.59375 -" id="Cmmi10-69"/> - <path d="M 6.203125 8.109375 -Q 6.203125 9.578125 6.5 10.890625 -L 13.71875 39.59375 -L 3.21875 39.59375 -Q 2.203125 39.59375 2.203125 40.921875 -Q 2.59375 43.109375 3.515625 43.109375 -L 14.59375 43.109375 -L 18.609375 59.421875 -Q 19 60.75 20.171875 61.671875 -Q 21.34375 62.59375 22.796875 62.59375 -Q 24.078125 62.59375 24.921875 61.828125 -Q 25.78125 61.078125 25.78125 59.8125 -Q 25.78125 59.515625 25.75 59.34375 -Q 25.734375 59.1875 25.6875 58.984375 -L 21.6875 43.109375 -L 31.984375 43.109375 -Q 33.015625 43.109375 33.015625 41.796875 -Q 32.953125 41.546875 32.8125 40.953125 -Q 32.671875 40.375 32.421875 39.984375 -Q 32.171875 39.59375 31.6875 39.59375 -L 20.796875 39.59375 -L 13.625 10.6875 -Q 12.890625 7.859375 12.890625 5.8125 -Q 12.890625 1.515625 15.828125 1.515625 -Q 20.21875 1.515625 23.609375 5.640625 -Q 27 9.765625 28.8125 14.703125 -Q 29.203125 15.28125 29.59375 15.28125 -L 30.8125 15.28125 -Q 31.203125 15.28125 31.4375 15.015625 -Q 31.6875 14.75 31.6875 14.40625 -Q 31.6875 14.203125 31.59375 14.109375 -Q 29.390625 8.0625 25.1875 3.46875 -Q 21 -1.125 15.578125 -1.125 -Q 11.625 -1.125 8.90625 1.453125 -Q 6.203125 4.046875 6.203125 8.109375 -" id="Cmmi10-74"/> - <path d="M 7.515625 13.28125 -Q 6.6875 13.28125 6.140625 13.90625 -Q 5.609375 14.546875 5.609375 15.28125 -Q 5.609375 16.109375 6.140625 16.6875 -Q 6.6875 17.28125 7.515625 17.28125 -L 70.3125 17.28125 -Q 71.046875 17.28125 71.578125 16.6875 -Q 72.125 16.109375 72.125 15.28125 -Q 72.125 14.546875 71.578125 13.90625 -Q 71.046875 13.28125 70.3125 13.28125 -z -M 7.515625 32.71875 -Q 6.6875 32.71875 6.140625 33.296875 -Q 5.609375 33.890625 5.609375 34.71875 -Q 5.609375 35.453125 6.140625 36.078125 -Q 6.6875 36.71875 7.515625 36.71875 -L 70.3125 36.71875 -Q 71.046875 36.71875 71.578125 36.078125 -Q 72.125 35.453125 72.125 34.71875 -Q 72.125 33.890625 71.578125 33.296875 -Q 71.046875 32.71875 70.3125 32.71875 -z -" id="Cmr10-3d"/> - <path d="M 2.6875 -19.390625 -Q 2.390625 -19.390625 2.140625 -19.046875 -Q 1.90625 -18.703125 1.90625 -18.40625 -L 17.28125 43.40625 -Q 18.609375 48.390625 21.140625 53.078125 -Q 23.6875 57.765625 27.515625 61.796875 -Q 31.34375 65.828125 35.9375 68.171875 -Q 40.53125 70.515625 45.703125 70.515625 -Q 49.421875 70.515625 52.421875 68.875 -Q 55.421875 67.234375 57.15625 64.28125 -Q 58.890625 61.328125 58.890625 57.625 -Q 58.890625 54.046875 57.515625 50.796875 -Q 56.15625 47.5625 53.703125 44.75 -Q 51.265625 41.9375 48.484375 40.1875 -Q 50.09375 39.15625 51.359375 37.5625 -Q 52.640625 35.984375 53.421875 34.25 -Q 54.203125 32.515625 54.640625 30.390625 -Q 55.078125 28.265625 55.078125 26.421875 -Q 55.078125 21.296875 52.875 16.3125 -Q 50.6875 11.328125 46.890625 7.265625 -Q 43.109375 3.21875 38.21875 0.84375 -Q 33.34375 -1.515625 28.21875 -1.515625 -Q 22.609375 -1.515625 18.109375 1.5625 -Q 13.625 4.640625 11.921875 9.90625 -L 4.6875 -18.796875 -Q 4.6875 -19.390625 3.90625 -19.390625 -z -M 28.421875 1.21875 -Q 32.90625 1.21875 36.546875 4.171875 -Q 40.1875 7.125 42.546875 11.59375 -Q 44.921875 16.0625 46.15625 21.0625 -Q 47.40625 26.078125 47.40625 30.171875 -Q 47.40625 35.25 44.484375 38.1875 -Q 41.0625 36.921875 37.796875 36.921875 -Q 29.890625 36.921875 29.890625 39.59375 -Q 29.890625 43.109375 38.921875 43.109375 -Q 42.140625 43.109375 44.828125 42.09375 -Q 46.96875 43.75 48.71875 46.96875 -Q 50.484375 50.203125 51.390625 53.71875 -Q 52.296875 57.234375 52.296875 60.296875 -Q 52.296875 63.578125 50.5625 65.75 -Q 48.828125 67.921875 45.515625 67.921875 -Q 39.40625 67.921875 34.15625 64.15625 -Q 28.90625 60.40625 25.296875 54.65625 -Q 21.6875 48.921875 20.125 42.828125 -L 14.59375 20.703125 -Q 14.0625 18.40625 13.921875 15.578125 -Q 13.921875 9.328125 18.015625 5.265625 -Q 22.125 1.21875 28.421875 1.21875 -M 32.90625 39.890625 -Q 34.421875 39.5 37.890625 39.5 -Q 39.59375 39.5 41.3125 40.09375 -Q 41.21875 40.1875 40.921875 40.1875 -Q 39.84375 40.484375 38.625 40.484375 -Q 34.078125 40.484375 32.90625 39.890625 -" id="Cmmi10-af"/> - <path d="M 3.515625 5.421875 -Q 2.875 5.609375 2.875 6.390625 -L 15.09375 51.8125 -Q 15.671875 53.65625 17.078125 54.78125 -Q 18.5 55.90625 20.3125 55.90625 -Q 22.65625 55.90625 24.4375 54.359375 -Q 26.21875 52.828125 26.21875 50.484375 -Q 26.21875 49.46875 25.6875 48.1875 -L 7.625 4.984375 -Q 7.28125 4.296875 6.6875 4.296875 -Q 6.15625 4.296875 5 4.78125 -Q 3.859375 5.28125 3.515625 5.421875 -" id="Cmsy10-30"/> - <path d="M 7.8125 2.875 -Q 9.578125 1.515625 12.796875 1.515625 -Q 15.921875 1.515625 18.3125 4.515625 -Q 20.703125 7.515625 21.578125 11.078125 -L 26.125 28.8125 -Q 27.203125 33.640625 27.203125 35.40625 -Q 27.203125 37.890625 25.8125 39.75 -Q 24.421875 41.609375 21.921875 41.609375 -Q 18.75 41.609375 15.96875 39.625 -Q 13.1875 37.640625 11.28125 34.59375 -Q 9.375 31.546875 8.59375 28.421875 -Q 8.40625 27.78125 7.8125 27.78125 -L 6.59375 27.78125 -Q 5.8125 27.78125 5.8125 28.71875 -L 5.8125 29 -Q 6.78125 32.71875 9.125 36.25 -Q 11.46875 39.796875 14.859375 41.984375 -Q 18.265625 44.1875 22.125 44.1875 -Q 25.78125 44.1875 28.734375 42.234375 -Q 31.6875 40.28125 32.90625 36.921875 -Q 34.625 39.984375 37.28125 42.078125 -Q 39.9375 44.1875 43.109375 44.1875 -Q 45.265625 44.1875 47.5 43.421875 -Q 49.75 42.671875 51.171875 41.109375 -Q 52.59375 39.546875 52.59375 37.203125 -Q 52.59375 34.671875 50.953125 32.828125 -Q 49.3125 31 46.78125 31 -Q 45.171875 31 44.09375 32.03125 -Q 43.015625 33.0625 43.015625 34.625 -Q 43.015625 36.71875 44.453125 38.296875 -Q 45.90625 39.890625 47.90625 40.1875 -Q 46.09375 41.609375 42.921875 41.609375 -Q 39.703125 41.609375 37.328125 38.625 -Q 34.96875 35.640625 33.984375 31.984375 -L 29.59375 14.3125 -Q 28.515625 10.296875 28.515625 7.71875 -Q 28.515625 5.171875 29.953125 3.34375 -Q 31.390625 1.515625 33.796875 1.515625 -Q 38.484375 1.515625 42.15625 5.640625 -Q 45.84375 9.765625 47.015625 14.703125 -Q 47.21875 15.28125 47.796875 15.28125 -L 49.03125 15.28125 -Q 49.421875 15.28125 49.65625 15.015625 -Q 49.90625 14.75 49.90625 14.40625 -Q 49.90625 14.3125 49.8125 14.109375 -Q 48.390625 8.15625 43.84375 3.515625 -Q 39.3125 -1.125 33.59375 -1.125 -Q 29.9375 -1.125 26.984375 0.84375 -Q 24.03125 2.828125 22.796875 6.203125 -Q 21.234375 3.265625 18.46875 1.0625 -Q 15.71875 -1.125 12.59375 -1.125 -Q 10.453125 -1.125 8.171875 -0.359375 -Q 5.90625 0.390625 4.484375 1.953125 -Q 3.078125 3.515625 3.078125 5.90625 -Q 3.078125 8.25 4.703125 10.171875 -Q 6.34375 12.109375 8.796875 12.109375 -Q 10.453125 12.109375 11.578125 11.109375 -Q 12.703125 10.109375 12.703125 8.5 -Q 12.703125 6.390625 11.296875 4.828125 -Q 9.90625 3.265625 7.8125 2.875 -" id="Cmmi10-78"/> - <path d="M 7.515625 23 -Q 6.6875 23 6.140625 23.625 -Q 5.609375 24.265625 5.609375 25 -Q 5.609375 25.734375 6.140625 26.359375 -Q 6.6875 27 7.515625 27 -L 36.921875 27 -L 36.921875 56.5 -Q 36.921875 57.28125 37.5 57.78125 -Q 38.09375 58.296875 38.921875 58.296875 -Q 39.65625 58.296875 40.28125 57.78125 -Q 40.921875 57.28125 40.921875 56.5 -L 40.921875 27 -L 70.3125 27 -Q 71.046875 27 71.578125 26.359375 -Q 72.125 25.734375 72.125 25 -Q 72.125 24.265625 71.578125 23.625 -Q 71.046875 23 70.3125 23 -L 40.921875 23 -L 40.921875 -6.5 -Q 40.921875 -7.28125 40.28125 -7.78125 -Q 39.65625 -8.296875 38.921875 -8.296875 -Q 38.09375 -8.296875 37.5 -7.78125 -Q 36.921875 -7.28125 36.921875 -6.5 -L 36.921875 23 -z -" id="Cmr10-2b"/> - <path d="M 2.78125 -18.796875 -Q 2.78125 -18.21875 2.875 -18.015625 -L 17.578125 41.015625 -Q 18.015625 42.4375 19.15625 43.3125 -Q 20.3125 44.1875 21.78125 44.1875 -Q 23.046875 44.1875 23.921875 43.421875 -Q 24.8125 42.671875 24.8125 41.40625 -Q 24.8125 41.109375 24.78125 40.9375 -Q 24.75 40.765625 24.703125 40.578125 -L 18.796875 17.1875 -Q 17.828125 13.03125 17.828125 10.015625 -Q 17.828125 6.296875 19.578125 3.90625 -Q 21.34375 1.515625 24.90625 1.515625 -Q 32.171875 1.515625 37.703125 10.59375 -Q 37.75 10.6875 37.765625 10.734375 -Q 37.796875 10.796875 37.796875 10.890625 -L 45.015625 39.890625 -Q 45.359375 41.21875 46.578125 42.15625 -Q 47.796875 43.109375 49.21875 43.109375 -Q 50.390625 43.109375 51.296875 42.328125 -Q 52.203125 41.546875 52.203125 40.28125 -Q 52.203125 39.703125 52.09375 39.5 -L 44.921875 10.6875 -Q 44.1875 7.859375 44.1875 5.8125 -Q 44.1875 1.515625 47.125 1.515625 -Q 50.25 1.515625 51.828125 5.375 -Q 53.421875 9.234375 54.59375 14.703125 -Q 54.78125 15.28125 55.421875 15.28125 -L 56.59375 15.28125 -Q 56.984375 15.28125 57.25 14.96875 -Q 57.515625 14.65625 57.515625 14.3125 -Q 55.765625 7.328125 53.6875 3.09375 -Q 51.609375 -1.125 46.921875 -1.125 -Q 43.609375 -1.125 41.046875 0.78125 -Q 38.484375 2.6875 37.703125 5.90625 -Q 35.203125 2.78125 31.859375 0.828125 -Q 28.515625 -1.125 24.8125 -1.125 -Q 18.5625 -1.125 14.984375 1.8125 -L 9.90625 -18.40625 -Q 9.625 -19.828125 8.453125 -20.703125 -Q 7.28125 -21.578125 5.8125 -21.578125 -Q 4.59375 -21.578125 3.6875 -20.8125 -Q 2.78125 -20.0625 2.78125 -18.796875 -" id="Cmmi10-b9"/> - <path d="M 12.3125 14.109375 -Q 12.3125 10.75 13.53125 7.859375 -Q 14.75 4.984375 17.203125 3.25 -Q 19.671875 1.515625 23 1.515625 -Q 25.25 1.515625 27.78125 2.484375 -Q 30.328125 3.46875 32.5 4.640625 -Q 34.671875 5.8125 34.71875 5.8125 -Q 35.25 5.8125 35.5625 5.203125 -Q 35.890625 4.59375 35.890625 4 -Q 35.890625 3.46875 35.59375 3.328125 -Q 29.34375 -1.125 22.90625 -1.125 -Q 17.625 -1.125 13.375 1.34375 -Q 9.125 3.8125 6.8125 8.203125 -Q 4.5 12.59375 4.5 17.828125 -Q 4.5 23 6.59375 27.65625 -Q 8.6875 32.328125 12.390625 35.796875 -Q 16.109375 39.265625 20.796875 41.1875 -Q 25.484375 43.109375 30.609375 43.109375 -L 36.28125 43.109375 -Q 37.796875 43.109375 37.796875 41.609375 -Q 37.796875 40.765625 37.234375 40.171875 -Q 36.671875 39.59375 35.890625 39.59375 -L 30.421875 39.59375 -Q 26.421875 39.59375 23.171875 37.828125 -Q 19.921875 36.078125 17.71875 32.953125 -Q 15.53125 29.828125 14.3125 25.875 -L 31.984375 25.875 -Q 32.671875 25.875 33.078125 25.453125 -Q 33.5 25.046875 33.5 24.421875 -Q 33.5 23.578125 32.953125 22.984375 -Q 32.421875 22.40625 31.59375 22.40625 -L 13.375 22.40625 -Q 12.3125 17.234375 12.3125 14.109375 -" id="Cmmi10-b2"/> - </defs> - <g style="fill:#5a89a4;" transform="translate(21.6 72)scale(0.16 -0.16)"> - <use transform="translate(0 0.601562)" xlink:href="#Cmmi10-79"/> - <use transform="translate(49.023438 -16.404687)scale(0.7)" xlink:href="#Cmmi10-69"/> - <use transform="translate(73.120117 -16.404687)scale(0.7)" xlink:href="#Cmmi10-74"/> - <use transform="translate(122.314844 0.601562)" xlink:href="#Cmr10-3d"/> - <use transform="translate(217.558984 0.601562)" xlink:href="#Cmmi10-af"/> - <use transform="translate(285.885312 38.865625)scale(0.7)" xlink:href="#Cmsy10-30"/> - <use transform="translate(311.50582 0.601562)" xlink:href="#Cmmi10-78"/> - <use transform="translate(368.585898 -16.404687)scale(0.7)" xlink:href="#Cmmi10-69"/> - <use transform="translate(392.682578 -16.404687)scale(0.7)" xlink:href="#Cmmi10-74"/> - <use transform="translate(441.877305 0.601562)" xlink:href="#Cmr10-2b"/> - <use transform="translate(537.121445 0.601562)" xlink:href="#Cmmi10-b9"/> - <use transform="translate(597.326523 -16.404687)scale(0.7)" xlink:href="#Cmmi10-69"/> - <use transform="translate(645.359141 0.601562)" xlink:href="#Cmr10-2b"/> - <use transform="translate(740.603281 0.601562)" xlink:href="#Cmmi10-b2"/> - <use transform="translate(781.081797 -16.404687)scale(0.7)" xlink:href="#Cmmi10-69"/> - <use transform="translate(805.178477 -16.404687)scale(0.7)" xlink:href="#Cmmi10-74"/> - </g> - </g> - </g> - <defs> - <clipPath id="p65e1c8b035"> - <rect height="72" width="69.12" x="194.4" y="9"/> - </clipPath> - <clipPath id="p4dc94feb3b"> - <rect height="72" width="69.12" x="272.16" y="9"/> - </clipPath> - <clipPath id="pfceed726e3"> - <rect height="72" width="69.12" x="349.92" y="9"/> - </clipPath> - </defs> -</svg>
Not sure if anyone prefers to publish the new logo when we release pandas 1.0 and the new website is life. I don't have a strong preference, but I'd say let's change the logo now if nobody cares, so one thing less to think about. I'll change the twitter logo and tweet about it once this is merged.
https://api.github.com/repos/pandas-dev/pandas/pulls/29215
2019-10-25T00:31:54Z
2019-10-25T16:18:35Z
2019-10-25T16:18:35Z
2019-10-25T16:18:35Z