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

pandas-如何使用python cut方法创建bin,接受一个参数并返回适当的bin?

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

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

年龄属性的范围是19-87。你的任务是编写一个名为age_binner的函数,该函数会将此功能离散化到以下bin中:

约束是:

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

你的函数应接受一个参数(int或float),并以字符串形式返回适当的bin标签。

我知道如何创建垃圾箱并使用cut方法,但不确定如何接受一个参数并返回垃圾箱标签。

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

得到了答案:

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))