Skip to content

PERF: Series(dict) returns RangeIndex when possible #58118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ Performance improvements
~~~~~~~~~~~~~~~~~~~~~~~~
- :attr:`Categorical.categories` returns a :class:`RangeIndex` columns instead of an :class:`Index` if the constructed ``values`` was a ``range``. (:issue:`57787`)
- :class:`DataFrame` returns a :class:`RangeIndex` columns when possible when ``data`` is a ``dict`` (:issue:`57943`)
- :class:`Series` returns a :class:`RangeIndex` index when possible when ``data`` is a ``dict`` (:issue:`58118`)
- :func:`concat` returns a :class:`RangeIndex` level in the :class:`MultiIndex` result when ``keys`` is a ``range`` or :class:`RangeIndex` (:issue:`57542`)
- :meth:`RangeIndex.append` returns a :class:`RangeIndex` instead of a :class:`Index` when appending values that could continue the :class:`RangeIndex` (:issue:`57467`)
- :meth:`Series.str.extract` returns a :class:`RangeIndex` columns instead of an :class:`Index` column when possible (:issue:`57542`)
Expand Down
5 changes: 4 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7144,7 +7144,10 @@ def maybe_sequence_to_range(sequence) -> Any | range:
return sequence
if len(sequence) == 0:
return range(0)
np_sequence = np.asarray(sequence, dtype=np.int64)
try:
np_sequence = np.asarray(sequence, dtype=np.int64)
except OverflowError:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the OverflowError required in this case? Have we added that elsewhere to support the RangeIndex return?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line will fail if the sequence contains an int over the max int64 value e.g. test_loc_uint64.

This is the only pathway that can convert an arbitrary sequence to a RangeIndex return

return sequence
diff = np_sequence[1] - np_sequence[0]
if diff == 0:
return sequence
Expand Down
5 changes: 2 additions & 3 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
PeriodIndex,
default_index,
ensure_index,
maybe_sequence_to_range,
)
import pandas.core.indexes.base as ibase
from pandas.core.indexes.multi import maybe_droplevels
Expand Down Expand Up @@ -538,16 +539,14 @@ def _init_dict(
_data : BlockManager for the new Series
index : index for the new Series
"""
keys: Index | tuple

# Looking for NaN in dict doesn't work ({np.nan : 1}[float('nan')]
# raises KeyError), so we iterate the entire dict, and align
if data:
# GH:34717, issue was using zip to extract key and values from data.
# using generators in effects the performance.
# Below is the new way of extracting the keys and values

keys = tuple(data.keys())
keys = maybe_sequence_to_range(tuple(data.keys()))
values = list(data.values()) # Generating list of values- faster way
elif index is not None:
# fastpath for Series(data=None). Just use broadcasting a scalar
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2251,3 +2251,9 @@ def test_series_with_complex_nan(input_list):
result = Series(ser.array)
assert ser.dtype == "complex128"
tm.assert_series_equal(ser, result)


def test_dict_keys_rangeindex():
result = Series({0: 1, 1: 2})
expected = Series([1, 2], index=RangeIndex(2))
tm.assert_series_equal(result, expected, check_index_type=True)