将描述字符串添加到numpy数组

时间:2013-10-05 12:13:28

标签: python arrays numpy

我想在python numpy数组中添加一个描述。

例如,当使用numpy作为交互式数据语言时,我想做类似的事情:

A = np.array([[1,2,3],[4,5,6]])
A.description = "Holds all the data from experiment 1. Each row contains an intensity measurement with the following columns: time [s], intensity [W/m^2], error [%]."

但它给出了:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'description'

如果没有子类化numpy.ndarray类,这可能吗?

此致 纳斯

1 个答案:

答案 0 :(得分:3)

最简单的方法是使用namedtuple来保存数组和解密:

>>> from collections import namedtuple
>>> Array = namedtuple('Array', ['data', 'description'])
>>> A = Array(np.array([[1,2,3],[4,5,6]]), "Holds all the data from experiment 1. Each row contains an intensity measurement with the following columns: time [s], intensity [W/m^2], error [%].")
>>> A.data
array([[1, 2, 3],
       [4, 5, 6]])
>>> A.description
'Holds all the data from experiment 1. Each row contains an intensity measurement with the following columns: time [s], intensity [W/m^2], error [%].'