4

我正在尝试从statsmodels. 我将在示例代码之后详细说明。

import scikits.statsmodels.api as sm
import pandas as pd
data = sm.datasets.longley.load()
df = pd.DataFrame(data.exog, columns=data.exog_name)
y = data.endog
df['intercept'] = 1.
olsresult = sm.OLS(y, df).fit()

此摘要输出包括变量名称。当您调用类似 olsresult.params 的内容时,它会返回以下内容:

In [21]: olsresult.params
Out[21]: 
GNPDEFL           15.061872
GNP               -0.035819
UNEMP             -2.020230
ARMED             -1.033227
POP               -0.051104
YEAR            1829.151465
intercept   -3482258.634596

现在我很好奇的是创建一个像字典一样的东西,变量名作为键,参数值作为值。所以,诸如此类的东西{'GNPDELF':15.0618, 'GNP':-0.035819}。如果不可能做到这一点,有没有其他方法可以单独访问变量名称和值?

4

2 回答 2

6

总是值得尝试显而易见的.. :^)

In [14]: olsresult.params
Out[14]: 
GNPDEFL           15.061872
GNP               -0.035819
UNEMP             -2.020230
ARMED             -1.033227
POP               -0.051104
YEAR            1829.151465
intercept   -3482258.634597

In [15]: dict(olsresult.params)
Out[15]: 
{'ARMED': -1.0332268671737328,
 'GNP': -0.035819179292614578,
 'GNPDEFL': 15.061872271452557,
 'POP': -0.051104105653539733,
 'UNEMP': -2.0202298038172479,
 'YEAR': 1829.151464613984,
 'intercept': -3482258.6345966831}

另见对象的.to_dict()方法。Series

于 2012-08-06T21:41:15.663 回答
5

olsresult.params is a pandas.Series object which is dict like, maybe you don`t need to convert to a dict.

In [12]: olsresult.params.get('GNP')
Out[12]: -0.035819179292566283

In [13]: olsresult.params['GNP']
Out[13]: -0.035819179292566283

In [14]: for key, value in olsresult.params.iteritems():
   ....:     print key, value
   ....:
GNPDEFL 15.0618722714
GNP -0.0358191792926
UNEMP -2.02022980382
ARMED -1.03322686717
POP -0.0511041056537
YEAR 1829.15146461
intercept -3482258.6346
于 2012-08-07T10:04:04.987 回答