python - Numpy 和 Matplotlib - AttributeError: 'numpy.ndarray' 对象没有属性 'replace'
问题描述
我正在尝试使用数据列的日志值生成一个图,但我一直遇到这个错误matplotlib
,python
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
a0
会产生警告和 -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,并带有一个where
andout
参数,可以用来绕过这个警告:
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. ])
推荐阅读
- ios - 为什么 UIAccessibility.post(notification: .announcement, argument: "arg") 没有通过画外音宣布?
- php - 如何对依赖 if 语句进行单元测试?
- python - 有没有办法在 numba jitclass 中包含字符串属性?
- html - 我想在透明背景上制作不透明文本
- python - 基本 TensorFlow 问题(输入和输出数组)
- python - 如何使用名为repeat的列制作sql表?需要 Django 应用程序
- python - 在 Python 3.5 中读取在 Python 2.7 中生成的文件
- google-apps - 使用 Admin SDK + SERVICE ACCOUNT 的 GSuite 市场列表
- javascript - 根据列值发送电子邮件 = 是
- javascript - 为什么 initialState 不显示未定义的字段但在 redux 中保留空字段?