首页 > 解决方案 > 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]

标签: pythonarraysnumpy

解决方案


我试着让它更干净一点。我看到的主要问题是您没有使用公式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

推荐阅读