datascience.tables.Table.apply

Table.apply(fn, column_label=None)[source]

Apply fn to each element of column_label. If no column_label provided, fn` applied to each row of table.

Args:
fn (function) – The function to be applied to elements of
column_label.
column_label (single str or array of str) – Names of
columns to be passed into fn. Length must match number of arguments in fn signature.
Raises:
ValueError – if column_label is not an existing
column in the table.
TypeError – if insufficent 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, make_array('count', 'points'))
array([ 9,  6,  6, 10])
>>> t.apply(lambda x: x - 1, make_array('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])