0
votes

I'm trying to generate a plot with matplotlib in python using the log values of a data column but I keep running into this error,

Traceback (most recent call last):
File "/home/PycharmProjects/proj1/test.py", line 158, in

graph(file_path)   

File "/home/PycharmProjects/proj1/test.py", line 90, in graph

y = np.array(np.log2(y1).replace(-np.inf, 0)) 

AttributeError: 'numpy.ndarray' object has no attribute 'replace'

Given below is the code,

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

I would really appreciate some help to solve this. Thanks.

1
A pandas Series has a replace method, but a numpy.ndarray does not. Even if y1 is a series (I don't know get_pdf), np.log2() returns an array, not another Series. - hpaulj
I would probably use a mask to do what you're aiming for y[y == -np.inf] = 0. The other way would be to replace the -np.inf position before the application of the log (I presume that the np.inf values are where you're doing log2(0)) - Andrew

1 Answers

0
votes

With log2 a 0 produces a warning and -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.       ])

But log2 is a ufunc, and takes a where and out parameter, which can be used to bypass this warning:

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