我想使用statsmodelsOLS 类来创建多元回归模型。考虑以下数据集:
import statsmodels.api as sm
import pandas as pd
import numpy as np
dict = {'industry': ['mining', 'transportation', 'hospitality', 'finance', 'entertainment'],
'debt_ratio':np.random.randn(5), 'cash_flow':np.random.randn(5) + 90}
df = pd.DataFrame.from_dict(dict)
x = data[['debt_ratio', 'industry']]
y = data['cash_flow']
def reg_sm(x, y):
x = np.array(x).T
x = sm.add_constant(x)
results = sm.OLS(endog = y, exog = x).fit()
return results
Run Code Online (Sandbox Code Playgroud)
当我运行以下代码时:
reg_sm(x, y)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
TypeError: '>=' not supported between instances of 'float' and 'str'
Run Code Online (Sandbox Code Playgroud)
我已经尝试将industry变量转换为分类变量,但仍然出现错误。我别无选择。
我使用最佳子集选择包来确定构建模型的最佳自变量(我确实有这样做的特定原因,而不是直接使用最佳子集对象)。我想以编程方式提取特征名称并使用生成的字符串来构建我的模型公式。结果会是这样的:
x <- "x1 + x2 + x3"
y <- "Surv(time, event)"
Run Code Online (Sandbox Code Playgroud)
因为我正在构建coxph模型,所以公式如下:
coxph(Surv(time, event) ~ x1 + x2 + x3)
Run Code Online (Sandbox Code Playgroud)
使用这些字符串字段,我尝试构建如下公式:
form <- y ~ x
Run Code Online (Sandbox Code Playgroud)
这创建了一个类对象formula,但是当我调用它时,coxph它不会根据从公式对象创建的引用进行评估。我收到以下错误:
Error in model.frame.default(formula = y ~ x) : object is not a matrix
Run Code Online (Sandbox Code Playgroud)
如果我eval在调用中调用对象 y 和 x coxph,我会得到以下结果:
Error in model.frame.default(formula = eval(y) ~ eval(x), data = df) :
Run Code Online (Sandbox Code Playgroud)
变量长度不同(针对“eval(x)”找到)
我不太确定如何继续。感谢您的输入。
我有以下数据帧
x y count
1 1 2018-02-24 4.031540
2 2 2018-02-25 5.244303
3 3 2018-02-26 5.441465
4 NA 2018-02-27 4.164104
5 5 2018-02-28 5.172919
6 6 2018-03-01 5.591410
7 7 2018-03-02 4.691716
8 8 2018-03-03 5.465360
9 9 2018-03-04 3.269378
10 NA 2018-03-05 5.300679
11 11 2018-03-06 5.489664
12 12 2018-03-07 4.423334
13 13 2018-03-08 3.808764
14 14 2018-03-09 6.450136
15 15 2018-03-10 5.541785
16 16 2018-03-11 4.762889
17 17 2018-03-12 5.511649
18 18 2018-03-13 6.795386
19 19 2018-03-14 6.615762 …Run Code Online (Sandbox Code Playgroud) 我有一个向量,我想采用向量的增量平均值.
a <- 2 4 6 2 4 0 1 0 0 1
Run Code Online (Sandbox Code Playgroud)
这有效:
for(i in seq_along(a)) {
print(mean(a[1:seq_along(a)[[i]]]))
}
[1] 2
[1] 3
[1] 4
[1] 3.5
[1] 3.6
[1] 3
[1] 2.714286
[1] 2.375
[1] 2.111111
[1] 2
Run Code Online (Sandbox Code Playgroud)
但现在我想把它扩展到一个向量列表,我被卡住了.
b <- list(x = rnorm(10, mean = 5), x2 = rnorm(10, mean = 20))
b
$x
[1] 4.893252 5.129610 4.599701 5.409024 4.666844 5.787243 5.697621 2.968771 5.216302 6.268629
$x2
[1] 19.50947 22.14797 20.80683 19.47857 21.24126 18.36233 20.57424 19.68233 20.67508 19.83930 …Run Code Online (Sandbox Code Playgroud)