python-3.x - 改变数据的形状和结构
问题描述
我有以下数据集
办公室 | 员工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 | 17 月 17 日 | 0 |
AA | 2月17日 | 0 |
AA | 3 月 17 日 | 0 |
AA | Apr-17 | 0 |
AA | 5 月 17 日 | 0 |
AA | 17 年 6 月 | 0 |
AA | 7 月 17 日 | 0 |
AA | 17 年 8 月 | 0 |
AA | 17 年 9 月 | 0 |
AA | 17 月 17 日 | 0 |
AA | 11 月 17 日 | 1 |
AA | 17 月 17 日 | 1 |
AA | 18 年 1 月 | 2 |
AA | 2月18日 | 3 |
AA | 3月18日 | 3 |
AA | Apr-18 | 2 |
AB | 14 年 1 月 | 1 |
AB | 2月-14日 | 2 |
AB | 3 月 14 日 | 2 |
AB | Apr-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
推荐阅读
- http - 捕获套接字异常
- python-3.x - Django在多个数据库和多个项目之间导入模型
- python - 如何在 python PyQt 中为倒计时应用程序编写代码
- javascript - 中心化 Axios API 取消
- javascript - 如何使用枚举(作为静态变量附加到类)作为类型
- django - 我如何告诉 gunicorn 在进行出站呼叫时使用代理服务器?
- database - 无法连接到 PostgreSQL 服务器:致命:角色“apache”不存在
- node.js - 是否可以针对其他字段而不是 _id 在猫鼬中填充数据
- python - 如何检查列表中的双重元素,然后在 Python 2 中删除这两个元素
- http - Flutter:我收到一个错误,即不再出现在小部件树中的小部件的 State 对象