微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

改变数据的形状和结构

如何解决改变数据的形状和结构

我有以下数据集

办公室 员工 ID 加入日期 离职日期
AA 700237 27-11-2017
AA 700238 11-01-2018
AA 700252 14-02-2018 08-04-2018
AB 700287 18-01-2014
AB 700449 28-02-2014 17-04-2014

这个想法是在有人加入时添加活动列,如果有人在任何月份辞职并因此想要使用python将其更改为以下格式

办公室 月和年 活跃
AA 1 月 17 日 0
AA 2 月 17 日 0
AA 3 月 17 日 0
AA 4 月 17 日 0
AA 5 月 17 日 0
AA 6 月 17 日 0
AA 7 月 17 日 0
AA 8 月 17 日 0
AA 9 月 17 日 0
AA 10 月 17 日 0
AA 11 月 17 日 1
AA 12 月 17 日 1
AA 1 月 18 日 2
AA 2 月 18 日 3
AA 3 月 18 日 3
AA 4 月 18 日 2
AB 1 月 14 日 1
AB 2 月 14 日 2
AB 3 月 14 日 2
AB 4 月 14 日 1

请帮忙。

解决方法

使用:

#convert columns to datetimes
df['Joining Date'] = pd.to_datetime(df['Joining Date'],dayfirst=True)
df['Attrition Date'] = pd.to_datetime(df['Attrition Date'],dayfirst=True)

#add new rows by first January of minimal year per groups
df1 = df.groupby('Office')['Joining Date'].min() - pd.offsets.DateOffset(month=1,day=1)
df = df.append(df1.reset_index()).sort_values(['Office','Joining Date'])


#replace missing values in Attrition Date by maximal date with next month
#replace missing values in Joining  Date by maximal date with next month
next_month = (df.groupby('Office')['Attrition Date'].transform('max') + 
               pd.offsets.DateOffset(months=1))
next_month1 = (df.groupby('Office')['Joining Date'].transform('max') + 
               pd.offsets.DateOffset(months=1))

df['Attrition Date'] = df['Attrition Date'].fillna(next_month).fillna(next_month1)


#explode start and end datetimes converted to months with years
f = lambda x: pd.date_range(x['Joining Date'],x['Attrition Date'],freq='M').strftime('%b-%y')
df['Month & Year'] = df.apply(f,axis=1)

#count number of Employee ID with omit missing values
df = (df.explode('Month & Year')
        .groupby(['Office','Month & Year'],sort=False)['Employee ID']
        .count()
        .reset_index(name='Active'))

print (df)
   Office Month & Year  Active
0      AA       Jan-17       0
1      AA       Feb-17       0
2      AA       Mar-17       0
3      AA       Apr-17       0
4      AA       May-17       0
5      AA       Jun-17       0
6      AA       Jul-17       0
7      AA       Aug-17       0
8      AA       Sep-17       0
9      AA       Oct-17       0
10     AA       Nov-17       1
11     AA       Dec-17       1
12     AA       Jan-18       2
13     AA       Feb-18       3
14     AA       Mar-18       3
15     AA       Apr-18       2
16     AB       Jan-14       1
17     AB       Feb-14       2
18     AB       Mar-14       2
19     AB       Apr-14       1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。