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

Python 将描述字符串添加到numpy数组,python,arrays,numpy,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 [%

我想为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'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:'numpy.ndarray'对象没有属性'description'
这是否可以在不子类化numpy.ndarray类的情况下实现

问候,,
Jonas

最简单的方法是使用a来保存数组和描述:

>>> 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 [%].'

最简单的方法是使用a来保存数组和描述:

>>> 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 [%].'

也许最简单的方法是创建一个包含数组和描述的类。这样,您就不必对ndarray进行子类化,正如您可能知道的那样,这有点古怪。这也是一种更明智的方法,可以使函数处理数组中的数据。如果您不想让描述在数组操作中存活,子类化很容易实现。如果您想要更多,它需要更多的操作,并且会留下一些无论如何都不会保留信息的操作。也许最简单的事情是创建一个包含数组和描述的类。这样,您就不必对ndarray进行子类化,正如您可能知道的那样,这有点古怪。这也是一种更明智的方法,可以使函数处理数组中的数据。如果您不想让描述在数组操作中存活,子类化很容易实现。如果您想要更多,它需要更多一点,并且会留下一些操作,这些操作无论如何都不会保留信息。很好。但我可能会编写自己的数据类(如John Z.所建议的),并使用一个函数将数据和描述保存并加载到.dat文件中。在这之前,namedtuple将是我的解决方案。很好。但我可能会编写自己的数据类(如John Z.所建议的),并使用一个函数将数据和描述保存并加载到.dat文件中。在此之前,namedtuple将是我的解决方案。