无法对字典中的值执行numpy操作 [英] not being able to do numpy operations on values on a dictionary

查看:120
本文介绍了无法对字典中的值执行numpy操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

total_minutes_by_account is a dictionary with values by account.

total_min显示用逗号分隔的值,但出现以下错误.

total_min shows the values seperated by comma but get the error below.

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'

推荐答案

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

In Py3, adict.values() returns a dict_values object, not a list. numpy functions expect numpy arrays or lists (of lists).

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'

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

在Py3中,rangedict.keys()需要相同的额外触摸.

In Py3, range and dict.keys() require the same extra touch.

========

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

np.mean first tries to convert the input to an array, but with values() that isn't what we want. It makes a single item object array containing this whole object.

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]])

这篇关于无法对字典中的值执行numpy操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆