forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathframe.py
5176 lines (4341 loc) · 183 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
import operator
import sys
import collections
import warnings
import types
from numpy import nan as NA
import numpy as np
import numpy.ma as ma
from pandas.core.common import (isnull, notnull, PandasError, _try_sort,
_default_index, _maybe_upcast, _is_sequence,
_infer_dtype_from_scalar, _values_from_object,
_coerce_to_dtypes, _DATELIKE_DTYPES, is_list_like)
from pandas.core.generic import NDFrame
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import (_maybe_droplevels,
_convert_to_index_sliceable,
_check_bool_indexer, _maybe_convert_indices)
from pandas.core.internals import (BlockManager,
create_block_manager_from_arrays,
create_block_manager_from_blocks)
from pandas.core.series import Series, _radd_compat
import pandas.computation.expressions as expressions
from pandas.computation.eval import eval as _eval
from pandas.computation.expr import _ensure_scope
from pandas.compat.scipy import scoreatpercentile as _quantile
from pandas.compat import(range, zip, lrange, lmap, lzip, StringIO, u,
OrderedDict, raise_with_traceback)
from pandas import compat
from pandas.util.terminal import get_terminal_size
from pandas.util.decorators import deprecate, Appender, Substitution
from pandas.tseries.period import PeriodIndex
from pandas.tseries.index import DatetimeIndex
import pandas.core.algorithms as algos
import pandas.core.datetools as datetools
import pandas.core.common as com
import pandas.core.format as fmt
import pandas.core.nanops as nanops
import pandas.lib as lib
import pandas.algos as _algos
from pandas.core.config import get_option
#----------------------------------------------------------------------
# Docstring templates
_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
level : int or name
Broadcast across a level, matching Index values on the
passed MultiIndex level
Notes
-----
Mismatched indices will be unioned together
Returns
-------
result : DataFrame
"""
_stat_doc = """
Return %(name)s over requested axis.
%(na_action)s
Parameters
----------
axis : {0, 1}
0 for row-wise, 1 for column-wise
skipna : boolean, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA
level : int, default None
If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a DataFrame
%(extras)s
Returns
-------
%(shortname)s : Series (or DataFrame if level specified)
"""
_doc_exclude_na = "NA/null values are excluded"
_numeric_only_doc = """numeric_only : boolean, default None
Include only float, int, boolean data. If None, will attempt to use
everything, then use only numeric data
"""
_merge_doc = """
Merge DataFrame objects by performing a database-style join operation by
columns or indexes.
If joining columns on columns, the DataFrame indexes *will be
ignored*. Otherwise if joining indexes on indexes or indexes on a column or
columns, the index will be passed on.
Parameters
----------%s
right : DataFrame
how : {'left', 'right', 'outer', 'inner'}, default 'inner'
* left: use only keys from left frame (SQL: left outer join)
* right: use only keys from right frame (SQL: right outer join)
* outer: use union of keys from both frames (SQL: full outer join)
* inner: use intersection of keys from both frames (SQL: inner join)
on : label or list
Field names to join on. Must be found in both DataFrames. If on is
None and not merging on indexes, then it merges on the intersection of
the columns by default.
left_on : label or list, or array-like
Field names to join on in left DataFrame. Can be a vector or list of
vectors of the length of the DataFrame to use a particular vector as
the join key instead of columns
right_on : label or list, or array-like
Field names to join on in right DataFrame or vector/list of vectors per
left_on docs
left_index : boolean, default False
Use the index from the left DataFrame as the join key(s). If it is a
MultiIndex, the number of keys in the other DataFrame (either the index
or a number of columns) must match the number of levels
right_index : boolean, default False
Use the index from the right DataFrame as the join key. Same caveats as
left_index
sort : boolean, default False
Sort the join keys lexicographically in the result DataFrame
suffixes : 2-length sequence (tuple, list, ...)
Suffix to apply to overlapping column names in the left and right
side, respectively
copy : boolean, default True
If False, do not copy data unnecessarily
Examples
--------
>>> A >>> B
lkey value rkey value
0 foo 1 0 foo 5
1 bar 2 1 bar 6
2 baz 3 2 qux 7
3 foo 4 3 bar 8
>>> merge(A, B, left_on='lkey', right_on='rkey', how='outer')
lkey value_x rkey value_y
0 bar 2 bar 6
1 bar 2 bar 8
2 baz 3 NaN NaN
3 foo 1 foo 5
4 foo 4 foo 5
5 NaN NaN qux 7
Returns
-------
merged : DataFrame
"""
#----------------------------------------------------------------------
# Factory helper methods
def _arith_method(op, name, str_rep=None, default_axis='columns', fill_zeros=None, **eval_kwargs):
def na_op(x, y):
try:
result = expressions.evaluate(
op, str_rep, x, y, raise_on_error=True, **eval_kwargs)
result = com._fill_zeros(result, y, fill_zeros)
except TypeError:
xrav = x.ravel()
result = np.empty(x.size, dtype=x.dtype)
if isinstance(y, (np.ndarray, Series)):
yrav = y.ravel()
mask = notnull(xrav) & notnull(yrav)
result[mask] = op(xrav[mask], yrav[mask])
else:
mask = notnull(xrav)
result[mask] = op(xrav[mask], y)
result, changed = com._maybe_upcast_putmask(result, -mask, np.nan)
result = result.reshape(x.shape)
return result
@Appender(_arith_doc % name)
def f(self, other, axis=default_axis, level=None, fill_value=None):
if isinstance(other, DataFrame): # Another DataFrame
return self._combine_frame(other, na_op, fill_value, level)
elif isinstance(other, Series):
return self._combine_series(other, na_op, fill_value, axis, level)
elif isinstance(other, (list, tuple)):
if axis is not None and self._get_axis_name(axis) == 'index':
casted = Series(other, index=self.index)
else:
casted = Series(other, index=self.columns)
return self._combine_series(casted, na_op, fill_value, axis, level)
elif isinstance(other, np.ndarray):
if other.ndim == 1:
if axis is not None and self._get_axis_name(axis) == 'index':
casted = Series(other, index=self.index)
else:
casted = Series(other, index=self.columns)
return self._combine_series(casted, na_op, fill_value,
axis, level)
elif other.ndim == 2:
casted = DataFrame(other, index=self.index,
columns=self.columns)
return self._combine_frame(casted, na_op, fill_value, level)
else:
raise ValueError("Incompatible argument shape %s" % (other.shape,))
else:
return self._combine_const(other, na_op)
f.__name__ = name
return f
def _flex_comp_method(op, name, str_rep=None, default_axis='columns'):
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
xrav = x.ravel()
result = np.empty(x.size, dtype=x.dtype)
if isinstance(y, (np.ndarray, Series)):
yrav = y.ravel()
mask = notnull(xrav) & notnull(yrav)
result[mask] = op(np.array(list(xrav[mask])),
np.array(list(yrav[mask])))
else:
mask = notnull(xrav)
result[mask] = op(np.array(list(xrav[mask])), y)
if op == operator.ne: # pragma: no cover
np.putmask(result, -mask, True)
else:
np.putmask(result, -mask, False)
result = result.reshape(x.shape)
return result
@Appender('Wrapper for flexible comparison methods %s' % name)
def f(self, other, axis=default_axis, level=None):
if isinstance(other, DataFrame): # Another DataFrame
return self._flex_compare_frame(other, na_op, str_rep, level)
elif isinstance(other, Series):
return self._combine_series(other, na_op, None, axis, level)
elif isinstance(other, (list, tuple)):
if axis is not None and self._get_axis_name(axis) == 'index':
casted = Series(other, index=self.index)
else:
casted = Series(other, index=self.columns)
return self._combine_series(casted, na_op, None, axis, level)
elif isinstance(other, np.ndarray):
if other.ndim == 1:
if axis is not None and self._get_axis_name(axis) == 'index':
casted = Series(other, index=self.index)
else:
casted = Series(other, index=self.columns)
return self._combine_series(casted, na_op, None, axis, level)
elif other.ndim == 2:
casted = DataFrame(other, index=self.index,
columns=self.columns)
return self._flex_compare_frame(casted, na_op, str_rep, level)
else:
raise ValueError("Incompatible argument shape: %s" %
(other.shape,))
else:
return self._combine_const(other, na_op)
f.__name__ = name
return f
def _comp_method(func, name, str_rep):
@Appender('Wrapper for comparison method %s' % name)
def f(self, other):
if isinstance(other, DataFrame): # Another DataFrame
return self._compare_frame(other, func, str_rep)
elif isinstance(other, Series):
return self._combine_series_infer(other, func)
else:
# straight boolean comparisions we want to allow all columns
# (regardless of dtype to pass thru)
return self._combine_const(other, func, raise_on_error=False).fillna(True).astype(bool)
f.__name__ = name
return f
#----------------------------------------------------------------------
# DataFrame class
class DataFrame(NDFrame):
""" 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
Column labels to use for resulting frame. Will default to
np.arange(n) if no column labels are 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'])
See also
--------
DataFrame.from_records: constructor from tuples, also record arrays
DataFrame.from_dict: from dicts of Series, arrays, or dicts
DataFrame.from_csv: from CSV files
DataFrame.from_items: from sequence of (key, value) pairs
read_csv / read_table / read_clipboard
"""
_auto_consolidate = True
_verbose_info = True
@property
def _constructor(self):
return DataFrame
_constructor_sliced = Series
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):
mgr = self._init_mgr(
data, axes=dict(index=index, columns=columns), dtype=dtype, copy=copy)
elif isinstance(data, dict):
mgr = self._init_dict(data, index, columns, dtype=dtype)
elif isinstance(data, ma.MaskedArray):
# masked recarray
if isinstance(data, ma.mrecords.MaskedRecords):
mgr = _masked_rec_array_to_mgr(data, index, columns, dtype, copy)
# a masked array
else:
mask = ma.getmaskarray(data)
if mask.any():
data, fill_value = _maybe_upcast(data, copy=True)
data[mask] = fill_value
else:
data = data.copy()
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
copy=copy)
elif isinstance(data, (np.ndarray, Series)):
if data.dtype.names:
data_columns = list(data.dtype.names)
data = dict((k, data[k]) for k in data_columns)
if columns is None:
columns = data_columns
mgr = self._init_dict(data, index, columns, dtype=dtype)
elif getattr(data,'name',None):
mgr = self._init_dict({ data.name : data }, index, columns, dtype=dtype)
else:
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
copy=copy)
elif isinstance(data, (list, types.GeneratorType)):
if isinstance(data, types.GeneratorType):
data = list(data)
if len(data) > 0:
if index is None and isinstance(data[0], Series):
index = _get_names_from_index(data)
if is_list_like(data[0]) and getattr(data[0],'ndim',1) == 1:
arrays, columns = _to_arrays(data, columns, dtype=dtype)
columns = _ensure_index(columns)
if index is None:
index = _default_index(len(data))
mgr = _arrays_to_mgr(arrays, columns, index, columns,
dtype=dtype)
else:
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
copy=copy)
else:
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
copy=copy)
else:
try:
arr = np.array(data, dtype=dtype, copy=copy)
except (ValueError, TypeError) as e:
exc = TypeError('DataFrame constructor called with '
'incompatible data and dtype: %s' % e)
raise_with_traceback(exc)
if arr.ndim == 0 and index is not None and columns is not None:
if isinstance(data, compat.string_types) and dtype is None:
dtype = np.object_
if dtype is None:
dtype, data = _infer_dtype_from_scalar(data)
values = np.empty((len(index), len(columns)), dtype=dtype)
values.fill(data)
mgr = self._init_ndarray(values, index, columns, dtype=dtype,
copy=False)
else:
raise PandasError('DataFrame constructor not properly called!')
NDFrame.__init__(self, mgr, fastpath=True)
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.
"""
if dtype is not None:
dtype = np.dtype(dtype)
if columns is not None:
columns = _ensure_index(columns)
# prefilter if columns passed
data = dict((k, v) for k, v in compat.iteritems(data) if k in columns)
if index is None:
index = extract_index(list(data.values()))
else:
index = _ensure_index(index)
arrays = []
data_names = []
for k in columns:
if k not in data:
# no obvious "empty" int column
if dtype is not None and issubclass(dtype.type,
np.integer):
continue
if dtype is None:
# 1783
v = np.empty(len(index), dtype=object)
else:
v = np.empty(len(index), dtype=dtype)
v.fill(NA)
else:
v = data[k]
data_names.append(k)
arrays.append(v)
else:
keys = list(data.keys())
if not isinstance(data, OrderedDict):
keys = _try_sort(list(data.keys()))
columns = data_names = Index(keys)
arrays = [data[k] for k in columns]
return _arrays_to_mgr(arrays, data_names, index, columns,
dtype=dtype)
def _init_ndarray(self, values, index, columns, dtype=None,
copy=False):
if isinstance(values, Series):
if columns is None and values.name is not None:
columns = [values.name]
if index is None:
index = values.index
else:
values = values.reindex(index)
# zero len case (GH #2234)
if not len(values) and len(columns):
values = np.empty((0, 1), dtype=object)
values = _prep_ndarray(values, copy=copy)
if dtype is not None:
if values.dtype != dtype:
try:
values = values.astype(dtype)
except Exception as orig:
e = ValueError("failed to cast to '%s' (Exception was: %s)"
% (dtype, orig))
raise_with_traceback(e)
N, K = values.shape
if index is None:
index = _default_index(N)
else:
index = _ensure_index(index)
if columns is None:
columns = _default_index(K)
else:
columns = _ensure_index(columns)
return create_block_manager_from_blocks([values.T], [columns, index])
@property
def _verbose_info(self):
warnings.warn('The _verbose_info property will be removed in version '
'0.13. please use "max_info_rows"', FutureWarning)
return get_option('display.max_info_rows') is None
@property
def axes(self):
return [self.index, self.columns]
@property
def shape(self):
return (len(self.index), len(self.columns))
def _repr_fits_vertical_(self):
"""
Check length against max_rows.
"""
max_rows = get_option("display.max_rows")
return len(self) <= max_rows
def _repr_fits_horizontal_(self, ignore_width=False):
"""
Check if full repr fits in horizontal boundaries imposed by the display
options width and max_columns. In case off non-interactive session, no
boundaries apply.
ignore_width is here so ipnb+HTML output can behave the way
users expect. display.max_columns remains in effect.
GH3541, GH3573
"""
width, height = fmt.get_console_size()
max_columns = get_option("display.max_columns")
nb_columns = len(self.columns)
# exceed max columns
if ((max_columns and nb_columns > max_columns) or
((not ignore_width) and width and nb_columns > (width // 2))):
return False
if (ignore_width # used by repr_html under IPython notebook
or not com.in_interactive_session()): # scripts ignore terminal dims
return True
if (get_option('display.width') is not None or
com.in_ipython_frontend()):
# check at least the column row for excessive width
max_rows = 1
else:
max_rows = get_option("display.max_rows")
# when auto-detecting, so width=None and not in ipython front end
# check whether repr fits horizontal by actualy checking
# the width of the rendered repr
buf = StringIO()
# only care about the stuff we'll actually print out
# and to_string on entire frame may be expensive
d = self
if not (max_rows is None): # unlimited rows
# min of two, where one may be None
d = d.iloc[:min(max_rows, len(d))]
else:
return True
d.to_string(buf=buf)
value = buf.getvalue()
repr_width = max([len(l) for l in value.split('\n')])
return repr_width < width
def __unicode__(self):
"""
Return a string representation for a particular DataFrame
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
py2/py3.
"""
buf = StringIO(u(""))
fits_vertical = self._repr_fits_vertical_()
fits_horizontal = False
if fits_vertical:
# This needs to compute the entire repr
# so don't do it unless rownum is bounded
fits_horizontal = self._repr_fits_horizontal_()
if fits_vertical and fits_horizontal:
self.to_string(buf=buf)
else:
width, _ = fmt.get_console_size()
max_columns = get_option("display.max_columns")
expand_repr = get_option("display.expand_frame_repr")
# within max_cols and max_rows, but cols exceed width
# of terminal, then use expand_repr
if (fits_vertical and
expand_repr and
len(self.columns) <= max_columns):
self.to_string(buf=buf, line_width=width)
else:
max_info_rows = get_option('display.max_info_rows')
verbose = (max_info_rows is None or
self.shape[0] <= max_info_rows)
self.info(buf=buf, verbose=verbose)
return buf.getvalue()
def _repr_html_(self):
"""
Return a html representation for a particular DataFrame.
Mainly for IPython notebook.
"""
# ipnb in html repr mode allows scrolling
# users strongly prefer to h-scroll a wide HTML table in the browser
# then to get a summary view. GH3541, GH3573
ipnbh = com.in_ipnb() and get_option('display.notebook_repr_html')
# qtconsole doesn't report it's line width, and also
# behaves badly when outputting an HTML table
# that doesn't fit the window, so disable it.
if com.in_qtconsole():
raise ValueError('Disable HTML output in QtConsole')
if get_option("display.notebook_repr_html"):
fits_vertical = self._repr_fits_vertical_()
fits_horizontal = False
if fits_vertical:
fits_horizontal = self._repr_fits_horizontal_(
ignore_width=ipnbh)
if fits_horizontal and fits_vertical:
return ('<div style="max-height:1000px;'
'max-width:1500px;overflow:auto;">\n' +
self.to_html() + '\n</div>')
else:
buf = StringIO(u(""))
max_info_rows = get_option('display.max_info_rows')
verbose = (max_info_rows is None or
self.shape[0] <= max_info_rows)
self.info(buf=buf, verbose=verbose)
info = buf.getvalue()
info = info.replace('&', r'&')
info = info.replace('<', r'<')
info = info.replace('>', r'>')
return ('<pre>\n' + info + '\n</pre>')
else:
return None
def iteritems(self):
"""Iterator over (column, series) pairs"""
if self.columns.is_unique and hasattr(self, '_item_cache'):
for k in self.columns:
yield k, self._get_item_cache(k)
else:
for i, k in enumerate(self.columns):
yield k, self.icol(i)
def iterrows(self):
"""
Iterate over rows of DataFrame as (index, Series) pairs.
Notes
-----
* ``iterrows`` does **not** preserve dtypes across the rows (dtypes
are preserved across columns for DataFrames). For example,
>>> df = DataFrame([[1, 1.0]], columns=['x', 'y'])
>>> row = next(df.iterrows())[1]
>>> print row['x'].dtype
float64
>>> print df['x'].dtype
int64
Returns
-------
it : generator
A generator that iterates over the rows of the frame.
"""
columns = self.columns
for k, v in zip(self.index, self.values):
s = Series(v, index=columns, name=k)
yield k, s
def itertuples(self, index=True):
"""
Iterate over rows of DataFrame as tuples, with index value
as first element of the tuple
"""
arrays = []
if index:
arrays.append(self.index)
# use integer indexing because of possible duplicate column names
arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))
return zip(*arrays)
if compat.PY3: # pragma: no cover
items = iteritems
def __len__(self):
"""Returns length of info axis, but here we use the index """
return len(self.index)
#----------------------------------------------------------------------
# Arithmetic methods
add = _arith_method(operator.add, 'add', '+')
mul = _arith_method(operator.mul, 'multiply', '*')
sub = _arith_method(operator.sub, 'subtract', '-')
div = divide = _arith_method(lambda x, y: x / y, 'divide', '/')
pow = _arith_method(operator.pow, 'pow', '**')
mod = _arith_method(lambda x, y: x % y, 'mod')
radd = _arith_method(_radd_compat, 'radd')
rmul = _arith_method(operator.mul, 'rmultiply')
rsub = _arith_method(lambda x, y: y - x, 'rsubtract')
rdiv = _arith_method(lambda x, y: y / x, 'rdivide')
rpow = _arith_method(lambda x, y: y ** x, 'rpow')
rmod = _arith_method(lambda x, y: y % x, 'rmod')
__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, fill_zeros=np.inf, truediv=True)
# numexpr produces a different value (python/numpy: 0.000, numexpr: inf)
# when dividing by zero, so can't use floordiv speed up (yet)
# __floordiv__ = _arith_method(operator.floordiv, '__floordiv__', '//',
__floordiv__ = _arith_method(operator.floordiv, '__floordiv__',
default_axis=None, fill_zeros=np.inf)
__pow__ = _arith_method(operator.pow, '__pow__', '**', default_axis=None)
# currently causes a floating point exception to occur - so sticking with unaccelerated for now
# __mod__ = _arith_method(operator.mod, '__mod__', '%', default_axis=None, fill_zeros=np.nan)
__mod__ = _arith_method(
operator.mod, '__mod__', default_axis=None, fill_zeros=np.nan)
__radd__ = _arith_method(_radd_compat, '__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, fill_zeros=np.inf)
__rfloordiv__ = _arith_method(lambda x, y: y // x, '__rfloordiv__',
default_axis=None, fill_zeros=np.inf)
__rpow__ = _arith_method(lambda x, y: y ** x, '__rpow__',
default_axis=None)
__rmod__ = _arith_method(lambda x, y: y % x, '__rmod__', default_axis=None,
fill_zeros=np.nan)
# boolean operators
__and__ = _arith_method(operator.and_, '__and__', '&')
__or__ = _arith_method(operator.or_, '__or__', '|')
__xor__ = _arith_method(operator.xor, '__xor__')
# Python 2 division methods
if not compat.PY3:
__div__ = _arith_method(operator.div, '__div__', '/',
default_axis=None, fill_zeros=np.inf, truediv=False)
__rdiv__ = _arith_method(lambda x, y: y / x, '__rdiv__',
default_axis=None, fill_zeros=np.inf)
# 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__', '>=')
eq = _flex_comp_method(operator.eq, 'eq', '==')
ne = _flex_comp_method(operator.ne, 'ne', '!=')
lt = _flex_comp_method(operator.lt, 'lt', '<')
gt = _flex_comp_method(operator.gt, 'gt', '>')
le = _flex_comp_method(operator.le, 'le', '<=')
ge = _flex_comp_method(operator.ge, 'ge', '>=')
def dot(self, other):
"""
Matrix multiplication with DataFrame or Series objects
Parameters
----------
other : DataFrame or Series
Returns
-------
dot_product : DataFrame or Series
"""
if isinstance(other, (Series, DataFrame)):
common = self.columns.union(other.index)
if (len(common) > len(self.columns) or
len(common) > len(other.index)):
raise ValueError('matrices are not aligned')
left = self.reindex(columns=common, copy=False)
right = other.reindex(index=common, copy=False)
lvals = left.values
rvals = right.values
else:
left = self
lvals = self.values
rvals = np.asarray(other)
if lvals.shape[1] != rvals.shape[0]:
raise ValueError('Dot product shape mismatch, %s vs %s' %
(lvals.shape, rvals.shape))
if isinstance(other, DataFrame):
return self._constructor(np.dot(lvals, rvals),
index=left.index,
columns=other.columns)
elif isinstance(other, Series):
return Series(np.dot(lvals, rvals), index=left.index)
elif isinstance(rvals, np.ndarray):
result = np.dot(lvals, rvals)
if result.ndim == 2:
return self._constructor(result, index=left.index)
else:
return Series(result, index=left.index)
else: # pragma: no cover
raise TypeError('unsupported type: %s' % type(other))
#----------------------------------------------------------------------
# IO methods (to / from other formats)
@classmethod
def from_dict(cls, data, orient='columns', dtype=None):
"""
Construct DataFrame from dict of array-like or dicts
Parameters
----------
data : dict
{field : array-like} or {field : dict}
orient : {'columns', 'index'}, default 'columns'
The "orientation" of the data. If the keys of the passed dict
should be the columns of the resulting DataFrame, pass 'columns'
(default). Otherwise if the keys should be rows, pass 'index'.
Returns
-------
DataFrame
"""
index, columns = None, None
orient = orient.lower()
if orient == 'index':
if len(data) > 0:
# TODO speed up Series case
if isinstance(list(data.values())[0], (Series, dict)):
data = _from_nested_dict(data)
else:
data, index = list(data.values()), list(data.keys())
elif orient != 'columns': # pragma: no cover
raise ValueError('only recognize index or columns for orient')
return cls(data, index=index, columns=columns, dtype=dtype)
def to_dict(self, outtype='dict'):
"""
Convert DataFrame to dictionary.
Parameters
----------
outtype : str {'dict', 'list', 'series'}
Determines the type of the values of the dictionary. The
default `dict` is a nested dictionary {column -> {index -> value}}.
`list` returns {column -> list(values)}. `series` returns
{column -> Series(values)}.
Abbreviations are allowed.
Returns
-------
result : dict like {column -> {index -> value}}
"""
if not self.columns.is_unique:
warnings.warn("DataFrame columns are not unique, some "
"columns will be omitted.", UserWarning)
if outtype.lower().startswith('d'):
return dict((k, v.to_dict()) for k, v in compat.iteritems(self))
elif outtype.lower().startswith('l'):
return dict((k, v.tolist()) for k, v in compat.iteritems(self))
elif outtype.lower().startswith('s'):
return dict((k, v) for k, v in compat.iteritems(self))
else: # pragma: no cover
raise ValueError("outtype %s not understood" % outtype)
@classmethod
def from_records(cls, data, index=None, exclude=None, columns=None,
coerce_float=False, nrows=None):
"""
Convert structured or record ndarray to DataFrame
Parameters
----------
data : ndarray (structured dtype), list of tuples, dict, or DataFrame
index : string, list of fields, array-like
Field of array to use as the index, alternately a specific set of
input labels to use
exclude: sequence, default None
Columns or fields to exclude
columns : sequence, default None
Column names to use. If the passed data do not have named
associated with them, this argument provides names for the
columns. Otherwise this argument indicates the order of the columns
in the result (any names not found in the data will become all-NA
columns)
coerce_float : boolean, default False
Attempt to convert values to non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets
Returns
-------
df : DataFrame
"""
# Make a copy of the input columns so we can modify it
if columns is not None:
columns = _ensure_index(columns)
if com.is_iterator(data):
if nrows == 0:
return cls()
try:
if compat.PY3:
first_row = next(data)
else:
first_row = next(data)
except StopIteration:
return cls(index=index, columns=columns)
dtype = None
if hasattr(first_row, 'dtype') and first_row.dtype.names:
dtype = first_row.dtype
values = [first_row]
i = 1
for row in data:
values.append(row)
i += 1
if i >= nrows:
break