# Subdivide a numerical vector with a normal distribution

I have a numerical array of prices values. I'd like to do classification on this parameter, so I'd like to create a certain number of classes with the same granularity. I'd like to create a generalized function that given the array and the number of classes i'd like to have it automatically return the price intervals for those classes. Currently this is my price attribute:

df_cleaned.price.describe()
>>>
count    122668.000000
mean      11253.349594
std        7856.513917
min        1010.000000
25%        4995.000000
50%        8995.000000
75%       15965.000000
max       34991.000000
Name: price, dtype: float64


And I created a function manually to create 6 classes and it looks like this:

def normalize_price(df):
cond = [
(df['price'] >= 1000) & (df['price'] <= 4999),
(df['price'] >= 5000) & (df['price'] <= 8999),
(df['price'] >= 9000) & (df['price'] <= 15999),
(df['price'] >= 16000) & (df['price'] <= 24999),
(df['price'] >= 25000) & (df['price'] <= 34000),
(df['price'] >= 34001) & (df['price'] <= 40000)
]

choice = [
1000,
5000,
9000,
16000,
25000,
35000,
]

df['price'] = np.select(cond, choice, df['price'])
return df


Can anyone help me improvint this function? pls thanks

You seem to be describing the method cut in pandas (documentation)

This method does exactly what you want, if you want to separate a dataframe into n equal-sized bins or manually specify the ranges.

Example:

df = pd.DataFrame(np.array([10, 50, 99, 140, 250, 300, 450, 499]), columns=['price'])

bins = pd.IntervalIndex.from_tuples([(0, 100), (100, 300), (300, 500)])
df['price'] = pd.cut(df['price'], bins)


Output: You can simply specify the number of bins you want:

df = pd.DataFrame(np.array([10, 50, 99, 140, 250, 300, 450, 499]), columns=['price'])

df['price'] = pd.cut(df['price'], bins=3)


Output: I hope this helps improve your code.