title: python pandas dataframe : fill nans with a conditional mean
body: <p>I have the following dataframe: </p>
  
  <pre><code>import numpy as np 
  import pandas as pd
  df = pd.DataFrame(data={'Cat' : ['A', 'A', 'A','B', 'B', 'A', 'B'],
                          'Vals' : [1, 2, 3, 4, 5, np.nan, np.nan]})
  
      Cat   Vals
  0   A     1
  1   A     2
  2   A     3
  3   B     4
  4   B     5
  5   A   NaN
  6   B   NaN
  </code></pre>
  
  <p>And I want indexes <code>5</code> and <code>6</code> to be filled with the conditional mean of 'Vals' based on the 'Cat' column, namely <code>2</code> and <code>4.5</code></p>
  
  <p>The following code works fine:</p>
  
  <pre><code>means = df.groupby('Cat').Vals.mean()
  for i in df[df.Vals.isnull()].index:
      df.loc[i, 'Vals'] = means[df.loc[i].Cat]
  
      Cat   Vals
  0   A     1
  1   A     2
  2   A     3
  3   B     4
  4   B     5
  5   A     2
  6   B   4.5
  </code></pre>
  
  <p>But I'm looking for something nicer, like</p>
  
  <pre><code>df.Vals.fillna(df.Vals.mean(Conditionally to column 'Cat'))
  </code></pre>
  
  <p>Edit: I found this, which is one line shorter, but I'm still not happy with it:</p>
  
  <pre><code>means = df.groupby('Cat').Vals.mean()
  df.Vals = df.apply(lambda x: means[x.Cat] if pd.isnull(x.Vals) else x.Vals, axis=1)
  </code></pre>