首页 > 解决方案 > Numpy 和 Matplotlib - AttributeError: 'numpy.ndarray' 对象没有属性 'replace'

问题描述

我正在尝试使用数据列的日志值生成一个图,但我一直遇到这个错误matplotlibpython

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

我真的很感激一些帮助来解决这个问题。谢谢。

标签: pythonnumpymatplotlib

解决方案


使用log2a0会产生警告和 -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.       ])

Butlog2是一个 ufunc,并带有一个whereandout参数,可以用来绕过这个警告:

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.       ])

推荐阅读