我正在尝试绘制直方图,但我一直收到这个错误;
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
plt.hist(a)
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2827, in hist
stacked=stacked, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 8312, in hist
xmin = min(xmin, xi.min())
File "/usr/lib/python2.7/dist-packages/numpy/core/_methods.py", line 21, in _amin
out=out, keepdims=keepdims)
TypeError: cannot perform reduce with flexible type
我对python很新,我想做的就是这个;
import numpy, matplotlib.pyplot
line = " "
a = []
b = []
c = []
alpha = []
beta = []
gama = []
while x.readline():
line = x.readline()
a.append(line[16:23])
b.append(line[25:32])
c.append(line[27:34])
alpha.append(line[40:47])
beta.append(line[49:54])
gama.append(line[56:63])
pyplot.hist(a)'
当我运行这段代码时,我遇到了这个错误。我哪里做错了?我真的很感激帮助
答案 0 :(得分:1)
看起来你试图根据字符串而不是数字来绘制直方图。尝试这样的事情:
from matplotlib import pyplot
import random
# generate a series of numbers
a = [random.randint(1, 10) for _ in xrange(100)]
# generate a series of strings that look like numbers
b = [str(n) for n in a]
# try to create histograms of the data
pyplot.hist(a) # it produces a histogram (approximately flat, as expected)
pyplot.hist(b) # produces the error as you reported.
通常,最好使用预先编写的库来读取外部文件中的数据(例如,请参阅numpy's genfromtxt
或csv
module)。
但至少,您可能需要将读入的数据视为数字,因为readline返回字符串。例如:
for line in f.read():
fields = line.strip().split()
nums = [int(field) for field in fields]
现在nums
为您提供该行的整数列表。