11""" define the IntervalIndex """
22
33import numpy as np
4- import pandas as pd
54
65from pandas .types .missing import notnull , isnull
76from pandas .types .common import (_ensure_platform_int ,
87 is_datetime_or_timedelta_dtype ,
98 is_integer_dtype ,
9+ is_object_dtype ,
10+ is_categorical_dtype ,
1011 is_float_dtype ,
1112 is_interval_dtype )
1213from pandas .indexes .base import (Index , _ensure_index ,
1314 default_pprint , _index_shared_docs )
15+ from pandas .tslib import Timestamp , Timedelta
1416from pandas .indexes .multi import MultiIndex
1517from pandas .compat .numpy import function as nv
1618from pandas .core import common as com
2426
2527def _get_next_label (label ):
2628 dtype = getattr (label , 'dtype' , type (label ))
27- if isinstance (label , (pd . Timestamp , pd . Timedelta )):
29+ if isinstance (label , (Timestamp , Timedelta )):
2830 dtype = 'datetime64'
2931 if is_datetime_or_timedelta_dtype (dtype ):
3032 return label + np .timedelta64 (1 , 'ns' )
@@ -39,7 +41,7 @@ def _get_next_label(label):
3941
4042def _get_prev_label (label ):
4143 dtype = getattr (label , 'dtype' , type (label ))
42- if isinstance (label , (pd . Timestamp , pd . Timedelta )):
44+ if isinstance (label , (Timestamp , Timedelta )):
4345 dtype = 'datetime64'
4446 if is_datetime_or_timedelta_dtype (dtype ):
4547 return label - np .timedelta64 (1 , 'ns' )
@@ -340,6 +342,19 @@ def copy(self, deep=False, name=None):
340342 name = name if name is not None else self .name
341343 return self ._shallow_copy (left , right , name = name )
342344
345+ @Appender (_index_shared_docs ['astype' ])
346+ def astype (self , dtype , copy = True ):
347+ if is_interval_dtype (dtype ):
348+ if copy :
349+ self = self .copy ()
350+ return self
351+ elif is_object_dtype (dtype ):
352+ return Index (self .values , dtype = object )
353+ elif is_categorical_dtype (dtype ):
354+ from pandas import Categorical
355+ return Categorical (self , ordered = True )
356+ raise ValueError ('Cannot cast IntervalIndex to dtype %s' % dtype )
357+
343358 @cache_readonly
344359 def dtype (self ):
345360 return np .dtype ('O' )
@@ -513,6 +528,26 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None):
513528 else :
514529 return self ._tree .get_indexer (target )
515530
531+ def sort_values (self , return_indexer = False , ascending = True ):
532+ """
533+ Return sorted copy of Index
534+ """
535+ mask = self ._mask
536+
537+ # nans are sorted to the highest values
538+ _as = self .argsort ()
539+ _as [mask ] = - 1
540+
541+ if not ascending :
542+ _as = _as [::- 1 ]
543+
544+ sorted_index = self .take (_as )
545+
546+ if return_indexer :
547+ return sorted_index , _as
548+ else :
549+ return sorted_index
550+
516551 def where (self , cond , other = None ):
517552 raise NotImplementedError
518553
0 commit comments