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>Two problems: Note that <code>df.loc[(df['Type'] == 'Dog') &amp; (df['Killed'])]</code> isn't doing what (I presume) you think it is doing. Instead of selecting rows where type is dog and the column 'Killed', you are selecting rows of type dog, then doing elementwise "and" with the column 'Killed', which will give you garbage - <code>False</code> precisely where the columns 'Killed' is <code>nan</code>!</p>

<p>See:</p>

<pre><code>In [6]: df.loc[(df['Type'] == 'Dog') &amp; (df['Killed'])]
Out[6]: 
  Type  Killed  Survived
0  Dog     5.0         2
1  Dog     3.0         4
</code></pre>

<p>What you want is the following:</p>

<pre><code>In [5]: df.loc[(df['Type'] == 'Dog'), ['Killed']]
Out[5]: 
   Killed
0     5.0
1     3.0
3     NaN
</code></pre>

<p>One more problem is that you need to use assignment in combination with <code>.loc</code>. and <code>.fillna</code>, so like the following:</p>

<pre><code>In [6]: df.loc[(df['Type'] == 'Dog'), ['Killed']] = df.loc[(df['Type'] == 'Dog'), ['Killed']].fillna(2.25)

In [7]: df
Out[7]: 
  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><h2> NOTE </h2> The value you gave for your mean is wrong or does not correspond to the data you gave in the answer. The mean should be 4.</p>

python pandas indexing mean