1

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

3
  • 1
    Maybe the simplest thing would be to make a class which contains the array and your description. That way you wouldn't have to subclass ndarray, which as you probably know is a bit wacky. Commented Oct 5, 2013 at 12:18
  • That would also be a more sensible way of making functions that deal with that data in the array. Commented Oct 5, 2013 at 12:21
  • If you don't want the description to survive array operations, subclassing work easily for this. If you want more, it requires a bit more and will leave a few operations where the information will not be preserved anyway. Commented Oct 6, 2013 at 9:04

1 Answer 1

3

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 [%].'
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. But probably I will write my own data class (like John Z. suggested), with a function to save and load the data and the description to a .dat file. Until this is done, the namedtuple will be my solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.