-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
/
Copy pathindex.py
2807 lines (2268 loc) · 85.7 KB
/
index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=E1101,E1103,W0232
from itertools import izip
import numpy as np
import pandas.tslib as tslib
import pandas.lib as lib
import pandas.algos as _algos
import pandas.index as _index
from pandas.lib import Timestamp
from pandas.util.decorators import cache_readonly
from pandas.core.common import isnull
import pandas.core.common as com
from pandas.util import py3compat
from pandas.core.config import get_option
__all__ = ['Index']
def _indexOp(opname):
"""
Wrapper function for index comparison operations, to avoid
code duplication.
"""
def wrapper(self, other):
func = getattr(self.view(np.ndarray), opname)
result = func(other)
try:
return result.view(np.ndarray)
except: # pragma: no cover
return result
return wrapper
class InvalidIndexError(Exception):
pass
_o_dtype = np.dtype(object)
def _shouldbe_timestamp(obj):
return (tslib.is_datetime_array(obj)
or tslib.is_datetime64_array(obj)
or tslib.is_timestamp_array(obj))
class Index(np.ndarray):
"""
Immutable ndarray implementing an ordered, sliceable set. The basic object
storing axis labels for all pandas objects
Parameters
----------
data : array-like (1-dimensional)
dtype : NumPy dtype (default: object)
copy : bool
Make a copy of input ndarray
name : object
Name to be stored in the index
Note
----
An Index instance can **only** contain hashable objects
"""
# To hand over control to subclasses
_join_precedence = 1
# Cython methods
_groupby = _algos.groupby_object
_arrmap = _algos.arrmap_object
_left_indexer_unique = _algos.left_join_indexer_unique_object
_left_indexer = _algos.left_join_indexer_object
_inner_indexer = _algos.inner_join_indexer_object
_outer_indexer = _algos.outer_join_indexer_object
_box_scalars = False
name = None
asi8 = None
_engine_type = _index.ObjectEngine
def __new__(cls, data, dtype=None, copy=False, name=None):
from pandas.tseries.period import PeriodIndex
if isinstance(data, np.ndarray):
if issubclass(data.dtype.type, np.datetime64):
from pandas.tseries.index import DatetimeIndex
result = DatetimeIndex(data, copy=copy, name=name)
if dtype is not None and _o_dtype == dtype:
return Index(result.to_pydatetime(), dtype=_o_dtype)
else:
return result
elif issubclass(data.dtype.type, np.timedelta64):
return Int64Index(data, copy=copy, name=name)
if dtype is not None:
try:
data = np.array(data, dtype=dtype, copy=copy)
except TypeError:
pass
elif isinstance(data, PeriodIndex):
return PeriodIndex(data, copy=copy, name=name)
if issubclass(data.dtype.type, np.integer):
return Int64Index(data, copy=copy, dtype=dtype, name=name)
subarr = com._asarray_tuplesafe(data, dtype=object)
elif np.isscalar(data):
raise ValueError('Index(...) must be called with a collection '
'of some kind, %s was passed' % repr(data))
else:
# other iterable of some kind
subarr = com._asarray_tuplesafe(data, dtype=object)
if dtype is None:
inferred = lib.infer_dtype(subarr)
if inferred == 'integer':
return Int64Index(subarr.astype('i8'), name=name)
elif inferred != 'string':
if (inferred.startswith('datetime') or
tslib.is_timestamp_array(subarr)):
from pandas.tseries.index import DatetimeIndex
return DatetimeIndex(subarr, copy=copy, name=name)
elif inferred == 'period':
return PeriodIndex(subarr, name=name)
subarr = subarr.view(cls)
subarr.name = name
return subarr
def __array_finalize__(self, obj):
if not isinstance(obj, type(self)):
# Only relevant if array being created from an Index instance
return
self.name = getattr(obj, 'name', None)
def _shallow_copy(self):
return self.view()
def __str__(self):
"""
Return a string representation for a particular Index
Invoked by str(df) in both py2/py3.
Yields Bytestring in Py2, Unicode String in py3.
"""
if py3compat.PY3:
return self.__unicode__()
return self.__bytes__()
def __bytes__(self):
"""
Return a string representation for a particular Index
Invoked by bytes(df) in py3 only.
Yields a bytestring in both py2/py3.
"""
encoding = com.get_option("display.encoding")
return self.__unicode__().encode(encoding, 'replace')
def __unicode__(self):
"""
Return a string representation for a particular Index
Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3.
"""
prepr = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'),quote_strings=True)
return '%s(%s, dtype=%s)' % (type(self).__name__, prepr, self.dtype)
def __repr__(self):
"""
Return a string representation for a particular Index
Yields Bytestring in Py2, Unicode String in py3.
"""
return str(self)
def to_series(self):
"""
return a series with both index and values equal to the index keys
useful with map for returning an indexer based on an index
"""
import pandas as pd
return pd.Series(self.values,index=self,name=self.name)
def astype(self, dtype):
return Index(self.values.astype(dtype), name=self.name,
dtype=dtype)
def to_datetime(self, dayfirst=False):
"""
For an Index containing strings or datetime.datetime objects, attempt
conversion to DatetimeIndex
"""
from pandas.tseries.index import DatetimeIndex
if self.inferred_type == 'string':
from dateutil.parser import parse
parser = lambda x: parse(x, dayfirst=dayfirst)
parsed = lib.try_parse_dates(self.values, parser=parser)
return DatetimeIndex(parsed)
else:
return DatetimeIndex(self.values)
def _assert_can_do_setop(self, other):
return True
def tolist(self):
"""
Overridden version of ndarray.tolist
"""
return list(self.values)
@cache_readonly
def dtype(self):
return self.values.dtype
@property
def nlevels(self):
return 1
# for compat with multindex code
def _get_names(self):
return [self.name]
def _set_names(self, values):
if len(values) != 1:
raise AssertionError('Length of new names must be 1, got %d'
% len(values))
self.name = values[0]
names = property(fset=_set_names, fget=_get_names)
@property
def _constructor(self):
return Index
@property
def _has_complex_internals(self):
# to disable groupby tricks in MultiIndex
return False
def summary(self, name=None):
if len(self) > 0:
head = self[0]
if hasattr(head,'format'):
head = head.format()
tail = self[-1]
if hasattr(tail,'format'):
tail = tail.format()
index_summary = ', %s to %s' % (com.pprint_thing(head),
com.pprint_thing(tail))
else:
index_summary = ''
if name is None:
name = type(self).__name__
return '%s: %s entries%s' % (name, len(self), index_summary)
def _mpl_repr(self):
# how to represent ourselves to matplotlib
return self.values
@property
def values(self):
return np.asarray(self)
@property
def is_monotonic(self):
return self._engine.is_monotonic
def is_lexsorted_for_tuple(self, tup):
return True
@cache_readonly
def is_unique(self):
return self._engine.is_unique
def is_numeric(self):
return self.inferred_type in ['integer', 'floating']
def holds_integer(self):
return self.inferred_type in ['integer', 'mixed-integer']
def get_duplicates(self):
from collections import defaultdict
counter = defaultdict(lambda: 0)
for k in self.values:
counter[k] += 1
return sorted(k for k, v in counter.iteritems() if v > 1)
_get_duplicates = get_duplicates
def _cleanup(self):
self._engine.clear_mapping()
@cache_readonly
def _engine(self):
# property, for now, slow to look up
return self._engine_type(lambda: self.values, len(self))
def _get_level_number(self, level):
if not isinstance(level, int):
if level != self.name:
raise AssertionError('Level %s must be same as name (%s)'
% (level, self.name))
level = 0
return level
@cache_readonly
def inferred_type(self):
return lib.infer_dtype(self)
def is_type_compatible(self, typ):
return typ == self.inferred_type
@cache_readonly
def is_all_dates(self):
return self.inferred_type == 'datetime'
def __iter__(self):
return iter(self.values)
def __reduce__(self):
"""Necessary for making this object picklable"""
object_state = list(np.ndarray.__reduce__(self))
subclass_state = self.name,
object_state[2] = (object_state[2], subclass_state)
return tuple(object_state)
def __setstate__(self, state):
"""Necessary for making this object picklable"""
if len(state) == 2:
nd_state, own_state = state
np.ndarray.__setstate__(self, nd_state)
self.name = own_state[0]
else: # pragma: no cover
np.ndarray.__setstate__(self, state)
def __deepcopy__(self, memo={}):
"""
Index is not mutable, so disabling deepcopy
"""
return self
def __contains__(self, key):
hash(key)
# work around some kind of odd cython bug
try:
return key in self._engine
except TypeError:
return False
def __hash__(self):
return hash(self.view(np.ndarray))
def __setitem__(self, key, value):
raise Exception(str(self.__class__) + ' object is immutable')
def __getitem__(self, key):
"""Override numpy.ndarray's __getitem__ method to work as desired"""
arr_idx = self.view(np.ndarray)
if np.isscalar(key):
return arr_idx[key]
else:
if com._is_bool_indexer(key):
key = np.asarray(key)
result = arr_idx[key]
if result.ndim > 1:
return result
return Index(result, name=self.name)
def append(self, other):
"""
Append a collection of Index options together
Parameters
----------
other : Index or list/tuple of indices
Returns
-------
appended : Index
"""
name = self.name
to_concat = [self]
if isinstance(other, (list, tuple)):
to_concat = to_concat + list(other)
else:
to_concat.append(other)
for obj in to_concat:
if isinstance(obj, Index) and obj.name != name:
name = None
break
to_concat = self._ensure_compat_concat(to_concat)
to_concat = [x.values if isinstance(x, Index) else x
for x in to_concat]
return Index(np.concatenate(to_concat), name=name)
@staticmethod
def _ensure_compat_concat(indexes):
from pandas.tseries.api import DatetimeIndex, PeriodIndex
klasses = DatetimeIndex, PeriodIndex
is_ts = [isinstance(idx, klasses) for idx in indexes]
if any(is_ts) and not all(is_ts):
return [_maybe_box(idx) for idx in indexes]
return indexes
def take(self, indexer, axis=0):
"""
Analogous to ndarray.take
"""
indexer = com._ensure_platform_int(indexer)
taken = self.view(np.ndarray).take(indexer)
return self._constructor(taken, name=self.name)
def format(self, name=False, formatter=None, **kwargs):
"""
Render a string representation of the Index
"""
header = []
if name:
header.append(com.pprint_thing(self.name,
escape_chars=('\t', '\r', '\n'))
if self.name is not None else '')
if formatter is not None:
return header + list(self.map(formatter))
return self._format_with_header(header, **kwargs)
def _format_with_header(self, header, na_rep='NaN', **kwargs):
values = self.values
from pandas.core.format import format_array
if values.dtype == np.object_:
values = lib.maybe_convert_objects(values, safe=1)
if values.dtype == np.object_:
result = [com.pprint_thing(x, escape_chars=('\t', '\r', '\n'))
for x in values]
# could have nans
mask = isnull(values)
if mask.any():
result = np.array(result)
result[mask] = na_rep
result = result.tolist()
else:
result = _trim_front(format_array(values, None, justify='left'))
return header + result
def to_native_types(self, slicer=None, **kwargs):
""" slice and dice then format """
values = self
if slicer is not None:
values = values[slicer]
return values._format_native_types(**kwargs)
def _format_native_types(self, na_rep='', **kwargs):
""" actually format my specific types """
mask = isnull(self)
values = np.array(self,dtype=object,copy=True)
values[mask] = na_rep
return values.tolist()
def equals(self, other):
"""
Determines if two Index objects contain the same elements.
"""
if self is other:
return True
if not isinstance(other, Index):
return False
if type(other) != Index:
return other.equals(self)
return np.array_equal(self, other)
def asof(self, label):
"""
For a sorted index, return the most recent label up to and including
the passed label. Return NaN if not found
"""
if isinstance(label, (Index, np.ndarray)):
raise TypeError('%s' % type(label))
if label not in self:
loc = self.searchsorted(label, side='left')
if loc > 0:
return self[loc - 1]
else:
return np.nan
if not isinstance(label, Timestamp):
label = Timestamp(label)
return label
def asof_locs(self, where, mask):
"""
where : array of timestamps
mask : array of booleans where data is not NA
"""
locs = self.values[mask].searchsorted(where.values, side='right')
locs = np.where(locs > 0, locs - 1, 0)
result = np.arange(len(self))[mask].take(locs)
first = mask.argmax()
result[(locs == 0) & (where < self.values[first])] = -1
return result
def order(self, return_indexer=False, ascending=True):
"""
Return sorted copy of Index
"""
_as = self.argsort()
if not ascending:
_as = _as[::-1]
sorted_index = self.take(_as)
if return_indexer:
return sorted_index, _as
else:
return sorted_index
def sort(self, *args, **kwargs):
raise Exception('Cannot sort an Index object')
def shift(self, periods=1, freq=None):
"""
Shift Index containing datetime objects by input number of periods and
DateOffset
Returns
-------
shifted : Index
"""
if periods == 0:
# OK because immutable
return self
offset = periods * freq
return Index([idx + offset for idx in self])
def argsort(self, *args, **kwargs):
"""
See docstring for ndarray.argsort
"""
return self.view(np.ndarray).argsort(*args, **kwargs)
def __add__(self, other):
if isinstance(other, Index):
return self.union(other)
else:
return Index(self.view(np.ndarray) + other)
__eq__ = _indexOp('__eq__')
__ne__ = _indexOp('__ne__')
__lt__ = _indexOp('__lt__')
__gt__ = _indexOp('__gt__')
__le__ = _indexOp('__le__')
__ge__ = _indexOp('__ge__')
def __sub__(self, other):
return self.diff(other)
def __and__(self, other):
return self.intersection(other)
def __or__(self, other):
return self.union(other)
def union(self, other):
"""
Form the union of two Index objects and sorts if possible
Parameters
----------
other : Index or array-like
Returns
-------
union : Index
"""
if not hasattr(other, '__iter__'):
raise Exception('Input must be iterable!')
if len(other) == 0 or self.equals(other):
return self
if len(self) == 0:
return _ensure_index(other)
self._assert_can_do_setop(other)
if self.dtype != other.dtype:
this = self.astype('O')
other = other.astype('O')
return this.union(other)
if self.is_monotonic and other.is_monotonic:
try:
result = self._outer_indexer(self, other.values)[0]
except TypeError:
# incomparable objects
result = list(self.values)
# worth making this faster? a very unusual case
value_set = set(self.values)
result.extend([x for x in other.values if x not in value_set])
else:
indexer = self.get_indexer(other)
indexer = (indexer == -1).nonzero()[0]
if len(indexer) > 0:
other_diff = com.take_nd(other.values, indexer,
allow_fill=False)
result = com._concat_compat((self.values, other_diff))
try:
result.sort()
except Exception:
pass
else:
# contained in
try:
result = np.sort(self.values)
except TypeError: # pragma: no cover
result = self.values
# for subclasses
return self._wrap_union_result(other, result)
def _wrap_union_result(self, other, result):
name = self.name if self.name == other.name else None
return type(self)(data=result, name=name)
def intersection(self, other):
"""
Form the intersection of two Index objects. Sortedness of the result is
not guaranteed
Parameters
----------
other : Index or array-like
Returns
-------
intersection : Index
"""
if not hasattr(other, '__iter__'):
raise Exception('Input must be iterable!')
self._assert_can_do_setop(other)
other = _ensure_index(other)
if self.equals(other):
return self
if self.dtype != other.dtype:
this = self.astype('O')
other = other.astype('O')
return this.intersection(other)
if self.is_monotonic and other.is_monotonic:
try:
result = self._inner_indexer(self, other.values)[0]
return self._wrap_union_result(other, result)
except TypeError:
pass
indexer = self.get_indexer(other.values)
indexer = indexer.take((indexer != -1).nonzero()[0])
return self.take(indexer)
def diff(self, other):
"""
Compute sorted set difference of two Index objects
Notes
-----
One can do either of these and achieve the same result
>>> index - index2
>>> index.diff(index2)
Returns
-------
diff : Index
"""
if not hasattr(other, '__iter__'):
raise Exception('Input must be iterable!')
if self.equals(other):
return Index([], name=self.name)
if not isinstance(other, Index):
other = np.asarray(other)
result_name = self.name
else:
result_name = self.name if self.name == other.name else None
theDiff = sorted(set(self) - set(other))
return Index(theDiff, name=result_name)
def unique(self):
"""
Return array of unique values in the Index. Significantly faster than
numpy.unique
Returns
-------
uniques : ndarray
"""
from pandas.core.nanops import unique1d
return unique1d(self.values)
def get_loc(self, key):
"""
Get integer location for requested label
Returns
-------
loc : int if unique index, possibly slice or mask if not
"""
return self._engine.get_loc(key)
def get_value(self, series, key):
"""
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
try:
return self._engine.get_value(series, key)
except KeyError, e1:
if len(self) > 0 and self.inferred_type == 'integer':
raise
try:
return tslib.get_value_box(series, key)
except IndexError:
raise
except TypeError:
# generator/iterator-like
if com.is_iterator(key):
raise InvalidIndexError(key)
else:
raise e1
except Exception: # pragma: no cover
raise e1
except TypeError:
# python 3
if np.isscalar(key): # pragma: no cover
raise IndexError(key)
raise InvalidIndexError(key)
def set_value(self, arr, key, value):
"""
Fast lookup of value from 1-dimensional ndarray. Only use this if you
know what you're doing
"""
self._engine.set_value(arr, key, value)
def get_level_values(self, level):
"""
Return vector of label values for requested level, equal to the length
of the index
Parameters
----------
level : int
Returns
-------
values : ndarray
"""
num = self._get_level_number(level)
return self
def get_indexer(self, target, method=None, limit=None):
"""
Compute indexer and mask for new index given the current index. The
indexer should be then used as an input to ndarray.take to align the
current data to the new index. The mask determines whether labels are
found or not in the current index
Parameters
----------
target : Index
method : {'pad', 'ffill', 'backfill', 'bfill'}
pad / ffill: propagate LAST valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
Notes
-----
This is a low-level method and probably should be used at your own risk
Examples
--------
>>> indexer = index.get_indexer(new_index)
>>> new_values = cur_values.take(indexer)
Returns
-------
indexer : ndarray
"""
method = self._get_method(method)
target = _ensure_index(target)
pself, ptarget = self._possibly_promote(target)
if pself is not self or ptarget is not target:
return pself.get_indexer(ptarget, method=method, limit=limit)
if self.dtype != target.dtype:
this = self.astype(object)
target = target.astype(object)
return this.get_indexer(target, method=method, limit=limit)
if not self.is_unique:
raise Exception('Reindexing only valid with uniquely valued Index '
'objects')
if method == 'pad':
if not self.is_monotonic:
raise AssertionError('Must be monotonic for forward fill')
indexer = self._engine.get_pad_indexer(target.values, limit)
elif method == 'backfill':
if not self.is_monotonic:
raise AssertionError('Must be monotonic for backward fill')
indexer = self._engine.get_backfill_indexer(target.values, limit)
elif method is None:
indexer = self._engine.get_indexer(target.values)
else:
raise ValueError('unrecognized method: %s' % method)
return com._ensure_platform_int(indexer)
def _possibly_promote(self, other):
# A hack, but it works
from pandas.tseries.index import DatetimeIndex
if self.inferred_type == 'date' and isinstance(other, DatetimeIndex):
return DatetimeIndex(self), other
return self, other
def groupby(self, to_groupby):
return self._groupby(self.values, to_groupby)
def map(self, mapper):
return self._arrmap(self.values, mapper)
def isin(self, values):
"""
Compute boolean array of whether each index value is found in the
passed set of values
Parameters
----------
values : set or sequence of values
Returns
-------
is_contained : ndarray (boolean dtype)
"""
value_set = set(values)
return lib.ismember(self._array_values(), value_set)
def _array_values(self):
return self
def _get_method(self, method):
if method:
method = method.lower()
aliases = {
'ffill': 'pad',
'bfill': 'backfill'
}
return aliases.get(method, method)
def reindex(self, target, method=None, level=None, limit=None):
"""
For Index, simply returns the new index and the results of
get_indexer. Provided here to enable an interface that is amenable for
subclasses of Index whose internals are different (like MultiIndex)
Returns
-------
(new_index, indexer, mask) : tuple
"""
target = _ensure_index(target)
if level is not None:
if method is not None:
raise ValueError('Fill method not supported if level passed')
_, indexer, _ = self._join_level(target, level, how='right',
return_indexers=True)
else:
if self.equals(target):
indexer = None
else:
indexer = self.get_indexer(target, method=method,
limit=limit)
return target, indexer
def join(self, other, how='left', level=None, return_indexers=False):
"""
Internal API method. Compute join_index and indexers to conform data
structures to the new index.
Parameters
----------
other : Index
how : {'left', 'right', 'inner', 'outer'}
level :
return_indexers : boolean, default False
Returns
-------
join_index, (left_indexer, right_indexer)
"""
if (level is not None and (isinstance(self, MultiIndex) or
isinstance(other, MultiIndex))):
return self._join_level(other, level, how=how,
return_indexers=return_indexers)
other = _ensure_index(other)
if len(other) == 0 and how in ('left', 'outer'):
join_index = self._shallow_copy()
if return_indexers:
rindexer = np.repeat(-1, len(join_index))
return join_index, None, rindexer
else:
return join_index
if len(self) == 0 and how in ('right', 'outer'):
join_index = other._shallow_copy()
if return_indexers:
lindexer = np.repeat(-1, len(join_index))
return join_index, lindexer, None
else:
return join_index
if self._join_precedence < other._join_precedence:
how = {'right': 'left', 'left': 'right'}.get(how, how)
result = other.join(self, how=how, level=level,
return_indexers=return_indexers)
if return_indexers:
x, y, z = result
result = x, z, y
return result
if self.dtype != other.dtype:
this = self.astype('O')
other = other.astype('O')
return this.join(other, how=how,
return_indexers=return_indexers)
_validate_join_method(how)
if not self.is_unique and not other.is_unique:
return self._join_non_unique(other, how=how,
return_indexers=return_indexers)
elif not self.is_unique or not other.is_unique:
if self.is_monotonic and other.is_monotonic:
return self._join_monotonic(other, how=how,
return_indexers=return_indexers)
else:
return self._join_non_unique(other, how=how,
return_indexers=return_indexers)
elif self.is_monotonic and other.is_monotonic:
try:
return self._join_monotonic(other, how=how,
return_indexers=return_indexers)
except TypeError:
pass