pandas:如何将bin值追加回原始数据帧

ELI*_*ELI 3 python numpy pandas

我是Pandas的新手,我有一个如下的数据框

id    values   
 1       2.1
 2       0.8  
 3       1.0
 4       3.2
Run Code Online (Sandbox Code Playgroud)

我想将列"值"分成不同的bin,比如bin = 2并添加一列"counts",表示bin中有多少行,例如:

id     values   counts
 1        2.1       2 (since 2.1 and 3.2 both belong to the bin 2-4)
 2        0.8       2 
 3        1.0       2
 4        3.2       2
Run Code Online (Sandbox Code Playgroud)

我知道value_counts函数可以计算频率,但我不知道如何将它们追加回原始数据帧.

任何帮助深表感谢!

piR*_*red 5

numpys searchsorted来定义bin并bincount计算它们.
这应该非常快.

#         This defines the bin edges
#        [1, 2, 3] would have created
#               different bins
#                    v
b = np.searchsorted([2], df['values'].values)
df.assign(counts=np.bincount(b)[b])

   id  values  counts
0   1     2.1       2
1   2     0.8       2
2   3     1.0       2
3   4     3.2       2
Run Code Online (Sandbox Code Playgroud)
  • np.searchsorted 标识第一个数组中第二个数组的每个元素需要放置的位置,以便维护排序.
    • 这意味着:
    • 2.1需要追求的是2哪个位置1.
    • 0.8需要走到2哪个位置之前0.
    • 1.0需要走到2哪个位置之前0.
    • 3.2需要追求的是2哪个位置1.
  • np.bincount 方便地计算积分箱的频率......就像我们刚刚创建的那样.
  • 通过箱子的出现来切割计数的箱子,我们得到了transform类似的count