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>For me working:</p>

<pre><code>df.ix[df['Type'] == 'Dog', 'Killed'] = df.ix[df['Type'] == 'Dog', 'Killed'].fillna(2.25)
print (df)
  Type  Killed  Survived
0  Dog    5.00         2
1  Dog    3.00         4
2  Cat    1.00         7
3  Dog    2.25         3
4  cow     NaN         2
</code></pre>

<p>If need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a> by <code>Series</code> - because 2 columns <code>Killed</code> and <code>Survived</code>:</p>

<pre><code>m = df[df['Type'] == 'Dog'].mean().round()
print (m)
Killed      4.0
Survived    3.0
dtype: float64

df.ix[df['Type'] == 'Dog'] = df.ix[df['Type'] == 'Dog'].fillna(m)
print (df)
  Type  Killed  Survived
0  Dog     5.0         2
1  Dog     3.0         4
2  Cat     1.0         7
3  Dog     4.0         3
4  cow     NaN         2
</code></pre>

<p>If need fillna only in column <code>Killed</code>:</p>

<pre><code>#if dont need rounding, omit it
m = round(df.ix[df['Type'] == 'Dog', 'Killed'].mean())
print (m)
4

df.ix[df['Type'] == 'Dog', 'Killed'] = df.ix[df['Type'] == 'Dog', 'Killed'].fillna(m)
print (df)
  Type  Killed  Survived
0  Dog     5.0         2
1  Dog     3.0         8
2  Cat     1.0         7
3  Dog     4.0         3
4  cow     NaN         2
</code></pre>

<p>You can reuse code like:</p>

<pre><code>filtered = df.ix[df['Type'] == 'Dog', 'Killed']
print (filtered)
0    5.0
1    3.0
3    NaN
Name: Killed, dtype: float64

df.ix[df['Type'] == 'Dog', 'Killed'] = filtered.fillna(filtered.mean())
print (df)
  Type  Killed  Survived
0  Dog     5.0         2
1  Dog     3.0         8
2  Cat     1.0         7
3  Dog     4.0         3
4  cow     NaN         2
</code></pre>

python pandas indexing mean