2017-05-13 68 views
-1

我有以下列表:移動窗口和積計算的Python

a= [1,2,3,4,5,6,7,8,9,10,11,12] 
wts= [0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.10,0.10,0.30] 

期望的結果是

result = [8.2,7.76,7.848,7.9504,8.179253333,8.420282667,8.628383467,8.790601973,8.894139057,8.930025594,8.891166196,8.770706404] 

結果列表「a」和列表「WTS的移動窗口和積」。

例如結果8.2由代碼

sum(map(lambda xi, yi: xi * yi,x,wt)) 

結果由通過追加8.2到列表「A」而獲得的一個新的窗口得到的獲得。

新列表a應該是從上面的結果中追加結果的地方。

a = [1,2,3,4,5,6,7,8,9,10,11,12,8.2] 

現在計算的結果列表即結果的下一個值[1] = 7.76,它應該是

a = [2,3,4,5,6,7,8,9,10,11,12,8.2] and 
wts = [0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.10,0.10,0.30] 

的SUMPRODUCT的'WTS名單是固定的,只列表「一」將會移動窗口,新的結果會被附加到a.Anython的任何腳本來實現這一點將會很有幫助。

基於下面,我將下面的函數應用於數據框。您能否介紹一下我如何將這個函數應用到基於多個組的數據框上(基於Groupby)。

def wma(Curr,wts): 
    Curr.values.tolist() 
    wts.values.tolist() 
    len_list = len(Curr) 
    # Create a fixed sized queue 
    q = deque(maxlen=len_list) 
    # Add list a to q 
    q.extend(Curr) 
    i = 0 
    result = [] 
    while i < len(a): 
     val = sum([x*y for x, y in zip(q, wts)]) 
     q.append(val) 
     result.append(float(round(val, 2))) 
     i += 1 
    return result 

例如,我有一個數據框有5列,即(列A,列B,列C,權重,當前)。類型錯誤:unhashable類型:「名單」我用下面的代碼

s1 = s1.groupby(['Column A', 'Column B', 'Column C']).apply(wma(df['Current'],df['Weights'])) 

我收到以下錯誤應用上述功能。任何幫助都會有很大的幫助。

回答

1

在這種情況下,你需要使用fixed-sized queue,如下圖所示:

嘗試:

from collections import deque 

a= [1,2,3,4,5,6,7,8,9,10,11,12] 
wts= [0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.055555556,0.10,0.10,0.30] 
len_a = len(a) 

# Create a fixed sized queue 
q = deque(maxlen=len_a) 

# Add list a to q 
q.extend(a) 

# See the q 
print('q: ', q) 

i = 0 
result = [] 

while i < len(a): 
    val = sum([x*y for x, y in zip(q, wts)]) 
    q.append(val) 
    result.append(float(round(val, 2))) 
    i += 1 

print('result: ', result) 

# Output 
q: deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], maxlen=12) 
result: [8.2, 7.76, 7.85, 7.95, 8.18, 8.42, 8.63, 8.79, 8.89, 8.93, 8.89, 8.77] 
+0

感謝這個答覆。這個Deque是我今天學到的一個新概念。 – ceeka9388

+0

@ ceeka9388,它也可以使用'list'來完成,它只需要從'0'位置'流行'和'追加''val',但是使用'queue'要快得多。 – JkShaw

+0

我需要一些幫助,將其應用於數據框作爲函數。任何建議在這裏都會有很大的幫助。 – ceeka9388