Home > Net >  Python pandas - define and apply a function inline
Python pandas - define and apply a function inline

Time:03-07

Let say I have below code

import pandas as pd

def calc(df, var1, var2) :
    return (df[var1] * df[var2]).sum()

Dat = pd.DataFrame({'product_name': ['laptop', 'printer', 'printer', 'printer', 'laptop', 'printer'], 'price': [1200, 150, 1200, 150, 1200, 150],  'price1': [1200, 150, 1200, 150, 1200, 150]})
Dat.groupby(['product_name']).apply(calc, 'price', 'price1')

While this is fine, I am wondering if I could define the function calc directly within the apply() method in the last line. I am looking for a generic rule where I could do this for any user defined function with any number of arguments

Any pointer will be appreciated.

CodePudding user response:

You can use lambda function: https://www.w3schools.com/python/python_lambda.asp

Dat.groupby(['product_name']).apply(lambda df: (df['price'] * df['price1']).sum())
  • Related