如何在数据帧匹配中获得第一个索引

2024-03-29 11:31:08 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个与条件匹配的索引列表,其中列表中有许多按顺序相邻的跨距,如何轻松地只选择每个跨距中的第一个跨距

以至于

magicallySelect([1,2,3,10,11,12,100,101,102]) == [1,10,100]

但是——重要的是,这也应该适用于其他指标,比如日期(在我的数据中就是这样)。我希望得到的实际代码是:

original.reset_index(inplace=True)

predict = {}
for app in apps:
    reg = linear_model.LinearRegression()
    reg.fit(original.index.values.reshape(-1, 1), original[app].values)

    slope = reg.coef_.tolist()[0]
    delta = original[app].apply(lambda x: abs(slope - x))

    forecast['test_delta'] = forecast[app].apply(lambda x: abs(slope - x))
    tdm = forecast['test_delta'].mean()
    tds = forecast['test_delta'].std(ddof=0)

    # identify moments that are σ>2 abnormal
    forecast['z'] = forecast['test_delta'].apply(lambda x: abs(x - tdm / tds))
    sig = forecast.index[forecast[forecast['z'] > 2]].tolist()

    predict[app] = FIRST_INDEX_IN_EACH_SPAN_OF(sig)

Tags: lambdatestapp列表indexabsregpredict
1条回答
网友
1楼 · 发布于 2024-03-29 11:31:08
l = [1,2,3,10,11,12,100,101,102]
indices =  [l[i] for i in range(len(l)) if l[i-1]!=l[i]-1]

稍微对其重新排序以适用于datetimes,这将为您提供列表中与上一个项目的差距大于1天的所有项目(默认情况下加上第一个项目):

indices = [l[0]] + [l[i] for i in range(len(l)) if (l[i]-l[i-1]).days>1]

对于以分钟为单位的时间差,可以将其转换为秒,并将其替换为。例如,在15分钟(900秒)内,您可以:

indices = [l[0]] + [l[i] for i in range(len(l)) if (l[i]-l[i-1]).seconds>900]

相关问题 更多 >