title: Getting a ratio in Pandas groupby object
body: <p>I have a dataframe that looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/SLNhS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SLNhS.png" alt="enter image description here"></a></p>
  
  <p>I want to create another column called "engaged_percent" for each state which is basically the number of unique engaged_count divided by the user_count of each particular state. </p>
  
  <p>I tried doing the following:</p>
  
  <pre><code>def f(x):
      engaged_percent = x['engaged_count'].nunique()/x['user_count']
      return pd.Series({'engaged_percent': engaged_percent})
  
  by = df3.groupby(['user_state']).apply(f)
  by
  </code></pre>
  
  <p>But it gave me the following result:</p>
  
  <p><a href="https://i.stack.imgur.com/rkJHC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rkJHC.png" alt="enter image description here"></a></p>
  
  <p>What I want is something like this:</p>
  
  <pre><code>user_state        engaged_percent
  ---------------------------------
  California           2/21 = 0.09
  Florida              2/7 =  0.28
  </code></pre>
  
  <p>I think my approach is correct , however I am not sure why my result shows up like the one seen in the second picture.</p>
  
  <p>Any help would be much appreciated! Thanks in advance!</p>