Python Pandas:使用零值的数字分组对/ bin进行分类

时间:2017-09-18 16:02:16

标签: python pandas grouping nan categories

我不确定,如果这是最有效的方式,但我正在努力将客户支出分组到垃圾箱/桶中。

这是我正在努力的事情:

bins = [0,250,500,750,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000,8000,1000000000000]
#I didn't know how to create 8000+ so I just added a crazy number in the end, it works

group_names = ['0-250','251-500','501-749','750-999','1000-1499','1500-1999','2000-2499','2500-2999','3000-3499','3500-3999','4000-4499','4500-4999','5000-5499','5500-5999','6000-6499','6500-6999','7000-7499','8000+']

categories = pd.cut(df_2014['Dollar'], bins, labels=group_names)
df['Category'] = pd.cut(df['Dollar'], bins, labels=group_names)
df['Buckets'] = pd.cut(df['Dollar'], bins)

这是我的代码:

Best_ID_S| Dollar | Category |  Buckets
abc2464    0.00     NaN
fdhg357    672.00   501-749        (500, 750]
hjg5235    250.00   0-250          (0, 250]
mjhur57    199.00   0-250          (0, 250]
erew3452   116.25   0-250          (0, 250]

这是我得到的,当我做df.head():

{{1}}

如果美元价值为0,我需要它为0-250桶。但我得到了NaN。

2 个答案:

答案 0 :(得分:5)

right参数的默认值为true。数学(表示排除左边的一个,因此需要[来包含左边的值。所以将pd.cut更改为

df['Category'] = pd.cut(df['Dollar'], bins, labels=group_names,right=False)
df['Buckets'] = pd.cut(df['Dollar'], bins,right=False)
 Best_ID_S|  Dollar Category     Buckets
0    abc2464    0.00    0-250    [0, 250)
1    fdhg357  672.00  501-749  [500, 750)
2    hjg5235  250.00  251-500  [250, 500)
3    mjhur57  199.00    0-250    [0, 250)
4   erew3452  116.25    0-250    [0, 250)

如果让它保持包容性,您还可以通过保留正确的参数include_lowestTrue设置为True

答案 1 :(得分:1)

要创建高于8000的bin,您可以将最后一个bin用作np.inf

bins = [0,250,500,750,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000,8000,np.inf]

要包含下限,可以使用参数include_lowest = True

df['Category'] = pd.cut(df['Dollar'], bins, labels=group_names, include_lowest=True)
df['Buckets'] = pd.cut(df['Dollar'], bins, include_lowest=True)

你得到了

    Best_ID_S   Dollar  Category    Buckets
0   abc2464     0.00    0-250   [0, 250]
1   fdhg357     672.00  501-749 (500, 750]
2   hjg5235     250.00  0-250   [0, 250]
3   mjhur57     199.00  0-250   [0, 250]
4   erew3452    116.25  0-250   [0, 250]