【问题标题】:Numpy and Matplotlib - AttributeError: 'numpy.ndarray' object has no attribute 'replace'Numpy 和 Matplotlib - AttributeError: 'numpy.ndarray' 对象没有属性 'replace'
【发布时间】:2019-05-07 20:31:54
【问题描述】:

我正在尝试使用数据列的 log 值在 python 中生成带有 matplotlib 的图,但我一直遇到此错误,

回溯(最近一次通话最后一次):
文件“/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()

我非常感谢能帮助您解决这个问题。谢谢。

【问题讨论】:

  • pandas Series 有一个 replace 方法,但 numpy.ndarray 没有。即使y1 是一个系列(我不知道get_pdf),np.log2() 返回一个数组,而不是另一个系列。
  • 我可能会使用面具来完成您的目标y[y == -np.inf] = 0。另一种方法是在应用日志之前替换 -np.inf 位置(我假设 np.inf 值是您正在执行 log2(0) 的位置)

标签: python numpy matplotlib


【解决方案1】:

使用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,并带有whereout参数,可以用来绕过这个警告:

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

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 2020-11-29
    • 2020-10-06
    • 2018-01-25
    • 2016-06-29
    • 2020-03-25
    • 2013-12-07
    • 2017-10-16
    • 2020-02-23
    相关资源
    最近更新 更多