Q:

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

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to flatten a hierarchical index in columns?... >>
<< How to use pivot function in a pandas DataFrame?...