大Pandas卵母细胞的高效扩增

2024-03-28 10:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想探索在pandas(或其他接受数据帧/系列友好的库)中高效执行扩展OLS的解决方案。你知道吗

  1. 假设数据集很大,我对任何带有for循环的解决方案都不感兴趣
  2. 我正在寻找扩张而不是滚动的解决方案。滚动函数总是需要一个固定的窗口,而扩展使用一个可变窗口(从开始)
  3. 请不要建议pandas.stats.ols.MovingOLS,因为它已被否决
  4. 请不要推荐其他不推荐使用的方法,如expanding_mean。你知道吗

例如,有一个数据帧df,有两列Xy。为了更简单,我们来计算beta。 现在,我在想

import numpy as np
import pandas as pd
import statsmodel.api as sm

def my_OLS_func(df, y_name, X_name):
  y = df[y_name]
  X = df[X_name]
  X = sm.add_constatn(X)
  b = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(y)
  return b

df = pd.DataFrame({'X':[1,2.5,3], 'y':[4,5,6.3]})

df['beta'] = df.expanding().apply(my_OLS_func, args = ('y', 'X'))

df['beta']的期望值为0(或NaN)、0.666666671.038462。你知道吗

但是,这种方法似乎不起作用,因为这种方法似乎非常不灵活。我不知道怎样才能把这两个级数作为参数来传递。 如有任何建议,将不胜感激。你知道吗


Tags: 数据方法nameimportpandasdfasnp
1条回答
网友
1楼 · 发布于 2024-03-28 10:36:59

一种方法是使用Statsmodels中的RecursiveLS(递归最小二乘)模型:

# Simulate some data
rs = np.random.RandomState(seed=12345)

nobs = 100000
beta = [10., -0.2]
sigma2 = 2.5

exog = sm.add_constant(rs.uniform(size=nobs))
eps = rs.normal(scale=sigma2**0.5, size=nobs)
endog = np.dot(exog, beta) + eps

# Construct and fit the recursive least squares model
mod = sm.RecursiveLS(endog, exog)
res = mod.fit()
# This is a 2 x 100,000 numpy array with the regression coefficients
# that would be estimated when using data from the beginning of the
# sample to each point. You should usually ignore the first k=2
# datapoints since they are controlled by a diffuse prior.
res.recursive_coefficients.filtered

相关问题 更多 >