我有以下列表:
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应该是附加上述结果的结果。
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]
'wts'列表是固定的,只有列表'a'将是移动窗口,新结果被附加到a.Any python脚本以实现这一点在这将有很大的帮助。
基于Below,我将以下函数应用于数据帧。请问关于如何将此函数应用于基于多个组的数据帧(基于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列,权重,当前)。我使用以下代码
应用上述功能s1 = s1.groupby(['Column A', 'Column B', 'Column C']).apply(wma(df['Current'],df['Weights']))
我收到以下错误:TypeError:unhashable type:'list'。任何帮助都会有很大的帮助。
答案 0 :(得分: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]