-
Notifications
You must be signed in to change notification settings - Fork 282
/
tables.py
2066 lines (1750 loc) · 75.7 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', 'Q']
import abc
import collections
import collections.abc
import functools
import inspect
import itertools
import numbers
import urllib.parse
import warnings
import numpy as np
import matplotlib
matplotlib.use('agg', warn=False)
import matplotlib.pyplot as plt
import pandas
import IPython
import datascience.maps as _maps
import datascience.formats as _formats
import datascience.util as _util
class Table(collections.abc.MutableMapping):
"""A sequence of string-labeled columns."""
def __init__(self, labels=None, _deprecated=None, *, formatter=_formats.default_formatter):
"""Create an empty table with column labels.
>>> tiles = Table(['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
if _deprecated is not None:
warnings.warn("Two-argument __init__ is deprecated. Use Table().with_columns(...)", FutureWarning)
columns, labels = labels, _deprecated
columns = columns if columns is not None else []
labels = labels if labels is not None else []
assert len(labels) == len(columns), 'label/column number mismatch'
else:
labels = labels if labels is not None else []
columns = [[] for _ in labels]
self._num_rows = 0 if len(columns) is 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 empty(cls, labels=None):
"""Create an empty table. Column labels are optional. [Deprecated]
Args:
``labels`` (None or list): If ``None``, a table with 0
columns is created.
If a list, each element is a column label in a table with
0 rows.
Returns:
A new instance of ``Table``.
"""
warnings.warn("Table.empty(labels) is deprecated. Use Table(labels)", FutureWarning)
if labels is None:
return cls()
values = [[] for label in labels]
return cls(values, labels)
# 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)."""
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.
filepath_or_buffer -- string or file handle / StringIO; The string
could be a URL. Valid URL schemes include http,
ftp, s3, and file.
"""
# Look for .csv at the end of the path; use "," as a separator if found
try:
path = urllib.parse.urlparse(filepath_or_buffer).path
except AttributeError:
path = filepath_or_buffer
try:
if 'sep' not in vargs and path.endswith('.csv'):
vargs['sep'] = ','
except AttributeError:
pass
df = pandas.read_table(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):
"""Convert a Pandas DataFrame into a Table."""
labels = df.columns
return cls().with_columns([(label, df[label].values) for label in labels])
@classmethod
def from_array(cls, arr):
"""Convert a structured NumPy array into a Table."""
return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])
#################
# Magic Methods #
#################
def __getitem__(self, index_or_label):
label = self._as_label(index_or_label)
return self.column(label)
def __setitem__(self, label, values):
self.append_column(label, values)
def __delitem__(self, 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)
# Deprecated
def __getattr__(self, attr):
"""Return a method that applies to all columns or a table of attributes. [Deprecated]
E.g., t.sum() on a Table will return a table with the sum of each column.
"""
if self.columns and all(hasattr(c, attr) for c in self.columns):
warnings.warn("Implicit column method lookup is deprecated.", FutureWarning)
attrs = [getattr(c, attr) for c in self.columns]
if all(callable(attr) for attr in attrs):
@functools.wraps(attrs[0])
def method(*args, **vargs):
"""Create a table from the results of calling attrs."""
columns = [attr(*args, **vargs) for attr in attrs]
return self._with_columns(columns)
return method
else:
return self._with_columns([[attr] for attr in attrs])
else:
msg = "'{0}' object has no attribute '{1}'".format(type(self).__name__, attr)
raise AttributeError(msg)
####################
# Accessing Values #
####################
@property
def num_rows(self):
"""Number of rows."""
return self._num_rows
@property
def rows(self):
"""Return a view of all rows."""
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."""
return tuple(self._columns.keys())
# Deprecated
@property
def column_labels(self):
"""Return a tuple of column labels. [Deprecated]"""
warnings.warn("column_labels is deprecated; use labels", FutureWarning)
return self.labels
@property
def num_columns(self):
"""Number of columns."""
return len(self.labels)
@property
def columns(self):
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', ['c', 'd'],
... 'count', [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``.
"""
return self._columns[self._as_label(index_or_label)]
# Deprecated
def values(self, label):
"""Returns the values of a column as an array. [Deprecated]"""
warnings.warn("values is deprecated; use column", FutureWarning)
return self.column(label)
def column_index(self, column_label):
"""Return the index of a column."""
return self.labels.index(column_label)
def apply(self, fn, column_label):
"""Returns an array where ``fn`` is applied to each set of elements
by row from the specified columns in ``column_label``.
Args:
``fn`` (function): The function to be applied to elements specified
by ``column_label``.
``column_label`` (single string or list of strings): Names of
columns to be passed into function ``fn``. Length must match
number of elements ``fn`` takes.
Raises:
``ValueError``: column name in ``column_label`` is not an existing
column in the table.
Returns:
A numpy array consisting of results of applying ``fn`` to elements
specified by ``column_label`` in each row.
>>> t = Table().with_columns([
... 'letter', ['a', 'b', 'c', 'z'],
... 'count', [9, 3, 3, 1],
... 'points', [1, 2, 2, 10]])
>>> t
letter | count | points
a | 9 | 1
b | 3 | 2
c | 3 | 2
z | 1 | 10
>>> t.apply(lambda x, y: x * y, ['count', 'points'])
array([ 9, 6, 6, 10])
>>> t.apply(lambda x: x - 1, 'points')
array([0, 1, 1, 9])
"""
rows = zip(*self.select(column_label).columns)
return np.array([fn(*row) for row in rows])
############
# Mutation #
############
def set_format(self, column_label_or_labels, formatter):
"""Set the format of a column."""
if inspect.isclass(formatter) and issubclass(formatter, _formats.Formatter):
formatter = formatter()
for label in self._as_labels(column_label_or_labels):
if callable(formatter):
self._formats[label] = lambda v, label: v if label else str(formatter(v))
elif isinstance(formatter, _formats.Formatter):
if formatter.converts_values:
self[label] = self.apply(formatter.convert, label)
column = self[label]
self._formats[label] = formatter.format_column(label, column)
else:
raise Exception('Expected Formatter or function: ' + str(formatter))
return self
def move_to_start(self, column_label):
"""Move a column to the first in order."""
self._columns.move_to_end(column_label, last=False)
return self
def move_to_end(self, column_label):
"""Move a column to the last in order."""
self._columns.move_to_end(column_label)
return self
def append(self, row_or_table):
"""Append a row or all rows of a table. An appended table must have all
columns of self."""
if 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:
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):
"""Appends a column to the table or replaces a column.
``__setitem__`` is aliased to this method:
``table.append_column('new_col', [1, 2, 3])`` is equivalent to
``table['new_col'] = [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.
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', ['a', 'b', 'c', 'z'],
... 'count', [9, 3, 3, 1],
... 'points', [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', [10, 20, 30, 40])
>>> table
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')
>>> table
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, [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 _is_non_string_iterable(values):
values = [values] * max(self.num_rows, 1)
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
def relabel(self, column_label, new_label):
"""Change the labels of columns specified by ``column_label`` to
labels in ``new_label``.
Args:
``column_label`` (single str or list/array of str): The label(s) of
columns to be changed. Must be str.
``new_label`` (single str or list/array of str): The new label(s) of
columns to be changed. Must be str.
Number of elements must match number of elements in
``column_label``.
Returns:
Original table with modified labels
>>> table = Table().with_columns([
... 'points', (1, 2, 3),
... 'id', (12345, 123, 5123)])
>>> table.relabel('id', 'yolo')
points | yolo
1 | 12345
2 | 123
3 | 5123
>>> table.relabel(['points', 'yolo'], ['red', 'blue'])
red | blue
1 | 12345
2 | 123
3 | 5123
>>> table.relabel(['red', 'green', 'blue'], ['cyan', 'magenta', 'yellow', 'key'])
Traceback (most recent call last):
...
ValueError: Invalid arguments. column_label and new_label must be of equal length.
>>> table.relabel(['red', 'blue'], ['blue', 'red'])
blue | red
1 | 12345
2 | 123
3 | 5123
"""
if isinstance(column_label, numbers.Integral):
column_label = self._as_label(column_label)
if isinstance(column_label, str) and isinstance(new_label, str):
column_label, new_label = [column_label], [new_label]
if len(column_label) != len(new_label):
raise ValueError('Invalid arguments. column_label and new_label '
'must be of equal length.')
old_to_new = dict(zip(column_label, new_label)) # maps old labels to new ones
for label in column_label:
if not (label in self.labels):
raise ValueError('Invalid labels. Column labels must '
'already exist in table in order to be replaced.')
rewrite = lambda s: old_to_new[s] if s in old_to_new else s
columns = [(rewrite(s), c) for s, c in self._columns.items()]
self._columns = collections.OrderedDict(columns)
for label in self._formats:
# TODO(denero) Error when old and new columns share a name
if label in column_label:
formatter = self._formats.pop(label)
self._formats[old_to_new[label]] = formatter
return self
##################
# Transformation #
##################
def copy(self, *, shallow=False):
"""Return a copy of a Table."""
table = type(self)()
for label in self.labels:
if shallow:
column = self[label]
else:
column = np.copy(self[label])
self._add_column_and_format(table, label, column)
return table
def select(self, column_label_or_labels):
"""Return a Table with selected column or columns by label.
Args:
``column_label_or_labels`` (string or list of strings): The header
names of the columns to be selected. ``column_label_or_labels`` must
be an existing header name.
Returns:
An instance of ``Table`` containing only selected columns.
>>> t = Table().with_columns([
... 'burgers', ['cheeseburger', 'hamburger', 'veggie burger'],
... 'prices', [6, 5, 5],
... 'calories', [743, 651, 582]])
>>> t
burgers | prices | calories
cheeseburger | 6 | 743
hamburger | 5 | 651
veggie burger | 5 | 582
>>> t.select(['burgers', 'calories'])
burgers | calories
cheeseburger | 743
hamburger | 651
veggie burger | 582
>>> t.select('prices')
prices
6
5
5
"""
labels = self._as_labels(column_label_or_labels)
table = Table()
for label in labels:
self._add_column_and_format(table, label, np.copy(self[label]))
return table
# These, along with a snippet below, are necessary for Sphinx to
# correctly load the `take` and `exclude` docstrings. The definitions
# will be over-ridden during class instantiation.
def take(self):
raise NotImplementedError()
def exclude(self):
raise NotImplementedError()
def drop(self, column_label_or_labels):
"""Return a Table with only columns other than selected label or labels."""
exclude = _as_labels(column_label_or_labels)
return self.select([c for c in self.labels if c not in exclude])
def where(self, column_or_label, value=None):
"""Return a Table of rows for which the column is value or a non-zero value."""
column = self._get_column(column_or_label)
if value is not None:
column = column == value
return self.take(np.nonzero(column)[0])
def sort(self, column_or_label, descending=False, distinct=False):
"""Return a Table of sorted rows by the values in a column."""
column = self._get_column(column_or_label)
if distinct:
_, row_numbers = np.unique(column, return_index=True)
else:
row_numbers = np.argsort(column, axis=0, kind='mergesort')
assert (row_numbers < self.num_rows).all(), row_numbers
if descending:
row_numbers = np.array(row_numbers[::-1])
return self.take(row_numbers)
def group(self, column_or_label, collect=None):
"""Group rows by unique values in a column; count or aggregate others.
column_or_label -- values to group (label, index, or column)
collect -- a function applied to values in other columns for each group
The grouped column will appear first in the result table. If no collect
function is provided, only counts are shown.
"""
self = self.copy(shallow=True)
collect = _zero_on_type_error(collect)
# Remove column used for grouping
column = self._get_column(column_or_label)
if isinstance(column_or_label, str) or isinstance(column_or_label, numbers.Integral):
column_label = self._as_label(column_or_label)
del self[column_label]
else:
column_label = self._unused_label('group')
# Group by column
groups = self.index_by(column)
keys = sorted(groups.keys())
# Generate grouped columns
if collect is None:
labels = [column_label, 'count' if column_label != 'count' else self._unused_label('count')]
columns = [keys, [len(groups[k]) for k in keys]]
else:
columns, labels = [], []
for i, label in enumerate(self.labels):
labels.append(_collected_label(collect, label))
c = [collect(np.array([row[i] for row in groups[k]])) for k in keys]
columns.append(c)
grouped = type(self)().with_columns(zip(labels, columns))
assert column_label == self._unused_label(column_label)
grouped[column_label] = keys
grouped.move_to_start(column_label)
return grouped
def groups(self, labels, collect=None):
"""Group rows by multiple columns, aggregating values."""
collect = _zero_on_type_error(collect)
columns = []
labels = self._as_labels(labels)
for label in labels:
if label not in self.labels:
raise ValueError("All labels must exist in the table")
columns.append(self._get_column(label))
grouped = self.group(list(zip(*columns)), lambda s: s)
grouped._columns.popitem(last=False) # Discard the column of tuples
# Flatten grouping values and move them to front
counts = [len(v) for v in grouped[0]]
for label in labels[::-1]:
grouped[label] = grouped.apply(_assert_same, label)
grouped.move_to_start(label)
# Aggregate other values
if collect is None:
count = 'count' if 'count' not in labels else self._unused_label('count')
return grouped.select(labels).with_column(count, counts)
else:
for label in grouped.labels:
if label in labels:
continue
column = [collect(v) for v in grouped[label]]
del grouped[label]
grouped[_collected_label(collect, label)] = column
return grouped
def pivot(self, columns, rows, values=None, collect=None, zero=None):
"""Generate a table with a column for rows (or a column for each row
in rows list) and a column for each unique value in columns. Each row
counts/aggregates the values that match both row and column.
columns -- column label in self
rows -- column label or a list of column labels
values -- column label in self (or None to produce counts)
collect -- aggregation function over values
zero -- zero value for non-existent row-column combinations
"""
if collect is not None and values is None:
raise TypeError('collect requires values to be specified')
if values is not None and collect is None:
raise TypeError('values requires collect to be specified')
rows = self._as_labels(rows)
if values is None:
selected = self.select([columns] + rows)
else:
selected = self.select([columns, values] + rows)
grouped = selected.groups([columns] + rows, collect)
if values is None:
values = grouped.labels[-1]
# Generate existing combinations of values from columns in rows
rows_values = sorted(list(set(self.select(rows).rows)))
pivoted = type(self)(rows).with_rows(rows_values)
# Generate other columns and add them to pivoted
by_columns = grouped.index_by(columns)
for label in sorted(by_columns):
tuples = [t[1:] for t in by_columns[label]] # Discard column value
column = _fill_with_zeros(rows_values, tuples, zero)
pivot = self._unused_label(str(label))
pivoted[pivot] = column
return pivoted
def pivot_bin(self, pivot_columns, value_column, bins=None, **vargs) :
"""Form a table with columns formed by the unique tuples in pivot_columns
containing counts per bin of the values associated with each tuple in the value_column.
By default, bins are chosen to contain all values in the value_column. The
following named arguments from numpy.histogram can be applied to
specialize bin widths:
Args:
``bins`` (int or sequence of scalars): If bins is an int,
it defines the number of equal-width bins in the given range
(10, by default). If bins is a sequence, it defines the bin
edges, including the rightmost edge, allowing for non-uniform
bin widths.
``range`` ((float, float)): The lower and upper range of
the bins. If not provided, range contains all values in the
table. Values outside the range are ignored.
``normed`` (bool): If False, the result will contain the number of
samples in each bin. If True, the result is normalized such that
the integral over the range is 1.
"""
pivot_columns = _as_labels(pivot_columns)
selected = self.select(pivot_columns + [value_column])
grouped=selected.groups(pivot_columns)
# refine bins by taking a histogram over all the data
if bins is not None:
vargs['bins'] = bins
_, rbins = np.histogram(self[value_column],**vargs)
# create a table with these bins a first column and counts for each group
vargs['bins'] = rbins
binned = Table([rbins],['bin'])
for group in grouped.rows:
col_label = "-".join(map(str,group[0:-1]))
col_vals = group[-1]
counts,_ = np.histogram(col_vals,**vargs)
binned[col_label] = np.append(counts,0)
return binned
def stack(self, key, labels=None):
"""Takes k original columns and returns two columns, with col. 1 of
all column names and col. 2 of all associated data.
"""
rows, labels = [], labels or self.labels
for row in self.rows:
[rows.append((getattr(row, key), k, v)) for k, v in row.asdict().items()
if k != key and k in labels]
return type(self)([key, 'column', 'value']).with_rows(rows)
def join(self, column_label, other, other_label=None):
"""Generate a table with the columns of self and other, containing rows
for all values of a column that appear in both tables.
If a join value appears more than once in self, each row will be used,
but in the other table, only the first of each will be used.
If the result is empty, return None.
"""
if self.num_rows == 0 or other.num_rows == 0:
return None
if not other_label:
other_label = column_label
self_rows = self.index_by(column_label)
other_rows = other.index_by(other_label)
# Gather joined rows from self_rows that have join values in other_rows
joined_rows = []
for label, rows in self_rows.items():
if label in other_rows:
other_row = other_rows[label][0]
joined_rows += [row + other_row for row in rows]
if not joined_rows:
return None
labels = list(self.labels)
labels += [self._unused_label(s) for s in other.labels]
joined = type(self)(labels).with_rows(joined_rows)
del joined[self._unused_label(other_label)] # Remove redundant column
return joined.move_to_start(column_label).sort(column_label)
def stats(self, ops=(min, max, np.median, sum)):
"""Compute statistics for each column and place them in a table."""
names = [op.__name__ for op in ops]
ops = [_zero_on_type_error(op) for op in ops]
columns = [[op(column) for op in ops] for column in self.columns]
table = Table(columns, self.labels)
stats = table._unused_label('statistic')
table[stats] = names
table.move_to_start(stats)
return table
def _as_label(self, index_or_label):
"""Convert index to label."""
if isinstance(index_or_label, str):
return index_or_label
if isinstance(index_or_label, numbers.Integral):
return self.labels[index_or_label]
else:
raise ValueError(str(index_or_label) + ' is not a label or index')
def _as_labels(self, label_or_labels):
"""Convert single label to list and convert indices to labels."""
return [self._as_label(s) for s in _as_labels(label_or_labels)]
def _unused_label(self, label):
"""Generate an unused label."""
original = label
existing = self.labels
i = 2
while label in existing:
label = '{}_{}'.format(original, i)
i += 1
return label
def _get_column(self, column_or_label):
"""Convert label to column and check column length."""
c = column_or_label
if isinstance(c, collections.Hashable) and c in self.labels:
return self[c]
elif isinstance(c, numbers.Integral):
return self[c]
elif isinstance(c, str):
raise ValueError('label "{}" not in labels {}'.format(c, self.labels))
else:
assert len(c) == self.num_rows, 'column length mismatch'
return c
def percentile(self, p):
"""Returns a new table with one row containing the pth percentile for
each column.
Assumes that each column only contains one type of value.
Returns a new table with one row and the same column labels.
The row contains the pth percentile of the original column, where the
pth percentile of a column is the smallest value that at at least as
large as the p% of numbers in the column.
>>> table = Table().with_columns([
... 'count', [9, 3, 3, 1],
... 'points', [1, 2, 2, 10]])
>>> table
count | points
9 | 1
3 | 2
3 | 2
1 | 10
>>> table.percentile(67)
count | points
9 | 10
"""
percentiles = [[_util.percentile(p, column)] for column in self.columns]
return self._with_columns(percentiles)
def sample(self, k=None, with_replacement=False, weights=None):
"""Returns a new table where k rows are randomly sampled from the
original table.
Kwargs:
k (int or None): If None (default), all the rows in the table are
sampled. If an integer, k rows from the original table are
sampled.
with_replacement (bool): If False (default), samples the rows
without replacement. If True, samples the rows with replacement.
weights (list/array or None): If None (default), samples the rows
using a uniform random distribution. If a list/array is passed
in, it must be the same length as the number of rows in the
table and the values must sum to 1. The rows will then be
sampled according the the probability distribution in
``weights``.
Returns:
A new instance of ``Table``.
>>> jobs = Table().with_columns([
... 'job', ['a', 'b', 'c', 'd'],
... 'wage', [10, 20, 15, 8]])
>>> jobs
job | wage
a | 10
b | 20
c | 15
d | 8
>>> jobs.sample() # doctest: +SKIP
job | wage
b | 20
c | 15
a | 10
d | 8
>>> jobs.sample(k = 2) # doctest: +SKIP
job | wage
b | 20
c | 15
>>> jobs.sample(k = 2, with_replacement = True,
... weights = [0.5, 0.5, 0, 0]) # doctest: +SKIP
job | wage
a | 10
a | 10
"""
n = self.num_rows
if k is None:
k = n
index = np.random.choice(n, k, replace=with_replacement, p=weights)
columns = [[c[i] for i in index] for c in self.columns]
sample = self._with_columns(columns)
return sample
def split(self, k):
"""Returns a tuple of two tables where the first table contains
``k`` rows randomly sampled and the second contains the remaining rows.
Args:
``k`` (int): The number of rows randomly sampled into the first
table. ``k`` must be between 1 and ``num_rows - 1``.
Raises:
``ValueError``: ``k`` is not between 1 and ``num_rows - 1``.
Returns:
A tuple containing two instances of ``Table``.
>>> jobs = Table().with_columns([
... 'job', ['a', 'b', 'c', 'd'],
... 'wage', [10, 20, 15, 8]])
>>> jobs
job | wage
a | 10
b | 20
c | 15
d | 8
>>> sample, rest = jobs.split(3)
>>> sample # doctest: +SKIP
job | wage
c | 15
a | 10
b | 20
>>> rest # doctest: +SKIP
job | wage
d | 8
"""
if not 1 <= k <= self.num_rows - 1:
raise ValueError("Invalid value of k. k must be between 1 and the"
"number of rows - 1")
rows = [self.rows[index] for index in
np.random.permutation(self.num_rows)]
cls = type(self)
first = cls(self.labels).with_rows(rows[:k])
rest = cls(self.labels).with_rows(rows[k:])
for column_label in self._formats:
first._formats[column_label] = self._formats[column_label]
rest._formats[column_label] = self._formats[column_label]
return first, rest
def with_row(self, row):
"""Return a table with an additional row.
Args:
``row`` (sequence): A value for each column.
Raises:
``ValueError``: If the row length differs from the column count.
>>> tiles = Table(['letter', 'count', 'points'])
>>> tiles.with_row(['c', 2, 3]).with_row(['d', 4, 2])
letter | count | points
c | 2 | 3
d | 4 | 2
"""
self = self.copy()
self.append(row)
return self
def with_rows(self, rows):
"""Return a table with additional rows.
Args:
``rows`` (sequence of sequences): Each row has a value per column.
If ``rows`` is a 2-d array, its shape must be (_, n) for n columns.
Raises:
``ValueError``: If a row length differs from the column count.
>>> tiles = Table(['letter', 'count', 'points'])
>>> tiles.with_rows([['c', 2, 3], ['d', 4, 2]])
letter | count | points
c | 2 | 3
d | 4 | 2
"""
self = self.copy()
self.append(self._with_columns(zip(*rows)))
return self
def with_column(self, label, values):
"""Return a table with an additional or replaced column.
Args:
``label`` (str): The column label. If an existing label is used,
that column will be replaced in the returned table.
``values`` (single value or sequence): If a single value, every
value in the new column is ``values``.
If a sequence, the new column contains the values in
``values``. ``values`` must be the same length as the table.