Pandas - operations on groups using transform
<p>Here is my example:</p>

<pre><code>import pandas as pd
import numpy as np

df = pd.DataFrame({'A A': ['one', 'one', 'two', 'two', 'one'] ,
                   'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
                   'C': ['12/15/2011', '11/11/2001', '08/30/2015', '07/3/1999','03/03/2000' ],
                      'D':[1,7,3,4,5]})

df['C'] = pd.to_datetime(df['C'])

def date_test(x):
    key_date = pd.Timestamp(np.datetime64('2015-08-13'))
    end_date = pd.Timestamp(np.datetime64('2016-10-10'))
    result = False

    for i in x.index:
        if key_date &lt; x[i] &lt; end_date:
            result = True

    return result

def int_test(x):
    result = False
    for i in x.index:
        if 1 &lt; x[i] &lt; 9:
            result = True

    return result
</code></pre>

<p>Now I am grouping by column <code>B</code> and transforming column <code>C</code> and <code>D</code></p>

<p>The following code producess column of ones. </p>

<pre><code>df.groupby(['B'])['D'].transform(int_test)
</code></pre>

<p>And the following code produces column of dates</p>

<pre><code>df.groupby(['B'])['C'].transform(date_test)
</code></pre>

<p>I would expect them both to produce collection of ones and zeros and not dates. My goal is to get collection of ones and zeros. Any thoughts?</p>

<p><strong>Update</strong>: My main goal is to understand how <code>transform</code> works. </p>

<p>For type consistency with subsequent operations your can do with the results of a <code>transform</code> call, that function tries to cast the resulting Series into the dtype of the selected data it works against. The function source code has this dtype cast explicitly done.</p>

<p>Your boolean data can be turned into dates, thus you obtain a datetime series. Explicitly cast to <code>int</code> to get the expected type:</p>

<pre><code>df.groupby(['B'])['C'].transform(date_test).astype('int64')
</code></pre>

python pandas transform