forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframe.py
3209 lines (2616 loc) · 99 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 StringIO import StringIO
import csv
import operator
import sys
from numpy import nan
import numpy as np
from pandas.core.common import (isnull, notnull, PandasError,
_try_sort, _pfixed, _default_index,
_infer_dtype, _stringify, _maybe_upcast)
from pandas.core.daterange import DateRange
from pandas.core.generic import AxisProperty, NDFrame
from pandas.core.index import Index, MultiIndex, NULL_INDEX, _ensure_index
from pandas.core.indexing import _NDFrameIndexer, _maybe_droplevels
from pandas.core.internals import BlockManager, make_block, form_blocks
from pandas.core.series import Series, _is_bool_indexer
from pandas.util import py3compat
import pandas.core.common as common
import pandas.core.datetools as datetools
import pandas._tseries as lib
#----------------------------------------------------------------------
# Factory helper methods
_arith_doc = """
Binary operator %s with support to substitute a fill_value for missing data in
one of the inputs
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):
return self._combine_series(other, func, fill_value, axis)
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):
_auto_consolidate = True
_verbose_info = True
_het_axis = 1
_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):
"""Two-dimensional size-mutable, potentially heterogeneous tabular data
structure with labeled axes (rows and columns). Arithmetic operations
align on both row and column labels. Can be thought of as a dict-like
container for Series objects. The primary pandas data structure
Parameters
----------
data : numpy ndarray (structured or homogeneous), dict, or DataFrame
Dict can contain Series, arrays, constants, or list-like objects
index : Index or array-like
Index to use for resulting frame. Will default to np.arange(n) if no
indexing information part of input data and no index provided
columns : Index or array-like
Will default to np.arange(n) if not column labels provided
dtype : dtype, default None
Data type to force, otherwise infer
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=index)
>>> df2 = DataFrame(np.random.randn(10, 5))
>>> df3 = DataFrame(np.random.randn(10, 5),
columns=['a', 'b', 'c', 'd', 'e'])
"""
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.astype(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
self._series_cache = {}
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.
"""
# 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)
else:
columns = Index(_try_sort(data.keys()))
# figure out the index, if necessary
if index is None:
index = extract_index(data)
else:
index = _ensure_index(index)
# don't force copy because getting jammed in an ndarray anyway
homogenized = _homogenize(data, index, columns, dtype)
# from BlockManager perspective
axes = [columns, index]
# segregates dtypes and forms blocks matching to columns
blocks = form_blocks(homogenized, axes)
# consolidate for now
mgr = BlockManager(blocks, axes)
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 _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
# Fancy indexing
_ix = None
@property
def ix(self):
if self._ix is None:
self._ix = _NDFrameIndexer(self)
return self._ix
@property
def shape(self):
return (len(self.index), len(self.columns))
#----------------------------------------------------------------------
# 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.to_string(buf=buf)
else:
self.info(buf=buf, verbose=self._verbose_info)
return buf.getvalue()
def __iter__(self):
"""
Iterate over columns of the frame.
"""
return iter(self.columns)
def iteritems(self):
"""Iterator over (column, series) pairs"""
return ((k, self[k]) for k in self.columns)
iterkv = iteritems
if py3compat.PY3:
items = iteritems
def __len__(self):
"""Returns length of index"""
return len(self.index)
def __contains__(self, key):
"""True if DataFrame has this column"""
return key in self.columns
#----------------------------------------------------------------------
# Arithmetic methods
add = _arith_method(operator.add, 'add')
mul = _arith_method(operator.mul, 'multiply')
sub = _arith_method(operator.sub, 'subtract')
div = _arith_method(lambda x, y: x / y, '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)
__truediv__ = _arith_method(operator.truediv, '__truediv__',
default_axis=None)
__floordiv__ = _arith_method(operator.floordiv, '__floordiv__',
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)
__rtruediv__ = _arith_method(lambda x, y: y / x, '__rtruediv__',
default_axis=None)
__rfloordiv__ = _arith_method(lambda x, y: y // x, '__rfloordiv__',
default_axis=None)
__rpow__ = _arith_method(lambda x, y: y ** x, '__rpow__',
default_axis=None)
# Python 2 division methods
if not py3compat.PY3:
__div__ = _arith_method(operator.div, '__div__', default_axis=None)
__rdiv__ = _arith_method(lambda x, y: y / x, '__rdiv__', 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 to_dict(self):
"""
Convert DataFrame to nested dictionary
Returns
-------
result : dict like {column -> {index -> value}}
"""
return dict((k, v.to_dict()) for k, v in self.iteritems())
@classmethod
def from_records(cls, data, index=None, exclude=None):
"""
Convert structured or record ndarray to DataFrame
Parameters
----------
data : NumPy structured array
index : string, list of fields, array-like
Field of array to use as the index, alternately a specific set of
input labels to use
Returns
-------
df : DataFrame
"""
columns, sdict = _rec_to_dict(data)
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
for col in exclude:
del sdict[col]
columns.remove(col)
if index is not None:
if isinstance(index, basestring):
result_index = sdict.pop(index)
columns.remove(index)
else:
try:
arrays = []
for field in index:
arrays.append(sdict[field])
for field in index:
del sdict[field]
columns.remove(field)
result_index = MultiIndex.from_arrays(arrays)
except Exception:
result_index = index
else:
result_index = np.arange(len(data))
return cls(sdict, index=result_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 if requested
Parameters
----------
index : boolean, default True
Include index in resulting record array, stored in 'index' field
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 from_csv(cls, path, header=0, delimiter=',', index_col=0,
parse_dates=True):
"""
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 or sequence, default 0
Column to use for index. If a sequence is given, a MultiIndex
is used.
Notes
-----
Will attempt to convert index to datetimes for time series
data. Use read_table for more options
Returns
-------
y : DataFrame or DataFrame
"""
from pandas.io.parsers import read_table
return read_table(path, header=header, sep=delimiter,
parse_dates=parse_dates, index_col=index_col)
def to_sparse(self, fill_value=None, kind='block'):
"""
Convert to SparseDataFrame
Parameters
----------
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 to_csv(self, path, nanRep='', cols=None, header=True,
index=True, index_label=None, mode='w'):
"""
Write DataFrame to a comma-separated values (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)
index_label : string or sequence, default None
Column label for index column(s) if desired. If None is given, and
`header` and `index` are True, then the index names are used. A
sequence should be given if the DataFrame uses MultiIndex.
mode : Python write mode, default 'w'
"""
f = open(path, mode)
csvout = csv.writer(f, lineterminator='\n')
if cols is None:
cols = self.columns
series = self._series
if header:
if index:
# should write something for index label
if index_label is None:
if isinstance(self.index, MultiIndex):
index_label = []
for i, name in enumerate(self.index.names):
if name is None:
name = 'level_%d' % i
index_label.append(name)
else:
if self.index.name is None:
index_label = self.index.name
if index_label is None:
index_label = ['index']
elif not isinstance(index_label, (list, tuple, np.ndarray)):
# given a string for a DF with Index
index_label = [index_label]
csvout.writerow(list(index_label) + list(cols))
else:
csvout.writerow(cols)
nlevels = getattr(self.index, 'nlevels', 1)
for idx in self.index:
row_fields = []
if index:
if nlevels == 1:
row_fields = [idx]
else: # handle MultiIndex
row_fields = list(idx)
for i, col in enumerate(cols):
val = series[col].get(idx)
if isnull(val):
val = nanRep
row_fields.append(val)
csvout.writerow(row_fields)
f.close()
def to_string(self, buf=None, columns=None, colSpace=None,
nanRep='NaN', formatters=None, float_format=None,
sparsify=True):
from pandas.core.common import _format, adjoin
return_ = False
if buf is None: # pragma: no cover
buf = StringIO()
return_ = True
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)
if formatters is None:
formatters = {}
def _format_col(col):
formatter = formatters.get(col, _myformat)
return [formatter(x) for x in self[col]]
if columns is None:
columns = self.columns
else:
columns = [c for c in columns if c in self]
to_write = []
if len(columns) == 0 or len(self.index) == 0:
to_write.append('Empty %s' % type(self).__name__)
to_write.append(repr(self.index))
else:
(str_index,
str_columns) = self._get_formatted_labels(sparsify=sparsify)
stringified = [str_columns[i] + _format_col(c)
for i, c in enumerate(columns)]
to_write.append(adjoin(1, str_index, *stringified))
for s in to_write:
if isinstance(s, unicode):
to_write = [unicode(s) for s in to_write]
break
for s in to_write:
print >> buf, s
if return_:
return buf.getvalue()
def _get_formatted_labels(self, sparsify=True):
from pandas.core.index import _sparsify
if isinstance(self.index, MultiIndex):
fmt_index = self.index.format(sparsify=sparsify)
else:
fmt_index = self.index.format()
if isinstance(self.columns, MultiIndex):
fmt_columns = self.columns.format(sparsify=False, adjoin=False)
str_columns = zip(*[[' %s' % y for y in x]
for x in zip(*fmt_columns)])
if sparsify:
str_columns = _sparsify(str_columns)
str_columns = [list(x) for x in zip(*str_columns)]
str_index = [''] * self.columns.nlevels + fmt_index
else:
str_columns = [[' %s' % x] for x in self.columns.format()]
str_index = [''] + fmt_index
return str_index, str_columns
def info(self, verbose=True, buf=None):
"""
Concise summary of a DataFrame, used in __repr__ when very large.
Parameters
----------
verbose : boolean, default True
If False, don't print column count summary
buf : writable buffer, defaults to sys.stdout
"""
if buf is None: # pragma: no cover
buf = sys.stdout
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, unicode('Data columns:')
space = max([len(_stringify(k)) for k in self.columns]) + 4
col_counts = []
counts = self.count()
assert(len(cols) == len(counts))
for col, count in counts.iteritems():
colstr = _stringify(col)
col_counts.append('%s%d non-null values' %
(_put_str(colstr, space), count))
print >> buf, unicode('\n'.join(col_counts))
else:
if len(cols) <= 2:
print >> buf, unicode('Columns: %s' % repr(cols))
else:
print >> buf, unicode('Columns: %s to %s'
% (_stringify(cols[0]),
_stringify(cols[-1])))
counts = self.get_dtype_counts()
dtypes = ['%s(%d)' % k for k in sorted(counts.iteritems())]
buf.write(u'dtypes: %s' % ', '.join(dtypes))
@property
def dtypes(self):
return self.apply(lambda x: x.dtype)
def get_dtype_counts(self):
counts = {}
for _, series in self.iterkv():
if series.dtype in counts:
counts[series.dtype] += 1
else:
counts[series.dtype] = 1
return Series(counts)
#----------------------------------------------------------------------
# properties for index and columns
def _get_columns(self):
return self._data.axes[0]
def _set_columns(self, value):
self._data.set_axis(0, value)
self._series_cache.clear()
columns = property(fset=_set_columns, fget=_get_columns)
# reference underlying BlockManager
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.
Parameters
----------
columns : array-like
Specific column order
Returns
-------
values : ndarray
If the DataFrame is heterogeneous and contains booleans or objects,
the result will be of dtype=object
"""
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. If the DataFrame is
homogeneously-typed, the data is not copied
"""
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)
self._series_cache = {}
# legacy pickle formats
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, dtype=None):
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, key):
# slice rows
if isinstance(key, slice):
new_data = self._data.get_slice(key, axis=1)
return self._constructor(new_data)
# either boolean or fancy integer index
elif isinstance(key, np.ndarray):
if len(key) != len(self.index):
raise ValueError('Item wrong length %d instead of %d!' %
(len(key), len(self.index)))
# also raises Exception if object array with NA values
if _is_bool_indexer(key):
key = np.asarray(key, dtype=bool)
new_index = self.index[key]
return self.reindex(new_index)
elif isinstance(self.columns, MultiIndex):
return self._getitem_multilevel(key)
else:
return self._getitem_single(key)
def _slice(self, slobj, axis=0):
if axis == 0:
mgr_axis = 1
else:
mgr_axis = 0
new_data = self._data.get_slice(slobj, axis=mgr_axis)
return self._constructor(new_data)
def _getitem_multilevel(self, key):
loc = self.columns.get_loc(key)
if isinstance(loc, (slice, np.ndarray)):
new_columns = self.columns[loc]
result_columns = _maybe_droplevels(new_columns, key)
if self._is_mixed_type:
result = self.reindex(columns=new_columns)
result.columns = result_columns
else:
new_values = self.values[:, loc]
result = DataFrame(new_values, index=self.index,
columns=result_columns)
return result
else:
return self._getitem_single(key)
def _getitem_single(self, key):
res = self._series_cache.get(key)
if res is not None:
return res
values = self._data.get(key)
res = Series(values, index=self.index, name=key)
self._series_cache[key] = res
return res
def __getattr__(self, name):
"""After regular attribute access, try looking up the name of a column.
This allows simpler access to columns for interactive use."""
if name in self.columns:
return self[name]
raise AttributeError("'%s' object has no attribute '%s'" % \
(type(self).__name__, name))
def __setitem__(self, key, value):
# support boolean setting with DataFrame input, e.g.
# df[df > df2] = 0
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:
# set column
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('Cannot do boolean setting on mixed-type frame')
if isinstance(value, DataFrame):
assert(value._indexed_same(self))
np.putmask(self.values, mask, value.values)
else:
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)
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)
self._data.set(key, value)
try:
del self._series_cache[key]
except KeyError:
pass
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__') and not isinstance(value, basestring):
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)
try:
del self._series_cache[key]
except KeyError:
pass
def pop(self, item):
"""
Return column and drop from frame. Raise KeyError if not found.
Returns
-------
column : 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, axis=0, copy=True):
"""
Returns a cross-section (row or column) from the DataFrame as a Series
object. Defaults to returning a row (axis 0)
Parameters
----------
key : object
Some label contained in the index, or partially in a MultiIndex
axis : int, default 0
Axis to retrieve cross-section on
copy : boolean, default True
Whether to make a copy of the data
Returns
-------
xs : Series
"""