pandas pivot table aggfunc troubleshooting
<p>This <code>DataFrame</code> has two columns, both are object type.</p>

<pre><code>  Dependents Married
0          0      No
1          1     Yes
2          0     Yes
3          0     Yes
4          0      No
</code></pre>

<p>I want to aggregate 'Dependents' based on 'Married'.</p>

<pre><code>table = df.pivot_table(
        values='Dependents',
        index='Married',
        aggfunc = lambda x: x.map({'0':0,'1':1,'2':2,'3':3}).mean())
</code></pre>

<p>This works, however, surprisingly, the following doesn't:</p>

<pre><code>table = df.pivot_table(values = 'Dependents', 
        index = 'Married', 
        aggfunc = lambda x: x.map(int).mean())
</code></pre>

<p>It will produce a <code>None</code> instead.</p>

<p>Can anyone help explain?</p>

<p>Both examples of code provided in your question work. However, they are not the idiomatic way to achieve what you want to do -- particularly the first one.</p>

<p>I think this is the proper way to obtain the expected behavior.</p>

<pre><code># Test data
df = DataFrame({'Dependents': ['0', '1', '0', '0', '0'],
                'Married': ['No', 'Yes', 'Yes', 'Yes', 'No']})

# Converting object to int
df['Dependents'] = df['Dependents'].astype(int)
# Computing the mean by group
df.groupby('Married').mean()

         Dependents
Married            
No             0.00
Yes            0.33
</code></pre>

<p>However, the following code works.</p>

<pre><code>df.pivot_table(values = 'Dependents', index = 'Married', 
               aggfunc = lambda x: x.map(int).mean())
</code></pre>

<p>It is equivalent (and more readable) of converting to <code>int</code> with <code>map</code> before pivoting data.</p>

<pre><code>df['Dependents'] = df['Dependents'].map(int)
df.pivot_table(values = 'Dependents', index = 'Married')
</code></pre>

<h1>Edit</h1>

<p>I you have messy <code>DataFrame</code>, you can use <code>to_numeric</code> with the <code>error</code> parameter set to <code>coerce</code>.</p>

<blockquote>
  <p>If <code>coerce</code>, then invalid parsing will be set as <code>NaN</code></p>
</blockquote>

<p>Here is the <a class='doc-link' href="http://stackoverflow.com/documentation/pandas/2959/data-types/10052/changing-dtypes#t=201609241949239596277">link</a> to the Stack Overflow documentation concerning the change of types.</p>

<pre><code># Test data
df = DataFrame({'Dependents': ['0', '1', '2', '3+', 'NaN'], 
                 'Married': ['No', 'Yes', 'Yes', 'Yes', 'No']})

df['Dependents'] = pd.to_numeric(df['Dependents'], errors='coerce')
print(df)

   Dependents Married
0         0.0      No
1         1.0     Yes
2         2.0     Yes
3         NaN     Yes
4         NaN      No

print(df.groupby('Married').mean())

         Dependents
Married            
No              0.0
Yes             1.5
</code></pre>

python pandas pivot-table