错误:无法使用灵活类型进行归约

0 投票
1 回答
2958 浏览
提问于 2025-04-28 05:14

我正在尝试绘制一个直方图,但总是遇到这个错误;

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

每次我运行这段代码时都会出现那个错误。我哪里出错了?非常感谢任何帮助。

暂无标签

1 个回答

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的genfromtxt或者csv模块)。

但至少,你可能需要把读取到的数据当作数字来处理,因为readline返回的是字符串。例如:

for line in f.read():
    fields = line.strip().split()
    nums = [int(field) for field in fields]

现在nums会给你这一行的整数列表。

撰写回答