【问题标题】:get p-value and pearson's r for a lits of pandas columns获取 p-value 和 pearson\'s r 以获得 pandas 列的列表
【发布时间】:2022-11-27 19:16:25
【问题描述】:

我正在尝试制作相关系数的多索引表(矩阵)p值。我更愿意使用 scipy.stats 测试。

x = pd.DataFrame(
    list(
        zip(
            [1,2,3,4,5,6], [5, 7, 8, 4, 2, 8], [13, 16, 12, 11, 9, 10]
            )
            ),
            columns= ['a', 'b', 'c'] 
            )
 

# I've tried something like this
for i in range(len(x.columns)):
    r,p = pearsonr(x[x.columns[i]], x[x.columns[i+1]])
    print(f'{r}, {p}')

显然 for loop 不会起作用。我想要结束的是:

a b c
a r 1.0 -.09 -.8
p .00 .87 .06
b r -.09 1 .42
p .87 .00 .41
c r -.8 .42 1
p .06 .41 00

几年前我已经编写代码来解决这个问题(在这个社区的帮助下),但它只适用于 spearmanr 的旧版本。

任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas correlation


    【解决方案1】:

    这是使用 scipy pearsonr 和 Pandas corr 方法实现的一种方法:

    import pandas as pd
    from scipy.stats import pearsonr
    
    def pearsonr_pval(x, y):
        return pearsonr(x, y)[1]
    
    
    df = (
        pd.concat(
            [
                x.corr(method="pearson").reset_index().assign(value="r"),
                x.corr(method=pearsonr_pval).reset_index().assign(value="p"),
            ]
        )
        .groupby(["index", "value"])
        .agg(lambda x: list(x)[0])
    ).sort_index(ascending=[True, False])
    
    df.index.names = ["", ""]
    

    然后:

    print(df)
    # Output
                a         b         c
    
    a r  1.000000 -0.088273 -0.796421
      p  1.000000  0.867934  0.057948
    b r -0.088273  1.000000  0.421184
      p  0.867934  1.000000  0.405583
    c r -0.796421  0.421184  1.000000
      p  0.057948  0.405583  1.000000
    

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 2013-10-07
      相关资源
      最近更新 更多