-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
/
Copy pathseries.py
3559 lines (2938 loc) · 113 KB
/
series.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
"""
Data structure for 1-dimensional cross-sectional and time series data
"""
# pylint: disable=E1101,E1103
# pylint: disable=W0703,W0622,W0613,W0201
import operator
from distutils.version import LooseVersion
import types
import warnings
from numpy import nan, ndarray
import numpy as np
import numpy.ma as ma
from pandas.core.common import (isnull, notnull, _is_bool_indexer,
_default_index, _maybe_promote, _maybe_upcast,
_asarray_tuplesafe, is_integer_dtype,
_infer_dtype_from_scalar, is_list_like,
_NS_DTYPE, _TD_DTYPE)
from pandas.core.index import (Index, MultiIndex, InvalidIndexError,
_ensure_index, _handle_legacy_indexes)
from pandas.core.indexing import (_SeriesIndexer, _check_bool_indexer,
_check_slice_bounds, _maybe_convert_indices)
from pandas.tseries.index import DatetimeIndex
from pandas.tseries.period import PeriodIndex, Period
from pandas import compat
from pandas.util.terminal import get_terminal_size
from pandas.compat import zip, lzip, u, OrderedDict
import pandas.core.array as pa
import pandas.core.common as com
import pandas.core.datetools as datetools
import pandas.core.format as fmt
import pandas.core.generic as generic
import pandas.core.nanops as nanops
from pandas.util.decorators import Appender, Substitution, cache_readonly
import pandas.lib as lib
import pandas.tslib as tslib
import pandas.index as _index
from pandas.compat.scipy import scoreatpercentile as _quantile
from pandas.core.config import get_option
__all__ = ['Series', 'TimeSeries']
_SHOW_WARNINGS = True
#----------------------------------------------------------------------
# Wrapper function for Series arithmetic methods
def _arith_method(op, name, fill_zeros=None):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def na_op(x, y):
try:
result = op(x, y)
result = com._fill_zeros(result,y,fill_zeros)
except TypeError:
result = pa.empty(len(x), dtype=x.dtype)
if isinstance(y, pa.Array):
mask = notnull(x) & notnull(y)
result[mask] = op(x[mask], y[mask])
else:
mask = notnull(x)
result[mask] = op(x[mask], y)
result, changed = com._maybe_upcast_putmask(result,-mask,pa.NA)
return result
def wrapper(self, other, name=name):
from pandas.core.frame import DataFrame
dtype = None
wrap_results = lambda x: x
lvalues, rvalues = self, other
is_timedelta_lhs = com.is_timedelta64_dtype(self)
is_datetime_lhs = com.is_datetime64_dtype(self)
if is_datetime_lhs or is_timedelta_lhs:
# convert the argument to an ndarray
def convert_to_array(values):
if not is_list_like(values):
values = np.array([values])
inferred_type = lib.infer_dtype(values)
if inferred_type in set(['datetime64','datetime','date','time']):
if not (isinstance(values, pa.Array) and com.is_datetime64_dtype(values)):
values = tslib.array_to_datetime(values)
elif inferred_type in set(['timedelta','timedelta64']):
# need to convert timedelta to ns here
# safest to convert it to an object arrany to process
values = com._possibly_cast_to_timedelta(values)
elif inferred_type in set(['integer']):
if values.dtype.kind == 'm':
values = values.astype('timedelta64[ns]')
else:
values = pa.array(values)
return values
# convert lhs and rhs
lvalues = convert_to_array(lvalues)
rvalues = convert_to_array(rvalues)
is_timedelta_rhs = com.is_timedelta64_dtype(rvalues)
is_datetime_rhs = com.is_datetime64_dtype(rvalues)
# 2 datetimes or 2 timedeltas
if (is_timedelta_lhs and is_timedelta_rhs) or (is_datetime_lhs and
is_datetime_rhs):
if is_datetime_lhs and name != '__sub__':
raise TypeError("can only operate on a datetimes for subtraction, "
"but the operator [%s] was passed" % name)
elif is_timedelta_lhs and name not in ['__add__', '__sub__']:
raise TypeError("can only operate on a timedeltas for "
"addition and subtraction, but the operator [%s] was passed" % name)
dtype = 'timedelta64[ns]'
# we may have to convert to object unfortunately here
mask = isnull(lvalues) | isnull(rvalues)
if mask.any():
def wrap_results(x):
x = pa.array(x,dtype='timedelta64[ns]')
np.putmask(x,mask,tslib.iNaT)
return x
# datetime and timedelta
elif (is_timedelta_lhs and is_datetime_rhs) or (is_timedelta_rhs and is_datetime_lhs):
if name not in ['__add__', '__sub__']:
raise TypeError("can only operate on a timedelta and a datetime for "
"addition and subtraction, but the operator [%s] was passed" % name)
dtype = 'M8[ns]'
else:
raise ValueError('cannot operate on a series without a rhs '
'of a series/ndarray of type datetime64[ns] '
'or a timedelta')
lvalues = lvalues.view('i8')
rvalues = rvalues.view('i8')
if isinstance(rvalues, Series):
lvalues = lvalues.values
rvalues = rvalues.values
if self.index.equals(other.index):
name = _maybe_match_name(self, other)
return Series(wrap_results(na_op(lvalues, rvalues)),
index=self.index, name=name, dtype=dtype)
join_idx, lidx, ridx = self.index.join(other.index, how='outer',
return_indexers=True)
if lidx is not None:
lvalues = com.take_1d(lvalues, lidx)
if ridx is not None:
rvalues = com.take_1d(rvalues, ridx)
arr = na_op(lvalues, rvalues)
name = _maybe_match_name(self, other)
return Series(wrap_results(arr), index=join_idx, name=name,dtype=dtype)
elif isinstance(other, DataFrame):
return NotImplemented
else:
# scalars
if hasattr(lvalues,'values'):
lvalues = lvalues.values
return Series(wrap_results(na_op(lvalues, rvalues)),
index=self.index, name=self.name, dtype=dtype)
return wrapper
def _comp_method(op, name):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def na_op(x, y):
if x.dtype == np.object_:
if isinstance(y, list):
y = lib.list_to_object_array(y)
if isinstance(y, pa.Array):
if y.dtype != np.object_:
result = lib.vec_compare(x, y.astype(np.object_), op)
else:
result = lib.vec_compare(x, y, op)
else:
result = lib.scalar_compare(x, y, op)
else:
result = op(x, y)
return result
def wrapper(self, other):
from pandas.core.frame import DataFrame
if isinstance(other, Series):
name = _maybe_match_name(self, other)
if len(self) != len(other):
raise ValueError('Series lengths must match to compare')
return Series(na_op(self.values, other.values),
index=self.index, name=name)
elif isinstance(other, DataFrame): # pragma: no cover
return NotImplemented
elif isinstance(other, pa.Array):
if len(self) != len(other):
raise ValueError('Lengths must match to compare')
return Series(na_op(self.values, np.asarray(other)),
index=self.index, name=self.name)
else:
values = self.values
other = _index.convert_scalar(values, other)
if issubclass(values.dtype.type, np.datetime64):
values = values.view('i8')
# scalars
res = na_op(values, other)
if np.isscalar(res):
raise TypeError('Could not compare %s type with Series'
% type(other))
return Series(na_op(values, other),
index=self.index, name=self.name)
return wrapper
def _bool_method(op, name):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
if isinstance(y, list):
y = lib.list_to_object_array(y)
if isinstance(y, pa.Array):
if (x.dtype == np.bool_ and
y.dtype == np.bool_): # pragma: no cover
result = op(x, y) # when would this be hit?
else:
x = com._ensure_object(x)
y = com._ensure_object(y)
result = lib.vec_binop(x, y, op)
else:
result = lib.scalar_binop(x, y, op)
return result
def wrapper(self, other):
from pandas.core.frame import DataFrame
if isinstance(other, Series):
name = _maybe_match_name(self, other)
return Series(na_op(self.values, other.values),
index=self.index, name=name)
elif isinstance(other, DataFrame):
return NotImplemented
else:
# scalars
return Series(na_op(self.values, other),
index=self.index, name=self.name)
return wrapper
def _radd_compat(left, right):
radd = lambda x, y: y + x
# GH #353, NumPy 1.5.1 workaround
try:
output = radd(left, right)
except TypeError:
cond = com._np_version_under1p6 and left.dtype == np.object_
if cond: # pragma: no cover
output = np.empty_like(left)
output.flat[:] = [radd(x, right) for x in left.flat]
else:
raise
return output
def _maybe_match_name(a, b):
name = None
if a.name == b.name:
name = a.name
return name
def _flex_method(op, name):
doc = """
Binary operator %s with support to substitute a fill_value for missing data
in one of the inputs
Parameters
----------
other: Series or scalar value
fill_value : None or float value, default None (NaN)
Fill missing (NaN) values with this value. If both Series are
missing, the result will be missing
level : int or name
Broadcast across a level, matching Index values on the
passed MultiIndex level
Returns
-------
result : Series
""" % name
@Appender(doc)
def f(self, other, level=None, fill_value=None):
if isinstance(other, Series):
return self._binop(other, op, level=level, fill_value=fill_value)
elif isinstance(other, (pa.Array, list, tuple)):
if len(other) != len(self):
raise ValueError('Lengths must be equal')
return self._binop(Series(other, self.index), op,
level=level, fill_value=fill_value)
else:
return Series(op(self.values, other), self.index,
name=self.name)
f.__name__ = name
return f
def _unbox(func):
@Appender(func.__doc__)
def f(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if isinstance(result, pa.Array) and result.ndim == 0:
# return NumPy type
return result.dtype.type(result.item())
else: # pragma: no cover
return result
f.__name__ = func.__name__
return f
_stat_doc = """
Return %(name)s of values
%(na_action)s
Parameters
----------
skipna : boolean, default True
Exclude NA/null values
level : int, default None
If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a smaller Series
%(extras)s
Returns
-------
%(shortname)s : float (or Series if level specified)
"""
_doc_exclude_na = "NA/null values are excluded"
_doc_ndarray_interface = ("Extra parameters are to preserve ndarray"
"interface.\n")
def _make_stat_func(nanop, name, shortname, na_action=_doc_exclude_na,
extras=_doc_ndarray_interface):
@Substitution(name=name, shortname=shortname,
na_action=na_action, extras=extras)
@Appender(_stat_doc)
def f(self, axis=0, dtype=None, out=None, skipna=True, level=None):
if level is not None:
return self._agg_by_level(shortname, level=level, skipna=skipna)
return nanop(self.values, skipna=skipna)
f.__name__ = shortname
return f
#----------------------------------------------------------------------
# Series class
class Series(generic.PandasContainer, pa.Array):
"""
One-dimensional ndarray with axis labels (including time series).
Labels need not be unique but must be any hashable type. The object
supports both integer- and label-based indexing and provides a host of
methods for performing operations involving the index. Statistical
methods from ndarray have been overridden to automatically exclude
missing data (currently represented as NaN)
Operations between Series (+, -, /, *, **) align values based on their
associated index values-- they need not be the same length. The result
index will be the sorted union of the two indexes.
Parameters
----------
data : array-like, dict, or scalar value
Contains data stored in Series
index : array-like or Index (1d)
Values must be unique and hashable, same length as data. Index
object (or other iterable of same length as data) Will default to
np.arange(len(data)) if not provided. If both a dict and index
sequence are used, the index will override the keys found in the
dict.
dtype : numpy.dtype or None
If None, dtype will be inferred
copy : boolean, default False, copy input data
"""
_AXIS_NUMBERS = {
'index': 0
}
_AXIS_NAMES = dict((v, k) for k, v in compat.iteritems(_AXIS_NUMBERS))
def __new__(cls, data=None, index=None, dtype=None, name=None,
copy=False):
if data is None:
data = {}
if isinstance(data, MultiIndex):
raise NotImplementedError
if index is not None:
index = _ensure_index(index)
if isinstance(data, Series):
if name is None:
name = data.name
if index is None:
index = data.index
else:
data = data.reindex(index).values
elif isinstance(data, dict):
if index is None:
if isinstance(data, OrderedDict):
index = Index(data)
else:
index = Index(sorted(data))
try:
if isinstance(index, DatetimeIndex):
# coerce back to datetime objects for lookup
data = lib.fast_multiget(data, index.astype('O'),
default=pa.NA)
elif isinstance(index, PeriodIndex):
data = [data.get(i, nan) for i in index]
else:
data = lib.fast_multiget(data, index.values,
default=pa.NA)
except TypeError:
data = [data.get(i, nan) for i in index]
elif isinstance(data, types.GeneratorType):
data = list(data)
elif isinstance(data, (set, frozenset)):
raise TypeError("{0!r} type is unordered"
"".format(data.__class__.__name__))
if dtype is not None:
dtype = np.dtype(dtype)
subarr = _sanitize_array(data, index, dtype, copy,
raise_cast_failure=True)
if not isinstance(subarr, pa.Array):
return subarr
if index is None:
index = _default_index(len(subarr))
# Change the class of the array to be the subclass type.
if index.is_all_dates:
if not isinstance(index, (DatetimeIndex, PeriodIndex)):
index = DatetimeIndex(index)
subarr = subarr.view(TimeSeries)
else:
subarr = subarr.view(Series)
subarr.index = index
subarr.name = name
return subarr
def _make_time_series(self):
# oh boy #2139
self.__class__ = TimeSeries
@classmethod
def from_array(cls, arr, index=None, name=None, copy=False):
"""
Simplified alternate constructor
"""
if copy:
arr = arr.copy()
klass = Series
if index.is_all_dates:
if not isinstance(index, (DatetimeIndex, PeriodIndex)):
index = DatetimeIndex(index)
klass = TimeSeries
result = arr.view(klass)
result.index = index
result.name = name
return result
def __init__(self, data=None, index=None, dtype=None, name=None,
copy=False):
pass
@property
def _can_hold_na(self):
return not is_integer_dtype(self.dtype)
_index = None
index = lib.SeriesIndex()
def __array_finalize__(self, obj):
"""
Gets called after any ufunc or other array operations, necessary
to pass on the index.
"""
self._index = getattr(obj, '_index', None)
self.name = getattr(obj, 'name', None)
def __contains__(self, key):
return key in self.index
def __reduce__(self):
"""Necessary for making this object picklable"""
object_state = list(ndarray.__reduce__(self))
subclass_state = (self.index, self.name)
object_state[2] = (object_state[2], subclass_state)
return tuple(object_state)
def __setstate__(self, state):
"""Necessary for making this object picklable"""
nd_state, own_state = state
ndarray.__setstate__(self, nd_state)
# backwards compat
index, name = own_state[0], None
if len(own_state) > 1:
name = own_state[1]
self.index = _handle_legacy_indexes([index])[0]
self.name = name
# indexers
@property
def axes(self):
return [ self.index ]
@property
def ix(self):
if self._ix is None: # defined in indexing.py; pylint: disable=E0203
self._ix = _SeriesIndexer(self, 'ix')
return self._ix
def _xs(self, key, axis=0, level=None, copy=True):
return self.__getitem__(key)
def _ixs(self, i, axis=0):
"""
Return the i-th value or values in the Series by location
Parameters
----------
i : int, slice, or sequence of integers
Returns
-------
value : scalar (int) or Series (slice, sequence)
"""
try:
return _index.get_value_at(self, i)
except IndexError:
raise
except:
if isinstance(i, slice):
return self[i]
else:
label = self.index[i]
if isinstance(label, Index):
i = _maybe_convert_indices(i, len(self))
return self.reindex(i, takeable=True)
else:
return _index.get_value_at(self, i)
@property
def _is_mixed_type(self):
return False
def _slice(self, slobj, axis=0, raise_on_error=False):
if raise_on_error:
_check_slice_bounds(slobj, self.values)
return self._constructor(self.values[slobj], index=self.index[slobj])
def __getitem__(self, key):
try:
return self.index.get_value(self, key)
except InvalidIndexError:
pass
except KeyError:
if isinstance(key, tuple) and isinstance(self.index, MultiIndex):
# kludge
pass
elif key is Ellipsis:
return self
else:
raise
except Exception:
raise
if com.is_iterator(key):
key = list(key)
# boolean
# special handling of boolean data with NAs stored in object
# arrays. Since we can't represent NA with dtype=bool
if _is_bool_indexer(key):
key = _check_bool_indexer(self.index, key)
return self._get_with(key)
def _get_with(self, key):
# other: fancy integer or otherwise
if isinstance(key, slice):
from pandas.core.indexing import _is_index_slice
idx_type = self.index.inferred_type
if idx_type == 'floating':
indexer = self.ix._convert_to_indexer(key, axis=0)
elif idx_type == 'integer' or _is_index_slice(key):
indexer = key
else:
indexer = self.ix._convert_to_indexer(key, axis=0)
return self._get_values(indexer)
else:
if isinstance(key, tuple):
try:
return self._get_values_tuple(key)
except:
if len(key) == 1:
key = key[0]
if isinstance(key, slice):
return self._get_values(key)
raise
if not isinstance(key, (list, pa.Array)): # pragma: no cover
key = list(key)
if isinstance(key, Index):
key_type = key.inferred_type
else:
key_type = lib.infer_dtype(key)
if key_type == 'integer':
if self.index.inferred_type == 'integer':
return self.reindex(key)
else:
return self._get_values(key)
elif key_type == 'boolean':
return self._get_values(key)
else:
try:
# handle the dup indexing case (GH 4246)
if isinstance(key, (list,tuple)):
return self.ix[key]
return self.reindex(key)
except Exception:
# [slice(0, 5, None)] will break if you convert to ndarray,
# e.g. as requested by np.median
# hack
if isinstance(key[0], slice):
return self._get_values(key)
raise
def _get_values_tuple(self, key):
# mpl hackaround
if any(k is None for k in key):
return self._get_values(key)
if not isinstance(self.index, MultiIndex):
raise ValueError('Can only tuple-index with a MultiIndex')
# If key is contained, would have returned by now
indexer, new_index = self.index.get_loc_level(key)
return Series(self.values[indexer], index=new_index, name=self.name)
def _get_values(self, indexer):
try:
return Series(self.values[indexer], index=self.index[indexer],
name=self.name)
except Exception:
return self.values[indexer]
def get_dtype_counts(self):
return Series({ self.dtype.name : 1 })
def where(self, cond, other=nan, inplace=False):
"""
Return a Series where cond is True; otherwise values are from other
Parameters
----------
cond: boolean Series or array
other: scalar or Series
Returns
-------
wh: Series
"""
if isinstance(cond, Series):
cond = cond.reindex(self.index, fill_value=True)
if not hasattr(cond, 'shape'):
raise ValueError('where requires an ndarray like object for its '
'condition')
if len(cond) != len(self):
raise ValueError('condition must have same length as series')
if cond.dtype != np.bool_:
cond = cond.astype(np.bool_)
ser = self if inplace else self.copy()
if not isinstance(other, (list, tuple, pa.Array)):
ser._set_with(~cond, other)
return None if inplace else ser
if isinstance(other, Series):
other = other.reindex(ser.index)
elif isinstance(other, (tuple,list)):
# try to set the same dtype as ourselves
new_other = np.array(other,dtype=self.dtype)
if not (new_other == np.array(other)).all():
other = np.array(other)
else:
other = new_other
if len(other) != len(ser):
icond = ~cond
# GH 2745
# treat like a scalar
if len(other) == 1:
other = np.array(other[0])
# GH 3235
# match True cond to other
elif len(icond[icond]) == len(other):
dtype, fill_value = _maybe_promote(other.dtype)
new_other = np.empty(len(cond),dtype=dtype)
new_other.fill(fill_value)
new_other[icond] = other
other = new_other
else:
raise ValueError('Length of replacements must equal series length')
change = ser if inplace else None
com._maybe_upcast_putmask(ser,~cond,other,change=change)
return None if inplace else ser
def mask(self, cond):
"""
Returns copy of self whose values are replaced with nan if the
inverted condition is True
Parameters
----------
cond: boolean Series or array
Returns
-------
wh: Series
"""
return self.where(~cond, nan)
def abs(self):
"""
Return an object with absolute value taken. Only applicable to objects
that are all numeric
Returns
-------
abs: type of caller
"""
obj = np.abs(self)
return self._constructor(obj, name=self.name)
def __array_wrap__(self, out, ctx=None):
if (com._np_version_under1p7 and out.dtype.kind == 'm' and
out.dtype != _TD_DTYPE):
out = out.view('i8').astype(_TD_DTYPE)
return pa.Array.__array_wrap__(self, out, ctx)
def __setitem__(self, key, value):
try:
try:
self.index._engine.set_value(self, key, value)
return
except KeyError:
values = self.values
values[self.index.get_loc(key)] = value
return
except KeyError:
if (com.is_integer(key)
and not self.index.inferred_type == 'integer'):
values[key] = value
return
elif key is Ellipsis:
self[:] = value
return
raise KeyError('%s not in this series!' % str(key))
except TypeError as e:
# python 3 type errors should be raised
if 'unorderable' in str(e): # pragma: no cover
raise IndexError(key)
# Could not hash item
except ValueError:
# reassign a null value to iNaT
if com.is_timedelta64_dtype(self.dtype):
if isnull(value):
value = tslib.iNaT
try:
self.index._engine.set_value(self, key, value)
return
except (TypeError):
pass
if _is_bool_indexer(key):
key = _check_bool_indexer(self.index, key)
self.where(~key,value,inplace=True)
else:
self._set_with(key, value)
def _set_with(self, key, value):
# other: fancy integer or otherwise
if isinstance(key, slice):
from pandas.core.indexing import _is_index_slice
if self.index.inferred_type == 'integer' or _is_index_slice(key):
indexer = key
else:
indexer = self.ix._convert_to_indexer(key, axis=0)
return self._set_values(indexer, value)
else:
if isinstance(key, tuple):
try:
self._set_values(key, value)
except Exception:
pass
if not isinstance(key, (list, pa.Array)):
key = list(key)
if isinstance(key, Index):
key_type = key.inferred_type
else:
key_type = lib.infer_dtype(key)
if key_type == 'integer':
if self.index.inferred_type == 'integer':
self._set_labels(key, value)
else:
return self._set_values(key, value)
elif key_type == 'boolean':
self._set_values(key, value)
else:
self._set_labels(key, value)
def _set_labels(self, key, value):
if isinstance(key, Index):
key = key.values
else:
key = _asarray_tuplesafe(key)
indexer = self.index.get_indexer(key)
mask = indexer == -1
if mask.any():
raise ValueError('%s not contained in the index'
% str(key[mask]))
self._set_values(indexer, value)
def _set_values(self, key, value):
values = self.values
values[key] = _index.convert_scalar(values, value)
# help out SparseSeries
_get_val_at = ndarray.__getitem__
def __getslice__(self, i, j):
if i < 0:
i = 0
if j < 0:
j = 0
slobj = slice(i, j)
return self.__getitem__(slobj)
def __setslice__(self, i, j, value):
"""Set slice equal to given value(s)"""
if i < 0:
i = 0
if j < 0:
j = 0
slobj = slice(i, j)
return self.__setitem__(slobj, value)
def astype(self, dtype):
"""
See numpy.ndarray.astype
"""
dtype = np.dtype(dtype)
if dtype == _NS_DTYPE or dtype == _TD_DTYPE:
values = com._possibly_cast_to_datetime(self.values,dtype)
else:
values = com._astype_nansafe(self.values, dtype)
return self._constructor(values, index=self.index, name=self.name,
dtype=values.dtype)
def convert_objects(self, convert_dates=True, convert_numeric=False, copy=True):
"""
Attempt to infer better dtype
Parameters
----------
convert_dates : boolean, default True
if True, attempt to soft convert_dates, if 'coerce', force
conversion (and non-convertibles get NaT)
convert_numeric : boolean, default True
if True attempt to coerce to numbers (including strings),
non-convertibles get NaN
copy : boolean, default True
if True return a copy even if not object dtype
Returns
-------
converted : Series
"""
if self.dtype == np.object_:
return Series(com._possibly_convert_objects(self.values,
convert_dates=convert_dates, convert_numeric=convert_numeric),
index=self.index, name=self.name)
return self.copy() if copy else self
def repeat(self, reps):
"""
See ndarray.repeat
"""
new_index = self.index.repeat(reps)
new_values = self.values.repeat(reps)
return Series(new_values, index=new_index, name=self.name)
def reshape(self, newshape, order='C'):
"""
See numpy.ndarray.reshape
"""
if order not in ['C','F']:
raise TypeError("must specify a tuple / singular length to reshape")
if isinstance(newshape, tuple) and len(newshape) > 1:
return self.values.reshape(newshape, order=order)
else:
return ndarray.reshape(self, newshape, order)
def get(self, label, default=None):
"""
Returns value occupying requested label, default to specified
missing value if not present. Analogous to dict.get
Parameters
----------
label : object
Label value looking for
default : object, optional
Value to return if label not in index
Returns
-------
y : scalar
"""
try:
return self.get_value(label)