Python Forum
Function for grouping variables - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Function for grouping variables (/thread-14055.html)



Function for grouping variables - Scott - Nov-13-2018

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.


RE: Function for grouping variables - ichabod801 - Nov-13-2018

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.