diff --git a/pandas/core/series.py b/pandas/core/series.py index 7abd95c68ea2b..1ef6f2d7eee22 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -41,7 +41,11 @@ maybe_cast_to_datetime, maybe_castable, construct_1d_arraylike_from_scalar, construct_1d_object_array_from_listlike) -from pandas.core.dtypes.missing import isna, notna, remove_na_arraylike +from pandas.core.dtypes.missing import ( + isna, + notna, + remove_na_arraylike, + na_value_for_dtype) from pandas.core.index import (Index, MultiIndex, InvalidIndexError, Float64Index, _ensure_index) @@ -300,6 +304,11 @@ def _init_dict(self, data, index=None, dtype=None): if data: keys, values = zip(*compat.iteritems(data)) values = list(values) + elif index is not None: + # fastpath for Series(data=None). Just use broadcasting a scalar + # instead of reindexing. + values = na_value_for_dtype(dtype) + keys = index else: keys, values = [], [] @@ -307,9 +316,11 @@ def _init_dict(self, data, index=None, dtype=None): s = Series(values, index=keys, dtype=dtype) # Now we just make sure the order is respected, if any - if index is not None: + if data and index is not None: s = s.reindex(index, copy=False) - elif not PY36 and not isinstance(data, OrderedDict): + elif not PY36 and not isinstance(data, OrderedDict) and data: + # Need the `and data` to avoid sorting Series(None, index=[...]) + # since that isn't really dict-like try: s = s.sort_index() except TypeError: diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 82b5b1c10fa2d..7e59325c32ddc 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -122,6 +122,21 @@ def test_constructor_nan(self, input_arg): assert_series_equal(empty, empty2, check_index_type=False) + @pytest.mark.parametrize('dtype', [ + 'f8', 'i8', 'M8[ns]', 'm8[ns]', 'category', 'object', + 'datetime64[ns, UTC]', + ]) + @pytest.mark.parametrize('index', [None, pd.Index([])]) + def test_constructor_dtype_only(self, dtype, index): + # GH-20865 + result = pd.Series(dtype=dtype, index=index) + assert result.dtype == dtype + assert len(result) == 0 + + def test_constructor_no_data_index_order(self): + result = pd.Series(index=['b', 'a', 'c']) + assert result.index.tolist() == ['b', 'a', 'c'] + def test_constructor_series(self): index1 = ['d', 'b', 'a', 'c'] index2 = sorted(index1)