python - 在 Python 中的数据框中对所有可能的列组合应用函数——更好的方法

标签 python pandas dataframe

我想做的是使用 statsmodels.api 对 Dataframe 的所有可能的成对列组合应用线性回归。

我能够为以下代码做到这一点:

对于数据框 df :

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

#generate example Dataframe
df = pd.DataFrame(abs(np.random.randn(50, 4)*10), columns=list('ABCD'))

#extract all possible combinations of columns by column index number
i, j = np.tril_indices(df.shape[1], -1)

#generate a for loop that creates the variable an run the regression on each pairwise combination
for idx,item in enumerate(list(zip(i, j))):
    exec("model" + str(idx) +" = sm.OLS(df.iloc[:,"+str(item[0])+"],df.iloc[:,"+str(item[1])+"])")
    exec("regre_result" + str(idx) +" = model" + str(idx)+".fit()")

regre_result0.summary()

OLS Regression Results
Dep. Variable:  B   R-squared:  0.418
Model:  OLS Adj. R-squared: 0.406
Method: Least Squares   F-statistic:    35.17
Date:   Tue, 09 Jan 2018    Prob (F-statistic): 3.00e-07
Time:   14:16:25    Log-Likelihood: -174.29
No. Observations:   50  AIC:    350.6
Df Residuals:   49  BIC:    352.5
Df Model:   1       
Covariance Type:    nonrobust       
coef    std err t   P>|t|   [0.025  0.975]
A   0.7189  0.121   5.930   0.000   0.475   0.962
Omnibus:    14.290  Durbin-Watson:  1.828
Prob(Omnibus):  0.001   Jarque-Bera (JB):   16.289
Skew:   1.101   Prob(JB):   0.000290
Kurtosis:   4.722   Cond. No.   1.00

它有效,但我想有一种更简单的方法可以实现类似的结果,有人可以指出实现它的最佳方法吗?

最佳答案

为什么你要用 exec 和大量变量这样做,而不是仅仅附加到列表中?

您还可以使用 itertools.combinations 获取所有列对。

尝试这样的事情:

In [1]: import itertools
In [2]: import pandas as pd
In [3]: daf = pd.DataFrame(columns=list('ABCD'))
In [4]: list(itertools.combinations(daf.columns, 2))
Out[4]: [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
In [6]: col_pairs = list(itertools.combinations(daf.columns, 2))
In [6]: models = []
In [7]: results = []
In [8]: for a,b in col_pairs:
     ...:     model = get_model(df[a],df[b])
     ...:     models.append(model)
     ...:     result = get_result(model)
     ...:     results.append(result)
In [9]: results[0].summary()

get_model 将调用 sm.OLSget_result 将调用 fit(或者只是在这里调用那些没有将它们放在外部函数中。但不要用这种疯狂的执行方式 - best practice is to avoid using it)。

关于python - 在 Python 中的数据框中对所有可能的列组合应用函数——更好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48169141/

相关文章:

python - 在每个 "X"上分割一个字符串

python - groupby 上的“值的长度与索引的长度不匹配”

r - 使用 `car` 跨列范围重新编码

python - 从数据框中删除总和为零的行

python - 将 python pandas 数据帧发布到 slack 有哪些方法?

python - 遍历 Excel 文件的迭代器

python - 如何在Python中将多级别的API响应转换为数据帧

python - 如何从 Pandas 数据框中的当前行中减去前一行并将其应用于每一行;不使用循环?

python - 无法抓取屏幕上不可见但属于 slider /轮播的一部分的数据

python - Pandas - 以正确的方式连接两个不同结构的 JSON