title: Python: How to create weighted quantiles in Pandas?
body: <p>I understand how to create simple quantiles in Pandas using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="noreferrer">pd.qcut</a>. But after searching around, I don't see anything to create <em>weighted</em> quantiles. Specifically, I wish to create a variable which bins the values of a variable of interest (from smallest to largest) such that each bin contains an equal weight. So far this is what I have:</p>
  
  <pre><code>def wtdQuantile(dataframe, var, weight = None, n = 10):
      if weight == None:
          return pd.qcut(dataframe[var], n, labels = False)
      else:
          dataframe.sort_values(var, ascending = True, inplace = True)
          cum_sum = dataframe[weight].cumsum()
          cutoff = max(cum_sum)/n
          quantile = cum_sum/cutoff
          quantile[-1:] -= 1
          return quantile.map(int)
  </code></pre>
  
  <p>Is there an easier way, or something prebuilt from Pandas that I'm missing?</p>
  
  <p><strong>Edit:</strong> As requested, I'm providing some sample data. In the following, I'm trying to bin the "Var" variable using "Weight" as the weight. Using <code>pd.qcut</code>, we get an equal number of observations in each bin. Instead, I want an <em>equal weight</em> in each bin, or in this case, as close to equal as possible.</p>
  
  <pre><code>Weight  Var  pd.qcut(n=5)  Desired_Rslt
     10     1            0              0
     14     2            0              0
     18     3            1              0
     15     4            1              1
     30     5            2              1
     12     6            2              2
     20     7            3              2
     25     8            3              3
     29     9            4              3
     45    10            4              4
  </code></pre>