/
frame.py
3882 lines (3236 loc) · 128 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 itertools import izip
from StringIO import StringIO
import csv
import operator
import sys
from numpy import nan
import numpy as np
import numpy.ma as ma
from pandas.core.common import (isnull, notnull, PandasError, _try_sort,
_default_index, _stringify)
from pandas.core.daterange import DateRange
from pandas.core.generic import 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
from pandas.util import py3compat
from pandas.util.terminal import get_terminal_size
from pandas.util.decorators import deprecate, Appender, Substitution
from pandas.core.format import DataFrameFormatter, docstring_to_string
import pandas.core.nanops as nanops
import pandas.core.common as com
import pandas.core.generic as generic
import pandas.core.datetools as datetools
import pandas._tseries as lib
#----------------------------------------------------------------------
# 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.
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 True
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 True
Use the index from the right DataFrame as the join key. Same caveats as
left_index
sort : boolean, default True
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(func, name, default_axis='columns'):
@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, func, fill_value, level)
elif isinstance(other, Series):
return self._combine_series(other, func, fill_value, axis, level)
else:
return self._combine_const(other, func)
f.__name__ = name
return f
def comp_method(func, name):
@Appender('Wrapper for comparison method %s' % 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
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'])
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
"""
if data is None:
data = {}
if isinstance(data, DataFrame):
data = data._data
if isinstance(data, BlockManager):
mgr = self._init_mgr(data, index, columns, dtype=dtype, copy=copy)
elif isinstance(data, dict):
mgr = self._init_dict(data, index, columns, dtype=dtype)
elif isinstance(data, ma.MaskedArray):
mask = ma.getmaskarray(data)
datacopy = ma.copy(data)
datacopy[mask] = np.nan
mgr = self._init_ndarray(datacopy, index, columns, dtype=dtype,
copy=copy)
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):
if len(data) > 0:
if isinstance(data[0], (list, tuple)):
data, columns = _list_to_sdict(data, columns)
mgr = self._init_dict(data, index, columns, dtype=dtype)
elif isinstance(data[0], dict):
data, columns = _list_of_dict_to_sdict(data, columns)
mgr = self._init_dict(data, 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:
raise PandasError('DataFrame constructor not properly called!')
NDFrame.__init__(self, mgr)
@classmethod
def _from_axes(cls, data, axes):
# for construction from BlockManager
if isinstance(data, BlockManager):
return cls(data)
else:
columns, index = axes
return cls(data, index=index, columns=columns, copy=False)
def _init_mgr(self, mgr, index, columns, dtype=None, copy=False):
if columns is not None:
mgr = mgr.reindex_axis(columns, axis=0, copy=False)
if index is not None:
mgr = mgr.reindex_axis(index, axis=1, copy=False)
# do not copy BlockManager unless explicitly done
if copy and dtype is None:
mgr = mgr.copy()
elif dtype is not None:
# no choice but to copy
mgr = mgr.astype(dtype)
return 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.
"""
# 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):
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)
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
"""
terminal_width, terminal_height = get_terminal_size()
max_rows = (terminal_height if com.GlobalPrintConfig.max_rows == 0
else com.GlobalPrintConfig.max_rows)
max_columns = com.GlobalPrintConfig.max_columns
if max_columns > 0:
buf = StringIO()
if len(self.index) < max_rows and \
len(self.columns) <= max_columns:
self.to_string(buf=buf)
else:
self.info(buf=buf, verbose=self._verbose_info)
return buf.getvalue()
else:
if len(self.index) > max_rows:
buf = StringIO()
self.info(buf=buf, verbose=self._verbose_info)
return buf.getvalue()
else:
buf = StringIO()
self.to_string(buf=buf)
value = buf.getvalue()
if max([len(l) for l in value.split('\n')]) <= terminal_width:
return value
else:
buf = StringIO()
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)
def iterrows(self):
"""
Iterate over rows of DataFrame as (index, Series) pairs
"""
from itertools import izip
columns = self.columns
for k, v in izip(self.index, self.values):
s = v.view(Series)
s.index = columns
s.name = k
yield k, s
iterkv = iteritems
if py3compat.PY3: # pragma: no cover
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(lambda x, y: y + x, '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')
__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(lambda x, y: y + x, '__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)
# 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 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):
arr = operator.neg(self.values)
return self._wrap_array(arr, self.axes, copy=False)
# 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__')
def dot(self, other):
"""
Matrix multiplication with DataFrame objects. Does no data alignment
Parameters
----------
other : DataFrame
Returns
-------
dot_product : DataFrame
"""
lvals = self.values
rvals = other.values
result = np.dot(lvals, rvals)
return DataFrame(result, index=self.index, columns=other.columns)
#----------------------------------------------------------------------
# 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
"""
from collections import defaultdict
orient = orient.lower()
if orient == 'index':
# TODO: this should be seriously cythonized
new_data = defaultdict(dict)
for index, s in data.iteritems():
for col, v in s.iteritems():
new_data[col][index] = v
data = new_data
elif orient != 'columns': # pragma: no cover
raise ValueError('only recognize index or columns for orient')
return DataFrame(data, dtype=dtype)
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, columns=None,
names=None):
"""
Convert structured or record ndarray to DataFrame
Parameters
----------
data : ndarray (structured dtype), list of tuples, 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, replacing any found in passed data
Returns
-------
df : DataFrame
"""
import warnings
if names is not None: # pragma: no cover
columns = names
warnings.warn("'names' parameter to DataFrame.from_records is "
"being renamed to 'columns', 'names' will be "
"removed in 0.8.0", FutureWarning)
if isinstance(data, (np.ndarray, DataFrame, dict)):
columns, sdict = _rec_to_dict(data)
else:
sdict, columns = _list_to_sdict(data, columns)
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) or
not hasattr(index, "__iter__")):
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
elif isinstance(data, dict) and len(data) > 0:
# utilize first element of sdict to get length
result_index = np.arange(len(data.values()[0]))
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_items(cls, items, columns=None, orient='columns'):
"""
Convert (key, value) pairs to DataFrame. The keys will be the axis
index (usually the columns, but depends on the specified
orientation). The values should be arrays or Series
Parameters
----------
items : sequence of (key, value) pairs
Values should be arrays or Series
columns : sequence, optional
Must be passed in the
orient : {'columns', 'index'}, default 'items'
The "orientation" of the data. If the keys of the passed dict
should be the items of the result panel, pass 'items'
(default). Otherwise if the columns of the values of the passed
DataFrame objects should be the items (which in the case of
mixed-dtype data you should do), instead pass 'minor'
Returns
-------
frame : DataFrame
"""
keys, values = zip(*items)
if orient == 'columns':
cols_to_use = columns if columns is not None else keys
# iterable may have been consumed
return DataFrame(dict(zip(keys, values)), columns=cols_to_use)
elif orient == 'index':
if columns is None:
raise ValueError("Must pass columns with orient='index'")
arr = np.array(values, dtype=object).T
new_data = dict((k, lib.maybe_convert_objects(v))
for k, v in zip(columns, arr))
return DataFrame(new_data, index=keys, columns=columns)
elif orient != 'columns': # pragma: no cover
raise ValueError('only recognize index or columns for orient')
@classmethod
def from_csv(cls, path, header=0, sep=',', 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)
sep : string, default ','
Field delimiter
index_col : int or sequence, default 0
Column to use for index. If a sequence is given, a MultiIndex
is used. Different default from read_table
parse_dates : boolean, default True
Parse dates. Different default from read_table
Notes
-----
Preferable to use read_table for most general purposes but from_csv
makes for an easy roundtrip to and from file, especially with a
DataFrame of time series data
Returns
-------
y : DataFrame
"""
from pandas.io.parsers import read_table
return read_table(path, header=header, sep=sep,
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_panel(self):
"""
Transform long (stacked) format (DataFrame) into wide (3D, Panel)
format.
Currently the index of the DataFrame must be a 2-level MultiIndex. This
may be generalized later
Returns
-------
panel : Panel
"""
from pandas.core.panel import Panel
wide_shape = (len(self.columns), len(self.index.levels[0]),
len(self.index.levels[1]))
# only support this kind for now
assert(isinstance(self.index, MultiIndex) and
len(self.index.levels) == 2)
major_axis, minor_axis = self.index.levels
def make_mask(index):
"""
Create observation selection vector using major and minor
labels, for converting to wide format.
"""
N, K = index.levshape
selector = index.labels[1] + K * index.labels[0]
mask = np.zeros(N * K, dtype=bool)
mask.put(selector, True)
return mask
def _to_wide_homogeneous():
values = np.empty(wide_shape, dtype=self.values.dtype)
if not issubclass(values.dtype.type, np.integer):
values.fill(np.nan)
frame_values = self.values
for i in xrange(len(self.columns)):
values[i].flat[mask] = frame_values[:, i]
return Panel(values, self.columns, major_axis, minor_axis)
def _to_wide_mixed():
_, N, K = wide_shape
# TODO: make much more efficient
data = {}
for item in self.columns:
item_vals = self[item].values
values = np.empty((N, K), dtype=item_vals.dtype)
values.flat[mask] = item_vals
data[item] = DataFrame(values, index=major_axis,
columns=minor_axis)
return Panel(data, self.columns, major_axis, minor_axis)
mask = make_mask(self.index)
if self._is_mixed_type:
return _to_wide_mixed()
else:
return _to_wide_homogeneous()
to_wide = deprecate('to_wide', to_panel)
def to_csv(self, path, sep=",", na_rep='', cols=None, header=True,
index=True, index_label=None, mode='w', nanRep=None):
"""
Write DataFrame to a comma-separated values (csv) file
Parameters
----------
path : string
File path
nanRep : string, default ''
Missing data rep'n
cols : sequence, optional
Columns to write
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'
sep : character, default ","
Field delimiter for the output file.
"""
f = open(path, mode)
csvout = csv.writer(f, lineterminator='\n', delimiter=sep)
if nanRep is not None: # pragma: no cover
import warnings
warnings.warn("nanRep is deprecated, use na_rep",
FutureWarning)
na_rep = nanRep
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:
index_label = self.index.name
if index_label is None:
index_label = ['index']
else:
index_label = [index_label]
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 = na_rep
row_fields.append(val)
csvout.writerow(row_fields)
f.close()
@Appender(docstring_to_string, indents=1)
def to_string(self, buf=None, columns=None, col_space=None, colSpace=None,
header=True, index=True, na_rep='NaN', formatters=None,
float_format=None, sparsify=True, nanRep=None,
index_names=True, justify='left'):
"""
Render a DataFrame to a console-friendly tabular output.
"""
if nanRep is not None: # pragma: no cover
import warnings
warnings.warn("nanRep is deprecated, use na_rep",
FutureWarning)
na_rep = nanRep
if colSpace is not None: # pragma: no cover
import warnings
warnings.warn("colSpace is deprecated, use col_space",
FutureWarning)
col_space = colSpace
formatter = DataFrameFormatter(self, buf=buf, columns=columns,
col_space=col_space, na_rep=na_rep,
formatters=formatters,
float_format=float_format,
sparsify=sparsify,
justify=justify,
index_names=index_names,
header=header, index=index)
formatter.to_string()
if buf is None:
return formatter.buf.getvalue()
@Appender(docstring_to_string, indents=1)
def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
header=True, index=True, na_rep='NaN', formatters=None,
float_format=None, sparsify=True, index_names=True,
bold_rows=True):
"""
to_html-specific options
bold_rows : boolean, default True
Make the row labels bold in the output
Render a DataFrame to an html table.
"""
if colSpace is not None: # pragma: no cover
import warnings
warnings.warn("colSpace is deprecated, use col_space",
FutureWarning)
col_space = colSpace
formatter = DataFrameFormatter(self, buf=buf, columns=columns,
col_space=col_space, na_rep=na_rep,
header=header, index=index,
formatters=formatters,
float_format=float_format,
bold_rows=bold_rows,
sparsify=sparsify,
index_names=index_names)
formatter.to_html()
if buf is None:
return formatter.buf.getvalue()
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