python pandas dataframe 中的分箱(不是手动设置箱)

Sas*_*cha 4 python numpy bin dataframe pandas

我有一个数据框。我想对值进行分类并将其附加到新列。我可以用 pd.cut 来做到这一点。但问题是,使用 pd.cut 我手动设置标签和垃圾箱。但是,我只想设置步长(而不是 bin 号)。我也尝试过 np.linespace、np.arange 但我必须指定起点和终点以及 bin 计数。但可能存在一个数据帧,我无法知道数据帧中的最大和最小数量

df = pd.DataFrame([10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76],columns=['values'])
bins = [0, 10, 20,30, 40, 50, 60, 70]
labels = ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70']
df['bins'] = pd.cut(df['values'], bins, labels=labels)
print (df)

    values   bins
0       10   0-10
1       10   0-10
2       23  20-30
3       42  40-50
4       51  50-60
5       33  30-40
6       52  50-60
7       42  40-50
8       44  40-50
9       67  60-70
10      65  60-70
11      12  10-20
12      10   0-10
13       2   0-10
14       3   0-10
15       2   0-10
16      77    NaN
17      76    NaN
Run Code Online (Sandbox Code Playgroud)

这是我的输出,我想获得相同的输出,但不是手动设置 bin 和标签 ps 正如你从这里看到的,如果我的值大于 70,它将是 Nan。所以这也是我想设置步长“10”的原因。我可以有连续值,所以我希望它通过使用步长大小 10 自动进行标记

我非常感谢你的帮助

谢谢!!!

Vai*_*ali 6

只是您的代码略有不同,请注意,我在 df 末尾添加了一行值为 93 的行。

df = pd.DataFrame([10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76, 93],columns=['values'])
bins = np.arange(0,df['values'].max() + 10, 10)
df['bins'] = pd.cut(df['values'], bins)

values  bins
0   10  (0, 10]
1   10  (0, 10]
2   23  (20, 30]
3   42  (40, 50]
4   51  (50, 60]
5   33  (30, 40]
6   52  (50, 60]
7   42  (40, 50]
8   44  (40, 50]
9   67  (60, 70]
10  65  (60, 70]
11  12  (10, 20]
12  10  (0, 10]
13  2   (0, 10]
14  3   (0, 10]
15  2   (0, 10]
16  77  (70, 80]
17  76  (70, 80]
18  93  (90, 100]
Run Code Online (Sandbox Code Playgroud)

编辑:要按照评论中的要求在箱中包含零,请将参数 include_lowest 设置为 True

df = pd.DataFrame([0, 0, 0, 10, 10, 23, 42, 51, 33, 52, 42,44, 67, 65, 12, 10, 2, 3, 2, 77, 76, 93],columns=['values'])
bins = np.arange(0,df['values'].max() + 10, 10)
df['bins'] = pd.cut(df['values'], bins, include_lowest=True)
Run Code Online (Sandbox Code Playgroud)

你得到

   values   bins
0   0   (-0.001, 10.0]
1   0   (-0.001, 10.0]
2   0   (-0.001, 10.0]
3   10  (-0.001, 10.0]
4   10  (-0.001, 10.0]
5   23  (20.0, 30.0]
6   42  (40.0, 50.0]
7   51  (50.0, 60.0]
8   33  (30.0, 40.0]
9   52  (50.0, 60.0]
10  42  (40.0, 50.0]
11  44  (40.0, 50.0]
12  67  (60.0, 70.0]
13  65  (60.0, 70.0]
14  12  (10.0, 20.0]
15  10  (-0.001, 10.0]
16  2   (-0.001, 10.0]
17  3   (-0.001, 10.0]
18  2   (-0.001, 10.0]
19  77  (70.0, 80.0]
20  76  (70.0, 80.0]
21  93  (90.0, 100.0]
Run Code Online (Sandbox Code Playgroud)