我试图使用数据列的log值在python
中使用matplotlib
生成一个图,但我一直遇到这个错误,
Traceback(最后一次调用(:
中的文件"/home/PycharmProjects/proj1/test.py",第158行graph(file_path)
文件"/home/PycharmProjects/proj1/test.py",第90行,在图形中
y = np.array(np.log2(y1).replace(-np.inf, 0))
AttributeError:"numpy.ndarray"对象没有属性"replace">
下面给出的是代码,
def graph(file_path):
dataset1 = pandas.read_csv(file_path)
data1 = dataset1.iloc[:, 5]
x, y1 = get_pdf(data1)
y = np.array(np.log2(y1).replace(-np.inf, 0))
plt.figure()
plt.plot(x, y, color= 'g', label = 'Test')
plt.legend()
output_image = "fig1.png"
plt.savefig(output_image)
plt.close()
plt.figure()
如果能帮我解决这个问题,我将不胜感激。谢谢
对于log2
,0
会产生警告和-inf:
In [537]: x = np.arange(5.)
In [538]: np.log2(x)
/usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in log2
#!/usr/bin/python3
Out[538]: array([ -inf, 0. , 1. , 1.5849625, 2. ])
但log2
是一个ufunc,并采用where
和out
参数,可用于绕过此警告:
In [539]: out = np.zeros_like(x)
In [540]: np.log2(x, out=out, where=x>0)
Out[540]: array([0. , 0. , 1. , 1.5849625, 2. ])
In [541]: out
Out[541]: array([0. , 0. , 1. , 1.5849625, 2. ])