为什么 Statsmodels OLS 不支持阅读包含多个单词的列?
Why does Statsmodels OLS doesn't support reading in columns with multiple words?
我一直在尝试使用 Seaborn 的 lmplot() 和 Statsmodels .ols() 函数来绘制简单的线性回归图及其相关的 p 值、r 平方等。
我注意到,当我指定要用于 lmplot 的列时,我可以指定一个列,即使它有多个词:
import seaborn as sns
import pandas as pd
input_csv = pd.read_csv('./test.csv',index_col = 0,header = 0)
input_csv
sns.lmplot(x='Age',y='Count of Specific Strands',data = input_csv)
<seaborn.axisgrid.FacetGrid at 0x2800985b710>
但是,如果我尝试使用 ols,我在输入 "Count of Specific Strands" 作为我的因变量时遇到错误(我只列出了错误中的最后几行):
import statsmodels.formula.api as smf
test_results = smf.ols('Count of Specific Strands ~ Age',data = input_csv).fit()
File "<unknown>", line 1
Count of Specific Strands
^
SyntaxError: invalid syntax
相反,如果我指定 "Counts of Specific Strand",如下所示,回归有效:
test_results = smf.ols('input_csv.iloc[:,1] ~ Age',data = input_csv).fit()
test_results.summary()
有人知道这是为什么吗?仅仅是因为 Statsmodels 的编写方式吗?是否有替代方法指定不涉及 iloc 或 loc 的回归分析的因变量?
这是由于公式解析器 patsy
的编写方式所致:参见 this link for more information
patsy
的作者们却想到了这个问题:(引自here)
This flexibility does create problems in one case, though – because we
interpret whatever you write in-between the + signs as Python code,
you do in fact have to write valid Python code. And this can be tricky
if your variable names have funny characters in them, like whitespace
or punctuation. Fortunately, patsy has a builtin “transformation”
called Q() that lets you “quote” such variables
因此,在你的情况下,你应该能够写:
smf.ols('Q("Count of Specific Strands") ~ Age',data = input_csv).fit()
我一直在尝试使用 Seaborn 的 lmplot() 和 Statsmodels .ols() 函数来绘制简单的线性回归图及其相关的 p 值、r 平方等。
我注意到,当我指定要用于 lmplot 的列时,我可以指定一个列,即使它有多个词:
import seaborn as sns
import pandas as pd
input_csv = pd.read_csv('./test.csv',index_col = 0,header = 0)
input_csv
sns.lmplot(x='Age',y='Count of Specific Strands',data = input_csv)
<seaborn.axisgrid.FacetGrid at 0x2800985b710>
但是,如果我尝试使用 ols,我在输入 "Count of Specific Strands" 作为我的因变量时遇到错误(我只列出了错误中的最后几行):
import statsmodels.formula.api as smf
test_results = smf.ols('Count of Specific Strands ~ Age',data = input_csv).fit()
File "<unknown>", line 1
Count of Specific Strands
^
SyntaxError: invalid syntax
相反,如果我指定 "Counts of Specific Strand",如下所示,回归有效:
test_results = smf.ols('input_csv.iloc[:,1] ~ Age',data = input_csv).fit()
test_results.summary()
有人知道这是为什么吗?仅仅是因为 Statsmodels 的编写方式吗?是否有替代方法指定不涉及 iloc 或 loc 的回归分析的因变量?
这是由于公式解析器 patsy
的编写方式所致:参见 this link for more information
patsy
的作者们却想到了这个问题:(引自here)
This flexibility does create problems in one case, though – because we interpret whatever you write in-between the + signs as Python code, you do in fact have to write valid Python code. And this can be tricky if your variable names have funny characters in them, like whitespace or punctuation. Fortunately, patsy has a builtin “transformation” called Q() that lets you “quote” such variables
因此,在你的情况下,你应该能够写:
smf.ols('Q("Count of Specific Strands") ~ Age',data = input_csv).fit()