【问题标题】:Adding string header and index to a numpy array将字符串标题和索引添加到 numpy 数组
【发布时间】:2015-12-30 06:47:39
【问题描述】:

假设我有一个 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 数据框,然后添加标题和索引。任何其他建议。

【问题讨论】:

  • np.savetxt 允许您定义标题。但是要添加字符串列,您必须定义一个结构化数组 - 一个包含 7 个字段、一个字符串和 6 个浮点数。

标签: python numpy pandas


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 2013-12-16
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多