如何将 hist 用于列表并解决错误:"输入类型不支持 ufunc 'isnan'



我使用以下代码生成一个列表,并希望为其绘制分布。

a = [random.randint(0, 1<<256) for i in range(500000)]
plt.hist(a, bins=400)
plt.show() 

但是,我遇到了如下所示的一些问题:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

我尝试使用以下代码将类型更改为numpy.ndarray,但它不起作用。

x=np.array(a)
plt.hist(x, bins=400)
plt.show()

但我遇到了同样的错误提示。 以下代码适用于numpy.ndarray

import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
print(type(x))
# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75)

plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$mu=100, sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.grid(True)
plt.show()

但我想弄清楚为什么我的不起作用。

plt.hist(a, bin=400)

不是正确的输入。你应该使用的是plt.hist(a, bins=400).此外,1<<256似乎是一个很大的数字,这对我来说似乎不对。

似乎问题是由于太大的"int"对象而 hist 无法处理它。当转移到浮子上时,它实际上可以工作。

num = 1<<256
a = [random.randint(0, num) for i in range(5000)]
b = [np.float(i) for i in a]
plt.hist(b, bins=400)
plt.show()

相关内容

最新更新