title: Group by weighted mean, allowing for zero value weights
body: <p>I want to take the weighted mean of a column in a group-by statement, like this</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  
  df = pd.DataFrame({'group': ['A', 'A', 'A', 'B', 'B', 'B'],
                     'value': [0.4, 0.3, 0.2, 0.4, 0.3, 0.2],
                     'weight': [2, 2, 4, 3, 1, 2]})
  
  df_grouped = df.groupby('group')[['value', 'weight']].apply(lambda x: sum(x['value']*x['weight'])/sum(x['weight']))
  
  df_grouped
  Out[17]: 
  group
  A    0.275000
  B    0.316667
  dtype: float64
  </code></pre>
  
  <p>So far all is well. <em>However</em>, in some cases the weights sum to zero, for instance</p>
  
  <pre><code>df = pd.DataFrame({'group': ['A', 'A', 'A', 'B', 'B', 'B'],
                     'value': [0.4, 0.3, 0.2, 0.4, 0.3, 0.2],
                     'weight': [1, 2, 3, 0, 0, 0]})
  </code></pre>
  
  <p>In this case I want to take the simple mean. The above expression obviously fail because of a divide by zero.</p>
  
  <p>The method I currently use is to replace the weights with one wherever the weights sum to one</p>
  
  <pre><code>df_temp = df.groupby('group')['weight'].transform('sum').reset_index()
  df['new_weight'] = np.where(df_temp['weight']==0, 1, df['weight'])
  
  df_grouped = df.groupby('group')[['value', 'new_weight']].apply(lambda x: sum(x['value']*x['new_weight'])/sum(x['new_weight']))
  </code></pre>
  
  <p>This is an ok solution. But can this be achieved by a one-liner? Some special function for instance?</p>