plot绘制各种曲线的程序,在python27下运行正常,到python35下 提示出现这个错误:
TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'
-
In python3,
dict.values
returns adict_values
object, which is not alist
ortuple
. Try coercing that into a list.total_minutes = list(total_minutes_by_account.values())
. – Abdou Apr 27 '17 at 16:40 -
It's a good idea to check the results of a
np.array(...)
statement. During testing look attotal_minutes
, or at least check itsshape
anddtype
. Don't just assume, check. In this case thedtype
is probablyobject
, not floats or ints. – hpaulj Apr 27 '17 at 17:29 -
Find below a summary of his answer. It helped me a lot.
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'
Solution: convert the dict_values to list:
In [1623]: list(dd.values()) Out[1623]: [[1, 2, 3], [4, 5, 6]] In [1624]: np.mean(list(dd.values())) Out[1624]: 3.5
In Py3, range and dict.keys() require the same extra touch.
========
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]])
25行修改后 28行也要加list函数 ,否则提示如下错误(下面代码黑色两行,原来python2中无list函数)
-
numpy.core._internal.AxisError: axis -1 is out of bounds for array of dimension 0
-
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pltimport collections
import time
import pickle as pickle_since_beginning = collections.defaultdict(lambda: {})
_since_last_flush = collections.defaultdict(lambda: {})_iter = [0]
def tick():
_iter[0] += 1def plot(name, value):
_since_last_flush[name][_iter[0]] = valuedef flush():
prints = []for name, vals in _since_last_flush.items():
prints.append("{}\t{}".format(name, np.mean(list(vals.values()))))
_since_beginning[name].update(vals)
x_vals = np.sort(list(_since_beginning[name].keys()))
y_vals = [_since_beginning[name][x] for x in x_vals]plt.clf()
plt.plot(x_vals, y_vals)
plt.xlabel('iteration')
plt.ylabel(name)
plt.savefig(name.replace(' ', '_')+'.jpg')print ("iter {}\t{}".format(_iter[0], "\t".join(prints)))
_since_last_flush.clear()with open('log.pkl', 'wb') as f:
pickle.dump(dict(_since_beginning), f, pickle.HIGHEST_PROTOCOL)