title: Fill NaN values of column X with the median value of X for each categorial variable in another column Y
body: <p>This was very difficult to phrase. But let me show you what I'm trying to accomplish. </p>
  
  <pre><code>df
  
  Y  X
  a  10
  a  5
  a  NaN
  b  12
  b  13
  b  NaN
  c  5
  c  NaN
  c  5
  c  6
  
  
  Y: 10 non-null object
  X: 7 non-null int64
  </code></pre>
  
  <p>Take category 'a' from column Y, it has the median X value (10+5/2), the other missing value for 'a' must be filled with this median value.</p>
  
  <p>Similarly, for category 'b' from column Y, among the non missing values in column X, the median X values is, (12+13/2)</p>
  
  <p>For category 'c' from column Y, among the non missing values in column X, the median X values is, 5 (middle most value)</p>
  
  <p><strong>I used a very long, repetitive code as follows.</strong></p>
  
  <pre><code>    grouped = df.groupby(['Y'])[['X']]
      grouped.agg([np.median])
  
                  X
                  median
      Y
      a           7.5
      b           12.5
      c           5
  
      df.X = df.X.fillna(-1)
  
      df.loc[(df['Y'] == 'a') &amp; (df['X'] == -1), 'X'] = 7.5
      df.loc[(df['Y'] == 'b') &amp; (df['X'] == -1), 'X'] = 12.5
      df.loc[(df['Y'] == 'c') &amp; (df['X'] == -1), 'X'] = 5
  </code></pre>
  
  <p><strong>I was told that there is not only repetition but also the use of magic numbers, which should be avoided.</strong></p>
  
  <p><strong>I want to write a function that does this filling efficiently.</strong></p>