我有一个包含电子邮件地址、日期和工作函数的数据集。我渴望获得当前职务函数和以前的职务函数(与当前职务函数以及在当前职务函数之前持有的职务函数不同的值(。例如john.k@abc.com当前为swe_mgr2,并且以前的作业函数为swe_mgrp1。我还热衷于捕捉上一次工作职能的持续时间。持续时间很难计算,因为开始日期是以随机方式捕获的,但它可以基于上一个作业函数的开始日期的第一行直到当前作业函数的起始日期的第一行将捕获。例如john.k@abc.com之前的工作职能为swe_mgr1,从2018年8月30日持续到2019年6月1日(即10个月(。
数据集
email startdate jobfunction
john.k@abc.com 01-01-2018 swe_ic1
john.k@abc.com 01-03-2018 swe_ic2
john.k@abc.com 30-08-2018 swe_mgr1
john.k@abc.com 01-06-2019 swe_mgr2
john.k@abc.com 01-06-2020 swe_mgr2
greg.h@abc.com 30-01-2018 mkt_ic2
greg.h@abc.com 01-06-2018 mkt_ic3
greg.h@abc.com 07-09-2018 mkt_mgr1
greg.h@abc.com 12-12-2018 mkt_mgr2
greg.h@abc.com 15-01-2019 mkt_mgr2
greg.h@abc.com 05-06-2019 mkt_mgr2
greg.h@abc.com 01-06-2020 mkt_mgr3
joseph.c@abc.com 01-06-2019 sales_ic1
joseph.c@abc.com 01-06-2020 sales_mgr1
预期输出为
email current_function previous_function duration_previous_function
john.k@abc.com swe_mgr2 swe_mgr1 10mths
greg.h@abc.com mkt_mgr3 mkt_mgr2 18mths
joseph.c@abc.com sales_mgr1 sales_ic1 12mths
我被困在试图获得上一个工作功能的第一步
此代码似乎可以检索当前作业函数,但不能检索以前的作业函数
df2 = df.groupby('email').last().sort_index().reset_index().drop_duplicates()
我还想知道这是否可以通过循环每个电子邮件地址来实现,但下面的代码不能很好地使用
emails = df['email']
assigndate = df['startdate']
jobname = df['jobfunction']
for i in emails:
prevjob = jobname.apply(lambda x: x.unique([-2]))
感谢任何形式的帮助和帮助,谢谢。
您可以在转换为datetimes后,首先按DataFrame.sort_values
对列进行排序,并按DataFrame.drop_duplicates
获取最后的重复项,然后按GroupBy.cumcount
为筛选前2行创建计数器,然后为DataFrame.set_index
和DataFrame.unstack
创建的MultiIndex
中的新级别创建计数器:
df['startdate'] = pd.to_datetime(df['startdate'], dayfirst=True)
df = (df.sort_values(['email','startdate'], ascending=[True, False])
.drop_duplicates(['email','jobfunction'], keep='last'))
df['g'] = df.groupby('email').cumcount()
df1 = df[df['g'].lt(2)].copy()
df1 = (df1.set_index(['email','g'])
.unstack()
.rename(columns={0:'current',1:'previous'}))
df1.columns = [f'{b}_{a}' for a,b in df1.columns]
df1 = df1.reset_index()
通过DataFrame.pop
和Series.dt.to_period
:转换为月份周期的最后减法列
df1['duration_previous_function'] = (df1.pop('current_startdate')
.dt.to_period('m')
.astype('int')
.sub(df1.pop('previous_startdate')
.dt.to_period('m')
.astype('int')))
print (df1)
email current_jobfunction previous_jobfunction
0 greg.h@abc.com mkt_mgr3 mkt_mgr2
1 john.k@abc.com swe_mgr2 swe_mgr1
2 joseph.c@abc.com sales_mgr1 sales_ic1
duration_previous_function
0 18
1 10
2 12