gpt4 book ai didi

python - 在 python pandas 中构造一个共现矩阵

转载 作者:IT老高 更新时间:2023-10-28 21:45:00 25 4
gpt4 key购买 nike

我知道如何在 R 中执行此操作.但是,pandas 中是否有任何函数可以将数据帧转换为 nxn 共现矩阵,其中包含同时出现的两个方面的计数。

例如一个矩阵df:

import pandas as pd

df = pd.DataFrame({'TFD' : ['AA', 'SL', 'BB', 'D0', 'Dk', 'FF'],
'Snack' : ['1', '0', '1', '1', '0', '0'],
'Trans' : ['1', '1', '1', '0', '0', '1'],
'Dop' : ['1', '0', '1', '0', '1', '1']}).set_index('TFD')

print df

>>>
Dop Snack Trans
TFD
AA 1 1 1
SL 0 0 1
BB 1 1 1
D0 0 1 0
Dk 1 0 0
FF 1 0 1

[6 rows x 3 columns]

会产生:

    Dop Snack Trans

Dop 0 2 3
Snack 2 0 2
Trans 3 2 0

由于矩阵镜像在对角线上,我想会有一种方法来优化代码。

最佳答案

这是一个简单的线性代数,您将矩阵与其转置相乘(您的示例包含字符串,不要忘记将它们转换为整数):

>>> df_asint = df.astype(int)
>>> coocc = df_asint.T.dot(df_asint)
>>> coocc
Dop Snack Trans
Dop 4 2 3
Snack 2 3 2
Trans 3 2 4

如果,如在 R 答案中,您想重置对角线,您可以使用 numpy 的 fill_diagonal :

>>> import numpy as np
>>> np.fill_diagonal(coocc.values, 0)
>>> coocc
Dop Snack Trans
Dop 0 2 3
Snack 2 0 2
Trans 3 2 0

关于python - 在 python pandas 中构造一个共现矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20574257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com