How to apply a function to a single column in pandas DataFrame?

Given a DataFrame, we have to apply a function to a single column. By Pranit Sharma Last updated : September 19, 2023

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Here, we are going to perform some operations on a single column.

Apply a function to a single column in pandas DataFrame

For this purpose, we will use apply() method inside which we will filter our specified column on which we want to apply a function. The apply() method takes the function which has to be applied on the DataFrame columns. The apply() method traverses each column one by one and then performs the specified operation inside it. To operate on a single column, we will check the column name inside apply() method, and if our column name matches then only the function specified will work.

Syntax

DataFrame.apply('function','condition')
Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example:

Python program to apply a function to a single column in pandas DataFrame

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks
d = {
    "Jarvis":[69,74,77,72],
    "Peter":[65,96,65,86],
    "Harry":[87,97,85,51],
    "Sam":[66,68,85,94]
}

# Now we will create DataFrame
df=pd.DataFrame(d)

# Viewing the DataFrame
print("DataFrame:\n",df,"\n\n")

# Applying the function to single column named Jarvis
result = df.apply(lambda x: x+10 if x.name == 'Jarvis' else x)

# View result
print(result)

Output

The output of the above program is:

DataFrame:
    Jarvis  Peter  Harry  Sam
0      69     65     87   66
1      74     96     97   68
2      77     65     85   85
3      72     86     51   94 


   Jarvis  Peter  Harry  Sam
0      79     65     87   66
1      84     96     97   68
2      87     65     85   85
3      82     86     51   94

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.