Skip to content

Commit 70708b3

Browse files
silenced warnings in pandas/tests/series
1 parent b924865 commit 70708b3

14 files changed

+106
-33
lines changed

pandas/core/construction.py

+43-2
Original file line numberDiff line numberDiff line change
@@ -621,10 +621,51 @@ def create_series_with_explicit_dtype(
621621
-------
622622
Series
623623
"""
624-
from pandas.core.series import Series
625-
626624
if is_empty_data(data) and dtype is None:
627625
dtype = dtype_if_empty
626+
return create_series_with_explicit_index_type(
627+
data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath
628+
)
629+
630+
631+
def create_series_with_explicit_index_type(
632+
data: Any = None,
633+
index: Optional[Union[ArrayLike, "Index"]] = None,
634+
dtype: Optional[Dtype] = None,
635+
name: Optional[str] = None,
636+
copy: bool = False,
637+
fastpath: bool = False,
638+
index_if_empty: Optional["Index"] = None,
639+
) -> "Series":
640+
"""
641+
Helper to pass an explicit index type when instantiating an Series where
642+
data is list-like and empty.
643+
644+
This silences a DeprecationWarning described in GitHub-16737.
645+
646+
Parameters
647+
----------
648+
data : Mirrored from Series.__init__
649+
index : Mirrored from Series.__init__
650+
dtype : Mirrored from Series.__init__
651+
name : Mirrored from Series.__init__
652+
copy : Mirrored from Series.__init__
653+
fastpath : Mirrored from Series.__init__
654+
index_if_empty : instance of (Index, RangeIndex)
655+
This index type will be passed explicitly when Series is initialised
656+
with `data` being list-like and empty.
657+
658+
Returns
659+
-------
660+
Series
661+
"""
662+
from pandas import Index, Series # noqa: F811
663+
664+
if index_if_empty is None:
665+
index_if_empty = Index([])
666+
667+
if is_list_like(data) and len(data) == 0:
668+
index = index_if_empty
628669
return Series(
629670
data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath
630671
)

pandas/tests/series/indexing/test_boolean.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from pandas import Index, Series
55
import pandas._testing as tm
6+
from pandas.core.construction import create_series_with_explicit_index_type
67
from pandas.core.indexing import IndexingError
78

89
from pandas.tseries.offsets import BDay
@@ -20,7 +21,7 @@ def test_getitem_boolean(string_series):
2021

2122

2223
def test_getitem_boolean_empty():
23-
s = Series([], dtype=np.int64)
24+
s = create_series_with_explicit_index_type([], dtype=np.int64)
2425
s.index.name = "index_name"
2526
s = s[s.isna()]
2627
assert s.index.name == "index_name"
@@ -30,7 +31,7 @@ def test_getitem_boolean_empty():
3031
# indexing with empty series
3132
s = Series(["A", "B"])
3233
expected = Series(dtype=object, index=Index([], dtype="int64"))
33-
result = s[Series([], dtype=object)]
34+
result = s[create_series_with_explicit_index_type([], dtype=object)]
3435
tm.assert_series_equal(result, expected)
3536

3637
# invalid because of the boolean indexer
@@ -40,7 +41,7 @@ def test_getitem_boolean_empty():
4041
r"the boolean Series and of the indexed object do not match"
4142
)
4243
with pytest.raises(IndexingError, match=msg):
43-
s[Series([], dtype=bool)]
44+
s[create_series_with_explicit_index_type([], dtype=bool)]
4445

4546
with pytest.raises(IndexingError, match=msg):
4647
s[Series([True], dtype=bool)]

pandas/tests/series/indexing/test_indexing.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import pandas as pd
1111
from pandas import Categorical, DataFrame, MultiIndex, Series, Timedelta, Timestamp
1212
import pandas._testing as tm
13+
from pandas.core.construction import create_series_with_explicit_index_type
1314

1415
from pandas.tseries.offsets import BDay
1516

@@ -160,7 +161,7 @@ def test_getitem_out_of_bounds(datetime_series):
160161

161162
# GH #917
162163
# With a RangeIndex, an int key gives a KeyError
163-
s = Series([], dtype=object)
164+
s = Series([], index=pd.RangeIndex(0), dtype=object)
164165
with pytest.raises(KeyError, match="-1"):
165166
s[-1]
166167

@@ -617,7 +618,7 @@ def test_setitem_na():
617618

618619
def test_timedelta_assignment():
619620
# GH 8209
620-
s = Series([], dtype=object)
621+
s = create_series_with_explicit_index_type([], dtype=object)
621622
s.loc["B"] = timedelta(1)
622623
tm.assert_series_equal(s, Series(Timedelta("1 days"), index=["B"]))
623624

pandas/tests/series/methods/test_drop_duplicates.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from pandas import Categorical, Series
55
import pandas._testing as tm
6+
from pandas.core.construction import create_series_with_explicit_index_type
67

78

89
@pytest.mark.parametrize(
@@ -46,8 +47,8 @@ def test_drop_duplicates_bool(keep, expected):
4647

4748
@pytest.mark.parametrize("values", [[], list(range(5))])
4849
def test_drop_duplicates_no_duplicates(any_numpy_dtype, keep, values):
49-
tc = Series(values, dtype=np.dtype(any_numpy_dtype))
50-
expected = Series([False] * len(tc), dtype="bool")
50+
tc = create_series_with_explicit_index_type(values, dtype=np.dtype(any_numpy_dtype))
51+
expected = create_series_with_explicit_index_type([False] * len(tc), dtype="bool")
5152

5253
if tc.dtype == "bool":
5354
# 0 -> False and 1-> True

pandas/tests/series/methods/test_interpolate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ def test_interpolate_corners(self, kwargs):
169169
s = Series([np.nan, np.nan])
170170
tm.assert_series_equal(s.interpolate(**kwargs), s)
171171

172-
s = Series([], dtype=object).interpolate()
172+
s = Series([], dtype=object, index=pd.RangeIndex(0)).interpolate()
173173
tm.assert_series_equal(s.interpolate(**kwargs), s)
174174

175175
def test_interpolate_index_values(self):

pandas/tests/series/methods/test_quantile.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import pandas as pd
77
from pandas import Index, Series
88
import pandas._testing as tm
9+
from pandas.core.construction import create_series_with_explicit_index_type
910
from pandas.core.indexes.datetimes import Timestamp
1011

1112

@@ -104,7 +105,7 @@ def test_quantile_nan(self):
104105
assert result == expected
105106

106107
# all nan/empty
107-
s1 = Series([], dtype=object)
108+
s1 = create_series_with_explicit_index_type([], dtype=object)
108109
cases = [s1, Series([np.nan, np.nan])]
109110

110111
for s in cases:
@@ -163,8 +164,12 @@ def test_quantile_box(self, case):
163164

164165
def test_datetime_timedelta_quantiles(self):
165166
# covers #9694
166-
assert pd.isna(Series([], dtype="M8[ns]").quantile(0.5))
167-
assert pd.isna(Series([], dtype="m8[ns]").quantile(0.5))
167+
assert pd.isna(
168+
create_series_with_explicit_index_type([], dtype="M8[ns]").quantile(0.5)
169+
)
170+
assert pd.isna(
171+
create_series_with_explicit_index_type([], dtype="m8[ns]").quantile(0.5)
172+
)
168173

169174
def test_quantile_nat(self):
170175
res = Series([pd.NaT, pd.NaT]).quantile(0.5)
@@ -186,7 +191,7 @@ def test_quantile_sparse(self, values, dtype):
186191
def test_quantile_empty(self):
187192

188193
# floats
189-
s = Series([], dtype="float64")
194+
s = create_series_with_explicit_index_type([], dtype="float64")
190195

191196
res = s.quantile(0.5)
192197
assert np.isnan(res)
@@ -196,7 +201,7 @@ def test_quantile_empty(self):
196201
tm.assert_series_equal(res, exp)
197202

198203
# int
199-
s = Series([], dtype="int64")
204+
s = create_series_with_explicit_index_type([], dtype="int64")
200205

201206
res = s.quantile(0.5)
202207
assert np.isnan(res)
@@ -206,7 +211,7 @@ def test_quantile_empty(self):
206211
tm.assert_series_equal(res, exp)
207212

208213
# datetime
209-
s = Series([], dtype="datetime64[ns]")
214+
s = create_series_with_explicit_index_type([], dtype="datetime64[ns]")
210215

211216
res = s.quantile(0.5)
212217
assert res is pd.NaT

pandas/tests/series/test_apply.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from pandas import DataFrame, Index, Series, isna
1111
import pandas._testing as tm
1212
from pandas.core.base import SpecificationError
13+
from pandas.core.construction import create_series_with_explicit_index_type
1314

1415

1516
class TestSeriesApply:
@@ -519,7 +520,7 @@ def test_map_empty(self, indices):
519520
if isinstance(indices, ABCMultiIndex):
520521
pytest.skip("Initializing a Series from a MultiIndex is not supported")
521522

522-
s = Series(indices)
523+
s = create_series_with_explicit_index_type(indices)
523524
result = s.map({})
524525

525526
expected = pd.Series(np.nan, index=s.index)

pandas/tests/series/test_combine_concat.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import pandas as pd
55
from pandas import Series
6+
from pandas.core.construction import create_series_with_explicit_index_type
67

78

89
class TestSeriesConcat:
@@ -94,7 +95,12 @@ def test_concat_empty_series_dtype_category_with_array(self):
9495
# GH 18515
9596
assert (
9697
pd.concat(
97-
[Series(np.array([]), dtype="category"), Series(dtype="float64")]
98+
[
99+
create_series_with_explicit_index_type(
100+
np.array([]), dtype="category"
101+
),
102+
Series(dtype="float64"),
103+
]
98104
).dtype
99105
== "float64"
100106
)

pandas/tests/series/test_constructors.py

+14-4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
)
2929
import pandas._testing as tm
3030
from pandas.core.arrays import IntervalArray, period_array
31+
from pandas.core.construction import create_series_with_explicit_index_type
3132

3233

3334
class TestSeriesConstructors:
@@ -134,12 +135,21 @@ def test_constructor_empty(self, input_class):
134135

135136
# With explicit dtype:
136137
empty = Series(dtype="float64")
137-
empty2 = Series(input_class(), dtype="float64")
138+
139+
if input_class is list:
140+
with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False):
141+
empty2 = Series(input_class(), dtype="float64")
142+
else:
143+
empty2 = Series(input_class(), dtype="float64")
138144
tm.assert_series_equal(empty, empty2, check_index_type=False)
139145

140146
# GH 18515 : with dtype=category:
141147
empty = Series(dtype="category")
142-
empty2 = Series(input_class(), dtype="category")
148+
if input_class is list:
149+
with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False):
150+
empty2 = Series(input_class(), dtype="category")
151+
else:
152+
empty2 = Series(input_class(), dtype="category")
143153
tm.assert_series_equal(empty, empty2, check_index_type=False)
144154

145155
if input_class is not list:
@@ -1391,7 +1401,7 @@ def test_constructor_generic_timestamp_no_frequency(self, dtype):
13911401
msg = "dtype has no unit. Please pass in"
13921402

13931403
with pytest.raises(ValueError, match=msg):
1394-
Series([], dtype=dtype)
1404+
create_series_with_explicit_index_type([], dtype=dtype)
13951405

13961406
@pytest.mark.parametrize(
13971407
"dtype,msg",
@@ -1404,7 +1414,7 @@ def test_constructor_generic_timestamp_bad_frequency(self, dtype, msg):
14041414
# see gh-15524, gh-15987
14051415

14061416
with pytest.raises(TypeError, match=msg):
1407-
Series([], dtype=dtype)
1417+
create_series_with_explicit_index_type([], dtype=dtype)
14081418

14091419
@pytest.mark.parametrize("dtype", [None, "uint8", "category"])
14101420
def test_constructor_range_dtype(self, dtype):

pandas/tests/series/test_dtypes.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
date_range,
2222
)
2323
import pandas._testing as tm
24+
from pandas.core.construction import create_series_with_explicit_index_type
2425

2526

2627
class TestSeriesDtypes:
@@ -404,9 +405,9 @@ def test_astype_empty_constructor_equality(self, dtype):
404405
"M",
405406
"m", # Generic timestamps raise a ValueError. Already tested.
406407
):
407-
init_empty = Series([], dtype=dtype)
408+
init_empty = create_series_with_explicit_index_type([], dtype=dtype)
408409
with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False):
409-
as_type_empty = Series([]).astype(dtype)
410+
as_type_empty = create_series_with_explicit_index_type([]).astype(dtype)
410411
tm.assert_series_equal(init_empty, as_type_empty)
411412

412413
def test_arg_for_errors_in_astype(self):

pandas/tests/series/test_duplicates.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33

44
from pandas import Categorical, Series
55
import pandas._testing as tm
6-
from pandas.core.construction import create_series_with_explicit_dtype
6+
from pandas.core.construction import (
7+
create_series_with_explicit_dtype,
8+
create_series_with_explicit_index_type,
9+
)
710

811

912
def test_nunique():
@@ -15,7 +18,7 @@ def test_nunique():
1518
assert result == 11
1619

1720
# GH 18051
18-
s = Series(Categorical([]))
21+
s = create_series_with_explicit_index_type(Categorical([]))
1922
assert s.nunique() == 0
2023
s = Series(Categorical([np.nan]))
2124
assert s.nunique() == 0
@@ -46,7 +49,7 @@ def test_unique():
4649
tm.assert_numpy_array_equal(result, expected)
4750

4851
# GH 18051
49-
s = Series(Categorical([]))
52+
s = create_series_with_explicit_index_type(Categorical([]))
5053
tm.assert_categorical_equal(s.unique(), Categorical([]))
5154
s = Series(Categorical([np.nan]))
5255
tm.assert_categorical_equal(s.unique(), Categorical([np.nan]))

pandas/tests/series/test_missing.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
isna,
2121
)
2222
import pandas._testing as tm
23+
from pandas.core.construction import create_series_with_explicit_index_type
2324

2425

2526
class TestSeriesMissingData:
@@ -562,7 +563,7 @@ def test_fillna(self, datetime_series):
562563
tm.assert_series_equal(result, expected)
563564
result = s1.fillna({})
564565
tm.assert_series_equal(result, s1)
565-
result = s1.fillna(Series((), dtype=object))
566+
result = s1.fillna(create_series_with_explicit_index_type((), dtype=object))
566567
tm.assert_series_equal(result, s1)
567568
result = s2.fillna(s1)
568569
tm.assert_series_equal(result, s2)
@@ -677,7 +678,7 @@ def test_timedelta64_nan(self):
677678
# tm.assert_series_equal(selector, expected)
678679

679680
def test_dropna_empty(self):
680-
s = Series([], dtype=object)
681+
s = create_series_with_explicit_index_type([], dtype=object)
681682

682683
assert len(s.dropna()) == 0
683684
s.dropna(inplace=True)

pandas/tests/series/test_operators.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from pandas import DataFrame, Index, Series, bdate_range
99
import pandas._testing as tm
1010
from pandas.core import ops
11+
from pandas.core.construction import create_series_with_explicit_index_type
1112

1213

1314
class TestSeriesLogicalOps:
@@ -32,7 +33,7 @@ def test_logical_operators_bool_dtype_with_empty(self):
3233

3334
s_tft = Series([True, False, True], index=index)
3435
s_fff = Series([False, False, False], index=index)
35-
s_empty = Series([], dtype=object)
36+
s_empty = create_series_with_explicit_index_type([], dtype=object)
3637

3738
res = s_tft & s_empty
3839
expected = s_fff
@@ -407,7 +408,7 @@ def test_logical_ops_label_based(self):
407408
# filling
408409

409410
# vs empty
410-
empty = Series([], dtype=object)
411+
empty = create_series_with_explicit_index_type([], dtype=object)
411412

412413
result = a & empty.copy()
413414
expected = Series([False, False, False], list("bca"))

0 commit comments

Comments
 (0)