Skip to content

Commit

Permalink
PERF: Fixed regression in Series(index=idx) constructor (pandas-dev#2…
Browse files Browse the repository at this point in the history
  • Loading branch information
TomAugspurger authored Apr 30, 2018
1 parent d274d0b commit c8fcfcb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
17 changes: 14 additions & 3 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -300,16 +304,23 @@ 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 = [], []

# Input is now list-like, so rely on "standard" construction:
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:
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit c8fcfcb

Please sign in to comment.