gpt4 book ai didi

python - 将字符串头和索引添加到 numpy 数组

转载 作者:行者123 更新时间:2023-12-01 04:27:23 24 4
gpt4 key购买 nike

假设我有一个 numpy 数字数组。就像 43,000X5000 一样。例如:

array([[-0.  ,  0.02,  0.03,  0.05,  0.06,  0.05],
[ 0.02, 0. , 0.02, 0.05, 0.04, 0.04],
[ 0.03, 0.02, 0. , 0.06, 0.05, 0.05],
[ 0.05, 0.05, 0.06, 0. , 0.02, 0.01],
[ 0.06, 0.04, 0.05, 0.02, -0. , 0.01],
[ 0.05, 0.04, 0.05, 0.01, 0.01, -0. ]])

我想打印一个结果,使其类似于具有这些值的交叉表,并且标题既作为列标题又作为索引。基本上我想做的是我有一个文本文档的距离矩阵。我想显示一个表格,其中每对文本文档的距离以及列和索引上的文本文档名称。

如下所示:

Austen_Emma Austen_Pride    Austen_Sense    CBronte_Jane    CBronte_Professor   CBronte_Villette
Austen_Emma -0.00 0.02 0.03 0.05 0.06 0.05
Austen_Pride 0.02 0.00 0.02 0.05 0.04 0.04
Austen_Sense 0.03 0.02 0.00 0.06 0.05 0.05
CBronte_Jane 0.05 0.05 0.06 0.00 0.02 0.01
CBronte_Professor 0.06 0.04 0.05 0.02 -0.00 0.01
CBronte_Villette 0.05 0.04 0.05 0.01 0.01 -0.00

我正在考虑将 numpy 矩阵转换为 pandas 数据帧,然后添加标题和索引。任何其他建议。

最佳答案

您可以使用 Pandas 执行以下操作:

import numpy as np
import pandas as pd

pd.set_option('display.width', 150)
header = ['Austen_Emma', 'Austen_Pride', 'Austen_Sense', 'CBronte_Jane', 'CBronte_Professor', 'CBronte_Villette']

a = np.array([[-0. , 0.02, 0.03, 0.05, 0.06, 0.05],
[ 0.02, 0. , 0.02, 0.05, 0.04, 0.04],
[ 0.03, 0.02, 0. , 0.06, 0.05, 0.05],
[ 0.05, 0.05, 0.06, 0. , 0.02, 0.01],
[ 0.06, 0.04, 0.05, 0.02, -0. , 0.01],
[ 0.05, 0.04, 0.05, 0.01, 0.01, -0. ]])

frame = pd.DataFrame(a, index=header, columns=header)
print frame

这将为您提供以下输出:

                   Austen_Emma  Austen_Pride  Austen_Sense  CBronte_Jane  CBronte_Professor  CBronte_Villette
Austen_Emma -0.00 0.02 0.03 0.05 0.06 0.05
Austen_Pride 0.02 0.00 0.02 0.05 0.04 0.04
Austen_Sense 0.03 0.02 0.00 0.06 0.05 0.05
CBronte_Jane 0.05 0.05 0.06 0.00 0.02 0.01
CBronte_Professor 0.06 0.04 0.05 0.02 -0.00 0.01
CBronte_Villette 0.05 0.04 0.05 0.01 0.01 -0.00

关于python - 将字符串头和索引添加到 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32900716/

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