Pandas apply() with Lambda Examples

pandas.DataFrame.apply() can be used with python lambda to execute expression. A lambda function in python is a small anonymous function that can take any number of arguments and execute an expression.

In this article I will explain how to use a pandas DataFrame.apply() with lambda by examples. lambda expressions are utilized to construct anonymous functions. You can create one by using the lambda keyword.

1. Quick Examples of pandas Apply with Lambda

If you are in a hurry, below are some of the quick examples of how to use lambda function with pandas DataFrame.apply().


# Below are quick examples

# apply a lambda function to each column
df2 = df.apply(lambda x : x + 10)

# Using Dataframe.apply() and lambda function
df["A"] = df["A"].apply(lambda x: x-2)

# Apply function NumPy.square() to square the values of two rows 
#'A'and'B
df2 = df.apply(lambda x: np.square(x) if x.name in ['A','B'] else x)

# Using DataFrame.map() to Single Column
df['A'] = df['A'].map(lambda A: A/2.)

# Using DataFrame.assign() and Lambda
df2 = df.assign(B=lambda df: df.B/2)

2. DataFrame.apply() Syntax

Below is a syntax of DataFrame.apply() method. func param is used with lambda expression.


DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)

Let’s create a sample DataFrame to work with some examples. Our DataFrame contains column names A, B, and C.


import pandas as pd
import numpy as np
data = [(3,5,7), (2,4,6),(5,8,9)]
df = pd.DataFrame(data, columns = ['A','B','C'])
print(df)

Yields below output.


   A  B  C
0  3  5  7
1  2  4  6
2  5  8  9

3. pandas Apply with Lambda to All Columns

You can apply a lambda expression using apply() method, the Below example adds 10 to all columns.


# apply a lambda function to each column
df2 = df.apply(lambda x : x + 10)
print(df2)

Yields below output.


    A   B   C
0  13  15  17
1  12  14  16
2  15  18  19

4. Apply Lambda Expression to Single Column

You can apply the lambda expression for a single column in the DataFrame. The following example subtracts every cell value by 2 for column A – df["A"]=df["A"].apply(lambda x:x-2).


# Using Dataframe.apply() and lambda function
df["A"] = df["A"].apply(lambda x: x-2)
print(df)

Yields below output.


   A  B  C
0  1  5  7
1  0  4  6
2  3  8  9

Similarly, you can also apply the Lambda function to all & multiple columns in pandas, I will leave this to you to explore.

5. Using pandas.DataFrame.map() with Lambda to Single Column

Here is another alternative using map() method.


# Using DataFrame.map() to Single Column
df['A'] = df['A'].map(lambda A: A/2.)
print(df)

Yields below output.


     A  B  C
0  1.5  5  7
1  1.0  4  6
2  2.5  8  9

6. DataFrame.assign() to Apply Lambda Function

You can also try assign() with lambda


# Using DataFrame.assign() and Lambda
df2 = df.assign(B=lambda df: df.B/2)
print(df2)

Yields below output.


   A    B  C
0  3  2.5  7
1  2  2.0  6
2  5  4.0  9

7. Multiple columns Using NumPy.square() and Lambda Function

Apply a lambda function to multiple columns in DataFrame using Dataframe apply(), lambda, and Numpy functions.


# Apply function NumPy.square() to square the values of two rows 
'A'and'B
df2 = df.apply(lambda x: np.square(x) if x.name in ['A','B'] else x)
print(df2)

Yields below output.


    A   B  C
0   9  25  7
1   4  16  6
2  25  64  9

Conclusion

In this article, you have learned what is lambda expression, how to create one using the lambda keyword and using it on pandas DataFrame. A lambda function in python is a small anonymous function that can take any number of arguments and execute an expression. lambda expressions are utilized to construct anonymous functions. You can create one by using the lambda keyword.

Happy Learning !!

Also Read

References

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

You are currently viewing Pandas apply() with Lambda Examples