【对比python】按指定次序分组 | 润乾 -欧洲杯在线开户

任务:
按次序列出technology,production,sales,hr的女员工人数和平均年龄

python

1 import pandas as pd
2 import datetime
3 emp_file = 'e:\\txt\\employee.txt'
4 dept_seq = ['technology','production','sales','hr']
5 emp_info = pd.read_csv(emp_file,sep='\t')
6 emp_g = emp_info.groupby(by='dept')
7 emp_g_index = [index for index,group in emp_g]
8 today = datetime.datetime.today().year
9 dept_femal_list = []
10 for dept in dept_seq:
11     if dept not in emp_g_index:
12         dept_femal_num = 0
13         age_a = none
14     else:
15         dept_emp = emp_g.get_group(dept)
16         dept_emp_femal = dept_emp[dept_emp['gender']=='f']
17         dept_femal_num = len(dept_emp_femal)
18         arr = pd.to_datetime(dept_emp_femal['birthday'])
19         age_a = (today-arr.dt.year).mean()
20     dept_femal_list.append([dept,dept_femal_num,age_a])
21 dept_femal_info = pd.dataframe(dept_femal_list,columns=['dept','femal_num','femal_age'])
22 print(dept_femal_info)

集算器

  a
1 e:\\txt\\employee.txt
2 [technology,production,sales,hr]
3 =file(a1).import@t()
4 =a3.align@a(a2,dept)
5 =a4.new(a2(#):dept,(f_emp=~.select(gender:"f"),f_emp.count()):femal_num,f_emp.avg(age@y(birthday)):femal_age)

以有序集合为基础的集算器加上特有的对齐运算处理这类计算就方便多了。

网站地图