【问题标题】:TypeError: only size-1 arrays can be converted to Python scalars NumpyTypeError:只有大小为 1 的数组可以转换为 Python 标量 Numpy
【发布时间】:2021-06-24 06:18:33
【问题描述】:

我有这个代码:

import matplotlib.pyplot as plt
import numpy as np
import math

x = np.linspace(-3,3,100)
y = math.sin(x**2) + 1.1 - ((math.e)**-x)

plt.plot(x,y,label='y = x**2')

plt.title('sin(x^2) + 1.1 - e^-x')

plt.xlabel('x axis')
plt.ylabel('y axis')

plt.grid(alpha=.4,linestyle='--')

plt.show()

我得到这个错误:

TypeError: only size-1 arrays can be converted to Python scalars

谁能帮我找出问题所在?

【问题讨论】:

  • math.sin() 不知道如何处理 numpy 数组。使用np.sin(x**2) 而不是math
  • math.sin() 需要一个值,而您正在传递一个矩阵。你可能想使用 np.sin()

标签: python numpy


【解决方案1】:

我认为问题在于您正在尝试将 Python 操作(特别是 math.sin)应用于数组,即 np.ndarray 类型的 NumPy 数组。 NumPy 实际上有一个解决方法,方法是实现应用相同基本操作的函数element-wise,即您需要替换该行:

y = math.sin(x**2) + 1.1 - ((math.e)**-x)

以下内容:

y = np.sin(x**2) + 1.1 - (np.exp(-x))

这解决了您面临的问题。

一般来说,在使用numpy 时,您需要执行这些类型的替换。但是,需要注意的是,numpy 可以将broadcasting 规则(即了解如何以元素方式将标量操作应用于np.ndarray 对象)应用于以下操作:

  • +(加法)
  • -(减法)
  • *(乘法)
  • /(师)
  • //(整数除法)
  • **(取幂)

【讨论】:

  • x**2 很好。
  • 感谢您的评论,我会更新这个答案!
猜你喜欢
  • 2021-10-17
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
  • 2015-02-16
  • 1970-01-01
  • 2019-06-19
  • 2020-08-09
相关资源
最近更新 更多