【问题标题】:Group by Category and Set Threshold in Python在 Python 中按类别分组并设置阈值
【发布时间】:2020-11-10 15:17:28
【问题描述】:

我有一个数据集 df,我想在其中对每个阈值进行分组。

group      start           end            Percent    

A          2019-04-01      2019-05-01     21       
A          2019-05-01      2019-06-01      8 
A          2019-07-01      2019-08-01      5        
B          2020-06-01      2020-07-01      7         
B          2020-07-01      2020-08-01      5  
B          2020-09-01      2020-10-01      3          

对于 A:如果值大于 20 - A 太高 如果值小于 6 - A 太低

对于 B:如果值大于 6 - B 太高 如果值小于 1 - B 太低

type      start           end            Percent           Result 

A          2019-04-01      2019-05-01     21                A Too High   
A          2019-05-01      2019-06-01      8                A Ok
A          2019-07-01      2019-08-01      5                A Too Low                 
B          2020-06-01      2020-07-01      7                B Too High                               
B          2020-07-01      2020-08-01      5                B Ok
B          2020-09-01      2020-10-01      3                B Ok      

这就是我正在做的事情:(我从 StackOverflow 成员那里得到了一些建议,但我想扩展)

df1 = df.groupby('type')

df2= df1['result']=pd.cut(df1.Percent, [-np.inf, 6, 20,np.inf], labels= 
['unacceptablelow','acceptable', 
'unacceptablehigh'])

df3= df2['result']=pd.cut(df2.Percent, [-np.inf, 1, 6,np.inf], labels= 
['unacceptablelow','acceptable', 
'unacceptablehigh'])

但是,我不确定如何将每个组设置为这些阈值。 我正在积极研究这个。任何建议表示赞赏。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用np.select(condition, choice, alternative)

    condition=[(df.group.eq('B')&df.Percent.gt(6))|(df.group.eq('A')&df.Percent.gt(20)),(df.group.eq('B')&df.Percent.lt(1))|(df.group.eq('A')&df.Percent.lt(6))]
        
        
    choice=['Too High','Too Low']
        
    df['result']=np.select(condition, choice, 'ok')
    

    【讨论】:

    • 嗨。好的,让我试试。中间值只是设置为:'Ok'
    • 哦,我明白了。谢谢你。让我试试
    猜你喜欢
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多