Apply transform of your own function in Pandas dataframe
<p>I have pandas dataframe on which I need to some data manipulation, the following code provide me the average of column "Variable" group by "Key":</p>

<pre><code>df.groupby('key').Variable.transform("mean")
</code></pre>

<p>The advantage of using "transform" is that it return back the result with the same index which is pretty useful.</p>

<p>Now, I want to have my customize function and use it within "transform" instead of "mean" more over my function need two or more column something like:</p>

<pre><code>lambda (Variable, Variable1, Variable2): (Variable + Variable1)/Variable2
</code></pre>

<p>(actual function of mine is more complicated than this example) and each row of my dataframe has Variable,Variable1 and Variable2. </p>

<p>I am wondering if I can define and use such a customized function within "transform" to be able to rerun the result back with same index?</p>

<p>Thanks,
Amir </p>

<p>Don't call transform against <code>Variable</code>, call it on the grouper and then call your variables against the dataframe the function receives as argument:</p>

<pre><code>df.groupby('key').transform(lambda x: (x.Variable + x.Variable1)/x.Variable2)
</code></pre>

python pandas dataframe aggregation