Skip to content

DataFrame.from_dict converts single-tuple index to plain Index when orient='index' #9751

@jiffyclub

Description

@jiffyclub

I have a dictionary of Series that I'm converting to a DataFrame via DataFrame.from_dict, and the Series have index values that are tuples, as in these examples:

In [39]: pd.DataFrame.from_dict({'a': pd.Series([1, 2, 3], index=[('x',), ('y',), ('z',)])}, orient='index')
Out[39]:
   x  y  z
a  1  2  3

In [40]: pd.DataFrame.from_dict({'a': pd.Series([1, 2, 3], index=[('x', 1), ('y', 2), ('z', 3)])}, orient='index')
Out[40]:
   x  y  z
   1  2  3
a  1  2  3

Note that in the first example the columns are a plain Index, but in the second example it's converted to MultiIndex. This causes a problem for me later when I index into the DataFrame columns and expect to get tuples out (with MultiIndex the values are represented as tuples).

When orient='columns' the tuples are not touched:

In [49]: pd.DataFrame.from_dict({'a': pd.Series([1, 2, 3], index=[('x',), ('y',), ('z',)])}, orient='columns')
Out[49]:
      a
(x,)  1
(y,)  2
(z,)  3

In [50]: pd.DataFrame.from_dict({'a': pd.Series([1, 2, 3], index=[('x', 1), ('y', 2), ('z', 3)])}, orient='columns')
Out[50]:
        a
(x, 1)  1
(y, 2)  2
(z, 3)  3

I can get what I'm after by using orient='columns' and then doing the transpose:

In [51]: pd.DataFrame.from_dict({'a': pd.Series([1, 2, 3], index=[('x',), ('y',), ('z',)])}, orient='columns').transpose()
Out[51]:
   (x,)  (y,)  (z,)
a     1     2     3

In [52]: pd.DataFrame.from_dict({'a': pd.Series([1, 2, 3], index=[('x', 1), ('y', 2), ('z', 3)])}, orient='columns').transpose()
Out[52]:
   (x, 1)  (y, 2)  (z, 3)
a       1       2       3

But I was caught unawares by single-item tuples being treated differently than multi-item tuples, and the difference in behavior between index/columns orientation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIO DataIO issues that don't fit into a more specific label

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions