Skip to content

DataFrame constructor ignores key order when data is an OrderedDict and orient is 'columns' #10514

Closed
@alan-wong

Description

@alan-wong

Whilst answering this question: http://stackoverflow.com/questions/31242021/python-3-4-pandas-dataframe-not-responding-to-ordered-dictionary

I had look at this and found the error is in index.py line 5746 on pandas 0.16.2:

def _union_indexes(indexes):
    if len(indexes) == 0:
        raise AssertionError('Must have at least 1 Index to union')
    if len(indexes) == 1:
        result = indexes[0]
        if isinstance(result, list):
            result = Index(sorted(result)) #<---- here
        return result

minimal example:

In [38]:
import pandas as pd
from collections import OrderedDict
d = OrderedDict([('XXX', OrderedDict([('B', 1), ('A', 2)]))])
pd.DataFrame(d)

Out[38]:
   XXX
A    2
B    1

The same thing occurs if you do:

pd.DataFrame.from_dict(d)

Note that passing 'orient='index'' preserves the order:

In [40]:
pd.DataFrame.from_dict(d, orient='index')

Out[40]:
     B  A
XXX  1  2

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReshapingConcat, Merge/Join, Stack/Unstack, Explode

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions