我有一个如下所示的数据框,
df1=
Index bins one two three four
a 1 0.760207 0.313230 1.257121 3.777180
b 2 0.920607 0.350345 -0.424963 0.032379
c 3 -0.975032 0.580298 1.819454 -0.807784
d 4 -0.886256 0.656349 0.306178 1.172622
e 5 0.512182 0.362790 1.066892 0.250835
我想要一个数据框,它简单地给出第一、二、三、四列的 r 平方值以及列箱。这样我想要的数据框如下所示。
df2=
columns r-square_with_bins
one 0.25
two 0.7
three 0.35
four 0.01
five 0.112
我在这里写的 r 平方值并不准确,仅用于理解数据帧结构。 在真实的数据集中,有超过 200 列,第一列是“bins”。 但问题和这个是一样的。
需要帮助。
最佳答案
您可以使用scipy.stats.linregress()
找到右值
,然后将其平方为 R²。
首先导入模块:
import scipy.stats
然后,例如,使用 'bins'
计算 'one'
列的 R²:
scipy.stats.linregress(df1[['bins', 'one']].to_numpy()).rvalue ** 2
对我来说结果是 0.15589578141321594。
为了对所有列(除了第一列'bins'
)执行此操作,只需在 for
循环中执行每个计算(使用例如,列表理解。)
这将创建一个新的 DataFrame df2
就像您所描述的那样:
df2 = pd.DataFrame({
'columns': df1.columns[1:],
'r-square_with_bins': [
scipy.stats.linregress(df1[['bins', col]].to_numpy()).rvalue ** 2
for col in df1.columns[1:]
]
})
这会产生以下数据帧:
r-square_with_bins
columns
one 0.155896
two 0.171381
three 0.004014
four 0.280958
关于python - 基于 R 平方值创建数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60124004/