gpt4 book ai didi

python - Pandas:如何将单热编码数据帧转换为邻接矩阵?

转载 作者:太空宇宙 更新时间:2023-11-03 14:48:04 24 4
gpt4 key购买 nike

我有一个数据框 df,其形式为:

      Col1   Col2    Col3   
0 0 1 0
1 1 1 0
2 0 1 1
3 1 1 0

我需要一个新的 df 的形式:

        Col1    Col2    Col3
Col1 0 2 0
Col2 2 0 1
Col3 0 1 0

基本上,这些值表示所有行的两个给定列的同时出现。

我该怎么做?

最佳答案

只需利用 matrix-multiplication那里-

In [21]: df_out = df.T.dot(df)

In [22]: np.fill_diagonal(df_out.values, 0)

In [23]: df_out
Out[23]:
Col1 Col2 Col3
Col1 0 2 0
Col2 2 0 1
Col3 0 1 0

关于python - Pandas:如何将单热编码数据帧转换为邻接矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47934443/

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