Skip to content

Commit b85bb42

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

14 files changed

+96
-31
lines changed

pandas/core/construction.py

+44
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,50 @@ def create_series_with_explicit_dtype(
625625

626626
if is_empty_data(data) and dtype is None:
627627
dtype = dtype_if_empty
628+
return create_series_with_explicit_index_type(
629+
data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath
630+
)
631+
632+
633+
def create_series_with_explicit_index_type(
634+
data: Any = None,
635+
index: Optional[Union[ArrayLike, "Index"]] = None,
636+
dtype: Optional[Dtype] = None,
637+
name: Optional[str] = None,
638+
copy: bool = False,
639+
fastpath: bool = False,
640+
index_if_empty: Optional["Index"] = None,
641+
) -> "Series":
642+
"""
643+
Helper to pass an explicit index type when instantiating an Series where
644+
data is list-like and empty.
645+
646+
This silences a DeprecationWarning described in GitHub-16737.
647+
648+
Parameters
649+
----------
650+
data : Mirrored from Series.__init__
651+
index : Mirrored from Series.__init__
652+
dtype : Mirrored from Series.__init__
653+
name : Mirrored from Series.__init__
654+
copy : Mirrored from Series.__init__
655+
fastpath : Mirrored from Series.__init__
656+
index_if_empty : instance of (Index, RangeIndex)
657+
This index type will be passed explicitly when Series is initialised
658+
with `data` being list-like and empty.
659+
660+
Returns
661+
-------
662+
Series
663+
"""
664+
from pandas import Series
665+
from pandas import Index
666+
667+
if index_if_empty is None:
668+
index_if_empty = Index([])
669+
670+
if is_list_like(data) and len(data) == 0:
671+
index = index_if_empty
628672
return Series(
629673
data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath
630674
)

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
@@ -5,6 +5,7 @@
55
import numpy as np
66
import pytest
77

8+
from pandas.core.construction import create_series_with_explicit_index_type
89
from pandas.core.dtypes.common import is_scalar
910

1011
import pandas as pd
@@ -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

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import pandas as pd
77
from pandas import Index, MultiIndex, Series, date_range, isna
88
import pandas._testing as tm
9+
from pandas.core.construction import create_series_with_explicit_index_type
910

1011

1112
@pytest.fixture(
@@ -169,7 +170,7 @@ def test_interpolate_corners(self, kwargs):
169170
s = Series([np.nan, np.nan])
170171
tm.assert_series_equal(s.interpolate(**kwargs), s)
171172

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

175176
def test_interpolate_index_values(self):

pandas/tests/series/methods/test_quantile.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import numpy as np
22
import pytest
33

4+
from pandas.core.construction import create_series_with_explicit_index_type
45
from pandas.core.dtypes.common import is_integer
56

67
import pandas as pd
@@ -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,8 @@ 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(create_series_with_explicit_index_type([], dtype="M8[ns]").quantile(0.5))
168+
assert pd.isna(create_series_with_explicit_index_type([], dtype="m8[ns]").quantile(0.5))
168169

169170
def test_quantile_nat(self):
170171
res = Series([pd.NaT, pd.NaT]).quantile(0.5)
@@ -186,7 +187,7 @@ def test_quantile_sparse(self, values, dtype):
186187
def test_quantile_empty(self):
187188

188189
# floats
189-
s = Series([], dtype="float64")
190+
s = create_series_with_explicit_index_type([], dtype="float64")
190191

191192
res = s.quantile(0.5)
192193
assert np.isnan(res)
@@ -196,7 +197,7 @@ def test_quantile_empty(self):
196197
tm.assert_series_equal(res, exp)
197198

198199
# int
199-
s = Series([], dtype="int64")
200+
s = create_series_with_explicit_index_type([], dtype="int64")
200201

201202
res = s.quantile(0.5)
202203
assert np.isnan(res)
@@ -206,7 +207,7 @@ def test_quantile_empty(self):
206207
tm.assert_series_equal(res, exp)
207208

208209
# datetime
209-
s = Series([], dtype="datetime64[ns]")
210+
s = create_series_with_explicit_index_type([], dtype="datetime64[ns]")
210211

211212
res = s.quantile(0.5)
212213
assert res is pd.NaT

pandas/tests/series/test_apply.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import numpy as np
55
import pytest
66

7+
from pandas.core.construction import create_series_with_explicit_index_type
78
from pandas.core.dtypes.generic import ABCMultiIndex
89

910
import pandas as pd
@@ -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

+2-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,7 @@ 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+
[create_series_with_explicit_index_type(np.array([]), dtype="category"), Series(dtype="float64")]
9899
).dtype
99100
== "float64"
100101
)

pandas/tests/series/test_constructors.py

+14-4
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from pandas._libs import lib
99
from pandas._libs.tslib import iNaT
1010

11+
from pandas.core.construction import create_series_with_explicit_index_type
1112
from pandas.core.dtypes.common import is_categorical_dtype, is_datetime64tz_dtype
1213
from pandas.core.dtypes.dtypes import CategoricalDtype
1314

@@ -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
@@ -7,6 +7,7 @@
77
import pytest
88

99
from pandas._libs.tslibs import iNaT
10+
from pandas.core.construction import create_series_with_explicit_index_type
1011

1112
from pandas.core.dtypes.dtypes import CategoricalDtype
1213

@@ -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

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +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_dtype
6+
from pandas.core.construction import create_series_with_explicit_dtype, create_series_with_explicit_index_type
77

88

99
def test_nunique():
@@ -15,7 +15,7 @@ def test_nunique():
1515
assert result == 11
1616

1717
# GH 18051
18-
s = Series(Categorical([]))
18+
s = create_series_with_explicit_index_type(Categorical([]))
1919
assert s.nunique() == 0
2020
s = Series(Categorical([np.nan]))
2121
assert s.nunique() == 0
@@ -46,7 +46,7 @@ def test_unique():
4646
tm.assert_numpy_array_equal(result, expected)
4747

4848
# GH 18051
49-
s = Series(Categorical([]))
49+
s = create_series_with_explicit_index_type(Categorical([]))
5050
tm.assert_categorical_equal(s.unique(), Categorical([]))
5151
s = Series(Categorical([np.nan]))
5252
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)