簡體   English   中英

Python function 時間序列數據模板

[英]Python function template for time-series data

我想處理一些數組/列表/時間序列數據,並希望為此使用許多不同的過濾器。

這導致了兩個問題:我不想每次都復制粘貼 function,尤其是在我更改某些內容時。 同樣具有不同的依賴關系(可能存在對前一個或第 n 個前一個元素或第 n 個后續元素的依賴),如果我不調整范圍,循環的數組可能 go 超出范圍。

過濾器的條件可以任意復雜,但總是涉及數據中的相對 position。

這是一個最小的例子:

import random as r
data = [r.random() for _ in range(100)]

def example_filter(data):
    counter = 0
    for i in range(1, len(data)):
        if((data[i-1]>0.8) and (data[i]<0.5)):
            counter +=1
            #might want to change something here
            #right now I would need to do this in all filters separately
    return counter

def example_filter_2(data):
    counter = 0
    for i in range(2, len(data)):
        if((data[i-2]>0.8) or ((data[i-1]>0.9) and (data[i]<0.2))):
            counter +=1
    return counter

我的想法是以某種方式壓縮條件(在實際示例中它們更復雜),使用轉換器 function 從它們中生成真實條件,將其作為字符串傳遞給模板 function,然后使用條件,就像這樣:

def filter_template(condition):
    def instance_of_filter(data):
        counter = 0
        #problem: the range isn't adjusted to account for out of bounds here
        for i in range(len(data)):
            #problem: condition will be passed as a string, so how can I evaluate it
            #also, I can't evaluate condition before I know what 'data' is, so I need to keep the dependency
            if condition:
                counter += 1
        return counter
    return instance_of_filter

有任何想法嗎?

您可以使用您最后的代碼思想,只需根據數據和索引將條件從變量更改為謂詞 function。

例子:


def filter_template(condition_func, start_at=0):
    def instance_of_filter(data):
        counter = 0
        for i in range(start_at, len(data)):
            if condition_func(data, i):
                counter += 1
        return counter
    return instance_of_filter


def condition1(data, i):
    return (data[i-1]>0.8) and (data[i]<0.5)

def condition2(data, i):
    return ((data[i-2]>0.8) or ((data[i-1]>0.9) and (data[i]<0.2)))

# usage
filter_template(condition1, 1)
filter_template(condition2, 2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM