繁体   English   中英

基于groupby Python的第一个和最后一个值的条件创建一个新列

[英]Creating a new column based on conditions of first and last value of groupby Python

我有一个 Pandas 数据框,想根据 groupby 的第一行和最后一行的条件创建一个包含值的新列。 需要的条件是

mgr 到 mgr = 被聘为 mgr

emp 到 mgr = 提升到 mgr

emp 到 emp = 被聘为 emp

mgr 到 emp = 状态变化

date        email          level 
01/01/2000  john@abc.com   mgr
05/06/2000  john@abc.com   mgr     
10/01/2001  john@abc.com   mgr     
14/02/2000  kimdo@abc.com  emp     
19/10/2001  kimdo@abc.com  mgr     
12/05/2000  waint@abc.com  emp  
08/08/2000  waint@abc.com  emp  
14/04/2001  waint@abc.com  emp     
22/05/2000  neds@abc.com   mgr
08/11/2000  neds@abc.com   mgr     
12/06/2001  neds@abc.com   emp

想达到以下结果

date        email          level   status
01/01/2000  john@abc.com   mgr     hired as mgr
10/01/2001  john@abc.com   mgr     hired as mgr
14/02/2000  kimdo@abc.com  emp     promoted to mgr
19/10/2001  kimdo@abc.com  mgr     promoted to mgr
12/05/2000  waint@abc.com  emp     hired as emp
14/04/2001  waint@abc.com  emp     hired as emp
22/05/2000  neds@abc.com   mgr     status change
12/06/2001  neds@abc.com   emp     status change

到目前为止,我能够根据 groupyby 选择数据帧的第一行和最后一行,但不完全确定如何应用条件来获取新的“状态”列。 感谢任何形式的帮助,谢谢。

df2 = df.groupby('email', as_index=False).nth([0,-1])
df2 = df.groupby('email', as_index=False).nth([0,-1])

你可以试试:

d={'mgr:mgr':'hired as mgr','emp:mgr':'promoted to mgr','emp:emp':'hired as emp','mgr:emp':'status change'}
#created a dict for mapping

最后:

df2.loc[:,'status']=df2.groupby('email')['level'].transform(':'.join).map(d)

df2输出:

    date        email           level   status
0   01/01/2000  john@abc.com    mgr     hired as mgr
2   10/01/2001  john@abc.com    mgr     hired as mgr
3   14/02/2000  kimdo@abc.com   emp     promoted to mgr
4   19/10/2001  kimdo@abc.com   mgr     promoted to mgr
5   12/05/2000  waint@abc.com   emp     hired as emp
7   14/04/2001  waint@abc.com   emp     hired as emp
8   22/05/2000  neds@abc.com    mgr     status change
10  12/06/2001  neds@abc.com    emp     status change

尝试创建一个map dictionary来映射状态。

fl = lambda s: s.iloc[[0,-1]]
d = {'mgr-mgr': 'hired as mgr', 'emp-mgr': 'promoted to mgr', 'emp-emp': 'hired as emp', 'mgr-emp': 'status change'}
res = df.groupby('email', as_index=False)['level'].apply(lambda x: (fl(x).shift(1) + "-" + (fl(x))).bfill()).map(d)
res.index= res.index.droplevel()
df['status'] = res
df.dropna(inplace=True)

日期 电子邮件 等级 地位
0 01/01/2000 约翰@abc.com 经理 受聘为经理
2 10/01/2001 约翰@abc.com 经理 受聘为经理
3 14/02/2000 kimdo@abc.com 临时工 晋升为经理
4 19/10/2001 kimdo@abc.com 经理 晋升为经理
5 12/05/2000 waint@abc.com 临时工 被聘为 emp
7 14/04/2001 waint@abc.com 临时工 被聘为 emp
8 22/05/2000 neds@abc.com 经理 状态改变
10 12/06/2001 neds@abc.com 临时工 状态改变

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM