在Python中按类别分组并设置阈值
我有一个数据集df,我想在其中对每个阈值进行分组在Python中按类别分组并设置阈值,python,pandas,numpy,Python,Pandas,Numpy,我有一个数据集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-
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成员那里得到了一些建议,但我想扩展)
但是,我不知道如何将每个组设置为这些阈值。
我正在积极研究这个问题。感谢您的建议。使用np.选择(条件、选择、替代)
使用np.选择(条件、选择、替代)
你好好的,让我试试。中间值只是设置为:“好”哦,我明白了。非常感谢。让我试试看。好的,让我试试。中间值只是设置为:“好”哦,我明白了。非常感谢。让我试试
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'])
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')