Skip to content

Commit 62f8723

Browse files
authored
TST: Use importorskip over skip_if_no_scipy (#54387)
* TST: Use importorskip over skip_if_no_scipy * another importorskip
1 parent 0eeb8cb commit 62f8723

26 files changed

+191
-254
lines changed

pandas/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1868,7 +1868,7 @@ def spmatrix(request):
18681868
"""
18691869
Yields scipy sparse matrix classes.
18701870
"""
1871-
from scipy import sparse
1871+
sparse = pytest.importorskip("scipy.sparse")
18721872

18731873
return getattr(sparse, request.param + "_matrix")
18741874

pandas/tests/arrays/sparse/test_accessor.py

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import numpy as np
44
import pytest
55

6-
import pandas.util._test_decorators as td
7-
86
import pandas as pd
97
from pandas import SparseDtype
108
import pandas._testing as tm
@@ -46,7 +44,6 @@ def test_from_coo(self):
4644
expected = pd.Series([4, 9, 7, 5], index=index, dtype="Sparse[int]")
4745
tm.assert_series_equal(result, expected)
4846

49-
@td.skip_if_no_scipy
5047
@pytest.mark.parametrize(
5148
"sort_labels, expected_rows, expected_cols, expected_values_pos",
5249
[
@@ -67,7 +64,7 @@ def test_from_coo(self):
6764
def test_to_coo(
6865
self, sort_labels, expected_rows, expected_cols, expected_values_pos
6966
):
70-
import scipy.sparse
67+
sp_sparse = pytest.importorskip("scipy.sparse")
7168

7269
values = SparseArray([0, np.nan, 1, 0, None, 3], fill_value=0)
7370
index = pd.MultiIndex.from_tuples(
@@ -89,7 +86,7 @@ def test_to_coo(
8986
A, rows, cols = ss.sparse.to_coo(
9087
row_levels=(0, 1), column_levels=(2, 3), sort_labels=sort_labels
9188
)
92-
assert isinstance(A, scipy.sparse.coo_matrix)
89+
assert isinstance(A, sp_sparse.coo_matrix)
9390
tm.assert_numpy_array_equal(A.toarray(), expected_A)
9491
assert rows == expected_rows
9592
assert cols == expected_cols
@@ -109,25 +106,23 @@ def test_accessor_raises(self):
109106
@pytest.mark.parametrize("format", ["csc", "csr", "coo"])
110107
@pytest.mark.parametrize("labels", [None, list(string.ascii_letters[:10])])
111108
@pytest.mark.parametrize("dtype", ["float64", "int64"])
112-
@td.skip_if_no_scipy
113109
def test_from_spmatrix(self, format, labels, dtype):
114-
import scipy.sparse
110+
sp_sparse = pytest.importorskip("scipy.sparse")
115111

116112
sp_dtype = SparseDtype(dtype, np.array(0, dtype=dtype).item())
117113

118-
mat = scipy.sparse.eye(10, format=format, dtype=dtype)
114+
mat = sp_sparse.eye(10, format=format, dtype=dtype)
119115
result = pd.DataFrame.sparse.from_spmatrix(mat, index=labels, columns=labels)
120116
expected = pd.DataFrame(
121117
np.eye(10, dtype=dtype), index=labels, columns=labels
122118
).astype(sp_dtype)
123119
tm.assert_frame_equal(result, expected)
124120

125121
@pytest.mark.parametrize("format", ["csc", "csr", "coo"])
126-
@td.skip_if_no_scipy
127122
def test_from_spmatrix_including_explicit_zero(self, format):
128-
import scipy.sparse
123+
sp_sparse = pytest.importorskip("scipy.sparse")
129124

130-
mat = scipy.sparse.random(10, 2, density=0.5, format=format)
125+
mat = sp_sparse.random(10, 2, density=0.5, format=format)
131126
mat.data[0] = 0
132127
result = pd.DataFrame.sparse.from_spmatrix(mat)
133128
dtype = SparseDtype("float64", 0.0)
@@ -138,34 +133,32 @@ def test_from_spmatrix_including_explicit_zero(self, format):
138133
"columns",
139134
[["a", "b"], pd.MultiIndex.from_product([["A"], ["a", "b"]]), ["a", "a"]],
140135
)
141-
@td.skip_if_no_scipy
142136
def test_from_spmatrix_columns(self, columns):
143-
import scipy.sparse
137+
sp_sparse = pytest.importorskip("scipy.sparse")
144138

145139
dtype = SparseDtype("float64", 0.0)
146140

147-
mat = scipy.sparse.random(10, 2, density=0.5)
141+
mat = sp_sparse.random(10, 2, density=0.5)
148142
result = pd.DataFrame.sparse.from_spmatrix(mat, columns=columns)
149143
expected = pd.DataFrame(mat.toarray(), columns=columns).astype(dtype)
150144
tm.assert_frame_equal(result, expected)
151145

152146
@pytest.mark.parametrize(
153147
"colnames", [("A", "B"), (1, 2), (1, pd.NA), (0.1, 0.2), ("x", "x"), (0, 0)]
154148
)
155-
@td.skip_if_no_scipy
156149
def test_to_coo(self, colnames):
157-
import scipy.sparse
150+
sp_sparse = pytest.importorskip("scipy.sparse")
158151

159152
df = pd.DataFrame(
160153
{colnames[0]: [0, 1, 0], colnames[1]: [1, 0, 0]}, dtype="Sparse[int64, 0]"
161154
)
162155
result = df.sparse.to_coo()
163-
expected = scipy.sparse.coo_matrix(np.asarray(df))
156+
expected = sp_sparse.coo_matrix(np.asarray(df))
164157
assert (result != expected).nnz == 0
165158

166159
@pytest.mark.parametrize("fill_value", [1, np.nan])
167-
@td.skip_if_no_scipy
168160
def test_to_coo_nonzero_fill_val_raises(self, fill_value):
161+
pytest.importorskip("scipy")
169162
df = pd.DataFrame(
170163
{
171164
"A": SparseArray(
@@ -179,10 +172,9 @@ def test_to_coo_nonzero_fill_val_raises(self, fill_value):
179172
with pytest.raises(ValueError, match="fill value must be 0"):
180173
df.sparse.to_coo()
181174

182-
@td.skip_if_no_scipy
183175
def test_to_coo_midx_categorical(self):
184176
# GH#50996
185-
import scipy.sparse
177+
sp_sparse = pytest.importorskip("scipy.sparse")
186178

187179
midx = pd.MultiIndex.from_arrays(
188180
[
@@ -193,7 +185,7 @@ def test_to_coo_midx_categorical(self):
193185

194186
ser = pd.Series(1, index=midx, dtype="Sparse[int]")
195187
result = ser.sparse.to_coo(row_levels=["x"], column_levels=["y"])[0]
196-
expected = scipy.sparse.coo_matrix(
188+
expected = sp_sparse.coo_matrix(
197189
(np.array([1, 1]), (np.array([0, 1]), np.array([0, 1]))), shape=(2, 2)
198190
)
199191
assert (result != expected).nnz == 0
@@ -226,11 +218,10 @@ def test_density(self):
226218

227219
@pytest.mark.parametrize("dtype", ["int64", "float64"])
228220
@pytest.mark.parametrize("dense_index", [True, False])
229-
@td.skip_if_no_scipy
230221
def test_series_from_coo(self, dtype, dense_index):
231-
import scipy.sparse
222+
sp_sparse = pytest.importorskip("scipy.sparse")
232223

233-
A = scipy.sparse.eye(3, format="coo", dtype=dtype)
224+
A = sp_sparse.eye(3, format="coo", dtype=dtype)
234225
result = pd.Series.sparse.from_coo(A, dense_index=dense_index)
235226

236227
index = pd.MultiIndex.from_tuples(
@@ -246,12 +237,11 @@ def test_series_from_coo(self, dtype, dense_index):
246237

247238
tm.assert_series_equal(result, expected)
248239

249-
@td.skip_if_no_scipy
250240
def test_series_from_coo_incorrect_format_raises(self):
251241
# gh-26554
252-
import scipy.sparse
242+
sp_sparse = pytest.importorskip("scipy.sparse")
253243

254-
m = scipy.sparse.csr_matrix(np.array([[0, 1], [0, 0]]))
244+
m = sp_sparse.csr_matrix(np.array([[0, 1], [0, 0]]))
255245
with pytest.raises(
256246
TypeError, match="Expected coo_matrix. Got csr_matrix instead."
257247
):

pandas/tests/arrays/sparse/test_constructors.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import pytest
33

44
from pandas._libs.sparse import IntIndex
5-
import pandas.util._test_decorators as td
65

76
import pandas as pd
87
from pandas import (
@@ -188,35 +187,32 @@ def test_constructor_inferred_fill_value(self, data, fill_value):
188187

189188
@pytest.mark.parametrize("format", ["coo", "csc", "csr"])
190189
@pytest.mark.parametrize("size", [0, 10])
191-
@td.skip_if_no_scipy
192190
def test_from_spmatrix(self, size, format):
193-
import scipy.sparse
191+
sp_sparse = pytest.importorskip("scipy.sparse")
194192

195-
mat = scipy.sparse.random(size, 1, density=0.5, format=format)
193+
mat = sp_sparse.random(size, 1, density=0.5, format=format)
196194
result = SparseArray.from_spmatrix(mat)
197195

198196
result = np.asarray(result)
199197
expected = mat.toarray().ravel()
200198
tm.assert_numpy_array_equal(result, expected)
201199

202200
@pytest.mark.parametrize("format", ["coo", "csc", "csr"])
203-
@td.skip_if_no_scipy
204201
def test_from_spmatrix_including_explicit_zero(self, format):
205-
import scipy.sparse
202+
sp_sparse = pytest.importorskip("scipy.sparse")
206203

207-
mat = scipy.sparse.random(10, 1, density=0.5, format=format)
204+
mat = sp_sparse.random(10, 1, density=0.5, format=format)
208205
mat.data[0] = 0
209206
result = SparseArray.from_spmatrix(mat)
210207

211208
result = np.asarray(result)
212209
expected = mat.toarray().ravel()
213210
tm.assert_numpy_array_equal(result, expected)
214211

215-
@td.skip_if_no_scipy
216212
def test_from_spmatrix_raises(self):
217-
import scipy.sparse
213+
sp_sparse = pytest.importorskip("scipy.sparse")
218214

219-
mat = scipy.sparse.eye(5, 4, format="csc")
215+
mat = sp_sparse.eye(5, 4, format="csc")
220216

221217
with pytest.raises(ValueError, match="not '4'"):
222218
SparseArray.from_spmatrix(mat)

pandas/tests/dtypes/test_common.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -211,11 +211,10 @@ def test_is_sparse(check_scipy):
211211
assert not com.is_sparse(scipy.sparse.bsr_matrix([1, 2, 3]))
212212

213213

214-
@td.skip_if_no_scipy
215214
def test_is_scipy_sparse():
216-
from scipy.sparse import bsr_matrix
215+
sp_sparse = pytest.importorskip("scipy.sparse")
217216

218-
assert com.is_scipy_sparse(bsr_matrix([1, 2, 3]))
217+
assert com.is_scipy_sparse(sp_sparse.bsr_matrix([1, 2, 3]))
219218

220219
assert not com.is_scipy_sparse(SparseArray([1, 2, 3]))
221220

pandas/tests/dtypes/test_inference.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333
missing as libmissing,
3434
ops as libops,
3535
)
36-
import pandas.util._test_decorators as td
3736

3837
from pandas.core.dtypes import inference
3938
from pandas.core.dtypes.common import (
@@ -1970,9 +1969,9 @@ def test_nan_to_nat_conversions():
19701969
assert s[8] is pd.NaT
19711970

19721971

1973-
@td.skip_if_no_scipy
19741972
@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
19751973
def test_is_scipy_sparse(spmatrix):
1974+
pytest.importorskip("scipy")
19761975
assert is_scipy_sparse(spmatrix([[0, 1]]))
19771976
assert not is_scipy_sparse(np.array([1]))
19781977

pandas/tests/frame/methods/test_cov_corr.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ class TestDataFrameCorr:
104104
# DataFrame.corr(), as opposed to DataFrame.corrwith
105105

106106
@pytest.mark.parametrize("method", ["pearson", "kendall", "spearman"])
107-
@td.skip_if_no_scipy
108107
def test_corr_scipy_method(self, float_frame, method):
108+
pytest.importorskip("scipy")
109109
float_frame.loc[float_frame.index[:5], "A"] = np.nan
110110
float_frame.loc[float_frame.index[5:10], "B"] = np.nan
111111
float_frame.loc[float_frame.index[:10], "A"] = float_frame["A"][10:20]
@@ -123,10 +123,10 @@ def test_corr_non_numeric(self, float_string_frame):
123123
expected = float_string_frame.loc[:, ["A", "B", "C", "D"]].corr()
124124
tm.assert_frame_equal(result, expected)
125125

126-
@td.skip_if_no_scipy
127126
@pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])
128127
def test_corr_nooverlap(self, meth):
129128
# nothing in common
129+
pytest.importorskip("scipy")
130130
df = DataFrame(
131131
{
132132
"A": [1, 1.5, 1, np.nan, np.nan, np.nan],
@@ -153,12 +153,12 @@ def test_corr_constant(self, meth):
153153
rs = df.corr(meth)
154154
assert isna(rs.values).all()
155155

156-
@td.skip_if_no_scipy
157156
@pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])
158157
def test_corr_int_and_boolean(self, meth):
159158
# when dtypes of pandas series are different
160159
# then ndarray will have dtype=object,
161160
# so it need to be properly handled
161+
pytest.importorskip("scipy")
162162
df = DataFrame({"a": [True, False], "b": [1, 0]})
163163

164164
expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"])
@@ -193,7 +193,6 @@ def test_corr_int(self):
193193
df.cov()
194194
df.corr()
195195

196-
@td.skip_if_no_scipy
197196
@pytest.mark.parametrize(
198197
"nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])]
199198
)
@@ -204,6 +203,7 @@ def test_corr_int(self):
204203
@pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"])
205204
def test_corr_nullable_integer(self, nullable_column, other_column, method):
206205
# https://github.com/pandas-dev/pandas/issues/33803
206+
pytest.importorskip("scipy")
207207
data = DataFrame({"a": nullable_column, "b": other_column})
208208
result = data.corr(method=method)
209209
expected = DataFrame(np.ones((2, 2)), columns=["a", "b"], index=["a", "b"])
@@ -249,23 +249,23 @@ def test_calc_corr_small_numbers(self):
249249
expected = DataFrame({"A": [1.0, 1.0], "B": [1.0, 1.0]}, index=["A", "B"])
250250
tm.assert_frame_equal(result, expected)
251251

252-
@td.skip_if_no_scipy
253252
@pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"])
254253
def test_corr_min_periods_greater_than_length(self, method):
254+
pytest.importorskip("scipy")
255255
df = DataFrame({"A": [1, 2], "B": [1, 2]})
256256
result = df.corr(method=method, min_periods=3)
257257
expected = DataFrame(
258258
{"A": [np.nan, np.nan], "B": [np.nan, np.nan]}, index=["A", "B"]
259259
)
260260
tm.assert_frame_equal(result, expected)
261261

262-
@td.skip_if_no_scipy
263262
@pytest.mark.parametrize("meth", ["pearson", "kendall", "spearman"])
264263
@pytest.mark.parametrize("numeric_only", [True, False])
265264
def test_corr_numeric_only(self, meth, numeric_only):
266265
# when dtypes of pandas series are different
267266
# then ndarray will have dtype=object,
268267
# so it need to be properly handled
268+
pytest.importorskip("scipy")
269269
df = DataFrame({"a": [1, 0], "b": [1, 0], "c": ["x", "y"]})
270270
expected = DataFrame(np.ones((2, 2)), index=["a", "b"], columns=["a", "b"])
271271
if numeric_only:
@@ -422,25 +422,25 @@ def test_corr_numerical_instabilities(self):
422422
expected = DataFrame({0: [1.0, -1.0], 1: [-1.0, 1.0]})
423423
tm.assert_frame_equal(result - 1, expected - 1, atol=1e-17)
424424

425-
@td.skip_if_no_scipy
426425
def test_corrwith_spearman(self):
427426
# GH#21925
427+
pytest.importorskip("scipy")
428428
df = DataFrame(np.random.default_rng(2).random(size=(100, 3)))
429429
result = df.corrwith(df**2, method="spearman")
430430
expected = Series(np.ones(len(result)))
431431
tm.assert_series_equal(result, expected)
432432

433-
@td.skip_if_no_scipy
434433
def test_corrwith_kendall(self):
435434
# GH#21925
435+
pytest.importorskip("scipy")
436436
df = DataFrame(np.random.default_rng(2).random(size=(100, 3)))
437437
result = df.corrwith(df**2, method="kendall")
438438
expected = Series(np.ones(len(result)))
439439
tm.assert_series_equal(result, expected)
440440

441-
@td.skip_if_no_scipy
442441
def test_corrwith_spearman_with_tied_data(self):
443442
# GH#48826
443+
pytest.importorskip("scipy")
444444
df1 = DataFrame(
445445
{
446446
"A": [1, np.nan, 7, 8],

pandas/tests/frame/methods/test_interpolate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,8 @@ def test_interp_nan_idx(self):
202202
with pytest.raises(NotImplementedError, match=msg):
203203
df.interpolate(method="values")
204204

205-
@td.skip_if_no_scipy
206205
def test_interp_various(self):
206+
pytest.importorskip("scipy")
207207
df = DataFrame(
208208
{"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]}
209209
)
@@ -241,8 +241,8 @@ def test_interp_various(self):
241241
expected.loc[13, "A"] = 5
242242
tm.assert_frame_equal(result, expected, check_dtype=False)
243243

244-
@td.skip_if_no_scipy
245244
def test_interp_alt_scipy(self):
245+
pytest.importorskip("scipy")
246246
df = DataFrame(
247247
{"A": [1, 2, np.nan, 4, 5, np.nan, 7], "C": [1, 2, 3, 5, 8, 13, 21]}
248248
)

0 commit comments

Comments
 (0)