Search code examples
pythonarraysnumpy

Add a description string to a numpy array


I'd like to add a description to a python numpy array.

For example, when using numpy as an interactive data language, I'd like to do something like:

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

But it gives:

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

Is this possible without subclassing the numpy.ndarray class?

Regards, Jonas


Solution

  • Simplest way would be to use a namedtuple to hold both the array and the description:

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