Debian Codegraph @

petl/io/numpy.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import division, print_function, absolute_import
3
4
5 from petl.compat import next, string_types
6 from petl.util.base import iterpeek, ValuesView, Table
7 from petl.util.materialise import columns
8
9
10 def infer_dtype(table):
11 import numpy as np
12 # get numpy to infer dtype
13 it = iter(table)
14 hdr = next(it)
15 flds = list(map(str, hdr))
16 rows = tuple(it)
17 dtype = np.rec.array(rows).dtype
18 dtype.names = flds
19 return dtype
20
21
22 def construct_dtype(flds, peek, dtype):
23 import numpy as np
24
25 if dtype is None:
26 dtype = infer_dtype(peek)
27
28 elif isinstance(dtype, string_types):
29 # insert field names from source table
30 typestrings = [s.strip() for s in dtype.split(',')]
31 dtype = [(f, t) for f, t in zip(flds, typestrings)]
32
33 elif (isinstance(dtype, dict) and
34 ('names' not in dtype or 'formats' not in dtype)):
35 # allow for partial specification of dtype
36 cols = columns(peek)
37 newdtype = {'names': [], 'formats': []}
38 for f in flds:
39 newdtype['names'].append(f)
40 if f in dtype and isinstance(dtype[f], tuple):
41 # assume fully specified
42 newdtype['formats'].append(dtype[f][0])
43 elif f not in dtype:
44 # not specified at all
45 a = np.array(cols[f])
46 newdtype['formats'].append(a.dtype)
47 else:
48 # assume directly specified, just need to add offset
49 newdtype['formats'].append(dtype[f])
50 dtype = newdtype
51
52 return dtype
53
54
55 def toarray(table, dtype=None, count=-1, sample=1000):
56 """
57 Load data from the given `table` into a
58 `numpy <http://www.numpy.org/>`_ structured array. E.g.::
59
60 >>> import petl as etl
61 >>> table = [('foo', 'bar', 'baz'),
62 ... ('apples', 1, 2.5),
63 ... ('oranges', 3, 4.4),
64 ... ('pears', 7, .1)]
65 >>> a = etl.toarray(table)
66 >>> a
67 array([('apples', 1, 2.5), ('oranges', 3, 4.4), ('pears', 7, 0.1)],
68 dtype=(numpy.record, [('foo', '<U7'), ('bar', '<i8'), ('baz', '<f8')]))
69 >>> # the dtype can be specified as a string
70 ... a = etl.toarray(table, dtype='S4, i2, f4')
71 >>> a
72 array([(b'appl', 1, 2.5), (b'oran', 3, 4.4), (b'pear', 7, 0.1)],
73 dtype=[('foo', 'S4'), ('bar', '<i2'), ('baz', '<f4')])
74 >>> # the dtype can also be partially specified
75 ... a = etl.toarray(table, dtype={'foo': 'S4'})
76 >>> a
77 array([(b'appl', 1, 2.5), (b'oran', 3, 4.4), (b'pear', 7, 0.1)],
78 dtype=[('foo', 'S4'), ('bar', '<i8'), ('baz', '<f8')])
79
80 If the dtype is not completely specified, `sample` rows will be
81 examined to infer an appropriate dtype.
82
83 """
84
85 import numpy as np
86 it = iter(table)
87 peek, it = iterpeek(it, sample)
88 hdr = next(it)
89 flds = list(map(str, hdr))
90 dtype = construct_dtype(flds, peek, dtype)
91
92 # numpy is fussy about having tuples, need to make sure
93 it = (tuple(row) for row in it)
94 sa = np.fromiter(it, dtype=dtype, count=count)
95
96 return sa
97
98
99 Table.toarray = toarray
100
101
102 def torecarray(*args, **kwargs):
103 """
104 Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.
105
106 """
107
108 import numpy as np
109 return toarray(*args, **kwargs).view(np.recarray)
110
111
112 Table.torecarray = torecarray
113
114
115 def fromarray(a):
116 """
117 Extract a table from a `numpy <http://www.numpy.org/>`_ structured array,
118 e.g.::
119
120 >>> import petl as etl
121 >>> import numpy as np
122 >>> a = np.array([('apples', 1, 2.5),
123 ... ('oranges', 3, 4.4),
124 ... ('pears', 7, 0.1)],
125 ... dtype='S8, i4, f4')
126 >>> table = etl.fromarray(a)
127 >>> table # doctest: +SKIP
128 +-----------+----+-----+
129 | f0 | f1 | f2 |
130 +===========+====+=====+
131 | 'apples' | 1 | 2.5 |
132 +-----------+----+-----+
133 | 'oranges' | 3 | 4.4 |
134 +-----------+----+-----+
135 | 'pears' | 7 | 0.1 |
136 +-----------+----+-----+
137
138 """
139
140 return ArrayView(a)
141
142
143 class ArrayView(Table):
144
145 def __init__(self, a):
146 self.a = a
147
148 def __iter__(self):
149 yield tuple(self.a.dtype.names)
150 for row in self.a:
151 yield tuple(row)
152
153
154 def valuestoarray(vals, dtype=None, count=-1, sample=1000):
155 """
156 Load values from a table column into a `numpy <http://www.numpy.org/>`_
157 array, e.g.::
158
159 >>> import petl as etl
160 >>> table = [('foo', 'bar', 'baz'),
161 ... ('apples', 1, 2.5),
162 ... ('oranges', 3, 4.4),
163 ... ('pears', 7, .1)]
164 >>> table = etl.wrap(table)
165 >>> table.values('bar').array()
166 array([1, 3, 7])
167 >>> # specify dtype
168 ... table.values('bar').array(dtype='i4')
169 array([1, 3, 7], dtype=int32)
170
171 """
172
173 import numpy as np
174 it = iter(vals)
175 if dtype is None:
176 peek, it = iterpeek(it, sample)
177 dtype = np.array(peek).dtype
178 a = np.fromiter(it, dtype=dtype, count=count)
179 return a
180
181
182 ValuesView.toarray = valuestoarray
183 ValuesView.array = valuestoarray