How to use a user function to fillna() in pandas
<p>This is a fragment of the dataframe I have:</p>

<pre><code>Title | Age     
------+--------
Mr.   | 30
Mr.   | NaN
Mr.   | 32
Mrs.  | 28
Mrs.  | 16
Mr.   | 34
Mrs.  | NaN
</code></pre>

<p>Edit: I added the last row, to clarify the question</p>

<p>I want to impute the NaNs (second and last row), for the second row, it should use the mean of the other "Mr." in the dataframe, so in this case, should be 32, in the last row it should use the mean of the other "Mrs.", so should be 22</p>

<p>To calculate the mean is as easy as doing</p>

<pre><code>value = df.loc[df["Title"] == "Mr."]["Age"].mean()
</code></pre>

<p>So I wrote a function called agefun:</p>

<pre><code>def agefun(df, t):
    return df.loc[df["Title"] == t]["Age"].mean()
</code></pre>

<p>And it works, now, how can I use this function with the fillna() function? I'd like something like:</p>

<pre><code>df['Age'].fillna(agefun(df, this_row_title))
</code></pre>

<p>But of course it doesn't work, I don't know how to tell the function I like the value corresponding to the Title in that specific row.</p>

<p>How can this be performed?</p>