ADVERTISEMENT
ADVERTISEMENT

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.
Submitted by Pranit Sharma, on May 04, 2022

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. 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')

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:

# 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:

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 »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.