我在Python2.7中有一个pandas数据帧,我想遍历这些行,得到两种类型事件之间的时间,以及两种类型事件之间的计数(在特定条件下)。在
我的数据是一个pandas.DateFrame
,看起来像这样:
Time Var1 EvntType Var2
0 15 1 2 17
1 19 1 1 45
2 21 6 2 43
3 23 3 2 65
4 25 0 2 76 #this one should be skipped
5 26 2 2 35
6 28 3 2 25
7 31 5 1 16
8 33 1 2 25
9 36 5 1 36
10 39 1 2 21
其中,我想忽略Var1
等于0的行,然后计算类型为1的事件与类型为1的事件之间的时间间隔(除了Var1 == 0
)之间的时间。因此,在上述情况下:
我是按照以下方式来做的:
i=0
eventCounter = 0
lastStartTime = 0
length = data[data['EvntType']==1].shape[0]
results = np.zeros((length,3),dtype=int)
for row in data[data['Var1'] > 0].iterrows():
myRow = row[1]
if myRow['EvntType'] == 1:
results[i,0] = lastStartTime
results[i,1] = myRow['Time'] - lastStartTime
results[i,2] = eventCounter
lastStartTime = myRow['Time']
eventCounter = 0
i += 1
else:
eventCounter += 1
这给了我想要的结果:
>>> results[1:]
array([[19, 12, 4],
[31, 5, 1]])
但这似乎真的绕过了,在大型数据帧上需要很长时间。我该如何改进?在
您可以使用以下方法删除
Var1
等于0的行:然后创建一个布尔掩码,其中
^{pr2}$EvntType
为1:查找与
mask
为真的行关联的Time
:还可以找到
mask
为真的序数索引:start_time
是times[:-1]
中的所有值。在time_inbetween
是时间上的差异,np.diff(times)
event_count
是idx
中的差减1。在收益率
相关问题 更多 >
编程相关推荐