Skip to content

PERF: postpone imports in Index constructor #31423

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
Changes from 1 commit
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
20 changes: 16 additions & 4 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,10 +277,6 @@ def __new__(
) -> "Index":

from pandas.core.indexes.range import RangeIndex
from pandas import PeriodIndex, DatetimeIndex, TimedeltaIndex
from pandas.core.indexes.numeric import Float64Index, Int64Index, UInt64Index
from pandas.core.indexes.interval import IntervalIndex
from pandas.core.indexes.category import CategoricalIndex

name = maybe_extract_name(name, data, cls)

Expand All @@ -296,10 +292,14 @@ def __new__(

# categorical
elif is_categorical_dtype(data) or is_categorical_dtype(dtype):
from pandas.core.indexes.category import CategoricalIndex

return CategoricalIndex(data, dtype=dtype, copy=copy, name=name, **kwargs)

# interval
elif is_interval_dtype(data) or is_interval_dtype(dtype):
from pandas.core.indexes.interval import IntervalIndex

closed = kwargs.pop("closed", None)
if is_dtype_equal(_o_dtype, dtype):
return IntervalIndex(
Expand All @@ -314,6 +314,8 @@ def __new__(
or is_datetime64_any_dtype(dtype)
or "tz" in kwargs
):
from pandas import DatetimeIndex

if is_dtype_equal(_o_dtype, dtype):
# GH#23524 passing `dtype=object` to DatetimeIndex is invalid,
# will raise in the where `data` is already tz-aware. So
Expand All @@ -328,6 +330,8 @@ def __new__(
return DatetimeIndex(data, copy=copy, name=name, dtype=dtype, **kwargs)

elif is_timedelta64_dtype(data) or is_timedelta64_dtype(dtype):
from pandas import TimedeltaIndex

if is_dtype_equal(_o_dtype, dtype):
# Note we can pass copy=False because the .astype below
# will always make a copy
Expand All @@ -338,6 +342,8 @@ def __new__(
return TimedeltaIndex(data, copy=copy, name=name, dtype=dtype, **kwargs)

elif is_period_dtype(data) or is_period_dtype(dtype):
from pandas import PeriodIndex

if is_dtype_equal(_o_dtype, dtype):
return PeriodIndex(data, copy=False, name=name, **kwargs).astype(object)
return PeriodIndex(data, dtype=dtype, copy=copy, name=name, **kwargs)
Expand All @@ -357,6 +363,12 @@ def __new__(

# index-like
elif isinstance(data, (np.ndarray, Index, ABCSeries)):
from pandas.core.indexes.numeric import (
Float64Index,
Int64Index,
UInt64Index,
)

if dtype is not None:
# we need to avoid having numpy coerce
# things that look like ints/floats to ints unless
Expand Down