获取python groupby中字符串的第一次和最后一次出现

2024-09-30 10:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python数据框架,包含以下列(考勤数据)

Empcode     T01         T01          T02          T03          T04
TranDate    10/09/2018  10/09/2018   10/09/2018   10/09/2018   10/09/2018
Trn Time    09.29       17.54        13.52        10.01        18.01

对于给定的事务处理日期和Empcode,我想获取第一次出现的Trn Time作为In Time,最后一次出现的TrnTime作为Out Time。你知道吗

如果键只有一个记录,则时间应该是输入/输出时间。你知道吗

g=df.groupby(['Empcode','TrnDate'])

print (pd.DataFrame({'In':g.TrnTime.nth(0),'out':g.TrnTime.nth(-1)}))

以上代码适用于Empcode和TranDate有2条记录的地方。你知道吗

如果只有一条记录,它就不起作用。你知道吗


Tags: 数据in框架time记录时间nthtrn
1条回答
网友
1楼 · 发布于 2024-09-30 10:32:25

if there is only one record for the key the time should come in Out Time

那就这样吧。定义一个函数,该函数正好执行此操作,并将其传递给GroupBy.apply

def fnc(g):
    res = {'Out': g.iat[-1]}
    if len(g) > 1:
        res['In'] = g.iat[0]
    return res

dfres = df.groupby(['Empcode','TranDate'])['Trn Time'].apply(fnc).unstack()
print(dfres)
                       In    Out
Empcode TranDate                
T01     10/09/2018  09.29  17.54
T02     10/09/2018    NaN  13.52
T03     10/09/2018    NaN  10.01
T04     10/09/2018    NaN  18.01

相关问题 更多 >

    热门问题