/
tables.py
6067 lines (5162 loc) · 238 KB
/
tables.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
"""Tables are sequences of labeled columns."""
__all__ = ['Table']
import abc
import collections
import collections.abc
import copy
import functools
import inspect
import itertools
import numbers
import urllib.parse
import warnings
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import pandas
import IPython
# import plotly.graph_objects as go
# from plotly.subplots import make_subplots
import datascience.formats as _formats
import datascience.util as _util
from datascience.util import make_array
import datascience.predicates as _predicates
# initializing go and make_subplots as globals set to None
go, make_subplots = None, None
_INTERACTIVE_PLOTS = False
# Set numpy printoptions to legacy to get around error terms, as described in
# https://github.com/data-8/datascience/issues/491
np.set_printoptions(legacy='1.13')
class Table(collections.abc.MutableMapping):
"""A sequence of string-labeled columns."""
plots = collections.deque(maxlen=10)
def __init__(self, labels=None, formatter=_formats.default_formatter):
"""Create an empty table with column labels.
>>> tiles = Table(make_array('letter', 'count', 'points'))
>>> tiles
letter | count | points
Args:
``labels`` (list of strings): The column labels.
``formatter`` (Formatter): An instance of :class:`Formatter` that
formats the columns' values.
"""
self._columns = collections.OrderedDict()
self._formats = dict()
self.formatter = formatter
labels = labels if labels is not None else []
columns = [[] for _ in labels]
self._num_rows = 0 if len(columns) == 0 else len(columns[0])
# Add each column to table
for column, label in zip(columns, labels):
self[label] = column
self.take = _RowTaker(self)
self.exclude = _RowExcluder(self)
# Deprecated
@classmethod
def from_rows(cls, rows, labels):
"""Create a table from a sequence of rows (fixed-length sequences). [Deprecated]"""
warnings.warn("Table.from_rows is deprecated. Use Table(labels).with_rows(...)", FutureWarning)
return cls(labels).with_rows(rows)
@classmethod
def from_records(cls, records):
"""Create a table from a sequence of records (dicts with fixed keys).
Args:
records: A list of dictionaries with same keys.
Returns:
If the list is empty, it will return an empty table.
Otherwise, it will return a table with the dictionary's keys as the column name, and the corresponding data.
If the dictionaries do not have identical keys, the keys of the first dictionary in the list is used.
Example:
>>> t = Table().from_records([
... {'column1':'data1','column2':1},
... {'column1':'data2','column2':2},
... {'column1':'data3','column2':3}
... ])
>>> t
column1 | column2
data1 | 1
data2 | 2
data3 | 3
"""
if not records:
return cls()
labels = sorted(list(records[0].keys()))
columns = [[rec[label] for rec in records] for label in labels]
return cls().with_columns(zip(labels, columns))
# Deprecated
@classmethod
def from_columns_dict(cls, columns):
"""Create a table from a mapping of column labels to column values. [Deprecated]"""
warnings.warn("Table.from_columns_dict is deprecated. Use Table().with_columns(...)", FutureWarning)
return cls().with_columns(columns.items())
@classmethod
def read_table(cls, filepath_or_buffer, *args, **vargs):
"""Read a table from a file or web address.
Args:
filepath_or_buffer -- string or file handle / StringIO; The string
could be a URL. Valid URL schemes include http,
ftp, s3, and file.
Returns:
a table read from argument
Example:
>>> Table.read_table('https://www.inferentialthinking.com/data/sat2014.csv')
State | Participation Rate | Critical Reading | Math | Writing | Combined
North Dakota | 2.3 | 612 | 620 | 584 | 1816
Illinois | 4.6 | 599 | 616 | 587 | 1802
Iowa | 3.1 | 605 | 611 | 578 | 1794
South Dakota | 2.9 | 604 | 609 | 579 | 1792
Minnesota | 5.9 | 598 | 610 | 578 | 1786
Michigan | 3.8 | 593 | 610 | 581 | 1784
Wisconsin | 3.9 | 596 | 608 | 578 | 1782
Missouri | 4.2 | 595 | 597 | 579 | 1771
Wyoming | 3.3 | 590 | 599 | 573 | 1762
Kansas | 5.3 | 591 | 596 | 566 | 1753
... (41 rows omitted)
"""
# Look for .csv at the end of the path; use "," as a separator if found
try:
path = urllib.parse.urlparse(filepath_or_buffer).path
if 'data8.berkeley.edu' in filepath_or_buffer:
raise ValueError('data8.berkeley.edu requires authentication, '
'which is not supported.')
except AttributeError:
path = filepath_or_buffer
try:
if 'sep' not in vargs and path.endswith('.csv'):
vargs['sep'] = ','
except AttributeError:
pass
df = pandas.read_csv(filepath_or_buffer, *args, **vargs)
return cls.from_df(df)
def _with_columns(self, columns):
"""Create a table from a sequence of columns, copying column labels."""
table = type(self)()
for label, column in zip(self.labels, columns):
self._add_column_and_format(table, label, column)
return table
def _add_column_and_format(self, table, label, column):
"""Add a column to table, copying the formatter from self."""
label = self._as_label(label)
table[label] = column
if label in self._formats:
table._formats[label] = self._formats[label]
@classmethod
def from_df(cls, df, keep_index=False):
"""Convert a Pandas DataFrame into a Table.
Args:
df -- Pandas DataFrame utilized for creation of Table
`keep_index` -- keeps the index of the DataFrame
and turns it into a column called `index` in the new Table
Returns:
a table from Pandas Dataframe in argument
Example:
>>> sample_DF = pandas.DataFrame(
... data = zip([1,2,3],['a','b','c'],['data1','data2','data3']),
... columns = ['column1','column2','column3']
... )
>>> sample_DF
column1 column2 column3
0 1 a data1
1 2 b data2
2 3 c data3
>>> t = Table().from_df(sample_DF)
>>> t
column1 | column2 | column3
1 | a | data1
2 | b | data2
3 | c | data3
"""
t = cls()
if keep_index:
t.append_column("index", df.index.values)
labels = df.columns
for label in labels:
t.append_column(label, df[label])
return t
@classmethod
def from_array(cls, arr):
"""Convert a structured NumPy array into a Table.
Args:
arr -- A structured NumPy array
Returns:
A table with the field names as the column names and the corresponding data.
Example:
>>> arr = np.array([
... ('A',1), ('B',2)],
... dtype=[('Name', 'U10'), ('Number', 'i4')]
... )
>>> arr
array([('A', 1), ('B', 2)], dtype=[('Name', '<U10'), ('Number', '<i4')])
>>> t = Table().from_array(arr)
>>> t
Name | Number
A | 1
B | 2
"""
return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])
#################
# Magic Methods #
#################
def __getitem__(self, index_or_label):
return self.column(index_or_label)
def __setitem__(self, index_or_label, values):
self.append_column(index_or_label, values)
def __delitem__(self, index_or_label):
label = self._as_label(index_or_label)
del self._columns[label]
if label in self._formats:
del self._formats[label]
def __len__(self):
return len(self._columns)
def __iter__(self):
return iter(self.labels)
####################
# Accessing Values #
####################
@property
def num_rows(self):
"""
Computes the number of rows in a table
Returns:
integer value stating number of rows
Example:
>>> t = Table().with_columns({
... 'letter': ['a', 'b', 'c', 'z'],
... 'count': [ 9, 3, 3, 1],
... 'points': [ 1, 2, 2, 10],
... })
>>> t.num_rows
4
"""
return self._num_rows
@property
def rows(self):
"""
Return a view of all rows.
Returns:
list-like Rows object that contains tuple-like Row objects
Example:
>>> t = Table().with_columns({
... 'letter': ['a', 'b', 'c', 'z'],
... 'count': [ 9, 3, 3, 1],
... 'points': [ 1, 2, 2, 10],
... })
>>> t.rows
Rows(letter | count | points
a | 9 | 1
b | 3 | 2
c | 3 | 2
z | 1 | 10)
"""
return self.Rows(self)
def row(self, index):
"""Return a row."""
return self.rows[index]
@property
def labels(self):
"""
Return a tuple of column labels.
Returns:
tuple of labels
Example:
>>> t = Table().with_columns({
... 'letter': ['a', 'b', 'c', 'z'],
... 'count': [ 9, 3, 3, 1],
... 'points': [ 1, 2, 2, 10],
... })
>>> t.labels
('letter', 'count', 'points')
"""
return tuple(self._columns.keys())
@property
def num_columns(self):
"""Number of columns."""
return len(self.labels)
@property
def columns(self):
"""
Return a tuple of columns, each with the values in that column.
Returns:
tuple of columns
Example:
>>> t = Table().with_columns({
... 'letter': ['a', 'b', 'c', 'z'],
... 'count': [ 9, 3, 3, 1],
... 'points': [ 1, 2, 2, 10],
... })
>>> t.columns
(array(['a', 'b', 'c', 'z'], dtype='<U1'),
array([9, 3, 3, 1]),
array([ 1, 2, 2, 10]))
"""
return tuple(self._columns.values())
def column(self, index_or_label):
"""Return the values of a column as an array.
table.column(label) is equivalent to table[label].
>>> tiles = Table().with_columns(
... 'letter', make_array('c', 'd'),
... 'count', make_array(2, 4),
... )
>>> list(tiles.column('letter'))
['c', 'd']
>>> tiles.column(1)
array([2, 4])
Args:
label (int or str): The index or label of a column
Returns:
An instance of ``numpy.array``.
Raises:
``ValueError``: When the ``index_or_label`` is not in the table.
"""
if (isinstance(index_or_label, str)
and index_or_label not in self.labels):
raise ValueError(
'The column "{}" is not in the table. The table contains '
'these columns: {}'
.format(index_or_label, ', '.join(self.labels))
)
if (isinstance(index_or_label, int)
and not 0 <= index_or_label < len(self.labels)):
raise ValueError(
'The index {} is not in the table. Only indices between '
'0 and {} are valid'
.format(index_or_label, len(self.labels) - 1)
)
return self._columns[self._as_label(index_or_label)]
@property
def values(self):
"""Return data in `self` as a numpy array.
If all columns are the same dtype, the resulting array
will have this dtype. If there are >1 dtypes in columns,
then the resulting array will have dtype `object`.
"""
dtypes = [col.dtype for col in self.columns]
if len(set(dtypes)) > 1:
dtype = object
else:
dtype = None
return np.array(self.columns, dtype=dtype).T
def column_index(self, label):
"""
Return the index of a column by looking up its label.
Args:
``label`` (str) -- label value of a column
Returns:
integer value specifying the index of the column label
Example:
>>> t = Table().with_columns({
... 'letter': ['a', 'b', 'c', 'z'],
... 'count': [ 9, 3, 3, 1],
... 'points': [ 1, 2, 2, 10],
... })
>>> t.column_index('letter')
0
"""
return self.labels.index(label)
def apply(self, fn, *column_or_columns):
"""Apply ``fn`` to each element or elements of ``column_or_columns``.
If no ``column_or_columns`` provided, `fn`` is applied to each row.
Args:
``fn`` (function) -- The function to apply to each element
of ``column_or_columns``.
``column_or_columns`` -- Columns containing the arguments to ``fn``
as either column labels (``str``) or column indices (``int``).
The number of columns must match the number of arguments
that ``fn`` expects.
Raises:
``ValueError`` -- if ``column_label`` is not an existing
column in the table.
``TypeError`` -- if insufficient number of ``column_label`` passed
to ``fn``.
Returns:
An array consisting of results of applying ``fn`` to elements
specified by ``column_label`` in each row.
>>> t = Table().with_columns(
... 'letter', make_array('a', 'b', 'c', 'z'),
... 'count', make_array(9, 3, 3, 1),
... 'points', make_array(1, 2, 2, 10))
>>> t
letter | count | points
a | 9 | 1
b | 3 | 2
c | 3 | 2
z | 1 | 10
>>> t.apply(lambda x: x - 1, 'points')
array([0, 1, 1, 9])
>>> t.apply(lambda x, y: x * y, 'count', 'points')
array([ 9, 6, 6, 10])
>>> t.apply(lambda x: x - 1, 'count', 'points')
Traceback (most recent call last):
...
TypeError: <lambda>() takes 1 positional argument but 2 were given
>>> t.apply(lambda x: x - 1, 'counts')
Traceback (most recent call last):
...
ValueError: The column "counts" is not in the table. The table contains these columns: letter, count, points
Whole rows are passed to the function if no columns are specified.
>>> t.apply(lambda row: row[1] * 2)
array([18, 6, 6, 2])
"""
if not column_or_columns:
return np.array([fn(row) for row in self.rows])
else:
if len(column_or_columns) == 1 and \
_util.is_non_string_iterable(column_or_columns[0]):
warnings.warn(
"column lists are deprecated; pass each as an argument", FutureWarning)
column_or_columns = column_or_columns[0]
rows = zip(*self.select(*column_or_columns).columns)
return np.array([fn(*row) for row in rows])
def first(self, label):
"""
Return the zeroth item in a column.
Args:
``label`` (str) -- value of column label
Returns:
zeroth item of column
Example:
>>> t = Table().with_columns({
... 'letter': ['a', 'b', 'c', 'z'],
... 'count': [ 9, 3, 3, 1],
... 'points': [ 1, 2, 2, 10],
... })
>>> t.first('letter')
'a'
"""
return self.column(label)[0]
def last(self, label):
"""
Return the last item in a column.
Args:
``label`` (str) -- value of column label
Returns:
last item of column
Example:
>>> t = Table().with_columns({
... 'letter': ['a', 'b', 'c', 'z'],
... 'count': [ 9, 3, 3, 1],
... 'points': [ 1, 2, 2, 10],
... })
>>> t.last('letter')
'z'
"""
return self.column(label)[-1]
############
# Mutation #
############
def set_format(self, column_or_columns, formatter):
"""
Set the pretty print format of a column(s) and/or convert its values.
Args:
``column_or_columns``: values to group (column label or index, or array)
``formatter``: a function applied to a single value within the
``column_or_columns`` at a time or a formatter class, or formatter
class instance.
Returns:
A Table with ``formatter`` applied to each ``column_or_columns``.
The following example formats the column "balance" by passing in a formatter
class instance. The formatter is run each time ``__repr__`` is called. So, while
the table is formatted upon being printed to the console, the underlying values
within the table remain untouched. It's worth noting that while ``set_format``
returns the table with the new formatters applied, this change is applied
directly to the original table and then the original table is returned. This
means ``set_format`` is what's known as an inplace operation.
>>> account_info = Table().with_columns(
... "user", make_array("gfoo", "bbar", "tbaz", "hbat"),
... "balance", make_array(200, 555, 125, 430))
>>> account_info
user | balance
gfoo | 200
bbar | 555
tbaz | 125
hbat | 430
>>> from datascience.formats import CurrencyFormatter
>>> account_info.set_format("balance", CurrencyFormatter("BZ$")) # Belize Dollar
user | balance
gfoo | BZ$200
bbar | BZ$555
tbaz | BZ$125
hbat | BZ$430
>>> account_info["balance"]
array([200, 555, 125, 430])
>>> account_info
user | balance
gfoo | BZ$200
bbar | BZ$555
tbaz | BZ$125
hbat | BZ$430
The following example formats the column "balance" by passing in a formatter
function.
>>> account_info = Table().with_columns(
... "user", make_array("gfoo", "bbar", "tbaz", "hbat"),
... "balance", make_array(200, 555, 125, 430))
>>> account_info
user | balance
gfoo | 200
bbar | 555
tbaz | 125
hbat | 430
>>> def iceland_krona_formatter(value):
... return f"{value} kr"
>>> account_info.set_format("balance", iceland_krona_formatter)
user | balance
gfoo | 200 kr
bbar | 555 kr
tbaz | 125 kr
hbat | 430 kr
The following, formats the column "balance" by passing in a formatter class.
Note the formatter class must have a Boolean ``converts_values`` attribute set
and a ``format_column`` method that returns a function that formats a single
value at a time. The ``format_column`` method accepts the name of the column and
the value of the column as arguments and returns a formatter function that
accepts a value and Boolean indicating whether that value is the column name.
In the following example, if the ``if label: return value`` was removed, the
column name "balance" would be formatted and printed as "balance kr". The
``converts_values`` attribute should be set to False unless a ``convert_values``
method is also defined on the formatter class.
>>> account_info = Table().with_columns(
... "user", make_array("gfoo", "bbar", "tbaz", "hbat"),
... "balance", make_array(200, 555, 125, 430))
>>> account_info
user | balance
gfoo | 200
bbar | 555
tbaz | 125
hbat | 430
>>> class IcelandKronaFormatter():
... def __init__(self):
... self.converts_values = False
...
... def format_column(self, label, column):
... def format_krona(value, label):
... if label:
... return value
... return f"{value} kr"
...
... return format_krona
>>> account_info.set_format("balance", IcelandKronaFormatter)
user | balance
gfoo | 200 kr
bbar | 555 kr
tbaz | 125 kr
hbat | 430 kr
>>> account_info["balance"]
array([200, 555, 125, 430])
``set_format`` can also be used to convert values. If you set the
``converts_values`` attribute to True and define a ``convert_column`` method
that accepts the column values and returns the converted column values on the
formatter class, the column values will be permanently converted to the new
column values in a one time operation.
>>> account_info = Table().with_columns(
... "user", make_array("gfoo", "bbar", "tbaz", "hbat"),
... "balance", make_array(200.01, 555.55, 125.65, 430.18))
>>> account_info
user | balance
gfoo | 200.01
bbar | 555.55
tbaz | 125.65
hbat | 430.18
>>> class IcelandKronaFormatter():
... def __init__(self):
... self.converts_values = True
...
... def format_column(self, label, column):
... def format_krona(value, label):
... if label:
... return value
... return f"{value} kr"
...
... return format_krona
...
... def convert_column(self, values):
... # Drop the fractional kr.
... return values.astype(int)
>>> account_info.set_format("balance", IcelandKronaFormatter)
user | balance
gfoo | 200 kr
bbar | 555 kr
tbaz | 125 kr
hbat | 430 kr
>>> account_info
user | balance
gfoo | 200 kr
bbar | 555 kr
tbaz | 125 kr
hbat | 430 kr
>>> account_info["balance"]
array([200, 555, 125, 430])
In the following example, multiple columns are configured to use the same
formatter. Note the following formatter takes into account the length of all
values in the column and formats them to be the same character length. This is
something that the default table formatter does for you but, if you write a
custom formatter, you must do yourself.
>>> account_info = Table().with_columns(
... "user", make_array("gfoo", "bbar", "tbaz", "hbat"),
... "checking", make_array(200, 555, 125, 430),
... "savings", make_array(1000, 500, 1175, 6700))
>>> account_info
user | checking | savings
gfoo | 200 | 1000
bbar | 555 | 500
tbaz | 125 | 1175
hbat | 430 | 6700
>>> class IcelandKronaFormatter():
... def __init__(self):
... self.converts_values = False
...
... def format_column(self, label, column):
... val_width = max([len(str(v)) + len(" kr") for v in column])
... val_width = max(len(str(label)), val_width)
...
... def format_krona(value, label):
... if label:
... return value
... return f"{value} kr".ljust(val_width)
...
... return format_krona
>>> account_info.set_format(["checking", "savings"], IcelandKronaFormatter)
user | checking | savings
gfoo | 200 kr | 1000 kr
bbar | 555 kr | 500 kr
tbaz | 125 kr | 1175 kr
hbat | 430 kr | 6700 kr
"""
if inspect.isclass(formatter):
formatter = formatter()
if callable(formatter) and not hasattr(formatter, 'format_column'):
formatter = _formats.FunctionFormatter(formatter)
if not hasattr(formatter, 'format_column'):
raise Exception('Expected Formatter or function: ' + str(formatter))
for label in self._as_labels(column_or_columns):
if formatter.converts_values:
self[label] = formatter.convert_column(self[label])
self._formats[label] = formatter
return self
def move_to_start(self, column_label):
"""
Move a column to be the first column.
The following example moves column C to be the first column. Note, move_to_start
not only returns the original table with the column moved but, it also moves
the column in the original. This is what's known as an inplace operation.
>>> table = Table().with_columns(
... "A", make_array(1, 2, 3, 4),
... "B", make_array("foo", "bar", "baz", "bat"),
... "C", make_array('a', 'b', 'c', 'd'))
>>> table
A | B | C
1 | foo | a
2 | bar | b
3 | baz | c
4 | bat | d
>>> table.move_to_start("C")
C | A | B
a | 1 | foo
b | 2 | bar
c | 3 | baz
d | 4 | bat
>>> table
C | A | B
a | 1 | foo
b | 2 | bar
c | 3 | baz
d | 4 | bat
"""
self._columns.move_to_end(self._as_label(column_label), last=False)
return self
def move_to_end(self, column_label):
"""
Move a column to be the last column.
The following example moves column A to be the last column. Note, move_to_end
not only returns the original table with the column moved but, it also moves
the column in the original. This is what's known as an inplace operation.
>>> table = Table().with_columns(
... "A", make_array(1, 2, 3, 4),
... "B", make_array("foo", "bar", "baz", "bat"),
... "C", make_array('a', 'b', 'c', 'd'))
>>> table
A | B | C
1 | foo | a
2 | bar | b
3 | baz | c
4 | bat | d
>>> table.move_to_end("A")
B | C | A
foo | a | 1
bar | b | 2
baz | c | 3
bat | d | 4
>>> table
B | C | A
foo | a | 1
bar | b | 2
baz | c | 3
bat | d | 4
"""
self._columns.move_to_end(self._as_label(column_label))
return self
def append(self, row_or_table):
"""
Append a row or all rows of a table in place. An appended table must have all
columns of self.
The following example appends a row record to the table,
followed by appending a table having all columns of self.
>>> table = Table().with_columns(
... "A", make_array(1),
... "B", make_array("foo"),
... "C", make_array('a'))
>>> table
A | B | C
1 | foo | a
>>> table.append([2, "bar", 'b'])
A | B | C
1 | foo | a
2 | bar | b
>>> table
A | B | C
1 | foo | a
2 | bar | b
>>> table.append(Table().with_columns(
... "A", make_array(3, 4),
... "B", make_array("baz", "bat"),
... "C", make_array('c', 'd')))
A | B | C
1 | foo | a
2 | bar | b
3 | baz | c
4 | bat | d
>>> table
A | B | C
1 | foo | a
2 | bar | b
3 | baz | c
4 | bat | d
"""
if isinstance(row_or_table, np.ndarray):
row_or_table = row_or_table.tolist()
elif not row_or_table:
return
if isinstance(row_or_table, Table):
t = row_or_table
columns = list(t.select(self.labels)._columns.values())
n = t.num_rows
else:
if (len(list(row_or_table)) != self.num_columns):
raise Exception('Row should have '+ str(self.num_columns) + " columns")
columns, n = [[value] for value in row_or_table], 1
for i, column in enumerate(self._columns):
if self.num_rows:
self._columns[column] = np.append(self[column], columns[i])
else:
self._columns[column] = np.array(columns[i])
self._num_rows += n
return self
def append_column(self, label, values, formatter=None):
"""Appends a column to the table or replaces a column.
``__setitem__`` is aliased to this method:
``table.append_column('new_col', make_array(1, 2, 3))`` is equivalent to
``table['new_col'] = make_array(1, 2, 3)``.
Args:
``label`` (str): The label of the new column.
``values`` (single value or list/array): If a single value, every
value in the new column is ``values``.
If a list or array, the new column contains the values in
``values``, which must be the same length as the table.
``formatter`` (single formatter): Adds a formatter to the column being
appended. No formatter added by default.
Returns:
Original table with new or replaced column
Raises:
``ValueError``: If
- ``label`` is not a string.
- ``values`` is a list/array and does not have the same length
as the number of rows in the table.
>>> table = Table().with_columns(
... 'letter', make_array('a', 'b', 'c', 'z'),
... 'count', make_array(9, 3, 3, 1),
... 'points', make_array(1, 2, 2, 10))
>>> table
letter | count | points
a | 9 | 1
b | 3 | 2
c | 3 | 2
z | 1 | 10
>>> table.append_column('new_col1', make_array(10, 20, 30, 40))
letter | count | points | new_col1
a | 9 | 1 | 10
b | 3 | 2 | 20
c | 3 | 2 | 30
z | 1 | 10 | 40
>>> table.append_column('new_col2', 'hello')
letter | count | points | new_col1 | new_col2
a | 9 | 1 | 10 | hello
b | 3 | 2 | 20 | hello
c | 3 | 2 | 30 | hello
z | 1 | 10 | 40 | hello
>>> table.append_column(123, make_array(1, 2, 3, 4))
Traceback (most recent call last):
...
ValueError: The column label must be a string, but a int was given
>>> table.append_column('bad_col', [1, 2])
Traceback (most recent call last):
...
ValueError: Column length mismatch. New column does not have the same number of rows as table.
"""
# TODO(sam): Allow append_column to take in a another table, copying
# over formatter as needed.
if not isinstance(label, str):
raise ValueError('The column label must be a string, but a '
'{} was given'.format(label.__class__.__name__))
if not isinstance(values, np.ndarray):
# Coerce a single value to a sequence
if not _util.is_non_string_iterable(values):
values = [values] * max(self.num_rows, 1)
# Manually cast `values` as an object due to this: https://github.com/data-8/datascience/issues/458
if any(_util.is_non_string_iterable(el) for el in values):
values = np.array(tuple(values), dtype=object)
else:
values = np.array(tuple(values))
if self.num_rows != 0 and len(values) != self.num_rows:
raise ValueError('Column length mismatch. New column does not have '
'the same number of rows as table.')
else:
self._num_rows = len(values)
self._columns[label] = values
if (formatter != None):
self.set_format(label, formatter)
return self
def relabel(self, column_label, new_label):
"""Changes the label(s) of column(s) specified by ``column_label`` to
labels in ``new_label``.
Args:
``column_label`` -- (single str or array of str) The label(s) of
columns to be changed to ``new_label``.
``new_label`` -- (single str or array of str): The label name(s)
of columns to replace ``column_label``.
Raises:
``ValueError`` -- if ``column_label`` is not in table, or if
``column_label`` and ``new_label`` are not of equal length.
``TypeError`` -- if ``column_label`` and/or ``new_label`` is not
``str``.
Returns:
Original table with ``new_label`` in place of ``column_label``.
>>> table = Table().with_columns(
... 'points', make_array(1, 2, 3),
... 'id', make_array(12345, 123, 5123))
>>> table.relabel('id', 'yolo')
points | yolo
1 | 12345
2 | 123
3 | 5123