我将数据存储在数据框中。它包含一个包含时间实例的列。请找到附件中的一个示例文件。
我们正在尝试检查time_split列中的连续性。
因此,我基本上要做的是,一旦失去连续性,就拆分数据帧。因此,基本上我们试图实现的是以某种方式检查时间列的行是否增加了我的1分钟,如果没有拆分数据帧的话。我尝试了基于小时的分组,但这不起作用,因为实例的连续性超过了小时,即持续了超过一个小时,并跳到了下一个小时。
如果能帮上忙我会很感激的。
谢谢。
发布于 2020-05-12 02:18:51
此代码根据当前样本和前一个样本之间的时间差生成组ids列表。
df.Time_split = pd.to_datetime(df.Time_split) # convert the strings to datetime objects
default = datetime.timedelta(minutes=1) # default speration, to check against
group = [0] # initial group number
prev = df.Time_split[0] # inital sample to compare
for i in range(1, len(df.Time_split)): # for second entry and up
delta = df.Time_split[i] - prev # delta time
if(default-delta == datetime.timedelta()): # if difference is zero
group.append(group[-1]) # current sample belongs to the same group as previous sample
else:
group.append(group[-1]+1) # create a new group
prev = df.Time_split[i] # update previous
df['group_number'] = group # add the list to the dataframe
# optional split by group:
frames = [df[df['group_number'] == x] for x in range(group[-1]+1)] 发布于 2020-12-22 11:17:45
我对Izaak Comelis在Python3中的代码有问题。如果发现这个细微的修改更可靠/更具可读性。
def _time_continuity(input_df, datetime_col='datetime', minutes=10):
'''
Assumes that the datetime column has already been sorted
df.sort_values(by=datetime_col)
'''
default = timedelta(minutes=minutes)
group = [0] # initial group number
grp_ctr = 0
dt_iter = iter(input_df[datetime_col])
prev = next(dt_iter) #skip first row
for i in dt_iter: # for second entry and up
delta = abs(i - prev) # delta time
if (delta <= default): # if difference is at tolerence
group.append(grp_ctr) # current sample belongs to the same group as previous sample
else:
grp_ctr += 1
group.append(grp_ctr)
prev = i # update previous
input_df['time_group'] = group # add the list to the dataframe
if len(set(group)) > 1:
print(f'There are {len(set(group))} time groups')
return input_df注意:您可以控制您希望timedelta值创建组的方式。在:
if (delta <= default):您可以将其更改为您想要的值,增量==默认值,增量>=默认值...这将确定是否建立了新的组。在我的用例中,我不关心时间增量是否小于10分钟。请记住,><方法将对重复的时间戳(delta==0)进行分组。如果您想要捕获它们,请使用==。
abs(i -prev)确保日期时间序列的排序不会干扰结果asc/desc。
https://stackoverflow.com/questions/61735543
复制相似问题