在pandas中执行excel-like标识

我有一个数据集列出了他们完成某些操作的员工和时间戳。 它分为三列:员工,date,小时。

我想统计每小时活跃的员工数量。 在Excel中,我将通过添加第四列EmpFactor来执行COUNTIFS操作:

 =1/COUNTIFS(Name range;Name;Date range;Date;Hour range;Hour) 

我随后可以通过在EmpFactor列上执行SUMIF来计算活动员工的数量。

我试着用下面的代码来EmpFactor使用pandas的EmpFactor列:

 for name,date,time in zip(df['Employee'],df['Date'],df['Time']): df['EmpFactor'] = 1/(df[(df.Employee == name) and (df.Day == dag) and (df.Time == tijd)].count()) 

但是这不起作用。 我已经通过很多主题进行了广泛的search,但还没有find合适的答案。

假设你有这样的DataFrame结构:

 import pandas as pd import numpy as np df = pd.DataFrame([['Alice', '2012-03-05', 23], ['Fred', '2012-03-05', 23], ['Bob', '2012-12-12', 00]], columns=('Employee', 'Date', 'Time')) # Here you have: Employee Date Time 0 Alice 2012-03-05 23 1 Fred 2012-03-05 23 2 Bob 2012-12-12 0 # convert to a date df['DateTime']=pd.to_datetime(df['Date']) # make it index df2=df.set_index('DateTime') # group by date and time g = df2.groupby([pd.TimeGrouper('D'), 'Time']) # get counts: print(g.count()) #Here you have: Employee Date DateTime Time 2012-03-05 23 2 2 2012-12-12 0 1 1 # to get inverted values: print(1/g.count()) Employee Date DateTime Time 2012-03-05 23 0.5 0.5 2012-12-12 0 1.0 1.0 

当然,最好使Time成为DateTime列的一部分。 如果你愿意,你可以练习)

这种方法相当快:我的笔记本电脑上用了大约3分钟的时间来分组47M行。

从这个数据框开始:

 df = pd.DataFrame({'Employee': list('ABCDEFGH'), 'Date': [1, 1, 1, 2, 2, 2, 3, 3], 'Time': [10, 10, 10, 11, 10, 11, 11, 12]}) print(df) 

输出:

  Date Employee Time 0 1 A 10 1 1 B 10 2 1 C 10 3 2 D 11 4 2 E 10 5 2 F 11 6 3 G 11 7 3 H 12 

您可以按DateTime分组并计算员工数:

 per_hour = df.groupby(['Date', 'Time']).count() per_hour['EmpFactor'] = 1 / per_hour.Employee print(per_hour) 

输出:

  Employee EmpFactor Date Time 1 10 3 0.333333 2 10 1 1.000000 11 2 0.500000 3 11 1 1.000000 12 1 1.000000