'Python pandas - define and apply a function inline

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source