forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 27
/
frame.py
2536 lines (2034 loc) · 76.2 KB
/
frame.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
"""
DataFrame
---------
An efficient 2D container for potentially mixed-type time series or other
labeled data series.
Similar to its R counterpart, data.frame, except providing automatic data
alignment and a host of useful data manipulation methods having to do with the
labeling information
"""
# pylint: disable=E1101,E1103
# pylint: disable=W0212,W0231,W0703,W0622
from cStringIO import StringIO
from datetime import datetime
import operator
import sys
import warnings
from numpy import nan
import numpy as np
from pandas.core.common import (isnull, notnull, PandasError, _ensure_index,
_try_sort, _pfixed, _default_index,
_infer_dtype)
from pandas.core.daterange import DateRange
from pandas.core.generic import AxisProperty, NDFrame
from pandas.core.index import Index, NULL_INDEX
from pandas.core.internals import BlockManager, make_block
from pandas.core.series import Series, _is_bool_indexer
import pandas.core.common as common
import pandas.core.datetools as datetools
import pandas._tseries as _tseries
#-------------------------------------------------------------------------------
# Factory helper methods
_arith_doc ="""
Arithmetic method: %s
Parameters
----------
other : Series, DataFrame, or constant
axis : {0, 1, 'index', 'columns'}
For Series input, axis to match Series index on
fill_value : None or float value, default None
Fill missing (NaN) values with this value. If both DataFrame locations are
missing, the result will be missing
Notes
-----
Mismatched indices will be unioned together
Returns
-------
result : DataFrame
"""
def _arith_method(func, name, default_axis='columns'):
def f(self, other, axis=default_axis, fill_value=None):
if isinstance(other, DataFrame): # Another DataFrame
return self._combine_frame(other, func, fill_value)
elif isinstance(other, Series):
if axis is not None:
axis = self._get_axis_name(axis)
if axis == 'index':
return self._combine_match_index(other, func, fill_value)
else:
return self._combine_match_columns(other, func, fill_value)
return self._combine_series_infer(other, func, fill_value)
else:
return self._combine_const(other, func)
f.__name__ = name
f.__doc__ = _arith_doc % name
return f
def comp_method(func, name):
def f(self, other):
if isinstance(other, DataFrame): # Another DataFrame
return self._compare_frame(other, func)
elif isinstance(other, Series):
return self._combine_series_infer(other, func)
else:
return self._combine_const(other, func)
f.__name__ = name
f.__doc__ = 'Wrapper for comparison method %s' % name
return f
#-------------------------------------------------------------------------------
# DataFrame class
class DataFrame(NDFrame):
"""
Homogenously indexed table with named columns, with intelligent arithmetic
operations, slicing, reindexing, aggregation, etc. Can function
interchangeably as a dictionary.
Parameters
----------
data : numpy ndarray or dict of sequence-like objects
Dict can contain Series, arrays, or list-like objects
Constructor can understand various kinds of inputs
index : Index or array-like
Index to use for resulting frame (optional if provided dict of Series)
columns : Index or array-like
Required if data is ndarray
dtype : dtype, default None (infer)
Data type to force
copy : boolean, default False
Copy data from inputs. Only affects DataFrame / 2d ndarray input
Examples
--------
>>> d = {'col1' : ts1, 'col2' : ts2}
>>> df = DataFrame(data=d, index=someIndex)
"""
_auto_consolidate = True
_AXIS_NUMBERS = {
'index' : 0,
'columns' : 1
}
_AXIS_NAMES = dict((v, k) for k, v in _AXIS_NUMBERS.iteritems())
def __init__(self, data=None, index=None, columns=None, dtype=None,
copy=False):
if data is None:
data = {}
if isinstance(data, DataFrame):
data = data._data
if isinstance(data, BlockManager):
# do not copy BlockManager unless explicitly done
mgr = data
if copy and dtype is None:
mgr = mgr.copy()
elif dtype is not None:
# no choice but to copy
mgr = mgr.cast(dtype)
elif isinstance(data, dict):
mgr = self._init_dict(data, index, columns, dtype=dtype)
elif isinstance(data, np.ndarray):
if data.dtype.names:
data_columns, data = _rec_to_dict(data)
if columns is None:
columns = data_columns
mgr = self._init_dict(data, index, columns, dtype=dtype)
else:
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
copy=copy)
elif isinstance(data, list):
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
copy=copy)
else:
raise PandasError('DataFrame constructor not properly called!')
self._data = mgr
def _init_dict(self, data, index, columns, dtype=None):
"""
Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases.
Somehow this got outrageously complicated
"""
from pandas.core.internals import form_blocks
# prefilter if columns passed
if columns is not None:
columns = _ensure_index(columns)
data = dict((k, v) for k, v in data.iteritems() if k in columns)
# figure out the index, if necessary
if index is None:
index = extract_index(data)
# don't force copy because getting jammed in an ndarray anyway
homogenized = _homogenize_series(data, index, dtype)
# segregates dtypes and forms blocks matching to columns
blocks, columns = form_blocks(homogenized, index, columns)
# consolidate for now
mgr = BlockManager(blocks, [columns, index])
return mgr.consolidate()
def _init_ndarray(self, values, index, columns, dtype=None,
copy=False):
values = _prep_ndarray(values, copy=copy)
if dtype is not None:
try:
values = values.astype(dtype)
except Exception:
raise ValueError('failed to cast to %s' % dtype)
N, K = values.shape
if index is None:
index = _default_index(N)
if columns is None:
columns = _default_index(K)
columns = _ensure_index(columns)
block = make_block(values.T, columns, columns)
return BlockManager([block], [columns, index])
def astype(self, dtype):
"""
Cast DataFrame to input numpy.dtype
Parameters
----------
dtype : numpy.dtype or Python type
Returns
-------
casted : DataFrame
"""
return self._constructor(self._data, dtype=dtype)
def _wrap_array(self, arr, axes, copy=False):
index, columns = axes
return self._constructor(arr, index=index, columns=columns, copy=copy)
@property
def axes(self):
return [self.index, self.columns]
@property
def _constructor(self):
return DataFrame
#----------------------------------------------------------------------
# Class behavior
def __nonzero__(self):
# e.g. "if frame: ..."
return len(self.columns) > 0 and len(self.index) > 0
def __repr__(self):
"""
Return a string representation for a particular DataFrame
"""
buf = StringIO()
if len(self.index) < 500 and len(self.columns) < 10:
self.toString(buf=buf)
else:
self.info(buf=buf)
return buf.getvalue()
def __iter__(self):
"""
Iterate over columns of the frame.
"""
return iter(self.columns)
def iteritems(self):
"""Iterator over (column, series) pairs"""
series = self._series
return ((k, series[k]) for k in self.columns)
def __len__(self):
"""
Returns number of columns/Series inside
"""
return len(self.index)
def __contains__(self, key):
"""
True if DataFrame has this column
"""
return key in self.columns
def copy(self):
"""
Make a copy of this DataFrame
"""
return self._constructor(self._data.copy())
#----------------------------------------------------------------------
# Arithmetic methods
add = _arith_method(operator.add, 'add')
mul = _arith_method(operator.mul, 'multiply')
sub = _arith_method(operator.sub, 'subtract')
div = _arith_method(operator.div, 'divide')
radd = _arith_method(operator.add, 'add')
rmul = _arith_method(operator.mul, 'multiply')
rsub = _arith_method(lambda x, y: y - x, 'subtract')
rdiv = _arith_method(lambda x, y: y / x, 'divide')
__add__ = _arith_method(operator.add, '__add__', default_axis=None)
__sub__ = _arith_method(operator.sub, '__sub__', default_axis=None)
__mul__ = _arith_method(operator.mul, '__mul__', default_axis=None)
__div__ = _arith_method(operator.div, '__div__', default_axis=None)
__truediv__ = _arith_method(operator.truediv, '__truediv__',
default_axis=None)
__pow__ = _arith_method(operator.pow, '__pow__', default_axis=None)
__radd__ = _arith_method(operator.add, '__radd__', default_axis=None)
__rmul__ = _arith_method(operator.mul, '__rmul__', default_axis=None)
__rsub__ = _arith_method(lambda x, y: y - x, '__rsub__', default_axis=None)
__rdiv__ = _arith_method(lambda x, y: y / x, '__rdiv__', default_axis=None)
__rtruediv__ = _arith_method(lambda x, y: y / x, '__rtruediv__',
default_axis=None)
__rpow__ = _arith_method(lambda x, y: y ** x, '__rpow__', default_axis=None)
def __neg__(self):
return self * -1
#----------------------------------------------------------------------
# Comparison methods
__eq__ = comp_method(operator.eq, '__eq__')
__ne__ = comp_method(operator.ne, '__ne__')
__lt__ = comp_method(operator.lt, '__lt__')
__gt__ = comp_method(operator.gt, '__gt__')
__le__ = comp_method(operator.le, '__le__')
__ge__ = comp_method(operator.ge, '__ge__')
#----------------------------------------------------------------------
# IO methods (to / from other formats)
def toDict(self):
"""
Convert DataFrame to nested dictionary (non-pandas)
Return
------
nested dict mapping: {column -> index -> value}
"""
return dict((k, v.toDict()) for k, v in self.iteritems())
@classmethod
def from_records(cls, data, indexField=None):
"""
Convert structured or record ndarray to DataFrame
Parameters
----------
input : NumPy structured array
Returns
-------
DataFrame
"""
if not data.dtype.names:
raise Exception('Input was not a structured array!')
columns, sdict = _rec_to_dict(data)
if indexField is not None:
index = sdict.pop(indexField)
columns.remove(indexField)
else:
index = np.arange(len(data))
return cls(sdict, index=index, columns=columns)
def to_records(self, index=True):
"""
Convert DataFrame to record array. Index will be put in the
'index' field of the record array.
Returns
-------
y : recarray
"""
if index:
arrays = [self.index] + [self[c] for c in self.columns]
names = ['index'] + list(self.columns)
else:
arrays = [self[c] for c in self.columns]
names = list(self.columns)
return np.rec.fromarrays(arrays, names=names)
@classmethod
def fromcsv(cls, path, header=0, delimiter=',', index_col=0):
"""
Read delimited file into DataFrame
Parameters
----------
path : string
header : int, default 0
Row to use at header (skip prior rows)
delimiter : string, default ','
index_col : int
Column to use for index
Notes
-----
Will attempt to convert index to datetimes for time series
data. Uses numpy.genfromtxt to do the actual parsing into
ndarray
Returns
-------
y : DataFrame or DataFrame
"""
from pandas.io.parsers import read_table
df = read_table(path, header=header, sep=delimiter,
index_col=index_col)
return df
def to_sparse(self, fill_value=None, kind='block'):
"""
Convert to SparseDataFrame
Parametpers
----------
fill_value : float, default NaN
kind : {'block', 'integer'}
Returns
-------
y : SparseDataFrame
"""
from pandas.core.sparse import SparseDataFrame
return SparseDataFrame(self._series, index=self.index,
default_kind=kind, default_fill_value=fill_value)
def toCSV(self, path, nanRep='', cols=None, header=True,
index=True, mode='wb'):
"""
Write the DataFrame to a CSV file
Parameters
----------
path : string
File path
nanRep : string, default ''
Missing data rep'n
cols : sequence, optional
header : boolean, default True
Write out column names
index : boolean, default True
Write row names (index)
"""
f = open(path, mode)
if cols is None:
cols = self.columns
series = self._series
if header:
joined_cols = ','.join([str(c) for c in cols])
if index:
# this could be dangerous
f.write('index,%s' % joined_cols)
else:
f.write(joined_cols)
f.write('\n')
for idx in self.index:
if index:
f.write(str(idx))
for i, col in enumerate(cols):
val = series[col].get(idx)
if isnull(val):
val = nanRep
else:
val = str(val)
if i > 0 or index:
f.write(',%s' % val)
else:
f.write('%s' % val)
f.write('\n')
f.close()
def toString(self, buf=sys.stdout, columns=None, colSpace=None,
nanRep='NaN', formatters=None, float_format=None):
from pandas.core.common import _format, adjoin
if colSpace is None:
def _myformat(v):
return _format(v, nanRep=nanRep,
float_format=float_format)
else:
def _myformat(v):
return _pfixed(v, colSpace, nanRep=nanRep,
float_format=float_format)
def _stringify(series):
return map(_myformat, series)
if columns is None:
columns = self.columns
else:
columns = [c for c in columns if c in self]
if len(columns) == 0 or len(self.index) == 0:
print >> buf, 'Empty %s' % type(self).__name__
print >> buf, repr(self.index)
else:
str_index = [''] + [str(x) for x in self.index]
stringified = [[' %s' % c] + _stringify(self[c]) for c in columns]
print >> buf, adjoin(2, str_index, *stringified)
def info(self, verbose=True, buf=sys.stdout):
"""
Concise summary of a DataFrame, used in __repr__ when very large.
"""
print >> buf, str(type(self))
print >> buf, self.index.summary()
if len(self.columns) == 0:
print >> buf, 'Empty %s' % type(self).__name__
return
cols = self.columns
if verbose:
print >> buf, 'Data columns:'
space = max([len(str(k)) for k in self.columns]) + 4
col_counts = []
counts = self.count()
assert(len(cols) == len(counts))
for col, count in counts.iteritems():
col_counts.append('%s%d non-null values' %
(_put_str(col, space), count))
print >> buf, '\n'.join(col_counts)
else:
if len(cols) <= 2:
print >> buf, 'Columns: %s' % repr(cols)
else:
print >> buf, 'Columns: %s to %s' % (cols[0], cols[-1])
counts = self._get_dtype_counts()
dtypes = ['%s(%d)' % k for k in sorted(counts.iteritems())]
buf.write('dtypes: %s' % ', '.join(dtypes))
def _get_dtype_counts(self):
counts = {}
for _, series in self.iteritems():
if series.dtype in counts:
counts[series.dtype] += 1
else:
counts[series.dtype] = 1
return counts
#----------------------------------------------------------------------
# properties for index and columns
# reference underlying BlockManager
columns = AxisProperty(0)
index = AxisProperty(1)
def as_matrix(self, columns=None):
"""
Convert the frame to its Numpy-array matrix representation
Columns are presented in sorted order unless a specific list
of columns is provided.
"""
self._consolidate_inplace()
return self._data.as_matrix(columns).T
values = property(fget=as_matrix)
def transpose(self):
"""
Returns a DataFrame with the rows/columns switched. Copy of data is not
made by default
"""
return self._constructor(data=self.values.T, index=self.columns,
columns=self.index, copy=False)
T = property(transpose)
#----------------------------------------------------------------------
# Picklability
def __getstate__(self):
return self._data
def __setstate__(self, state):
# old DataFrame pickle
if isinstance(state, BlockManager):
self._data = state
elif isinstance(state[0], dict): # pragma: no cover
self._unpickle_frame_compat(state)
else: # pragma: no cover
# old pickling format, for compatibility
self._unpickle_matrix_compat(state)
def _unpickle_frame_compat(self, state): # pragma: no cover
from pandas.core.common import _unpickle_array
if len(state) == 2: # pragma: no cover
series, idx = state
columns = sorted(series)
else:
series, cols, idx = state
columns = _unpickle_array(cols)
index = _unpickle_array(idx)
self._data = self._init_dict(series, index, columns, None)
def _unpickle_matrix_compat(self, state): # pragma: no cover
from pandas.core.common import _unpickle_array
# old unpickling
(vals, idx, cols), object_state = state
index = _unpickle_array(idx)
dm = DataFrame(vals, index=index, columns=_unpickle_array(cols),
copy=False)
if object_state is not None:
ovals, _, ocols = object_state
objects = DataFrame(ovals, index=index,
columns=_unpickle_array(ocols),
copy=False)
dm = dm.join(objects)
self._data = dm._data
#----------------------------------------------------------------------
# Private helper methods
def _intersect_index(self, other):
common_index = self.index
if not common_index.equals(other.index):
common_index = common_index.intersection(other.index)
return common_index
def _intersect_columns(self, other):
common_cols = self.columns
if not common_cols.equals(other.columns):
common_cols = common_cols.intersection(other.columns)
return common_cols
#----------------------------------------------------------------------
# Array interface
def __array__(self):
return self.values
def __array_wrap__(self, result):
return self._constructor(result, index=self.index, columns=self.columns,
copy=False)
#----------------------------------------------------------------------
# getitem/setitem related
def __getitem__(self, item):
"""
Retrieve column, slice, or subset from DataFrame.
Possible inputs
---------------
single value : retrieve a column as a Series
slice : reindex to indices specified by slice
boolean vector : like slice but more general, reindex to indices
where the input vector is True
Examples
--------
column = dm['A']
dmSlice = dm[:20] # First 20 rows
dmSelect = dm[dm.count(axis=1) > 10]
Notes
-----
This is a magic method. Do NOT call explicity.
"""
if isinstance(item, slice):
new_data = self._data.get_slice(item, axis=1)
return self._constructor(new_data)
elif isinstance(item, np.ndarray):
if len(item) != len(self.index):
raise ValueError('Item wrong length %d instead of %d!' %
(len(item), len(self.index)))
# also raises Exception if object array with NA values
if _is_bool_indexer(item):
item = np.asarray(item, dtype=bool)
new_index = self.index[item]
return self.reindex(new_index)
else:
values = self._data.get(item)
return Series(values, index=self.index)
def __setitem__(self, key, value):
"""
Add series to DataFrame in specified column.
If series is a numpy-array (not a Series/TimeSeries), it must be the
same length as the DataFrame's index or an error will be thrown.
Series/TimeSeries will be conformed to the DataFrame's index to
ensure homogeneity.
"""
# Array
if isinstance(key, DataFrame):
if not (key.index.equals(self.index) and
key.columns.equals(self.columns)):
raise PandasError('Can only index with like-indexed '
'DataFrame objects')
self._boolean_set(key, value)
else:
self._set_item(key, value)
def _boolean_set(self, key, value):
mask = key.values
if mask.dtype != np.bool_:
raise ValueError('Must pass DataFrame with boolean values only')
if self._data.is_mixed_dtype():
raise ValueError('Boolean setting not possible on mixed-type frame')
self.values[mask] = value
def insert(self, loc, column, value):
"""
Insert column into DataFrame at specified location. Raises Exception if
column is already contained in the DataFrame
Parameters
----------
loc : int
Must have 0 <= loc <= len(columns)
column : object
value : int, Series, or array-like
"""
value = self._sanitize_column(value)
value = np.atleast_2d(value) # is this a hack?
self._data.insert(loc, column, value)
def _set_item(self, key, value):
"""
Add series to DataFrame in specified column.
If series is a numpy-array (not a Series/TimeSeries), it must be the
same length as the DataFrame's index or an error will be thrown.
Series/TimeSeries will be conformed to the DataFrame's index to
ensure homogeneity.
"""
value = self._sanitize_column(value)
value = np.atleast_2d(value) # is this a hack?
self._data.set(key, value)
def _sanitize_column(self, value):
# Need to make sure new columns (which go into the BlockManager as new
# blocks) are always copied
if hasattr(value, '__iter__'):
if isinstance(value, Series):
if value.index.equals(self.index):
# copy the values
value = value.values.copy()
else:
value = value.reindex(self.index).values
else:
assert(len(value) == len(self.index))
if not isinstance(value, np.ndarray):
value = np.array(value)
if value.dtype.type == np.str_:
value = np.array(value, dtype=object)
else:
value = value.copy()
else:
value = np.repeat(value, len(self.index))
return value
def __delitem__(self, key):
"""
Delete column from DataFrame
"""
self._data.delete(key)
def pop(self, item):
"""
Return column and drop from frame. Raise KeyError if not
found.
Returns
-------
Series
"""
result = self[item]
del self[item]
return result
# to support old APIs
@property
def _series(self):
return self._data.get_series_dict()
def xs(self, key, copy=True):
"""
Returns a row from the DataFrame as a Series object.
Parameters
----------
key : some index contained in the index
Returns
-------
xs : Series
"""
if key not in self.index:
raise Exception('No cross-section for %s' % key)
self._consolidate_inplace()
values = self._data.xs(key, axis=1, copy=copy)
return Series(values.as_matrix(), index=self.columns)
#----------------------------------------------------------------------
# Reindexing
def reindex(self, index=None, columns=None, method=None):
"""
Reindex data inside, optionally filling according to some rule.
Parameters
----------
index : array-like, optional
preferably an Index object (to avoid duplicating data)
columns : array-like, optional
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
Returns
-------
y : same type as calling instance
"""
self._consolidate_inplace()
frame = self
if index is not None:
index = _ensure_index(index)
frame = frame._reindex_index(index, method)
if columns is not None:
columns = _ensure_index(columns)
frame = frame._reindex_columns(columns)
return frame
def _reindex_index(self, new_index, method):
if new_index is self.index:
return self.copy()
new_data = self._data.reindex_axis(new_index, method, axis=1)
return self._constructor(new_data)
def _reindex_columns(self, new_columns):
new_data = self._data.reindex_items(new_columns)
return self._constructor(new_data)
def reindex_like(self, other, method=None):
"""
Reindex DataFrame to match indices of another DataFrame
Parameters
----------
other : DataFrame
method : string or None
Notes
-----
Like calling s.reindex(index=other.index, columns=other.columns)
Returns
-------
reindexed : DataFrame
"""
# todo: object columns
return self.reindex(index=other.index, columns=other.columns,
method=method)
#----------------------------------------------------------------------
# Reindex-based selection methods
def filter(self, items=None, like=None, regex=None):
"""
Restrict frame's columns to set of items or wildcard
Parameters
----------
items : list-like
List of columns to restrict to (must not all be present)
like : string
Keep columns where "arg in col == True"
regex : string (regular expression)
Keep columns with re.search(regex, col) == True
Notes
-----
Arguments are mutually exclusive!
Returns
-------
DataFrame with filtered columns
"""
import re
if items is not None:
return self.reindex(columns=[r for r in items if r in self])
elif like:
return self.select(lambda x: like in x, axis=1)
elif regex:
matcher = re.compile(regex)
return self.select(lambda x: matcher.match(x) is not None, axis=1)
else:
raise ValueError('items was None!')
def select(self, crit, axis=0):
"""
Return data corresponding to axis labels matching criteria
Parameters
----------
crit : function
To be called on each index (label). Should return True or False
axis : {0, 1}
Returns
-------
selection : DataFrame
"""
return self._select_generic(crit, axis=axis)
def dropEmptyRows(self, specificColumns=None):
"""
Return DataFrame with rows omitted containing ALL NaN values
for optionally specified set of columns.
Parameters
----------
specificColumns : list-like, optional keyword
Columns to consider in removing NaN values. As a typical
application, you might provide the list of the columns involved in
a regression to exlude all the missing data in one shot.
Returns
-------
This DataFrame with rows containing any NaN values deleted
"""
if specificColumns:
theCount = self.filter(items=specificColumns).count(axis=1)
else:
theCount = self.count(axis=1)
return self.reindex(self.index[theCount != 0])
def dropIncompleteRows(self, specificColumns=None, minObs=None):
"""
Return DataFrame with rows omitted containing ANY NaN values for
optionally specified set of columns.
Parameters
----------
minObs : int or None (default)
Instead of requiring all the columns to have observations, require
only minObs observations
specificColumns : list-like, optional keyword
Columns to consider in removing NaN values. As a typical
application, you might provide the list of the columns involved in
a regression to exlude all the missing data in one shot.
Returns
-------
This DataFrame with rows containing any NaN values deleted
"""
N = len(self.columns)
if specificColumns:
colSet = set(specificColumns)
intersection = set(self.columns) & colSet
N = len(intersection)