我一直在考虑这个问题,想知道是否有人对如何最好地解决这个问题有任何见解。我有一个熊猫DataFrame有许多专栏,包括一个datetime64ns。我想找到一些方法来“分组”记录,这些记录的日期时间非常接近。例如,如果在两秒钟内通过分配一个称为分组ID的公共ID将以下事务组合在一起,我可能会感兴趣:
Transaction ID Time Grouped ID
1 08:10:02 1
2 08:10:03 1
3 08:10:50
4 08:10:55
5 08:11:00 2
6 08:11:01 2
7 08:11:02 2
8 08:11:03 3
9 08:11:04 3
10 08:15:00注意,如果事务继续以快速的间隔发生,我不希望时间窗口无限地展开--一旦一个完整的2秒窗口过去,一个新窗口将从下一个事务开始(如事务5-9所示)。此外,我最终将在毫秒级(即将事务合并在50 ms内)执行此分析,但为了便于上面的表示,我将停留在秒内。
非常感谢您所能提供的任何见解!
发布于 2014-11-03 23:33:33
我建议的解决方案要求您使用时间数据重新编制数据索引。您可以使用所需频率的日期时间列表,使用searchsorted查找索引中最近的日期时间,然后将其用于切片(如问题python pandas dataframe slicing by date conditions和Python pandas, how to truncate DatetimeIndex and fill missing data only in certain interval中所建议的)。
我使用的是熊猫0.14.1和DataOffset对象(http://pandas.pydata.org/pandas-docs/dev/timeseries.html?highlight=dateoffset)。我没有向datetime64查询,但我想您可能会修改代码。DataOffset下降到微秒级。
使用以下代码,
import pandas as pd
import pandas.tseries.offsets as pto
import numpy as np
# Create some ome test data
d_size = 15
df = pd.DataFrame({"value": np.arange(d_size)}, index=pd.date_range("2014/11/03", periods=d_size, freq=pto.Milli()))
# Define periods to define groups (ticks)
ticks = pd.date_range("2014/11/03", periods=d_size/3, freq=5*pto.Milli())
# find nearest indexes matching the ticks
index_ticks = np.unique(df.index.searchsorted(ticks))
# make a dataframe with the group ids
dgroups = pa.DataFrame(index=df.index, columns=['Group id',])
# sets the group ids
for i, (mini, maxi) in enumerate(zip(index_ticks[:-1], index_ticks[1:])):
dgroups.loc[mini:maxi] = i
# update original dataframe
df['Group id'] = dgroups['Group id']我获得了这样的数据:
value Group id
2014-11-03 00:00:00 0 0
2014-11-03 00:00:00.001000 1 0
2014-11-03 00:00:00.002000 2 0
2014-11-03 00:00:00.003000 3 0
2014-11-03 00:00:00.004000 4 0
2014-11-03 00:00:00.005000 5 1
2014-11-03 00:00:00.006000 6 1
2014-11-03 00:00:00.007000 7 1
2014-11-03 00:00:00.008000 8 1
2014-11-03 00:00:00.009000 9 1
2014-11-03 00:00:00.010000 10 2
2014-11-03 00:00:00.011000 11 2
2014-11-03 00:00:00.012000 12 2
2014-11-03 00:00:00.013000 13 2
2014-11-03 00:00:00.014000 14 2https://stackoverflow.com/questions/26724616
复制相似问题