unixeo
unixeo

Reputation: 1186

Preserve index when loading pyarrow parquet from pandas DataFrame

I need to convert a dict with dict values to parquet, I have data that look like this:

{"KEY":{"2018-12-06":250.0,"2018-12-07":234.0}}

I'm converting to pandas dataframe and then writing to pyarrow table:

import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

data = {"KEY":{"2018-12-06":250.0,"2018-12-07":234.0}}
df = pd.DataFrame.from_dict(data, orient='index')
table = pa.Table.from_pandas(df, preserve_index=False)
pq.write_table(table, 'file.parquet', flavor='spark')

I end up with data, that only have dates and values, but without the key of the dict.:

{"2018-12-06":250.0,"2018-12-07":234.0}

What I need is to also have the key of the data:

{"KEY": {"2018-12-06":250.0,"2018-12-07":234.0}}

Upvotes: 0

Views: 3478

Answers (2)

Manvendra Gupta
Manvendra Gupta

Reputation: 416

I am observing a related but separate issue where the the frequency type of DateTimeIndex is not preserved in round trip from pandas to table.

For example:

    >>> import pandas as pd
    >>> import pyarrow as pa
    >>> from collections import OrderedDict
    >>>
    >>>
    >>> pd.__version__
    '1.1.5'
    >>>
    >>> pa.__version__
    '4.0.1'
    >>>
    >>> dates = pd.date_range(start='2016-04-01', periods=4, name='DATE')
    >>> dict_data = OrderedDict()
    >>> dict_data['A'] = list('AABB')
    >>> dict_data['B'] = list('abab')
    >>> dict_data['C'] = list('wxyz')
    >>> dict_data['D'] = range(0, 4)
    >>> df = pd.DataFrame.from_dict(dict_data)
    >>> df = df.set_index(dates)
    >>>
    >>> df.index
    DatetimeIndex(['2016-04-01', '2016-04-02', '2016-04-03', '2016-04-04'], dtype='datetime64[ns]', name='DATE', freq='D')
    >>>
    >>> table = pa.Table.from_pandas(df, preserve_index=True)
    >>> df2 = table.to_pandas()
    >>> df2.index
    DatetimeIndex(['2016-04-01', '2016-04-02', '2016-04-03', '2016-04-04'], dtype='datetime64[ns]', name='DATE', freq=None)

Upvotes: 1

cs95
cs95

Reputation: 402413

If you wanted to preserve the index, then you should've specified as such; set preserve_index=True:

table = pa.Table.from_pandas(df, preserve_index=True)

pq.write_table(table, 'file.parquet', flavor='spark')
pq.read_table('file.parquet').to_pandas()  # Index is preserved.

     2018-12-06  2018-12-07
KEY       250.0       234.0

Upvotes: 3

Related Questions