Function Application

If you want to use your own function or functions from another library on your dataframe or series you should be aware of Three functions

  1. pipe()
  2. apply()
  3. applymap()

Which function to use depends on what your function expects that is, whether it expects to operate on entire Dataframe, row or column wise, or element-wise.

pipe

When you want to apply the function to entire dataframe you can use pipe function which takes the function name as an argument and all the actual arguments of the function. Pipe allows you to pass a callable with the expectation that the object that called is the object that gets passed to the callable.

What this code basically does is, It will pass each value of dataframe as ‘a’ and 2 will be passed as ‘b’ and the result is the addition of two values.

apply

When you want to apply a particular method on each of the columns separately, or if you want to apply a particular method on a few of the selected columns then you can use .apply method. The final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument.

Here np.mean() is applied to each and every column of the dataset and the result is the mean of each column.

if you want to perform the operation row-wise then use axis=1.

Now all the values from a row is passed as an argument to np.mean() and the resultant mean is returned.

applymap

Not all functions can be vectorized (neither the NumPy arrays which return another array nor any value), the methods applymap() on DataFrame and analogously map() on Series accept any Python function taking a single value and returning a single value. Dataframe.applymap() method applies a function that accepts and returns a scalar to every element of a DataFrame.

the map function will simply take the selected column and map each value of that column with the function applied.

applymap will do the same for the whole dataframe.

Close Menu