Open In App

Apply a function to each row or column in Dataframe using pandas.apply()

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Applying a function to a single or selected columns/rows in one go is a better way. For this we use the Pandas apply() function. There are different ways to apply a function to each row or column in Pandas DataFrame. We will learn about various ways to Apply Function to Every Row in this article.

Creating a Sample DataFrame

Before seeing different ways to apply a function to a row/column. Let’s create a small dataframe and see that. 

Python3




# import pandas and numpy library
import pandas as pd
import numpy as np
 
# list of tuples
matrix = [(1, 2, 3, 4),
          (5, 6, 7, 8,),
          (9, 10, 11, 12),
          (13, 14, 15, 16)]
 
# Create a Dataframe object
df = pd.DataFrame(matrix, columns=list('abcd'))
 
# Output
print(df)


Output : 

    a   b   c   d
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 13 14 15 16

Apply a Function to Each Element in a Column or Row

Below are some ways by which we can apply a function to each element in a column or row in Pandas in Python:

  • Applying lambda function to each column and row
  • Applying user defined function to each column and row
  • Applying numpy function to each column and row
  • Applying a Reducing function to each column and row

Applying lambda() Function to Each Column and Row

When working with Pandas, you can use lambda functions with the apply() method to perform operations on rows or columns of a DataFrame. This is especially useful for simple or one-time calculations.

Example 1: Applying lambda() Function to Each Column 

In this example, a lambda() function is applied to each column of the DataFrame (df), adding 10 to each value. The result is stored in a new DataFrame called new_df, and the updated values are printed.

Python3




# Applying a lambda function to each
# column which will add 10 to the value
new_df = df.apply(lambda x : x + 10)
 
# Output
print(new_df)


Output : 

    a   b   c   d
0 11 12 13 14
1 15 16 17 18
2 19 20 21 22
3 23 24 25 26

Example 2: Applying lambda() Function to Each Row

In this example, a lambda() function is applied to each row of the DataFrame (df), adding 5 to each value. The resulting DataFrame, named new_df, is printed to display the updated values.

Python3




# Applying a lambda function to each
# row which will add 5 to the value
new_df = df.apply(lambda x: x + 5, axis = 1)
 
# Output
print(new_df)


Output : 

    a   b   c   d
0 6 7 8 9
1 10 11 12 13
2 14 15 16 17
3 18 19 20 21



Applying User Defined Function to Each Column and Row

Performing a custom operation on the elements within rows or columns of a DataFrame requires the application of a user-defined function.

Example 1: Apply a Function to Each Element in a Column

In this example, a user-defined function squareData is applied to each column of the DataFrame (df), squaring each value. The resulting DataFrame, named new_df, is printed to display the squared values.

Python3




# function to returns x*x
def squareData(x):
    return x * x
 
# Applying a user defined function to
# each column that will square the given
# value
new_df = df.apply(squareData)
 
# Output
print(new_df)


Output : 

     a    b    c    d
0 1 4 9 16
1 25 36 49 64
2 81 100 121 144
3 169 196 225 256

Example 2: Applying User Defined Function to Each Row

In this example, a user-defined function squareData is applied to each row of the DataFrame (df), squaring each value. The resulting DataFrame, named new_df, is printed to display the squared values. The axis=1 parameter specifies the operation along rows.

Python3




# function to returns x*x
def squareData(x):
    return x * x
 
# Applying a user defined function
# to each row that will square the given value
new_df = df.apply(squareData, axis = 1)
 
# Output
print(new_df)


Output :

      a    b    c    d
0 1 4 9 16
1 25 36 49 64
2 81 100 121 144
3 169 196 225 256

In the above examples, we saw how a user defined function is applied to each row and column. We can also apply user defined functions which take two arguments. 

Example 3: Apply a Function to Each Element in a Column Taking Two Arguments

In this example, a user-defined function addData is applied to each column of the DataFrame (df), adding a specified value (1 in this case) to each column. The resulting DataFrame, named new_df, is printed to display the updated values.

Python3




# function to returns x+y
def addData(x, y):
    return x + y
 
# Applying a user defined function to each
# column which will add value in each
# column by given number
new_df = df.apply(addData, args = [1])
 
# Output
print(new_df)


Output: 

    a   b   c   d
0 2 3 4 5
1 6 7 8 9
2 10 11 12 13
3 14 15 16 17

Example 4: Applying User Defined Function to Each Row Taking Two Arguments

In this example, a user-defined function addData is applied to each row of the DataFrame (df), adding a specified value (3 in this case) to each row. The resulting DataFrame, named new_df, is printed to display the updated values. The axis=1 parameter specifies the operation along rows.

Python3




# function to returns x+y
def addData(x, y):
    return x + y
 
# Applying a user defined function to each
# row which will add value in each row by
# given number
new_df = df.apply(addData, axis = 1,
                    args = [3])
 
# Output
print(new_df)


Output : 

    a   b   c   d
0 4 5 6 7
1 8 9 10 11
2 12 13 14 15
3 16 17 18 19

Applying NumPy Function to Each Column and Row

Let’s use apply function to apply numpy function to row/column.

Example 1: Applying NumPy Function to Each Column

In this example, a NumPy function (np.square) is applied to each column of the DataFrame (df), squaring each value. The resulting DataFrame, named new_df, is printed to display the squared values.

Python3




# Applying a numpy function to each
# column by squaring each value
new_df = df.apply(np.square)
 
# Output
print(new_df)


Output : 

    a    b    c    d
0 1 4 9 16
1 25 36 49 64
2 81 100 121 144
3 169 196 225 256

Example 2: Applying NumPy Function to Each Row

In this example, a NumPy function (np.sqrt) is applied to each row of the DataFrame (df), calculating the square root of each value. The resulting DataFrame, named new_df, is printed to display the square root values. The axis=1 parameter specifies the operation along rows.

Python3




# Apply a numpy function to each row
# to find square root of each value
new_df = df.apply(np.sqrt, axis = 1)
 
# Output
print(new_df)


Output : 

          a         b         c         d
0 1.000000 1.414214 1.732051 2.000000
1 2.236068 2.449490 2.645751 2.828427
2 3.000000 3.162278 3.316625 3.464102
3 3.605551 3.741657 3.872983 4.000000

Applying a Reducing Function to Each Column and Row

A Reducing function will take a row or column as a series and returns either a series of the same size as that of the input row/column or it will return a single variable depending upon the function we use.

Example 1: Applying a Reducing Function to Each Column 

In this example, a NumPy function (np.sum) is applied to each column of the DataFrame (df), calculating the sum of all values in each column. The resulting Series, named new_df, represents the column-wise sums and is printed to display the results.

Python3




# Applying a numpy function to get the sum
# of all values in each column
new_df = df.apply(np.sum)
 
# Output
print(new_df)


Output : 

a    28
b 32
c 36
d 40
dtype: int64

Example 2: Applying a Reducing Function to Each Row

In this example, a NumPy function (np.sum) is applied to each row of the DataFrame (df), calculating the sum of all values in each row. The resulting Series, named new_df, represents the row-wise sums and is printed to display the results. The axis=1 parameter specifies the operation along rows.

Python3




# Applying a numpy function to get t
# he sum of all values in each row
new_df = df.apply(np.sum, axis = 1)
 
# Output
print(new_df)


Output : 

0    10
1 26
2 42
3 58
dtype: int64


Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads