Suppose you want to assign numbers to bins based on quantile.
import numpy as np
numbers = [5, 1, 1, 2, 1, 3, 2]
bins = np.quantile([5, 1, 1, 2, 1, 3, 2], [0, 0.5, 1])
# [1, 2, 5]
left_categories = np.searchsorted(bins, numbers)
# [2, 0, 0, 1, 0, 2, 1]
right_categories = np.searchsorted(bins, numbers, side='right')
# [3, 1, 1, 2, 1, 2, 2]
You can use np.searchsorted
or np.digitize
. This is useful for turning a numerical variable into a categorical variable.
Thanks to numpy - Python: Assigning # values in a list to bins, by rounding up - Stack Overflow for the tip.