簡體   English   中英

使用新值創建 `pd.Index` 的副本

[英]Create copy of `pd.Index` with new values

示例: pd.DatetimeIndex

例如,假設我有一個pd.DatetimeIndex

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')

我現在想要一個新的pd.DatetimeIndex就像di一樣,但包含值

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

我可以試試這個

new_di = di.reindex(v)[0]

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

但是請注意freq=None ,所以這不能解決我的問題。

事實上,我什至可以這樣做

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

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

編輯(感謝@mozway)

我可以

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

但這需要我將dipd.DatetimeIndex構造函數及其 arguments 匹配,我試圖避免這種情況。

示例pd.CategoricalIndex

另一個例子是這個

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

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

似乎沒有創建 object 的ci實例方法

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

給定值['B', 'C']


我的問題:給定一個pd.Index實例,我如何創建一個所有屬性都相同但值已更新的相同類型的新實例? 我試圖避免在一系列if isinstance語句中調用構造函數。

直接使用pandas.DatetimeIndex怎么樣?

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

或者,以編程方式匹配di

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM