Python Forum
Function for grouping variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function for grouping variables
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Grouping Data based on 30% bracket purnima1 4 1,142 Mar-10-2023, 07:38 PM
Last Post: deanhystad
  How to print variables in function? samuelbachorik 3 851 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  User-defined function to reset variables? Mark17 3 1,590 May-25-2022, 07:22 PM
Last Post: Gribouillis
  Grouping and sum of a list of objects Otbredbaron 1 3,132 Oct-23-2021, 01:42 PM
Last Post: Gribouillis
  Grouping and summing of dataset jef 0 1,608 Oct-04-2020, 11:03 PM
Last Post: jef
  Do I have to pass 85 variables to function? Milfredo 10 4,187 Sep-26-2020, 10:13 PM
Last Post: Milfredo
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,418 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  Grouping algorithm riccardoob 7 2,931 May-19-2020, 01:22 PM
Last Post: deanhystad
  Issues with storing variables outside of a function cerulean747 7 3,638 Apr-30-2020, 08:46 AM
Last Post: DeaD_EyE
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 2,885 Feb-09-2020, 02:05 PM
Last Post: new_to_python

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020