Pandas fillna() based on specific column attribute
<p>Let's say I have this table</p>

<pre><code>Type | Killed | Survived
Dog      5         2
Dog      3         4
Cat      1         7
Dog     nan        3
cow     nan        2
</code></pre>

<p>One of the value on <code>Killed</code> is missing for <code>[Type] = Dog</code>.</p>

<p>I want to impute the mean in <code>[Killed]</code> for <code>[Type] = Dog</code>.</p>

<p>My code is as follow:</p>

<ol>
<li>Search for the mean</li>
</ol>

<p><code>df[df['Type'] == 'Dog'].mean().round()</code></p>

<p>This will give me the mean (around 2.25)</p>

<ol start="2">
<li>Impute the mean (This is where the problem begins)</li>
</ol>

<p><code>df.loc[(df['Type'] == 'Dog') &amp; (df['Killed'])].fillna(2.25, inplace = True)</code></p>

<p>The code runs, but the value is not impute, the NaN value is still there.</p>

<p>My Question is, how do I impute the mean in <code>[Killed]</code> based on <code>[Type] = Dog</code>.</p>

<p><code>groupby</code> with <code>transform</code></p>

<pre><code>df.groupby('Type').Killed.transform(lambda x: x.fillna(x.mean()))
</code></pre>

<h3>Setup</h3>

<pre><code>df = pd.DataFrame([
        ['Dog', 5, 2],
        ['Dog', 3, 4],
        ['Cat', 1, 7],
        ['Dog', np.nan, 3],
        ['Cow', np.nan, 2]
    ], columns=['Type', 'Killed', 'Survived'])

df.Killed = df.groupby('Type').Killed.transform(lambda x: x.fillna(x.mean()))
df
</code></pre>

<p><a href="http://i.stack.imgur.com/FkEYl.png" rel="nofollow"><img src="http://i.stack.imgur.com/FkEYl.png" alt="enter image description here"></a></p>

<p>If you meant to consider the <code>np.nan</code> when calculating the mean</p>

<pre><code>df.Killed = df.groupby('Type').Killed.transform(lambda x: x.fillna(x.fillna(0).mean()))
df
</code></pre>

<p><a href="http://i.stack.imgur.com/SfAwg.png" rel="nofollow"><img src="http://i.stack.imgur.com/SfAwg.png" alt="enter image description here"></a></p>

python pandas indexing mean