在pandas的单独列中以2的幂分配存储区范围 [英] Assign bucket ranges in power of 2 in a separate column in pandas

查看:58
本文介绍了在pandas的单独列中以2的幂分配存储区范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列如下所示的值:

I have a column of values like below:

col
12
76
34

为此,我需要为其生成一个带有 col1 如下所述:

for which I need to generate a new column with the bucket labels for col1 as mentioned below:

col1     bucket-labels
12            8-16
76            64-128 
34            32-64

此处的值

编辑:
存储桶标签的间隔应在2 ^ n

The intervals of the bucket label should be in the range of 2^n

推荐答案

首先通过在此处,通过列表理解创建垃圾箱,通过 zip 创建标签,并将其传递给 cut 函数:

First get maximal value of power 2 by one of solution from here, create bins by list comprehension, labels by zip and pass it to cut function:

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

这篇关于在pandas的单独列中以2的幂分配存储区范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆