在熊猫中宾宁

时间:2014-09-04 17:17:49

标签: python pandas binning

鉴于Pandas中的以下数据框:

"Age","Gender","Impressions","Clicks","Signed_In"
36,0,3,0,1
73,1,3,0,1
30,0,3,0,1
49,1,3,0,1
47,1,11,0,1

我需要创建一个单独的分类变量(列),它根据年龄保存每行的bin标签。例如,反对行 -

36,0,3,0,1

我想要另一个专栏显示'介于35和45之间'。

最终记录应显示为 -

36,0,3,0,1,'Between 35 and 45'

1 个答案:

答案 0 :(得分:3)

您应该创建一组示例数据,以帮助人们回答您的问题:

import pandas as pd
import numpy as np
d  = {'Age' : [36, 73, 30, 49, 47],
  'Gender' : [0, 1, 0, 1, 1],
  'Impressions' : [3, 3, 3, 3, 11],
  'Clicks' : [0, 0, 0, 0, 0],
  'Signed_In' : [1, 1, 1, 1, 1]}
df = pd.DataFrame(d)

使人们可以轻松复制和粘贴,而不必手动创建问题。

numpy的round函数将舍入小数位负数:

df['Age_rounded'] = np.round(df['Age'], -1)

    Age Clicks  Gender  Impressions Signed_In   Age_rounded
0   36  0       0       3           1           40
1   73  0       1       3           1           70
2   30  0       0       3           1           30
3   49  0       1       3           1           50
4   47  0       1       11          1           50

然后,您可以将字典映射到这些值:

 categories_dict = {30 : 'Between 25 and 35',
                    40 : 'Between 35 and 45',
                    50 : 'Between 45 and 55',
                    70 : 'Between 65 and 75'}

 df['category'] = df['Age_rounded'].map(categories_dict)

    Age Clicks  Gender  Impressions Signed_In   Age_rounded category
0   36  0       0       3           1           40          Between 35 and 45
1   73  0       1       3           1           70          Between 65 and 75
2   30  0       0       3           1           30          Between 25 and 35
3   49  0       1       3           1           50          Between 45 and 55
4   47  0       1       11          1           50          Between 45 and 55