【问题标题】:python pandas binning numerical rangepython pandas binning 数值范围
【发布时间】:2016-07-10 22:22:44
【问题描述】:

我有一个请求,我想在其中合并一个数值

If the student marks is 
b/w 0-50 (incl 50) then assign the level column value = "L"
b/w 50-75(incl. 75) then assign the level column value ="M"
>75 then assign the level column value ="H"

这就是我得到的东西

raw_data = {'student':['A','B','C'],'marks_maths':[75,90,99]}
df = pd.DataFrame(raw_data, columns = ['student','marks_maths'])
bins = [0,50,75,>75]
groups = ['L','M','H']
df['maths_level'] = pd.cut(df['marks_maths'], bins, labels=groups)

我收到语法错误

File "<ipython-input-25-f0b9dd609c63>", line 3
    bins = [0,50,75,>75]
                    ^
SyntaxError: invalid syntax

我如何引用一个显示 >确定值的截止值?

【问题讨论】:

    标签: python pandas numeric binning


    【解决方案1】:

    试试这个:

     bins = [0,50,75,101] or bins = [0,50,75,np.inf]
    

    【讨论】:

    • 最大值可能是 101 或 1000..我不知道..所以我只想设置一个条件,即它是 > 某个值
    • 我最初赞成这个答案,但这没有意义。您不能在 or 语句中进行赋值。你是什​​么意思?
    • @Ami 你在说什么? 'or'是英文'or',不是代码'or'
    • 哦,所以它不应该被格式化为一个单独的代码块,对吧? or 在此处显示为关键字。
    • 对于任何使用该网站的人来说都很明显,上面的意思是什么。
    【解决方案2】:

    希望对你有帮助

    import numpy as np
    import pandas as pd
    
    # 20 random numbers between 0 and 100
    scores = np.random.randint(0,100,20)
    df = pd.DataFrame(scores, columns=['scores'])
    
    bins = [0,50,75, np.inf]
    
    df['binned_scores'] = pd.cut(df.scores, bins=[0,50,75, np.inf], include_lowest=False, right=True)
    df['bin_labels'] = pd.cut(df.scores, bins=[0,50,75, np.inf], include_lowest=False, right=True, labels=['L','M','H'])
    

    include_lowest 和 right 参数让您可以控制 bin 的边缘是否包含在内。

    【讨论】:

      【解决方案3】:

      只需将上限定义为最佳标记:

      bins = [0, 50, 75, 100]
      

      结果如你所愿:

        student  marks_maths maths_level
      0       A           75           M
      1       B           90           H
      2       C           99           H
      

      【讨论】:

      • 如果不想绑定也可以使用np.inf。
      • 上限可以是任何值..可以是 100 或 1000.我不知道最大值/上限值
      猜你喜欢
      • 2022-12-02
      • 2014-02-21
      • 2017-12-13
      • 2021-08-27
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      相关资源
      最近更新 更多