16
16
import pandas .core .common as com
17
17
from pandas .core .common import _values_from_object
18
18
from pandas .core .config import get_option
19
- import warnings
20
19
21
20
22
21
__all__ = ['Index' ]
@@ -27,6 +26,7 @@ def _indexOp(opname):
27
26
Wrapper function for index comparison operations, to avoid
28
27
code duplication.
29
28
"""
29
+
30
30
def wrapper (self , other ):
31
31
func = getattr (self .view (np .ndarray ), opname )
32
32
result = func (other )
@@ -54,6 +54,7 @@ def _shouldbe_timestamp(obj):
54
54
55
55
56
56
class Index (FrozenNDArray ):
57
+
57
58
"""
58
59
Immutable ndarray implementing an ordered, sliceable set. The basic object
59
60
storing axis labels for all pandas objects
@@ -160,7 +161,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False,
160
161
161
162
elif np .isscalar (data ):
162
163
raise TypeError ('Index(...) must be called with a collection '
163
- 'of some kind, %s was passed' % repr (data ))
164
+ 'of some kind, %s was passed' % repr (data ))
164
165
else :
165
166
# other iterable of some kind
166
167
subarr = com ._asarray_tuplesafe (data , dtype = object )
@@ -171,7 +172,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False,
171
172
return Int64Index (subarr .astype ('i8' ), copy = copy , name = name )
172
173
elif inferred != 'string' :
173
174
if (inferred .startswith ('datetime' ) or
174
- tslib .is_timestamp_array (subarr )):
175
+ tslib .is_timestamp_array (subarr )):
175
176
from pandas .tseries .index import DatetimeIndex
176
177
return DatetimeIndex (data , copy = copy , name = name , ** kwargs )
177
178
elif inferred == 'period' :
@@ -234,7 +235,7 @@ def to_series(self):
234
235
useful with map for returning an indexer based on an index
235
236
"""
236
237
import pandas as pd
237
- return pd .Series (self .values ,index = self ,name = self .name )
238
+ return pd .Series (self .values , index = self , name = self .name )
238
239
239
240
def astype (self , dtype ):
240
241
return Index (self .values .astype (dtype ), name = self .name ,
@@ -279,7 +280,7 @@ def _get_names(self):
279
280
def _set_names (self , values ):
280
281
if len (values ) != 1 :
281
282
raise ValueError ('Length of new names must be 1, got %d'
282
- % len (values ))
283
+ % len (values ))
283
284
self .name = values [0 ]
284
285
285
286
names = property (fset = _set_names , fget = _get_names )
@@ -335,11 +336,11 @@ def _has_complex_internals(self):
335
336
def summary (self , name = None ):
336
337
if len (self ) > 0 :
337
338
head = self [0 ]
338
- if hasattr (head ,'format' ) and \
339
+ if hasattr (head , 'format' ) and \
339
340
not isinstance (head , compat .string_types ):
340
341
head = head .format ()
341
342
tail = self [- 1 ]
342
- if hasattr (tail ,'format' ) and \
343
+ if hasattr (tail , 'format' ) and \
343
344
not isinstance (tail , compat .string_types ):
344
345
tail = tail .format ()
345
346
index_summary = ', %s to %s' % (com .pprint_thing (head ),
@@ -571,7 +572,7 @@ def to_native_types(self, slicer=None, **kwargs):
571
572
def _format_native_types (self , na_rep = '' , ** kwargs ):
572
573
""" actually format my specific types """
573
574
mask = isnull (self )
574
- values = np .array (self ,dtype = object ,copy = True )
575
+ values = np .array (self , dtype = object , copy = True )
575
576
values [mask ] = na_rep
576
577
return values .tolist ()
577
578
@@ -595,7 +596,7 @@ def identical(self, other):
595
596
Similar to equals, but check that other comparable attributes are also equal
596
597
"""
597
598
return self .equals (other ) and all (
598
- ( getattr (self ,c , None ) == getattr (other ,c , None ) for c in self ._comparables ))
599
+ (getattr (self , c , None ) == getattr (other , c , None ) for c in self ._comparables ))
599
600
600
601
def asof (self , label ):
601
602
"""
@@ -886,7 +887,8 @@ def set_value(self, arr, key, value):
886
887
Fast lookup of value from 1-dimensional ndarray. Only use this if you
887
888
know what you're doing
888
889
"""
889
- self ._engine .set_value (_values_from_object (arr ), _values_from_object (key ), value )
890
+ self ._engine .set_value (
891
+ _values_from_object (arr ), _values_from_object (key ), value )
890
892
891
893
def get_level_values (self , level ):
892
894
"""
@@ -1357,7 +1359,7 @@ def slice_locs(self, start=None, end=None):
1357
1359
1358
1360
# get_loc will return a boolean array for non_uniques
1359
1361
# if we are not monotonic
1360
- if isinstance (start_slice ,np .ndarray ):
1362
+ if isinstance (start_slice , np .ndarray ):
1361
1363
raise KeyError ("cannot peform a slice operation "
1362
1364
"on a non-unique non-monotonic index" )
1363
1365
@@ -1379,7 +1381,7 @@ def slice_locs(self, start=None, end=None):
1379
1381
if not is_unique :
1380
1382
1381
1383
# get_loc will return a boolean array for non_uniques
1382
- if isinstance (end_slice ,np .ndarray ):
1384
+ if isinstance (end_slice , np .ndarray ):
1383
1385
raise KeyError ("cannot perform a slice operation "
1384
1386
"on a non-unique non-monotonic index" )
1385
1387
@@ -1447,6 +1449,7 @@ def drop(self, labels):
1447
1449
1448
1450
1449
1451
class Int64Index (Index ):
1452
+
1450
1453
"""
1451
1454
Immutable ndarray implementing an ordered, sliceable set. The basic object
1452
1455
storing axis labels for all pandas objects. Int64Index is a special case of `Index`
@@ -1579,6 +1582,7 @@ def _wrap_joined_index(self, joined, other):
1579
1582
1580
1583
1581
1584
class MultiIndex (Index ):
1585
+
1582
1586
"""
1583
1587
Implements multi-level, a.k.a. hierarchical, index object for pandas
1584
1588
objects
@@ -1625,7 +1629,6 @@ def __new__(cls, levels=None, labels=None, sortorder=None, names=None,
1625
1629
if names is not None :
1626
1630
subarr ._set_names (names )
1627
1631
1628
-
1629
1632
if sortorder is not None :
1630
1633
subarr .sortorder = int (sortorder )
1631
1634
else :
@@ -1636,7 +1639,6 @@ def __new__(cls, levels=None, labels=None, sortorder=None, names=None,
1636
1639
def _get_levels (self ):
1637
1640
return self ._levels
1638
1641
1639
-
1640
1642
def _set_levels (self , levels , copy = False ):
1641
1643
# This is NOT part of the levels property because it should be
1642
1644
# externally not allowed to set levels. User beware if you change
@@ -1686,7 +1688,7 @@ def _get_labels(self):
1686
1688
def _set_labels (self , labels , copy = False ):
1687
1689
if len (labels ) != self .nlevels :
1688
1690
raise ValueError ("Length of levels and labels must be the same." )
1689
- self ._labels = FrozenList (_ensure_frozen (labs ,copy = copy )._shallow_copy ()
1691
+ self ._labels = FrozenList (_ensure_frozen (labs , copy = copy )._shallow_copy ()
1690
1692
for labs in labels )
1691
1693
1692
1694
def set_labels (self , labels , inplace = False ):
@@ -1811,13 +1813,13 @@ def _set_names(self, values):
1811
1813
values = list (values )
1812
1814
if len (values ) != self .nlevels :
1813
1815
raise ValueError ('Length of names (%d) must be same as level '
1814
- '(%d)' % (len (values ),self .nlevels ))
1816
+ '(%d)' % (len (values ), self .nlevels ))
1815
1817
# set the name
1816
1818
for name , level in zip (values , self .levels ):
1817
1819
level .rename (name , inplace = True )
1818
1820
1819
-
1820
- names = property ( fset = _set_names , fget = _get_names , doc = "Names of levels in MultiIndex" )
1821
+ names = property (
1822
+ fset = _set_names , fget = _get_names , doc = "Names of levels in MultiIndex" )
1821
1823
1822
1824
def _format_native_types (self , ** kwargs ):
1823
1825
return self .tolist ()
@@ -1845,7 +1847,7 @@ def _get_level_number(self, level):
1845
1847
count = self .names .count (level )
1846
1848
if count > 1 :
1847
1849
raise ValueError ('The name %s occurs multiple times, use a '
1848
- 'level number' % level )
1850
+ 'level number' % level )
1849
1851
level = self .names .index (level )
1850
1852
except ValueError :
1851
1853
if not isinstance (level , int ):
@@ -1980,9 +1982,9 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False,
1980
1982
formatted = lev .take (lab ).format (formatter = formatter )
1981
1983
1982
1984
# we have some NA
1983
- mask = lab == - 1
1985
+ mask = lab == - 1
1984
1986
if mask .any ():
1985
- formatted = np .array (formatted ,dtype = object )
1987
+ formatted = np .array (formatted , dtype = object )
1986
1988
formatted [mask ] = na_rep
1987
1989
formatted = formatted .tolist ()
1988
1990
@@ -2000,7 +2002,6 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False,
2000
2002
level .append (com .pprint_thing (name , escape_chars = ('\t ' , '\r ' , '\n ' ))
2001
2003
if name is not None else '' )
2002
2004
2003
-
2004
2005
level .extend (np .array (lev , dtype = object ))
2005
2006
result_levels .append (level )
2006
2007
@@ -2010,8 +2011,9 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False,
2010
2011
if sparsify :
2011
2012
sentinal = ''
2012
2013
# GH3547
2013
- # use value of sparsify as sentinal, unless it's an obvious "Truthey" value
2014
- if sparsify not in [True ,1 ]:
2014
+ # use value of sparsify as sentinal, unless it's an obvious
2015
+ # "Truthey" value
2016
+ if sparsify not in [True , 1 ]:
2015
2017
sentinal = sparsify
2016
2018
# little bit of a kludge job for #1217
2017
2019
result_levels = _sparsify (result_levels ,
@@ -2138,7 +2140,8 @@ def __contains__(self, key):
2138
2140
def __reduce__ (self ):
2139
2141
"""Necessary for making this object picklable"""
2140
2142
object_state = list (np .ndarray .__reduce__ (self ))
2141
- subclass_state = (list (self .levels ), list (self .labels ), self .sortorder , list (self .names ))
2143
+ subclass_state = (list (self .levels ), list (
2144
+ self .labels ), self .sortorder , list (self .names ))
2142
2145
object_state [2 ] = (object_state [2 ], subclass_state )
2143
2146
return tuple (object_state )
2144
2147
@@ -2490,7 +2493,8 @@ def reindex(self, target, method=None, level=None, limit=None,
2490
2493
"with a method or limit" )
2491
2494
return self [target ], target
2492
2495
2493
- raise Exception ("cannot handle a non-takeable non-unique multi-index!" )
2496
+ raise Exception (
2497
+ "cannot handle a non-takeable non-unique multi-index!" )
2494
2498
2495
2499
if not isinstance (target , MultiIndex ):
2496
2500
if indexer is None :
@@ -2685,12 +2689,13 @@ def partial_selection(key):
2685
2689
2686
2690
# here we have a completely specified key, but are using some partial string matching here
2687
2691
# GH4758
2688
- can_index_exactly = any ([ l .is_all_dates and not isinstance (k ,compat .string_types ) for k , l in zip (key , self .levels ) ])
2689
- if any ([ l .is_all_dates for k , l in zip (key , self .levels ) ]) and not can_index_exactly :
2692
+ can_index_exactly = any (
2693
+ [l .is_all_dates and not isinstance (k , compat .string_types ) for k , l in zip (key , self .levels )])
2694
+ if any ([l .is_all_dates for k , l in zip (key , self .levels )]) and not can_index_exactly :
2690
2695
indexer = slice (* self .slice_locs (key , key ))
2691
2696
2692
2697
# we have a multiple selection here
2693
- if not indexer .stop - indexer .start == 1 :
2698
+ if not indexer .stop - indexer .start == 1 :
2694
2699
return partial_selection (key )
2695
2700
2696
2701
key = tuple (self [indexer ].tolist ()[0 ])
@@ -2913,7 +2918,8 @@ def _assert_can_do_setop(self, other):
2913
2918
2914
2919
def astype (self , dtype ):
2915
2920
if np .dtype (dtype ) != np .object_ :
2916
- raise TypeError ("Setting %s dtype to anything other than object is not supported" % self .__class__ )
2921
+ raise TypeError (
2922
+ "Setting %s dtype to anything other than object is not supported" % self .__class__ )
2917
2923
return self ._shallow_copy ()
2918
2924
2919
2925
def insert (self , loc , item ):
@@ -2935,7 +2941,8 @@ def insert(self, loc, item):
2935
2941
if not isinstance (item , tuple ):
2936
2942
item = (item ,) + ('' ,) * (self .nlevels - 1 )
2937
2943
elif len (item ) != self .nlevels :
2938
- raise ValueError ('Item must have length equal to number of levels.' )
2944
+ raise ValueError (
2945
+ 'Item must have length equal to number of levels.' )
2939
2946
2940
2947
new_levels = []
2941
2948
new_labels = []
@@ -2990,7 +2997,7 @@ def _wrap_joined_index(self, joined, other):
2990
2997
2991
2998
# For utility purposes
2992
2999
2993
- def _sparsify (label_list , start = 0 ,sentinal = '' ):
3000
+ def _sparsify (label_list , start = 0 , sentinal = '' ):
2994
3001
pivoted = lzip (* label_list )
2995
3002
k = len (label_list )
2996
3003
@@ -3031,7 +3038,7 @@ def _ensure_index(index_like, copy=False):
3031
3038
if isinstance (index_like , list ):
3032
3039
if type (index_like ) != list :
3033
3040
index_like = list (index_like )
3034
- # # 2200 ?
3041
+ # 2200 ?
3035
3042
converted , all_arrays = lib .clean_index_list (index_like )
3036
3043
3037
3044
if len (converted ) > 0 and all_arrays :
@@ -3169,7 +3176,8 @@ def _get_consensus_names(indexes):
3169
3176
3170
3177
# find the non-none names, need to tupleify to make
3171
3178
# the set hashable, then reverse on return
3172
- consensus_names = set ([ tuple (i .names ) for i in indexes if all (n is not None for n in i .names ) ])
3179
+ consensus_names = set ([tuple (i .names )
3180
+ for i in indexes if all (n is not None for n in i .names )])
3173
3181
if len (consensus_names ) == 1 :
3174
3182
return list (list (consensus_names )[0 ])
3175
3183
return [None ] * indexes [0 ].nlevels
0 commit comments