Arrays (numpy)

petlx.array.toarray(table, dtype=None, count=-1, sample=1000)[source]

Convenience function to load data from the given table into a numpy structured array. E.g.:

>>> from petl import look
>>> from petlx.array import toarray
>>> look(table)
+-----------+-------+-------+
| 'foo'     | 'bar' | 'baz' |
+===========+=======+=======+
| 'apples'  | 1     | 2.5   |
+-----------+-------+-------+
| 'oranges' | 3     | 4.4   |
+-----------+-------+-------+
| 'pears'   | 7     | 0.1   |
+-----------+-------+-------+

>>> a = toarray(table)
>>> a
array([('apples', 1, 2.5), ('oranges', 3, 4.4), ('pears', 7, 0.1)], 
      dtype=[('foo', '|S7'), ('bar', '<i8'), ('baz', '<f8')])
>>> a['foo']
array(['apples', 'oranges', 'pears'], 
      dtype='|S7')
>>> a['bar']
array([1, 3, 7])
>>> a['baz']
array([ 2.5,  4.4,  0.1])
>>> a['foo'][0]
'apples'
>>> a['bar'][1]
3
>>> a['baz'][2]
0.10000000000000001

If no datatype is specified, sample rows will be examined to infer an appropriate datatype for each field.

The datatype can be specified as a string, e.g.:

>>> a = toarray(table, dtype='a4, i2, f4')
>>> a
array([('appl', 1, 2.5), ('oran', 3, 4.400000095367432),
       ('pear', 7, 0.10000000149011612)], 
      dtype=[('foo', '|S4'), ('bar', '<i2'), ('baz', '<f4')])

The datatype can also be partially specified, in which case datatypes will be inferred for other fields, e.g.:

>>> a = toarray(table, dtype={'foo': 'a4'})
>>> a
array([('appl', 1, 2.5), ('oran', 3, 4.4), ('pear', 7, 0.1)], 
      dtype=[('foo', '|S4'), ('bar', '<i8'), ('baz', '<f8')])
petlx.array.torecarray(*args, **kwargs)[source]

Convenient shorthand for toarray(...).view(np.recarray).

New in version 0.5.1.

petlx.array.fromarray(a)[source]

Extract rows from a numpy structured array.

New in version 0.4.

Project Versions

Previous topic

Excel files (openpyxl)

Next topic

Intervals (bx-python)

This Page