summaryrefslogtreecommitdiff
path: root/src/tablib/formats/_df.py
blob: 872f6befdb47336acd5129cb39eb5fe36e18caef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
""" Tablib - DataFrame Support.
"""

try:
    from pandas import DataFrame
except ImportError:
    DataFrame = None


class DataFrameFormat:
    title = 'df'
    extensions = ('df',)

    @classmethod
    def detect(cls, stream):
        """Returns True if given stream is a DataFrame."""
        if DataFrame is None:
            return False
        elif isinstance(stream, DataFrame):
            return True
        try:
            DataFrame(stream.read())
            return True
        except ValueError:
            return False

    @classmethod
    def export_set(cls, dset, index=None):
        """Returns DataFrame representation of DataBook."""
        if DataFrame is None:
            raise NotImplementedError(
                'DataFrame Format requires `pandas` to be installed.'
                ' Try `pip install "tablib[pandas]"`.')
        dataframe = DataFrame(dset.dict, columns=dset.headers)
        return dataframe

    @classmethod
    def import_set(cls, dset, in_stream):
        """Returns dataset from DataFrame."""
        dset.wipe()
        dset.dict = in_stream.to_dict(orient='records')