簡體   English   中英

基於 R 平方值創建數據框

[英]creating dataframe on the basis of R-squared value

我有一個如下所示的數據框,

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

我想得到一個數據框,它只給出帶有列 bin 的第一、二、三、四列的 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()找到rvalue ,然后將其平方為 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM