title: Groupby on condition and calculate sum of subgroups
body: <p>Here is my data:</p>
  
  <pre><code>import numpy as np 
  import pandas as pd
  z = pd.DataFrame({'a':[1,1,1,2,2,3,3],'b':[3,4,5,6,7,8,9], 'c':[10,11,12,13,14,15,16]})
  z
  
      a   b   c
  0   1   3   10
  1   1   4   11
  2   1   5   12
  3   2   6   13
  4   2   7   14
  5   3   8   15
  6   3   9   16
  </code></pre>
  
  <h1>Question:</h1>
  
  <p>How can I do calculation on different element of each subgroup? For example, for each group, I want to extract any element in column 'c' which its corresponding element in column 'b' is between 4 and 9, and sum them all.</p>
  
  <p>Here is the code I wrote: (It runs but I cannot get the correct result)</p>
  
  <pre><code>gbz = z.groupby('a')
  # For displaying the groups:
  gbz.apply(lambda x: print(x))
  
  
  list = []
  
  def f(x):
      list_new = []
      for row in range(0,len(x)):
          if (x.iloc[row,0] &gt; 4 and x.iloc[row,0] &lt; 9):
              list_new.append(x.iloc[row,1])
      list.append(sum(list_new))
  
  results = gbz.apply(f)
  </code></pre>
  
  <p>The output result should be something like this:</p>
  
  <pre><code>    a   c
  0   1   12
  1   2   27
  2   3   15
  </code></pre>