Q:

How to apply a function to two columns of Pandas DataFrame?

belongs to collection: Python Pandas Programs

0

In Pandas, we can achieve this task by using DataFrame.apply() method.

Pandas.DataFrame.apply() Method

This function itself takes a function as a parameter which has to be applied on the columns. To apply the function to multiple columns, we just need to define the name of the columns inside pandas.DataFrame.apply() method.

Syntax:

DataFrame.apply(parameters)

Parameter(s):

  • It takes the function which has to be applied on the column values.
  • It takes several other optional parameters like axisrawresult_type**kwds.

To work with Python Pandas, we need to import the pandas library. 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

# Defining a function for modification of 
# column values
def function(value):
      # Adding string ='Rs.' before the value
      return 'Rs.'+ value

# Creating a list of dictionary
data = {
    'Product':['Television','Mobile','Headphones'],
    'Price':['20000','10000','2000'],'Discount':['3000','500','100']
}

# Converting a DataFrame
df=pd.DataFrame(data)

# Display the DataFrame
print("\nDataFrame created:\n\n",df,"\n\n")

# Using the apply() method to call the function: function
df[['Price','Discount']] = df[['Price','Discount']].apply(function)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output:

Output | apply a function to two columns of DataFrame

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
Convert DataFrame column type from string to datet... >>
<< Constructing pandas DataFrame from values in varia...