Table of Contents
TogglePandas provides powerful methods to apply custom or library functions to DataFrame and Series objects. Depending on whether you want to apply a function to the entire DataFrame, row- or column-wise, or element-wise, Pandas offers several methods to achieve these tasks.
In this tutorial, we will explore three essential methods for function application in Pandas −
pipe()apply()map()Let’s dive into each method and see how they can be utilized effectively.
The pipe() function allows you to apply chainable functions that expect a DataFrame or Series as input. This method is useful for performing custom operations on the entire DataFrame in a clean and readable manner.
Here is the example that demonstrates how you can add a value to all elements in the DataFrame using the pipe() function.
Its output is as follows −
The apply() function is versatile and allows you to apply a function along the axes of a DataFrame. By default, it applies the function column-wise, but you can specify row-wise application using the axis parameter.
This example applies a function to the DataFrame columns. Here the np.mean() function calculates the mean of each column.
Its output is as follows −
This function applies the np.mean() function to the rows of the pandas DataFrame.
Its output is as follows −
The following example applies the lambda function to the DataFrame elements using the apply() method.
Its output is as follows −
When you need to apply a function to each element individually, you can use map() function. These methods are particularly useful when the function cannot be vectorized.
The following example demonstrates how to use the map() function for applying a custom function to the elements of the DataFrame object.
Its output is as follows −
