【问题标题】:pandas binning a list based on qcut of another listpandas 根据另一个列表的 qcut 对列表进行分箱
【发布时间】:2014-01-20 12:18:14
【问题描述】:

说我有一个清单:

a = [3, 5, 1, 1, 3, 2, 4, 1, 6, 4, 8]

以及a的子列表:

b = [5, 2, 6, 8]

我想通过pd.qcut(a,2) 获取箱并计算列表 b 的每个箱中的值的数量。那是

In[84]: pd.qcut(a,2)
Out[84]: 
Categorical: 
[[1, 3], (3, 8], [1, 3], [1, 3], [1, 3], [1, 3], (3, 8], [1, 3], (3, 8], (3, 8], (3, 8]]
Levels (2): Index(['[1, 3]', '(3, 8]'], dtype=object)

现在我知道 bin 是:[1,3] 和 (3,8],我想知道列表“b”的每个 bin 中有多少个值。当数字为箱数很小,但是当箱数很大时,最好的方法是什么?

【问题讨论】:

    标签: python pandas binning


    【解决方案1】:

    如之前的回答所示:您可以使用retbins 参数从qcut 获取bin 边界,如下所示:

    q, bins = pd.qcut(a, 2, retbins=True)
    

    然后您可以使用cut 将另一个列表中的值放入这些“箱”中。例如:

    myList = np.random.random(100)
    # Define bin bounds that cover the range returned by random()
    bins = [0, .1, .9, 1] 
    # Now we can get the "bin number" of each value in myList:
    binNum = pd.cut(myList, bins, labels=False, include_lowest=True)
    # And then we can count the number of values in each bin number:
    np.bincount(binNum)
    

    确保您的 bin 边界涵盖了出现在第二个列表中的整个值范围。 为确保这一点,您可以使用最大值和最小值填充 bin 边界。例如,

    cutBins = [float('-inf')] + bins.tolist() + [float('inf')]
    

    【讨论】:

      【解决方案2】:

      您可以使用 retbins 参数从 qcut 中取回 bin:

      >>> q, bins = pd.qcut(a, 2, retbins=True)
      

      然后使用pd.cut 获得b 与箱相关的索引:

      >>> b = np.array(b)
      >>> hist = pd.cut(b, bins, right=True).labels
      >>> hist[b==bins[0]] = 0
      >>> hist
      array([1, 0, 1, 1])
      

      请注意,您必须单独处理角盒bins[0],因为它不包含在最左边的 bin 中。

      【讨论】:

        猜你喜欢
        • 2013-08-15
        • 2016-09-28
        • 1970-01-01
        • 2018-11-15
        • 2021-05-02
        • 1970-01-01
        • 2011-03-22
        • 1970-01-01
        相关资源
        最近更新 更多