| 1 |
Introduction |
| 2 |
============ |
| 3 |
|
| 4 |
.. _intro_design_goals: |
| 5 |
|
| 6 |
Design goals |
| 7 |
------------ |
| 8 |
|
| 9 |
This package is designed primarily for convenience and ease of use, |
| 10 |
especially when working interactively with data that are unfamiliar, |
| 11 |
heterogeneous and/or of mixed quality. |
| 12 |
|
| 13 |
:mod:`petl` transformation pipelines make minimal use of system memory |
| 14 |
and can scale to millions of rows if speed is not a priority. However |
| 15 |
if you are working with very large datasets and/or performance-critical |
| 16 |
applications then other packages may be more suitable, e.g., see |
| 17 |
`pandas <http://pandas.pydata.org/>`_, `pytables |
| 18 |
<https://pytables.github.io/>`_, `bcolz <http://bcolz.blosc.org/>`_ |
| 19 |
and `blaze <http://blaze.pydata.org/>`_. See also :doc:`related_work`. |
| 20 |
|
| 21 |
.. _intro_pipelines: |
| 22 |
|
| 23 |
ETL pipelines |
| 24 |
------------- |
| 25 |
|
| 26 |
This package makes extensive use of lazy evaluation and iterators. This |
| 27 |
means, generally, that a pipeline will not actually be executed until |
| 28 |
data is requested. |
| 29 |
|
| 30 |
E.g., given a file at 'example.csv' in the current working directory:: |
| 31 |
|
| 32 |
>>> example_data = """foo,bar,baz |
| 33 |
... a,1,3.4 |
| 34 |
... b,2,7.4 |
| 35 |
... c,6,2.2 |
| 36 |
... d,9,8.1 |
| 37 |
... """ |
| 38 |
>>> with open('example.csv', 'w') as f: |
| 39 |
... f.write(example_data) |
| 40 |
... |
| 41 |
|
| 42 |
...the following code **does not** actually read the file or load any of its |
| 43 |
contents into memory:: |
| 44 |
|
| 45 |
>>> import petl as etl |
| 46 |
>>> table1 = etl.fromcsv('example.csv') |
| 47 |
|
| 48 |
Rather, `table1` is a **table container** (see :ref:`intro_conventions` |
| 49 |
below) which can be iterated over, extracting data from the |
| 50 |
underlying file on demand. |
| 51 |
|
| 52 |
Similarly, if one or more transformation functions are applied, e.g.:: |
| 53 |
|
| 54 |
>>> table2 = etl.convert(table1, 'foo', 'upper') |
| 55 |
>>> table3 = etl.convert(table2, 'bar', int) |
| 56 |
>>> table4 = etl.convert(table3, 'baz', float) |
| 57 |
>>> table5 = etl.addfield(table4, 'quux', lambda row: row.bar * row.baz) |
| 58 |
|
| 59 |
...no actual transformation work will be done until data are |
| 60 |
requested from `table5` (or any of the other tables returned by |
| 61 |
the intermediate steps). |
| 62 |
|
| 63 |
So in effect, a 5 step pipeline has been set up, and rows will pass through |
| 64 |
the pipeline on demand, as they are pulled from the end of the pipeline via |
| 65 |
iteration. |
| 66 |
|
| 67 |
A call to a function like :func:`petl.util.vis.look`, or any of the functions |
| 68 |
which write data to a file or database (e.g., :func:`petl.io.csv.tocsv`, |
| 69 |
:func:`petl.io.text.totext`, :func:`petl.io.sqlite3.tosqlite3`, |
| 70 |
:func:`petl.io.db.todb`), will pull data through the pipeline |
| 71 |
and cause all of the transformation steps to be executed on the |
| 72 |
requested rows, e.g.:: |
| 73 |
|
| 74 |
>>> etl.look(table5) |
| 75 |
+-----+-----+-----+--------------------+ |
| 76 |
| foo | bar | baz | quux | |
| 77 |
+=====+=====+=====+====================+ |
| 78 |
| 'A' | 1 | 3.4 | 3.4 | |
| 79 |
+-----+-----+-----+--------------------+ |
| 80 |
| 'B' | 2 | 7.4 | 14.8 | |
| 81 |
+-----+-----+-----+--------------------+ |
| 82 |
| 'C' | 6 | 2.2 | 13.200000000000001 | |
| 83 |
+-----+-----+-----+--------------------+ |
| 84 |
| 'D' | 9 | 8.1 | 72.89999999999999 | |
| 85 |
+-----+-----+-----+--------------------+ |
| 86 |
|
| 87 |
...although note that :func:`petl.util.vis.look` will by default only request |
| 88 |
the first 5 rows, and so the minimum amount of processing will be done to |
| 89 |
produce 5 rows. |
| 90 |
|
| 91 |
.. _intro_programming_styles: |
| 92 |
|
| 93 |
Functional and object-oriented programming styles |
| 94 |
------------------------------------------------- |
| 95 |
|
| 96 |
The :mod:`petl` package supports both functional and object-oriented |
| 97 |
programming styles. For example, the example in the section on |
| 98 |
:ref:`intro_pipelines` above could also be written as:: |
| 99 |
|
| 100 |
>>> import petl as etl |
| 101 |
>>> table = ( |
| 102 |
... etl |
| 103 |
... .fromcsv('example.csv') |
| 104 |
... .convert('foo', 'upper') |
| 105 |
... .convert('bar', int) |
| 106 |
... .convert('baz', float) |
| 107 |
... .addfield('quux', lambda row: row.bar * row.baz) |
| 108 |
... ) |
| 109 |
>>> table.look() |
| 110 |
+-----+-----+-----+--------------------+ |
| 111 |
| foo | bar | baz | quux | |
| 112 |
+=====+=====+=====+====================+ |
| 113 |
| 'A' | 1 | 3.4 | 3.4 | |
| 114 |
+-----+-----+-----+--------------------+ |
| 115 |
| 'B' | 2 | 7.4 | 14.8 | |
| 116 |
+-----+-----+-----+--------------------+ |
| 117 |
| 'C' | 6 | 2.2 | 13.200000000000001 | |
| 118 |
+-----+-----+-----+--------------------+ |
| 119 |
| 'D' | 9 | 8.1 | 72.89999999999999 | |
| 120 |
+-----+-----+-----+--------------------+ |
| 121 |
|
| 122 |
A ``wrap()`` function is also provided to use the object-oriented style with |
| 123 |
any valid table container object, e.g.:: |
| 124 |
|
| 125 |
>>> l = [['foo', 'bar'], ['a', 1], ['b', 2], ['c', 2]] |
| 126 |
>>> table = etl.wrap(l) |
| 127 |
>>> table.look() |
| 128 |
+-----+-----+ |
| 129 |
| foo | bar | |
| 130 |
+=====+=====+ |
| 131 |
| 'a' | 1 | |
| 132 |
+-----+-----+ |
| 133 |
| 'b' | 2 | |
| 134 |
+-----+-----+ |
| 135 |
| 'c' | 2 | |
| 136 |
+-----+-----+ |
| 137 |
|
| 138 |
.. _intro_interactive_use: |
| 139 |
|
| 140 |
Interactive use |
| 141 |
--------------- |
| 142 |
|
| 143 |
When using :mod:`petl` from within an interactive Python session, the |
| 144 |
default representation for table objects uses the :func:`petl.util.vis.look()` |
| 145 |
function, so a table object can be returned at the prompt to inspect it, e.g.:: |
| 146 |
|
| 147 |
>>> l = [['foo', 'bar'], ['a', 1], ['b', 2], ['c', 2]] |
| 148 |
>>> table = etl.wrap(l) |
| 149 |
>>> table |
| 150 |
+-----+-----+ |
| 151 |
| foo | bar | |
| 152 |
+=====+=====+ |
| 153 |
| 'a' | 1 | |
| 154 |
+-----+-----+ |
| 155 |
| 'b' | 2 | |
| 156 |
+-----+-----+ |
| 157 |
| 'c' | 2 | |
| 158 |
+-----+-----+ |
| 159 |
|
| 160 |
By default data values are rendered using the built-in :func:`repr` function. |
| 161 |
To see the string (:func:`str`) values instead, :func:`print` the table, e.g.: |
| 162 |
|
| 163 |
>>> print(table) |
| 164 |
+-----+-----+ |
| 165 |
| foo | bar | |
| 166 |
+=====+=====+ |
| 167 |
| a | 1 | |
| 168 |
+-----+-----+ |
| 169 |
| b | 2 | |
| 170 |
+-----+-----+ |
| 171 |
| c | 2 | |
| 172 |
+-----+-----+ |
| 173 |
|
| 174 |
.. _intro_ipython_notebook: |
| 175 |
|
| 176 |
IPython notebook integration |
| 177 |
---------------------------- |
| 178 |
|
| 179 |
Table objects also implement ``_repr_html_()`` and so will be displayed as an |
| 180 |
HTML table if returned from a cell in an IPython notebook. The functions |
| 181 |
:func:`petl.util.vis.display` and :func:`petl.util.vis.displayall` also |
| 182 |
provide more control over rendering of tables within an IPython notebook. |
| 183 |
|
| 184 |
For examples of usage see the `repr_html notebook <https://nbviewer.jupyter.org/github/petl-developers/petl/blob/master/repr_html.ipynb>`_. |
| 185 |
|
| 186 |
.. _intro_executable: |
| 187 |
|
| 188 |
``petl`` executable |
| 189 |
------------------- |
| 190 |
|
| 191 |
Also included in the ``petl`` distribution is a script to execute |
| 192 |
simple transformation pipelines directly from the operating system |
| 193 |
shell. E.g.:: |
| 194 |
|
| 195 |
$ petl "dummytable().tocsv()" > example.csv |
| 196 |
$ cat example.csv | petl "fromcsv().cut('foo', 'baz').convert('baz', float).selectgt('baz', 0.5).head().data().totsv()" |
| 197 |
|
| 198 |
The ``petl`` script is extremely simple, it expects a single |
| 199 |
positional argument, which is evaluated as Python code but with all of |
| 200 |
the functions in the :mod:`petl` namespace imported. |
| 201 |
|
| 202 |
.. _intro_conventions: |
| 203 |
|
| 204 |
Conventions - table containers and table iterators |
| 205 |
-------------------------------------------------- |
| 206 |
|
| 207 |
This package defines the following convention for objects acting as |
| 208 |
containers of tabular data and supporting row-oriented iteration over |
| 209 |
the data. |
| 210 |
|
| 211 |
A **table container** (also referred to here as a **table**) is |
| 212 |
any object which satisfies the following: |
| 213 |
|
| 214 |
1. implements the `__iter__` method |
| 215 |
|
| 216 |
2. `__iter__` returns a **table iterator** (see below) |
| 217 |
|
| 218 |
3. all table iterators returned by `__iter__` are independent, i.e., consuming items from one iterator will not affect any other iterators |
| 219 |
|
| 220 |
A **table iterator** is an iterator which satisfies the following: |
| 221 |
|
| 222 |
4. each item returned by the iterator is a sequence (e.g., tuple or list) |
| 223 |
|
| 224 |
5. the first item returned by the iterator is a **header row** comprising a sequence of **header values** |
| 225 |
|
| 226 |
6. each subsequent item returned by the iterator is a **data row** comprising a sequence of **data values** |
| 227 |
|
| 228 |
7. a **header value** is typically a string (`str`) but may be an object of any type as long as it implements `__str__` and is pickleable |
| 229 |
|
| 230 |
8. a **data value** is any pickleable object |
| 231 |
|
| 232 |
So, for example, a list of lists is a valid table container:: |
| 233 |
|
| 234 |
>>> table = [['foo', 'bar'], ['a', 1], ['b', 2]] |
| 235 |
|
| 236 |
Note that an object returned by the :func:`csv.reader` function from the |
| 237 |
standard Python :mod:`csv` module is a table iterator and **not** a table |
| 238 |
container, because it can only be iterated over once. However, it is |
| 239 |
straightforward to define functions that support the table container convention |
| 240 |
and provide access to data from CSV or other types of file or data source, see |
| 241 |
e.g. the :func:`petl.io.csv.fromcsv` function. |
| 242 |
|
| 243 |
The main reason for requiring that table containers support independent |
| 244 |
table iterators (point 3) is that data from a table may need to be |
| 245 |
iterated over several times within the same program or interactive |
| 246 |
session. E.g., when using :mod:`petl` in an interactive session to build up |
| 247 |
a sequence of data transformation steps, the user might want to |
| 248 |
examine outputs from several intermediate steps, before all of the |
| 249 |
steps are defined and the transformation is executed in full. |
| 250 |
|
| 251 |
Note that this convention does not place any restrictions on the |
| 252 |
lengths of header and data rows. A table may contain a header row |
| 253 |
and/or data rows of varying lengths. |
| 254 |
|
| 255 |
.. _intro_extending: |
| 256 |
|
| 257 |
Extensions - integrating custom data sources |
| 258 |
-------------------------------------------- |
| 259 |
|
| 260 |
The :mod:`petl.io` module has functions for extracting data from a number of |
| 261 |
well-known data sources. However, it is also straightforward to write an |
| 262 |
extension that enables integration with other data sources. For an object to |
| 263 |
be usable as a :mod:`petl` table it has to implement the **table container** |
| 264 |
convention described above. Below is the source code for an |
| 265 |
:class:`ArrayView` class which allows integration of :mod:`petl` with numpy |
| 266 |
arrays. This class is included within the :mod:`petl.io.numpy` |
| 267 |
module but also provides an example of how other data sources might be |
| 268 |
integrated:: |
| 269 |
|
| 270 |
>>> import petl as etl |
| 271 |
>>> class ArrayView(etl.Table): |
| 272 |
... def __init__(self, a): |
| 273 |
... # assume that a is a numpy array |
| 274 |
... self.a = a |
| 275 |
... def __iter__(self): |
| 276 |
... # yield the header row |
| 277 |
... header = tuple(self.a.dtype.names) |
| 278 |
... yield header |
| 279 |
... # yield the data rows |
| 280 |
... for row in self.a: |
| 281 |
... yield tuple(row) |
| 282 |
... |
| 283 |
|
| 284 |
Now this class enables the use of numpy arrays with :mod:`petl` functions, |
| 285 |
e.g.:: |
| 286 |
|
| 287 |
>>> import numpy as np |
| 288 |
>>> a = np.array([('apples', 1, 2.5), |
| 289 |
... ('oranges', 3, 4.4), |
| 290 |
... ('pears', 7, 0.1)], |
| 291 |
... dtype='U8, i4,f4') |
| 292 |
>>> t1 = ArrayView(a) |
| 293 |
>>> t1 |
| 294 |
+-----------+----+-----------+ |
| 295 |
| f0 | f1 | f2 | |
| 296 |
+===========+====+===========+ |
| 297 |
| 'apples' | 1 | 2.5 | |
| 298 |
+-----------+----+-----------+ |
| 299 |
| 'oranges' | 3 | 4.4000001 | |
| 300 |
+-----------+----+-----------+ |
| 301 |
| 'pears' | 7 | 0.1 | |
| 302 |
+-----------+----+-----------+ |
| 303 |
|
| 304 |
>>> t2 = t1.cut('f0', 'f2').convert('f0', 'upper').addfield('f3', lambda row: row.f2 * 2) |
| 305 |
>>> t2 |
| 306 |
+-----------+-----------+---------------------+ |
| 307 |
| f0 | f2 | f3 | |
| 308 |
+===========+===========+=====================+ |
| 309 |
| 'APPLES' | 2.5 | 5.0 | |
| 310 |
+-----------+-----------+---------------------+ |
| 311 |
| 'ORANGES' | 4.4000001 | 8.8000001907348633 | |
| 312 |
+-----------+-----------+---------------------+ |
| 313 |
| 'PEARS' | 0.1 | 0.20000000298023224 | |
| 314 |
+-----------+-----------+---------------------+ |
| 315 |
|
| 316 |
If you develop an extension for a data source that you think would also be |
| 317 |
useful for others, please feel free to submit a PR to the |
| 318 |
`petl GitHub repository <https://github.com/petl-developers/petl>`_, or if it |
| 319 |
is a domain-specific data source, the |
| 320 |
`petlx GitHub repository <https://github.com/petl-developers/petlx>`_. |
| 321 |
|
| 322 |
.. _intro_caching: |
| 323 |
|
| 324 |
Caching |
| 325 |
------- |
| 326 |
|
| 327 |
This package tries to make efficient use of memory by using iterators |
| 328 |
and lazy evaluation where possible. However, some transformations |
| 329 |
cannot be done without building data structures, either in memory or |
| 330 |
on disk. |
| 331 |
|
| 332 |
An example is the :func:`petl.transform.sorts.sort` function, which will either |
| 333 |
sort a table entirely in memory, or will sort the table in memory in chunks, |
| 334 |
writing chunks to disk and performing a final merge sort on the |
| 335 |
chunks. Which strategy is used will depend on the arguments passed |
| 336 |
into the :func:`petl.transform.sorts.sort` function when it is called. |
| 337 |
|
| 338 |
In either case, the sorting can take some time, and if the sorted data |
| 339 |
will be used more than once, it is undesirable to start again from |
| 340 |
scratch each time. It is better to cache the sorted data, if possible, |
| 341 |
so it can be re-used. |
| 342 |
|
| 343 |
The :func:`petl.transform.sorts.sort` function, and all functions which use |
| 344 |
it internally, provide a `cache` keyword argument which can be used to |
| 345 |
turn on or off the caching of sorted data. |
| 346 |
|
| 347 |
There is also an explicit :func:`petl.util.materialise.cache` function, which |
| 348 |
can be used to cache in memory up to a configurable number of rows from any |
| 349 |
table. |