【问题标题】:r squared based on columns from 2 dataframesr 基于来自 2 个数据帧的列的平方
【发布时间】:2021-08-18 20:11:50
【问题描述】:

我有2个数据帧df1和df2,df1如下代码所示,df2是每组每一列的填充平均值,也如下代码所示

import pandas as pd
import numpy as np
data = {'Group':['1', '1', '2', '2'],
        'A':[1, 5, 15, 170],
        'B':[7, 12, 100.1, 14],
        'C':[2, 3.1, 6, 1],
        }
df1 = pd.DataFrame(data)
df2 = df1.groupby("Group").transform(lambda x: x.mean())

我想计算 R 平方的值,循环遍历 2 个数据帧并计算每对列的 r 平方 df1['A'] & df2['A'] , d​​f1['B'] & df2 ['B'], .... 预期结果是一个数据框,其中填充了 A&A 、 B&B ... 列的 Rsquared 值。 谢谢!

【问题讨论】:

  • 你能在你的问题中写出预期的结果是什么吗?
  • @BeChillerToo Done
  • 我相信@BeChillerToo 的意思是您期望 A 和 A 的 Rsquared 值的 。多少个值,以什么形式,等等。
  • @HenryEcker 在这种情况下会有 3 个值, df1['A'] & df2['A'] 的 Rsquared , df1['B'] & df2['B'] & df1 ['C'] & df2['C'] ,但由两个表中的列循环产生
  • 好的,那三个值是什么? (数值)

标签: python pandas dataframe scikit-learn


【解决方案1】:

一种选择是使用intersection 获取共享列,使用scipy.stats.linregress 获取rvalue,然后将其平方:

# Columns Shared By Both DataFrames
cols = df1.columns.intersection(df2.columns)
# Iterate, Calculate, and Collect R-Squared Values
r_squared = {c: scipy.stats.linregress(x=df1[c], y=df2[c]).rvalue ** 2
             for c in cols}

r_squared:

{'A': 0.39989765735182164, 'B': 0.37808726682588906, 'C': 0.06442976976619669}

完整的工作示例:

import pandas as pd
import scipy.stats

data = {'Group': ['1', '1', '2', '2'],
        'A': [1, 5, 15, 170],
        'B': [7, 12, 100.1, 14],
        'C': [2, 3.1, 6, 1],
        }
df1 = pd.DataFrame(data)
df2 = df1.groupby("Group").transform('mean')

# Columns Shared By Both DataFrames
cols = df1.columns.intersection(df2.columns)
# Iterate, Calculate, and Collect R-Squared Values
r_squared = {c: scipy.stats.linregress(x=df1[c], y=df2[c]).rvalue ** 2
             for c in cols}

print(r_squared)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多