【问题标题】:Adding names to numpy arrays将名称添加到 numpy 数组
【发布时间】:2013-12-23 20:56:43
【问题描述】:

我有一个 2D numpy 数组:

my_array = numpy.array([[1,2],[3,4]])

当我打印出来时,它是这样的:

>>> print(my_array)
[[1 2]
 [3 4]]

是否可以在输出中添加标签或名称?例如,假设我有

names = [['a', 'b'], ['c', 'd']]

那我想要

a [[1 2]
b  [3 4]]
    c d

【问题讨论】:

  • 这不是答案,但是……听起来您可能对Pandas 感兴趣。

标签: python arrays numpy printing


【解决方案1】:

你不想pandas吗?

>>> import numpy
>>> import pandas as pd
>>> my_array = numpy.array([[1,2],[3,4]])
>>> pd.DataFrame(my_array, columns=list('cd'), index=list('ab'))
   c  d
a  1  2
b  3  4

【讨论】:

  • 我认为这不是一个真正的答案;他在问如何用 NumPy 做到这一点。 (这就是为什么我写了和评论一样的东西。)
  • @abarnert 好的,让我们等待 OP 澄清。
【解决方案2】:

可以使用np.savetxt 做到这一点,但它会很麻烦。

或者,您可以只对 strrepr 进行后处理,但这真的很难看——更复杂的数组会变得更糟,但即使是固定的 2x2 数组,它也是类似:

def format_my_2x2_array(a):
    s = str(a).splitlines()
    s[0] = 'a ' + s[0]
    s[1] = 'b ' + s[1]
    col0 = s[1].find('[') + 1
    col1 = s[1].find(' ', col0) + 1
    s.append(' ' * col0 + 'c' + ' ' * (col1 - col0 - 1) + 'd')
    return '\n'.join(s)

要以干净的方式完成此操作,您需要手动迭代内容并将它们连接起来,就像您想要打印出 NumPy 样式的普通 Python 列表一样。

如果列名和行名是数据的固有部分,您可能不想在 I/O 函数中添加它们,而是将它们与数据一起存储。这正是Pandas 的优点——基本上,DataFrame 可以用作带有索引名称的数组。如果您想使用 NumPy 执行此操作,那将无济于事,但就像您想使用 NumPy 而不是列表列表一样,例如,对矩阵或大型像素数组进行操作,您想使用 Pandas 而不是 NumPy ,例如,对具有命名行和列的结构进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2011-04-22
    • 2011-02-10
    • 2014-03-05
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多