How to apply a lambda function to pandas DataFrame?
In this article, we’ll look at how to use the apply
method to apply a lambda function to a DataFrame.
Applying a Lambda Function to a Python DataFrame
A lambda function is a small, anonymous function in Python that can take any number of arguments but can only have one expression.
- It’s often used to simplify code and make it more readable, and can be especially useful when working with data in a Pandas DataFrame.
To apply a lambda function to a DataFrame, you can use the apply
method. This method applies a function to each element in a specified axis (row or column) of a DataFrame.
Here’s an example of using a lambda function to calculate the square of each element in a DataFrame:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df['A'] = df['A'].apply(lambda x: x**2)
print(df)
In this example, the lambda function takes an argument x
and returns x**2
. The apply
method is used to apply this function to each element in the 'A'
column of the DataFrame df
. The result is a new DataFrame with the square of each element in the 'A'
column.
You can also use a lambda function to apply a more complex operation to a DataFrame. For example…