eum*_*iro 9 python datetime time-series weighted-average scikits
我有两个不同的时间序列,部分重叠的时间戳:
import scikits.timeseries as ts
from datetime import datetime
a = ts.time_series([1,2,3], dates=[datetime(2010,10,20), datetime(2010,10,21), datetime(2010,10,23)], freq='D')
b = ts.time_series([4,5,6], dates=[datetime(2010,10,20), datetime(2010,10,22), datetime(2010,10,23)], freq='D')
Run Code Online (Sandbox Code Playgroud)
代表以下数据:
Day: 20. 21. 22. 23.
a: 1 2 - 3
b: 4 - 5 6
Run Code Online (Sandbox Code Playgroud)
我想用系数a(0.3)和b(0.7)计算每天的加权平均值,同时忽略缺失值:
Day 20.: (0.3 * 1 + 0.7 * 4) / (0.3 + 0.7) = 3.1 / 1. = 3.1
Day 21.: (0.3 * 2 ) / (0.3 ) = 0.6 / 0.3 = 2
Day 22.: ( 0.7 * 5) / ( 0.7) = 3.5 / 0.7 = 5
Day 23.: (0.3 * 3 + 0.7 * 6) / (0.3 + 0.7) = 3.1 / 1. = 5.1
Run Code Online (Sandbox Code Playgroud)
当我第一次尝试对齐这些时间序列时:
a1, b1 = ts.aligned(a, b)
Run Code Online (Sandbox Code Playgroud)
我得到了正确的蒙面时间序列:
timeseries([1 2 -- 3],
dates = [20-Oct-2010 ... 23-Oct-2010],
freq = D)
timeseries([4 -- 5 6],
dates = [20-Oct-2010 ... 23-Oct-2010],
freq = D)
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时a1 * 0.3 + b1 * 0.7,它会忽略只存在于一个时间序列中的值:
timeseries([3.1 -- -- 5.1],
dates = [20-Oct-2010 ... 23-Oct-2010],
freq = D)
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能收到期待的?
timeseries([3.1 2. 5. 5.1],
dates = [20-Oct-2010 ... 23-Oct-2010],
freq = D)
Run Code Online (Sandbox Code Playgroud)
编辑:答案也应适用于两个以上具有不同权重和不同缺失值的初始时间序列.
因此,如果我们有四个时间序列,其权重为T1(0.1),T2(0.2),T3(0.3)和T4(0.4),则它们在给定时间戳下的权重将为:
| T1 | T2 | T3 | T4 |
weight | 0.1 | 0.2 | 0.3 | 0.4 |
-------------------------------------
all present | 10% | 20% | 30% | 40% |
T1 missing | | 22% | 33% | 45% |
T1,T2 miss. | | | 43% | 57% |
T4 missing | 17% | 33% | 50% | |
etc.
Run Code Online (Sandbox Code Playgroud)
我尝试过并发现了这个:
aWgt = 0.3
bWgt = 0.7
print (np.where(a1.mask, 0., a1.data * aWgt) +
np.where(b1.mask, 0., b1.data * bWgt)) / (np.where(a1.mask, 0., aWgt) +
np.where(b1.mask, 0., bWgt))
# array([ 3.1, 2. , 5. , 5.1])
Run Code Online (Sandbox Code Playgroud)
这适用于具有多个初始时间序列的已编辑问题。但希望有人能找到更好的。
编辑:这是我的职能:
def weightedAvg(weightedTimeseries):
sumA = np.sum((np.where(ts.mask, 0., ts.data * weight) for ts, weight in weightedTimeseries), axis=0)
sumB = np.sum((np.where(ts.mask, 0., weight) for ts, weight in weightedTimeseries), axis=0)
return np.divide(sumA, sumB)
weightedAvg(((a1, 0.3), (bb, 0.7)))
# array([ 3.1, 2. , 5. , 5.1])
Run Code Online (Sandbox Code Playgroud)
适用于任意数量的时间序列;-)
| 归档时间: |
|
| 查看次数: |
1465 次 |
| 最近记录: |