[英]Python function template for time-series data
I want to process some array/list/timeseries data, and want to use many different filters for this.我想处理一些数组/列表/时间序列数据,并希望为此使用许多不同的过滤器。
This led to two problems: I don't want to copy-paste the function every time, especially if I change something.这导致了两个问题:我不想每次都复制粘贴 function,尤其是在我更改某些内容时。 Also with different dependencies (there might be a dependency on the previous, or n-th previous element, or n-th following element), the array that is looped over can go out of bounds, if I don't adjust the ranges.同样具有不同的依赖关系(可能存在对前一个或第 n 个前一个元素或第 n 个后续元素的依赖),如果我不调整范围,循环的数组可能 go 超出范围。
The conditions for the filters could be arbitrarily complex, but always involve relative position in the data.过滤器的条件可以任意复杂,但总是涉及数据中的相对 position。
Here is a minimal example:这是一个最小的例子:
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
My idea was to somehow compress the conditions (they are more complicated in the real example), use a converter function to make the real condition out of them, pass it as a string to a template function, and then use the condition, like this:我的想法是以某种方式压缩条件(在实际示例中它们更复杂),使用转换器 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
Any ideas?有任何想法吗?
You can use your last code idea, just change the condition from variable to a predicate function based on data and index.您可以使用您最后的代码思想,只需根据数据和索引将条件从变量更改为谓词 function。
Example:例子:
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.