Quantcast
Channel: Bining a set of numbers in a specific way - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Sash Sinha for Bining a set of numbers in a specific way

$
0
0

You can use pandas.cut and pandas.DataFrame.groupby, you just need to make the last bin right boundary more than the actual inclusive boundry you want, e.g., 201 or 200.1 since you are specifying right=False:

import pandas as pdnums = pd.Series(range(100, 201))  bins_with_labels = pd.cut(    x=nums,    bins=[100, 135, 160, 175, 190, 201],  # For the last bin, you need to use a number larger than the final inclusive right boundary.     labels=['[100, 135)', '[135, 160)', '[160, 175)', '[175, 190)', '[190, 200]'],    right=False,    include_lowest=True,)grouped = nums.groupby(bins_with_labels).apply(list)print(grouped)

Output:

[100, 135)  [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134][135, 160)  [135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159][160, 175)  [160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174][175, 190)  [175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189][190, 200]  [190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200]

Viewing all articles
Browse latest Browse all 3

Trending Articles