datapad.fields.add#

datapad.fields.add(*args)#

Constructs a function to add or append new fields to a dict or list of data. The returned function will assume one of the following signatures:

F(data: list) -> list
F(data: dict) -> dict

This function is commonly used in conjunction with datapad.Sequence.map() to add new fields to structured sequence data.

Possible ways to call the add function:

# Append a single field with a value of `func(data)` to list `data`
add(func: Function)

# Add a single field to dict `data` by applying `data[key]` = `func(data)`
add(key: Hashable, func: Function)

# Append multiple fields with values [f(data) for f in funcs] to a list `data`
add(funcs: List[func: Function])

# Add multiple fields to a dict `data` by applying `data[key]` = `funcs[key](data)`
add(funcs: Dict[key: Hashable, value: Function])
Parameters:
  • key (hashable) – A string, int, or other hashable value to be used as the name of the added field.

  • func (function) – A function of the form f(data) to compute the value of the newly added element.

  • funcs (List[Function], or Dict[Hashable, Function]) –

    • If funcs is a list, data will be extended with values computed from f(data) for f in funcs

    • If funcs is a dict, data[key] will be updated with values computed from funcs[key]. Note: this will overwrite any existing keys with the same name in data.

Examples

In the examples below, assume data represents a single row or element from a datapad.Sequence object.

Add a single new element to end of list

>>> data = [1, 2, 3]
>>> F = add(lambda data: data[0] * data[1] * data[2])
>>> F(data)
[1, 2, 3, 6]

Add a single new dictionary key and value:

>>> data = {'a': 1, 'b': 2}
>>> F = add('c', lambda data: data['a'] + data['b'])
>>> F(data)
{'a': 1, 'b': 2, 'c': 3}

Add new dictionary keys:

>>> data = {'a': 1, 'b': 2}
>>> F = add({ 'c': (lambda data: data['a'] + data['b']), 'd': lambda data: 10})
>>> F(data)
{'a': 1, 'b': 2, 'c': 3, 'd': 10}

Append new list elements:

>>> data = ['foo', 'bar']
>>> F = add([lambda data: data[1] + data[0]])
>>> F(data)
['foo', 'bar', 'barfoo']