Is it possible to create a NumPy object that behaves very much like a collections.namedtuple, in the sense that elements can be accessed like so:
data[1] = 42
data['start date'] = '2011-09-20' # Slight generalization of what is possible with a namedtuple
I tried to use a complex data type:
>>> data = numpy.empty(shape=tuple(), dtype=[('start date', 'S11'), ('n', int)])
This creates a 0-dimensional value with a kind of namedtuple type; it almost works:
>>> data['start date'] = '2011-09-20'
>>> data
array(('2011-09-20', -3241474627884561860),
dtype=[('start date', '|S11'), ('n', '<i8')])
However, element access does not work, because the "array" is 0-dimensional:
>>> data[0] = '2011-09-20'
Traceback (most recent call last):
File "<ipython-input-19-ed41131430b9>", line 1, in <module>
data[0] = '2011-09-20'
IndexError: 0-d arrays can't be indexed.
Is there a way of obtaining the desired behavior described above (item assignment through both a string and an index) with a NumPy object?
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.
Python's namedtuple was created to improve code readability by providing a way to access values using descriptive field names instead of integer indices, which most of the time don't provide any context on what the values are. This feature also makes the code cleaner and more maintainable.
The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.
Named tuples are basically easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax. They can be used similarly to struct or other common record types, except that they are immutable.
You can do something like this using the numpy.rec
module. What you need is the record
class from this module, but I don't know how to directly create an instance of such a class. One indrect way is to first create a recarray
with a single entry:
>>> a = numpy.recarray(1, names=["start date", "n"], formats=["S11", "i4"])[0]
>>> a[0] = "2011-09-20"
>>> a[1] = 42
>>> a
('2011-09-20', 42)
>>> a["start date"]
'2011-09-20'
>>> a.n
42
If you figure out how to create an instance of record
directly, please let me know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With