'Create copy of `pd.Index` with new values

Example: pd.DatetimeIndex

Let's say I have a pd.DatetimeIndex, for example

di = pd.date_range(start='2000-01-01', periods=3, freq='B')

# di
DatetimeIndex(['2000-01-03', '2000-01-04', '2000-01-05'], dtype='datetime64[ns]', freq='B')

I now want a new pd.DatetimeIndex just like di, but containing the values

v = [pd.Timestamp('2000-01-10'), pd.Timestamp('2000-01-11')]

I might try this

new_di = di.reindex(v)[0]

#new_di
DatetimeIndex(['2000-01-10', '2000-01-11'], dtype='datetime64[ns]', freq=None)

But notice freq=None, so this doesn't solve my problem.

In fact, I'm even allowed to do this

totally_new_di = di.reindex([1, 2, 3])[0]

# totally_new_di
Int64Index([1, 2, 3], dtype='int64')

Edit (thanks @mozway):

I could do

new_di = pd.DatetimeIndex(['2000-01-10', '2000-01-11'], freq=di.freq)

but this would require me to match di with the pd.DatetimeIndex constructor and its arguments, which I am trying to avoid.

Example pd.CategoricalIndex

Another example is this

ci = pd.CategoricalIndex(['A', 'B'], categories=['A', 'B', 'C'])

# ci
CategoricalIndex(['A', 'B'], categories=['A', 'B', 'C'], ordered=False, dtype='category')

There seems to be no instance method of ci which creates the object

CategoricalIndex(['B', 'C'], categories=['A', 'B', 'C'], ordered=False, dtype='category')

given the values ['B', 'C'].


My question: Given an instance of pd.Index, how can I create a new instance of the same type where all attributes are the same, except the values have been updated? I am trying to avoid calling constructors in a family of if isinstance-statements.



Solution 1:[1]

What about using pandas.DatetimeIndex directly?

new_di = pd.DatetimeIndex(['2000-01-10', '2000-01-11'], freq='B')

or, to match di programmatically:

new_di = pd.DatetimeIndex(['2000-01-10', '2000-01-11'], freq=di.freq)

output:

DatetimeIndex(['2000-01-10', '2000-01-11'], dtype='datetime64[ns]', freq='B')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway