我有一个pandas DataFrame,其中的行对应于事件,列对应于这些事件的时间、纬度和经度。它看起来有点像:
time latitude longitude
0 1994-03-01 03:49:00.830 49.096 32.617 . . .
1 1994-10-04 11:41:28.080 10.964 133.891 . . .
2 1995-06-02 03:38:03.890 19.803 -52.799 . . .
3 1995-08-21 19:17:15.300 -19.851 -175.043 . . .
.
.
.
我想做的是将该数据集中的事件分组,以便将某个事件与特定时间和特定距离内的每个事件(timedif
和spacedif
)分组。
例如,假设timedif
是1年(忽略其他变量),那么我想要上面的事件0的一个组,它包含事件1但不包含事件2,并且事件1不应该接收组,因为它在组0中。然后是事件2的第二组,包含3等
我目前正在尝试的是非常低效的:
dfbuild = dfbuild.append({'head index': 0, 'sub index': [] },ignore_index = True)
for i in dfog.index:
for j in dfbuild.index:
if(timecomp(dfog.loc[dfbuild.loc[j]['head index']]['time'],dfog.loc[i]['time']) < timedif ):
if(geopy.distance.distance( (dfog.loc[i]['latitude'],dfog.loc[i]['longitude']),(dfog.loc[dfbuild.loc[j]['head index']]['latitude'],dfog.loc[dfbuild.loc[j]['head index']]['longitude']) ).km < spacedif ):
head = j
break
if(head == -1):
dfbuild = dfbuild.append({'head index': i, 'sub index': [] },ignore_index = True)
else:
dfbuild.loc[head]['sub index'].append(i)
head = -1
(timecomp只是使用datetime将字符串转换为datetime,然后减去它们;我使用geopy.dance.dancee()函数来获取纬度和经度之间的距离)
我知道这很难看,我认为我用错了.loc
,但它有效;我最终得到了一个DataFrame,它有两列,一列包含head index
值,另一列包含所有相应的sub index
值。然而,它的速度非常慢,而且随着数据集变得越来越大,速度呈指数级下降。
我能做些什么来加快速度?我也不喜欢这样做,所以如果我应该完全放弃它,以不同的方式去做,那是一种选择。
请注意,数据集中的行是按时间顺序排列的。
尝试使用geopandashttp://geopandas.org用于时间分组,例如:
times = pd.to_datetime(dfbuild.time)
dfbuild.groupby([times.hour, times.minute]).count()