无法对字典上的值进行numpy操作

new*_*hon 3 numpy python-3.x

total_minutes_by_account 是一个按帐户显示值的字典.

total_min 显示以逗号分隔的值,但会得到以下错误.

total_min=total_minutes_by_account.values()
import numpy as np
np.mean(total_min)

File "<ipython-input-17-7834a3d1e5e6>", line 1, in <module>
    np.mean(total_min)

  File "/Users/newtopython/anaconda/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 2942, in mean
    out=out, **kwargs)

  File "/Users/newtopython/anaconda/lib/python3.5/site-packages/numpy/core/_methods.py", line 72, in _mean
    ret = ret / rcount

TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'
Run Code Online (Sandbox Code Playgroud)

hpa*_*ulj 5

在Py3中,adict.values()返回一个dict_values对象,而不是一个列表. numpy函数期望numpy数组或列表(列表).

In [1618]: dd = {'a':[1,2,3], 'b':[4,5,6]}
In [1619]: dd
Out[1619]: {'a': [1, 2, 3], 'b': [4, 5, 6]}
In [1620]: dd.values()
Out[1620]: dict_values([[1, 2, 3], [4, 5, 6]])
In [1621]: np.mean(dd.values())
... 
TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'
Run Code Online (Sandbox Code Playgroud)

转换dict_values为列表:

In [1623]: list(dd.values())
Out[1623]: [[1, 2, 3], [4, 5, 6]]
In [1624]: np.mean(list(dd.values()))
Out[1624]: 3.5
Run Code Online (Sandbox Code Playgroud)

在PY3,range并且dict.keys()需要相同的额外的接触.

========

np.mean首先尝试将输入转换为数组,但这values()并不是我们想要的.它生成一个包含整个对象的单个项目对象数组.

In [1626]: np.array(dd.values())
Out[1626]: array(dict_values([[1, 2, 3], [4, 5, 6]]), dtype=object)
In [1627]: _.shape
Out[1627]: ()
In [1628]: np.array(list(dd.values()))
Out[1628]: 
array([[1, 2, 3],
       [4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)