| 1 |
# -*- coding: utf-8 -*- |
| 2 |
from __future__ import division, print_function, absolute_import |
| 3 |
|
| 4 |
|
| 5 |
import inspect |
| 6 |
|
| 7 |
|
| 8 |
from petl.util.base import Table |
| 9 |
|
| 10 |
|
| 11 |
def todataframe(table, index=None, exclude=None, columns=None, |
| 12 |
coerce_float=False, nrows=None): |
| 13 |
""" |
| 14 |
Load data from the given `table` into a |
| 15 |
`pandas <http://pandas.pydata.org/>`_ DataFrame. E.g.:: |
| 16 |
|
| 17 |
>>> import petl as etl |
| 18 |
>>> table = [('foo', 'bar', 'baz'), |
| 19 |
... ('apples', 1, 2.5), |
| 20 |
... ('oranges', 3, 4.4), |
| 21 |
... ('pears', 7, .1)] |
| 22 |
>>> df = etl.todataframe(table) |
| 23 |
>>> df |
| 24 |
foo bar baz |
| 25 |
0 apples 1 2.5 |
| 26 |
1 oranges 3 4.4 |
| 27 |
2 pears 7 0.1 |
| 28 |
|
| 29 |
""" |
| 30 |
import pandas as pd |
| 31 |
it = iter(table) |
| 32 |
try: |
| 33 |
header = next(it) |
| 34 |
except StopIteration: |
| 35 |
header = None # Will create an Empty DataFrame |
| 36 |
if columns is None: |
| 37 |
columns = header |
| 38 |
return pd.DataFrame.from_records(it, index=index, exclude=exclude, |
| 39 |
columns=columns, coerce_float=coerce_float, |
| 40 |
nrows=nrows) |
| 41 |
|
| 42 |
|
| 43 |
Table.todataframe = todataframe |
| 44 |
Table.todf = todataframe |
| 45 |
|
| 46 |
|
| 47 |
def fromdataframe(df, include_index=False): |
| 48 |
""" |
| 49 |
Extract a table from a `pandas <http://pandas.pydata.org/>`_ DataFrame. |
| 50 |
E.g.:: |
| 51 |
|
| 52 |
>>> import petl as etl |
| 53 |
>>> import pandas as pd |
| 54 |
>>> records = [('apples', 1, 2.5), ('oranges', 3, 4.4), ('pears', 7, 0.1)] |
| 55 |
>>> df = pd.DataFrame.from_records(records, columns=('foo', 'bar', 'baz')) |
| 56 |
>>> table = etl.fromdataframe(df) |
| 57 |
>>> table |
| 58 |
+-----------+-----+-----+ |
| 59 |
| foo | bar | baz | |
| 60 |
+===========+=====+=====+ |
| 61 |
| 'apples' | 1 | 2.5 | |
| 62 |
+-----------+-----+-----+ |
| 63 |
| 'oranges' | 3 | 4.4 | |
| 64 |
+-----------+-----+-----+ |
| 65 |
| 'pears' | 7 | 0.1 | |
| 66 |
+-----------+-----+-----+ |
| 67 |
|
| 68 |
""" |
| 69 |
|
| 70 |
return DataFrameView(df, include_index=include_index) |
| 71 |
|
| 72 |
|
| 73 |
class DataFrameView(Table): |
| 74 |
|
| 75 |
def __init__(self, df, include_index=False): |
| 76 |
assert hasattr(df, 'columns') \ |
| 77 |
and hasattr(df, 'iterrows') \ |
| 78 |
and inspect.ismethod(df.iterrows), \ |
| 79 |
'bad argument, expected pandas.DataFrame, found %r' % df |
| 80 |
self.df = df |
| 81 |
self.include_index = include_index |
| 82 |
|
| 83 |
def __iter__(self): |
| 84 |
if self.include_index: |
| 85 |
yield ('index',) + tuple(self.df.columns) |
| 86 |
for i, row in self.df.iterrows(): |
| 87 |
yield (i,) + tuple(row) |
| 88 |
else: |
| 89 |
yield tuple(self.df.columns) |
| 90 |
for _, row in self.df.iterrows(): |
| 91 |
yield tuple(row) |