计算列表的平均值

时间:2018-08-24 13:23:34

标签: python numpy dictionary

我想计算向量列表的均值。但是收到错误消息

ValueError                                Traceback (most recent call last)
<ipython-input-1293-04753fc36464> in <module>()
     13         else:
     14             NOT_FOUNT.append(j)
---> 15     Q_VEC.append(np.mean(DOC, axis=0))
     16     QUERY.append(WORD)
     17     #print(WORD, Q_VEC)

ValueError: setting an array element with a sequence.

我的代码:

Q_VEC=[]
QUERY=[]
NOT_FOUNT=[]
for i in W_LIST:
    DOC=[]
    WORD=[]
    for j in i:
        if j in list(D_FINAL.keys()):
            DOC.append(D_FINAL[j])   #D_FINAL[j] is an array
            WORD.append(j)
        else:
            NOT_FOUNT.append(j)
    Q_VEC.append(np.mean(DOC, axis=0))
    QUERY.append(WORD)

数据:

 W_LIST

 [['professional', 'training', None, None, 
None, None, None, None, None, None],
['undergraduate', 'management', None, None, 
None, None, None, None, None, None],
['professional', 'management', None, None, 
None, None, None, None, None, None]]

D_FINAL

{'professional': array([ -1.5453218 ,  
-2.9101162 ,  -1.7782371 ,  -0.7723548]),
'undergraduate': array([-5.044174  , 
-5.768703  ,  0.23328705,  1.6166878]),
'management': array([  0.9067916 ,  
-0.37680042,   2.2666857 ,  -1.3643779]),
'training': array([ -4343.5654  ,    
166.61334 ,  -4708.429   ,  11363.863])}

我想根据D_FINAL中的向量值计算W_LIST的平均值。

“专业培训”(将保存为“ QUERY”),矢量值为

[(-1.5453218)+(-4343.5654)/2,  (-2.9101162)+ 
(166.61334 )/2, (-1.7782371)+(-4708.429)/2, 
(-0.7723548)+(11363.863)/2]

平均向量将保存到'Q_VEC'

谢谢!

1 个答案:

答案 0 :(得分:0)

我发现字典中的元素长度不同,修复后,问题解决了。