diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 512e52add9807..4fcddb5cade4a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -278,10 +278,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) @@ -297,10 +293,16 @@ def __new__( # categorical elif is_categorical_dtype(data) or is_categorical_dtype(dtype): + # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 + 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): + # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 + from pandas.core.indexes.interval import IntervalIndex + closed = kwargs.pop("closed", None) if is_dtype_equal(_o_dtype, dtype): return IntervalIndex( @@ -315,6 +317,9 @@ def __new__( or is_datetime64_any_dtype(dtype) or "tz" in kwargs ): + # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 + 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 @@ -329,6 +334,9 @@ def __new__( return DatetimeIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) elif is_timedelta64_dtype(data) or is_timedelta64_dtype(dtype): + # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 + 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 @@ -339,6 +347,9 @@ def __new__( return TimedeltaIndex(data, copy=copy, name=name, dtype=dtype, **kwargs) elif is_period_dtype(data) or is_period_dtype(dtype): + # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 + 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) @@ -358,6 +369,13 @@ def __new__( # index-like elif isinstance(data, (np.ndarray, Index, ABCSeries)): + # Delay import for perf. https://github.com/pandas-dev/pandas/pull/31423 + 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