python - Python使用行索引作为numpy数组中方程的变量输入
问题描述
如果不创建 for 循环,我无法弄清楚如何在 python 中使用。我希望你能教我更简单的方法。
我修剪了相关的东西。我正在做一个 polyfit,然后想使用这些 a 和 b 系数 coeff[0:1] 来更新数组并求解相关的 y,例如:y = ax + b
我可以暴力破解它并在这里包含两种方法,但它们都很笨重。
import numpy as np
raw = [0, 3, 6, 8, 11, 15]
coeff = np.polyfit(np.arange(0, len(raw)), raw[:], 1) #fits slope of values in raw
fit = np.zeros(shape=(len(raw), 2))
fit[:,0] = np.arange(0,fit.shape[0]) # this creates an index so I can use the row index as the "x" variable
fit[:,1] = fit[:,0]*coeff[0] + fit[:,0]*coeff[1] # calculating y = ax * b in column [1]
## Alternate method with the for loop
for_fit = np.zeros(len(raw))
for i in range(0,len(raw)) :
for_fit[i] = i*coeff[0] + i*coeff[1]
解决方案
我试着让它更干净一点。我看到的主要问题是您没有使用公式y = ax+b
,而是使用y=ax+bx
.
import numpy as np
raw = [0, 3, 6, 8, 11, 15]
x = np.arange(0, len(raw))
coeff = np.polyfit(x, raw[:], 1)
y = x*coeff[0] + coeff[1]
为了可视化结果,我们可以使用:
import matplotlib.pyplot as plt
plt.plot(x, raw, 'bo')
plt.plot(x, y, 'r')
#EDIT 你在寻找这样的东西吗?
y_arr = np.empty((10, len(x)))
for i in range(10):
...
y_arr[i] = y
推荐阅读
- python - 如何在 django 中为电子邮件渲染 png
- typescript - 使用 typeorm 更新实体
- python - discord.py 如何接受可选参数
- javascript - 试图传递属性/组合组件,以堆叠按钮的属性
- c# - 回发后重新绑定控件后,更新面板中的事件未触发
- python - 将 Django 项目部署到 Heroku 时如何解决服务器错误(500)?
- javascript - 如何在我的应用程序中使用数据库 sqlite?
- javascript - 我的函数正在返回一个 Promise,但我从未告诉该函数返回一个 Promise
- machine-learning - 97.55 % 的准确度是否表明模型过拟合?
- java - 如何在java中将二维数组转换为二维ArrayList?