我一直在尝试通过使用lambda函数来选择sum()的哪些行来聚合组中的多个列。我的问题是sum()仅提供一个计数。我在熊猫方面表现平平,搜寻过但找不到答案。任何答复将不胜感激,我当然也感谢您的时间。
groupedByEmployeeShift['Duration1'] = groupedByEmployeeShift['Duration'] ### create a dummy column for ShiftOT below
groupedByEmployeeShift['RoundedInMinutes1'] = groupedByEmployeeShift['RoundedInMinutes'] ### create a dummy column for RoundedInMinutes below
groupedByEmployeeShift['RoundedOutMinutes1'] = groupedByEmployeeShift['RoundedOutMinutes'] ### create a dummy column for RoundedOutMinutes below
shiftStats = groupedByEmployeeShift.groupby('employee').agg(
WorkLocation = ('WorkedLocation', 'first'),
AllShifts = ('Duration', 'count'),
OTShifts = ('Duration1', lambda x: (x > 8).sum()),
NoRoundedInMinutes = ('RoundedInMinutes', lambda x: (x == 0).sum()),
NoRoundedOutMinutes = ('RoundedOutMinutes', lambda x: (x == 0).sum()),
RoundedInMinutes = ('RoundedInMinutes1', lambda x: (x > 0).sum()),
RoundedOutMinutes = ('RoundedOutMinutes1', lambda x: (x > 0).sum()))
逻辑运算的结果(例如(x > 0)
lambda函数中的结果)是布尔数组,因此(x > 0).sum()
将返回布尔结果的总和,这等于True
结果数组中实例的数量。
如果要x
在条件为时返回总和,则True
可以使用:lambda x: x[x > 0].sum()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句