【问题标题】:Normalise numpy array / occurrence matrix "across the diagonal"标准化numpy数组/出现矩阵“跨对角线”
【发布时间】:2021-12-18 21:51:34
【问题描述】:

我正在尝试对共现矩阵进行归一化(我想它被称为?) 我有以下来自 csv 文件的数据样本:

import pandas as pd

df = pd.DataFrame({'A':[1,1,1,0,1,1,1,1],
                    'B':[1,0,1,0,1,1,1,1],
                    'C':[0,1,0,1,1,0,1,1],
                    'D':[1,1,1,1,0,1,1,1],
                    'E':[0,1,1,1,1,1,1,0]})

... 我使用以下方法创建此矩阵: (Constructing a co-occurrence matrix in python pandas)

df_asint = df.astype(int)
coocc = df_asint.T.dot(df_asint)
print(coocc)

输出:

[4975 rows x 5 columns]
   A  B  C  D  E
A  7  6  4  6  5
B  6  6  3  5  4
C  4  3  5  4  4
D  6  5  4  7  5
E  5  4  4  5  6

现在的问题。我正在尝试将这些规范化为对角线。 如屏幕截图所示,我已经使用 Excel 解决了它。

关于如何在 pandas 中执行此操作有什么想法吗?

【问题讨论】:

    标签: python pandas dataframe matrix


    【解决方案1】:

    使用numpy:

    import numpy as np
    
    >>> coocc.divide(np.diag(coocc))
    
              A         B    C         D         E
    A  1.000000  1.000000  0.8  0.857143  0.833333
    B  0.857143  1.000000  0.6  0.714286  0.666667
    C  0.571429  0.500000  1.0  0.571429  0.666667
    D  0.857143  0.833333  0.8  1.000000  0.833333
    E  0.714286  0.666667  0.8  0.714286  1.000000
    

    如果你想强制上对角线值为零,你可以这样做:

    >>> pd.DataFrame(np.tril(coocc.divide(np.diag(coocc))), columns=coocc.columns, index=coocc.index)
    
              A         B    C         D    E
    A  1.000000  0.000000  0.0  0.000000  0.0
    B  0.857143  1.000000  0.0  0.000000  0.0
    C  0.571429  0.500000  1.0  0.000000  0.0
    D  0.857143  0.833333  0.8  1.000000  0.0
    E  0.714286  0.666667  0.8  0.714286  1.0
    

    【讨论】:

    • 这么简单真是太棒了。非常感谢!
    猜你喜欢
    • 2018-12-14
    • 2022-01-10
    • 2013-02-07
    • 2021-12-12
    • 2015-11-13
    • 2018-01-18
    • 2022-11-29
    • 2012-08-17
    • 2012-04-15
    相关资源
    最近更新 更多