python - Pandas 中的一致性表(每行对的每行之间的 Pearson 相关性)

标签 python python-3.x pandas numpy scipy

使用下面的 pandas 数据框,取自 dict of dict:

import numpy as np
import pandas as pd
from scipy.stats import pearsonr

NaN = np.nan


dd ={'A': {'A': '1', 'B': '2', 'C': '3'},
         'B': {'A': '4', 'B': '5', 'C': '6'},
         'C': {'A': '7', 'B': '8', 'C': '9'}}

df_link_link = pd.DataFrame.from_dict(dd, orient='index')

我想形成一个新的 pandas DataFrame,其中每一行的行之间的 Pearson 相关结果不包括相同行之间的 Pearson 相关(将 A 与其自身相关应该只是 NaN。这在此处被拼写为一个 dict of dicts:

dict_congruent = {'A': {'A': NaN, 
                        'B': pearsonr([NaN,2,3],[4,5,6]), 
                        'C': pearsonr([NaN,2,3],[7,8,9])},
                  'B': {'A': pearsonr([4,NaN,6],[1,2,3]), 
                        'B': NaN, 
                        'C': pearsonr([4,NaN,6],[7,8,9])},
                  'C': {'A': pearsonr([7,8,NaN],[1,2,3]), 
                        'B': pearsonr([7,8,NaN],[4,5,6]), 
                        'C': NaN }}

NaN 就是 numpy.nan。有没有一种方法可以在不遍历字典的情况下将其作为 Pandas 内的操作来执行?我有大约 7600 万对,所以非迭代方法会很棒,如果存在的话。

最佳答案

规范但不可行的解决方案

df.corr().mask(np.equal.outer(df.index.values, df.columns.values))

corr 的默认方法是 pearson

enter image description here


TL;DR
转换您的数据以使用它
系上蝴蝶结

非常广泛的数据

np.random.seed([3,1415])
m, n = 1000, 10000
df = pd.DataFrame(np.random.randn(m, n), columns=['s{}'.format(i) for i in range(n)])

魔法函数

def corr(df, step=100, mask_diagonal=False):

    n = df.shape[0]

    def corr_closure(df):
        d = df.values
        sums = d.sum(0, keepdims=True)
        stds = d.std(0, keepdims=True)

        def corr_(k=0, l=10):
            d2 = d.T.dot(d[:, k:l])
            sums2 = sums.T.dot(sums[:, k:l])
            stds2 = stds.T.dot(stds[:, k:l])

            return pd.DataFrame((d2 - sums2 / n) / stds2 / n,
                                df.columns, df.columns[k:l])

        return corr_

    c = corr_closure(df)

    step = min(step, df.shape[1])

    tups = zip(range(0, n, step), range(step, n + step, step))

    corr_table = pd.concat([c(*t) for t in tups], axis=1)

    if mask_diagonal:
        np.fill_diagonal(corr_table.values, np.nan)

    return corr_table

示范

ct = corr(df, mask_diagonal=True)
ct.iloc[:10, :10]

enter image description here


魔术解决方案解释
逻辑:

  • 使用闭包预先计算列总和和标准差
  • 返回一个函数,该函数获取要关联的列的位置

def corr_closure(df):
    d = df.values  # get underlying numpy array
    sums = d.sum(0, keepdims=True)  # pre calculate sums
    stds = d.std(0, keepdims=True)  # pre calculate standard deviations
    n = d.shape[0]  # grab number of rows

    def corr(k=0, l=10):
        d2 = d.T.dot(d[:, k:l])  # for this slice, run dot product
        sums2 = sums.T.dot(sums[:, k:l])  # dot pre computed sums with slice
        stds2 = stds.T.dot(stds[:, k:l])  # dot pre computed stds with slice

        # calculate correlations with the information I have
        return pd.DataFrame((d2 - sums2 / n) / stds2 / n,
                            df.columns, df.columns[k:l])

    return corr

时间
10 列
enter image description here

100 列
enter image description here

1000 列
enter image description here

10000 列
df.corr() 没有在合理的时间内完成
enter image description here

关于python - Pandas 中的一致性表(每行对的每行之间的 Pearson 相关性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40476713/

相关文章:

python - 从字符串中提取所有表情符号并忽略 Python 中的 Fitzpatrick 修饰符(肤色等)

python - 在 Python csv 到 xls 转换期间修改的格式

python - 如何打印出 JSON 输出的确切字段/字符串?

Python 错误 : "IndexError: string index out of range"

python - Pandas NLTK 标记 "unhashable type: ' 列表'"

python - 查找笔记本电脑的所有目录和文件

python - Pandas:针对时间序列数据生成直方图/数据透视图

python-3.x - SQLite数据存储

python - Pandas 替换类型问题

python - 错误 : Found array with dim 3. 预期估计器 <= 2