Python Forum

Full Version: Function for grouping variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I am trying to write a dynamic function for a dataframe that has about 20 columns. I am trying to bin variable values. So if they are within the lower quartile then bin 1 if they are below the mean then bin 2 etc. I have copy pasted what I have done below:


def binning(var):
if var <= np.percentile(var, 25) then var = 1
elif var <= np.percentile(var, 50) then var = 2
elif var <= np.percentile(var, 75) then var = 3
else var = 4
return var


I would then like to pass this function onto all 20 variables to bin them all accordingly.

I appreciate any help.

Thanks.
Use python tags for multiline code. The icode tags are for inline code.

Have you tried running that code? It doesn't look like it works to me.

Once it works, you'll probably want to use the map method of the series to apply it.