[Numpy-discussion] RecArray.tolist() suggestion

Francesc Alted falted at pytables.org
Fri Jul 9 03:55:03 EDT 2004


Hi,

As Perry said not too long ago that numarray crew would ask for suggestions
for RecArray improvements, I'm going to suggest a couple.

I find quite inconvenient the .tolist() method when applied to RecArray
objects as it is now:

>>> r[2:4]
array(
[(3, 33.0, 'c'),
(4, 44.0, 'd')],
formats=['1UInt8', '1Float32', '1a1'],
shape=2,
names=['c1', 'c2', 'c3'])
>>> r[2:4].tolist()
[<numarray.records.Record instance at 0x406a946c>, <numarray.records.Record instance at 0x406a912c>]


The suggested behaviour would be:

>>> r[2:4].tolist()
[(3, 33.0, 'c'),(4, 44.0, 'd')]

Another thing is that an element of recarray would be returned as a tuple
instead as a records.Record object:

>>> r[2]
<numarray.records.Record instance at 0x4064074c>

The suggested behaviour would be:

>>> r[2]
(3, 33.0, 'c')

I think the latter would be consistent with the convention that a
__getitem__(int) of a NumArray object returns a python type instead of a
rank-0 array. In the same way, a __getitem__(int) of a RecArray should
return a a python type (a tuple in this case).

Below is the code that I use right now to simulate this behaviour, but it
would be nice if the code would included into numarray.records module.

    def tolist(arr):
        """Converts a RecArray or Record to a list of rows"""
        outlist = []
        if isinstance(arr, records.Record):
            for i in range(arr.array._nfields):
                outlist.append(arr.array.field(i)[arr.row])
            outlist = tuple(outlist)  # return a tuple for records
        elif isinstance(arr, records.RecArray):
            for j in range(arr.nelements()):
                tmplist = []
                for i in range(arr._nfields):
                    tmplist.append(arr.field(i)[j])
                outlist.append(tuple(tmplist))
        return outlist


Cheers,

-- 
Francesc Alted





More information about the NumPy-Discussion mailing list