pd.cut non-uniform bin intervals

Viewed 394

I have a dataframe like this:

    a   b
0   0   9
1   1   8
2   2   7
3   3   6
4   4   5
5   5   4
6   6   3
7   7   2
8   8   1
9   9   0
10  10  0
11  11  1
12  12  1

I wanted to use pd.cut() to separate column a in different subcategories according its value. In order to do that, It's necessary to get bins. It looks like we can set bins manually by using pd.IntervalIndex.

But how can I make intervals like: [0], (0,2], (2,4], (4,6], (6,8], (8,10], (10,)?

I don't know if this is the correct way to represent it, but there it is: a inteval with only zero - [0] and a interval with every value greater than 10 - (100,)

1 Answers

There is not interval with one value. For get the same out, we could do Inf to close and start.

pd.cut(df.a,[-np.Inf, 0,2,4,6,8,10,np.Inf])
0     (-inf, 0.0]
1      (0.0, 2.0]
2      (0.0, 2.0]
3      (2.0, 4.0]
4      (2.0, 4.0]
5      (4.0, 6.0]
6      (4.0, 6.0]
7      (6.0, 8.0]
8      (6.0, 8.0]
9     (8.0, 10.0]
10    (8.0, 10.0]
11    (10.0, inf]
12    (10.0, inf]
Name: a, dtype: category
Categories (7, interval[float64]): [(-inf, 0.0] < (0.0, 2.0] < (2.0, 4.0] < (4.0, 6.0] < (6.0, 8.0] <
                                    (8.0, 10.0] < (10.0, inf]]
Related