datapad.fields.apply#
- datapad.fields.apply(*args)#
Constructs a function to transform the fields in 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 manipulate structured sequence data.Possible ways to call the
applyfunction:# apply func to all fields in data apply(func: Function) # apply func to data[key] field apply(key: Hashable, func: Function) # apply funcs[i] to data[i] fields apply(funcs: List[Function]) # apply funcs[key] to data[key] fields apply(funcs: Dict[Hashable, Function])
- Parameters:
key (string, int, hashable) – A string, int, or other hashable value to be used to look up the field value to transform.
func (function) – A function that will take a single field value and transform it into a new value.
funcs (List[Function], or Dict[Hashable, Function]) –
If funcs is a list,
F(data)will applyfuncs[i]todata[i].If funcs is a dict,
F(data)will applyfuncs[key]todata[key].If a key in
datahas no corresponding key infuncs, return thedata[key]field untransformed.If a key in
funcshas no corresponding key indata, abstain from applyingfuncs[key]
Examples
In the examples below, assume
datarepresents a single row or element from adatapad.Sequenceobject.Apply a single function to all fields:
>>> data = [1, 2, 3] >>> F = apply(lambda x: x * 2) >>> F(data) [2, 4, 6]
Apply a single function to a single field of a list (i.e. the value associated with the 2nd index):
>>> data = [1, 2, 3] >>> F = apply(1, lambda x: x * 2) >>> F(data) [1, 4, 3]
Apply a single function to a single field of a dict (i.e. the value associated with key ‘a’):
>>> data = {'a': 1, 'b': 2, 'c': 3} >>> F = apply('a', lambda x: x * 2) >>> F(data) {'a': 2, 'b': 2, 'c': 3}
Apply multiple functions to several fields of a dict (i.e. the values associated with keys ‘a’, ‘b’, ‘c’, and ‘d’):
>>> data = {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> F = apply({'a': lambda x: x*3, 'b': lambda x: 'foo'}) >>> F(data) {'a': 3, 'b': 'foo', 'c': 3, 'd': 4}
Apply multiple functions to several fields of a list (i.e. the values associated with index 0, and 1):
>>> data = [1, 2, 3, 4] >>> F = apply({1: lambda x: x*3, 0: lambda x: 'foo'}) >>> F(data) ['foo', 6, 3, 4]
Apply multiple functions to several fields of a list (i.e. the values associated with index 0, and 1):
>>> data = [1, 2, 3, 4] >>> F = apply([lambda x: x*2, lambda x: x*3]) >>> F(data) [2, 6, 3, 4]