turicreate.SArray.apply

SArray.apply(fn, dtype=None, skip_na=True)

Transform each element of the SArray by a given function. The result SArray is of type dtype. fn should be a function that returns exactly one value which can be cast into the type specified by dtype. If dtype is not specified, the first 100 elements of the SArray are used to make a guess about the data type.

Parameters:
fn : function

The function to transform each element. Must return exactly one value which can be cast into the type specified by dtype. This can also be a toolkit extension function which is compiled as a native shared library using SDK.

dtype : {None, int, float, str, list, array.array, dict, turicreate.Image}, optional

The data type of the new SArray. If None, the first 100 elements of the array are used to guess the target data type.

skip_na : bool, optional

If True, will not apply fn to any undefined values.

Returns:
out : SArray

The SArray transformed by fn. Each element of the SArray is of type dtype.

See also

SFrame.apply

Examples

>>> sa = turicreate.SArray([1,2,3])
>>> sa.apply(lambda x: x*2)
dtype: int
Rows: 3
[2, 4, 6]

Using native toolkit extension function:

#include <model_server/lib/toolkit_function_macros.hpp>
#include <cmath>

using namespace turi;
double logx(const flexible_type& x, double base) {
  return log((double)(x)) / log(base);
}

BEGIN_FUNCTION_REGISTRATION
REGISTER_FUNCTION(logx, "x", "base");
END_FUNCTION_REGISTRATION

compiled into example.so

>>> import example
>>> sa = turicreate.SArray([1,2,4])
>>> sa.apply(lambda x: example.logx(x, 2))
dtype: float
Rows: 3
[0.0, 1.0, 2.0]