我有一列值如下:
col
12
76
34
Run Code Online (Sandbox Code Playgroud)
我需要为其生成带有桶标签的新列,col1如下所述:
col1 bucket-labels
12 8-16
76 64-128
34 32-64
Run Code Online (Sandbox Code Playgroud)
此处列中的值可能会有所不同,结果也会有所不同.
编辑:桶标签的间隔应在2 ^ n的范围内
首先通过此处的解决方案获得功率2的最大值,通过列表理解创建分类,标记zip并将其传递给cut函数:
import math
a = df['col'].max()
bins = [1<<exponent for exponent in range(math.ceil(math.log(a, 2))+1)]
#another solution
#bins = [1<<exponent for exponent in range((int(a)-1).bit_length() + 1)]
print (bins)
[1, 2, 4, 8, 16, 32, 64, 128]
labels = ['{}-{}'.format(i, j) for i, j in zip(bins[:-1], bins[1:])]
df['bucket-labels'] = pd.cut(df['col'], bins=bins, labels=labels)
print (df)
col bucket-labels
0 12 8-16
1 34 32-64
2 76 64-128
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |