diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1738c03e754b2..5274213f114e3 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -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) @@ -296,10 +292,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( @@ -314,6 +316,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 @@ -328,6 +333,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 @@ -338,6 +346,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) @@ -357,6 +368,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