pandas.Series.apply

Invoke function on values of Series.

Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values.

param func
function

Python function or NumPy ufunc to apply.

param convert_dtype
bool, default True

Try to find better dtype for elementwise function results. If False, leave as dtype=object.

param args
tuple

Positional arguments passed to func after the series value. **kwds Additional keyword arguments passed to func.

return

Series or DataFrame If func returns a Series object the result will be a DataFrame.

Limitations

  • Parameters convert_dtype and args are currently unsupported by Intel Scalable Dataframe Compiler.

  • function returning a Series object is currently unsupported by Intel Scalable Dataframe Compiler.

Examples

Square the values by defining a function and passing it as an argument to apply().
import pandas as pd
import numpy as np
from numba import njit


@njit
def series_apply():
    s = pd.Series([20, 21, 12],
                  index=['London', 'New York', 'Helsinki'])

    def square(x):
        return x ** 2

    return s.apply(square)


print(series_apply())
$ python ./series/series_apply.py
London      400
New York    441
Helsinki    144
dtype: int64
Square the values by passing an anonymous function as an argument to apply().
import pandas as pd
import numpy as np
from numba import njit


@njit
def series_apply():
    s = pd.Series([20, 21, 12],
                  index=['London', 'New York', 'Helsinki'])

    return s.apply(lambda x: x ** 2)


print(series_apply())
$ python ./series/series_apply_lambda.py
London      400
New York    441
Helsinki    144
dtype: int64
Use a function from the Numpy library.
import pandas as pd
import numpy as np
from numba import njit


@njit
def series_apply():
    s = pd.Series([20, 21, 12],
                  index=['London', 'New York', 'Helsinki'])

    return s.apply(np.log)


print(series_apply())
$ python ./series/series_apply_log.py
London      2.995732
New York    3.044522
Helsinki    2.484907
dtype: float64

See also

Series.map

For element-wise operations.

Series.agg

Only perform aggregating type operations.

Series.transform

Only perform transforming type operations.