Skip to content

PERF: DataFrame(dict) returns RangeIndex columns when possible #57943

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 9 commits into from
Mar 25, 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 @@ -264,6 +264,7 @@ Removal of prior version deprecations/changes
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`)
- :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
13 changes: 2 additions & 11 deletions pandas/core/indexes/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import textwrap
from typing import (
TYPE_CHECKING,
cast,
Expand All @@ -23,6 +22,7 @@
ensure_index,
ensure_index_from_sequences,
get_unanimous_names,
maybe_sequence_to_range,
)
from pandas.core.indexes.category import CategoricalIndex
from pandas.core.indexes.datetimes import DatetimeIndex
Expand All @@ -34,16 +34,6 @@

if TYPE_CHECKING:
from pandas._typing import Axis
_sort_msg = textwrap.dedent(
"""\
Sorting because non-concatenation axis is not aligned. A future version
of pandas will change to not sort by default.

To accept the future behavior, pass 'sort=False'.

To retain the current behavior and silence the warning, pass 'sort=True'.
"""
)


__all__ = [
Expand All @@ -66,6 +56,7 @@
"all_indexes_same",
"default_index",
"safe_sort_index",
"maybe_sequence_to_range",
]


Expand Down
13 changes: 6 additions & 7 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7169,18 +7169,17 @@ def maybe_sequence_to_range(sequence) -> Any | range:
-------
Any : input or range
"""
if isinstance(sequence, (ABCSeries, Index, range)):
if isinstance(sequence, (ABCSeries, Index, range, ExtensionArray)):
return sequence
np_sequence = np.asarray(sequence)
if np_sequence.dtype.kind != "i" or len(np_sequence) == 1:
elif len(sequence) == 1 or lib.infer_dtype(sequence, skipna=False) != "integer":
return sequence
elif len(np_sequence) == 0:
elif len(sequence) == 0:
return range(0)
diff = np_sequence[1] - np_sequence[0]
diff = sequence[1] - sequence[0]
if diff == 0:
return sequence
elif len(np_sequence) == 2 or lib.is_sequence_range(np_sequence, diff):
return range(np_sequence[0], np_sequence[-1] + diff, diff)
elif len(sequence) == 2 or lib.is_sequence_range(np.asarray(sequence), diff):
return range(sequence[0], sequence[-1] + diff, diff)
else:
return sequence

Expand Down
3 changes: 2 additions & 1 deletion pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
default_index,
ensure_index,
get_objs_combined_axis,
maybe_sequence_to_range,
union_indexes,
)
from pandas.core.internals.blocks import (
Expand Down Expand Up @@ -403,7 +404,7 @@ def dict_to_mgr(
arrays[i] = arr

else:
keys = list(data.keys())
keys = maybe_sequence_to_range(list(data.keys()))
columns = Index(keys) if keys else default_index(0)
arrays = [com.maybe_iterable_to_list(data[k]) for k in keys]

Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2709,6 +2709,11 @@ def test_inference_on_pandas_objects(self):
result = DataFrame({"a": ser})
assert result.dtypes.iloc[0] == np.object_

def test_dict_keys_returns_rangeindex(self):
result = DataFrame({0: [1], 1: [2]}).columns
expected = RangeIndex(2)
tm.assert_index_equal(result, expected, exact=True)


class TestDataFrameConstructorIndexInference:
def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):
Expand Down
2 changes: 2 additions & 0 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1738,6 +1738,7 @@ def test_daily(self):
mask = ts.index.year == y
expected[y] = Series(ts.values[mask], index=doy[mask])
expected = DataFrame(expected, dtype=float).T
expected.index = expected.index.astype(np.int32)
tm.assert_frame_equal(result, expected)

def test_monthly(self):
Expand All @@ -1753,6 +1754,7 @@ def test_monthly(self):
mask = ts.index.year == y
expected[y] = Series(ts.values[mask], index=month[mask])
expected = DataFrame(expected, dtype=float).T
expected.index = expected.index.astype(np.int32)
tm.assert_frame_equal(result, expected)

def test_pivot_table_with_iterator_values(self, data):
Expand Down