[英]Pandas groupby a column and check multiple conditions to create a new categorical column
与我查询的内容类似,我正在尝试按特定的承认石斑鱼代码分组,这次还在设置类别之前检查其他多个条件。
例如,我有以下数据框:
会员ID | 录取代码 | 服务水平 | 插曲 |
---|---|---|---|
1 | 一种 | 5 | 3 |
2 | 一种 | 10 | 6 |
1 | 乙 | 2 | 3 |
2 | 乙 | 1 | 6 |
现在,不仅仅是检查平均值和设置类别,我想检查平均值是否是中位数的 2 倍,以及最小集数是否小于 5。我的意思是:
对于AdmittingCode a ,平均值为 7.5 ( (5 + 10) / 2 )。 最初,逻辑是组类别为MEMBERID 1 AdmittingCode为a,0,因为它是小于7.5 LOS(仅为5)和用于MEMBERID 2 AdmittingCode为,1,因为它是大于7.5 LOS(即10)使用以下代码:
m = df.groupby('AdmittingCode')['LOS'].transform('mean').lt(df['LOS'])
df['LOSCategory'] = m.astype(int)
但是,现在我想在设置类别列之前再检查 2 个条件。
如果上述两个条件都满足,我希望将类别设置为 0 或 1(即使对于上述条件仅满足 1 个但不满足其他条件的情况)。
注意:这里的均值和中位数基于每个AdmittingCode ,因此a 的均值与之前的查询b 的均值不同。
使用此逻辑,对于AdmittingCode a的平均值将是 7.5,中位数也是 7.5,对于MemberID 1与AdmittingCode a的LOS 5和剧集计数3 ,类别将设置为 0。这里,平均值不是中位数的 2 倍,以及计数,都小于 5。
最后观察到如下数据框:
会员ID | 录取代码 | 服务水平 | 插曲 | LOSC类别 |
---|---|---|---|---|
1 | 一种 | 5 | 3 | 0 |
2 | 一种 | 10 | 6 | 1 |
1 | 乙 | 2 | 3 | 0 |
2 | 乙 | 1 | 6 | 1 |
>>> df['LOSCategory'] = (df.groupby("AdmittingCode")
.apply(lambda x: x.apply(lambda xx:(x.LOS.mean() >= x.LOS.median()*2) | (xx.Episode >= 5), axis=1))
.astype(int)
.to_list()
)
>>> df
MemberID AdmittingCode LOS Episode LOSCategory
0 1 a 5 3 0
1 2 a 10 6 1
2 1 b 2 3 0
3 2 b 1 6 1
您需要编写一个返回所需结果的函数func
。
LOScategory = df.apply(
lambda row: func(row['MemberID'], row['AdmittingCode'],row['LOS'],row['Episode']),
axis=1)
df['LOScategory'] = LOScategory
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.