Warm tip: This article is reproduced from serverfault.com, please click

How to use python cut method to create bins, accept one parameter and return appropriate bin?

发布于 2020-11-25 04:31:25

The age attribute spans from 19-87. Your task is to write a function named age_binner that will discretize this feature into the following bins:

Contraints are:

age < 20: 'teenager'
20 <= age < 30: 'twenties'
30 <= age < 40: 'thirties'
40 <= age < 50: 'forties'
50 <= age < 60: 'fifties'
60 <= age: 'over-sixty'

Your function should accept one parameter (int or float) and return the appropriate bin label as a string.

I know how to create bins and use the cut method, but not sure how to accept one parameter and return bin label.

Questioner
Sandhya Indurkar
Viewed
0
Sandhya Indurkar 2020-11-28 07:36:45

Got the answer:

def age_binner(num):
    if num < 1:
      result = "enter a valid age"
    else:
      age = pd.DataFrame(list(range(20,88)), columns = ["age"])
      bins = [1, 19,29,39,49,59,88]
      labels=["teenager","twenties", "thirties", "fourties", "fifties", "over-sixty"]
      age["binned_age"] = pd.cut(age["age"], bins = bins, labels = labels)
      result = age.loc[age["age"]==num, "binned_age"].iloc[0]
    return (result)

 print(age_binner(38))