python中urframe函数的用法_python - 使用pandas dataframe和numpy进行多项式拟合 - 堆栈内存溢出...

我有一个脚本,其中有一个数据框,看起来像这样:

eb78191df4bb81220f18f8d9572eede1.png

并将某些列转换为numpy数组进行处理。 然后,我使用编写的一个小函数,该函数使用statsmodels.api基于传递给函数的两个数组来计算线性回归。 然后,该函数返回统计信息和线性拟合方程:

def computeLinearStats(x, y, yName, calc_tau = False):

'''

Takes as an argument two numpy arrays, one for x and one y, and a string for the

name of the y-variable, and a boolean for whether to calculate tau.

Uses Ordinary Least Squares to compute the statistical parameters for the

array against log(z), and determines the equation for the line of best fit.

Returns the results summary, residuals, statistical parameters in a list,

the best fit equation, and Kendall's tau.

'''

# Mask NaN values in both axes

mask = ~np.isnan(y) & ~np.isnan(x)

# Compute model parameters

model = sm.OLS(y[mask], sm.add_constant(x[mask]), missing= 'drop')

results = model.fit()

residuals = results.resid

if calc_tau:

tau = stats.kendalltau(x, y, nan_policy= 'omit')

else:

tau = [1, 1] # Use this to exclude computation of tau

#

# Compute fit parameters

params = stats.linregress(x[mask], y[mask])

fit = params[0]*x + params[1]

fitEquation = '$(%s)=(%.4g \pm %.4g) \\times log_{10}(redshift)+%.4g$'%(yName,

params[0], # slope

params[4], # stderr in slope

params[1]) # y-intercept

return results, residuals, params, fit, fitEquation, tau

例如,假设我正在从数据帧中寻找loz(z)和“ BI”之间的线性拟合。 计算完这些变量后,我会打电话给

results, residuals, params, fit, equation, tau = qf.computeLinearStats(log_z, (B-I), 'B-I', calc_tau = False)

得到线性拟合。

一切正常,但现在我需要拟合多项式而不是线性拟合。

我试过了

sources['log_z'] = np.log10(sources.z)

mask = ~np.isnan((B-I)) & ~np.isnan(log_z)

model = ols(formula='(B-I) ~ log_z', data = [log_z[mask], (B-I)

[mask]]).fit()

model = ols(formula='(B-I) + np.power((U-R),2) ~ log_z', data = [log_z[mask], (B-I)[mask]]).fit()

但是我明白了

PatsyError: Error evaluating factor: TypeError: list indices must be integers or slices, not str

(B-I) ~ log_z

^^^^^

即使x和y都是数组,也不是字符串。

在这种情况下找到多项式拟合的最简单方法是什么-比对log(z)像(BI) + (UR)**2类的东西? 此站点上的幻灯片41及更高版本似乎只是一个起点,但是我对如何应用它感到困惑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值