Skip to content

DataFrame.from_dict unexpectedly "flatten" tuples in the dictionary keys #16769

Closed
@tkf

Description

@tkf

Code Sample, a copy-pastable example if possible

In [1]: import pandas

In [2]: pandas.__version__
Out[2]: '0.20.2'

In [3]: pandas.DataFrame.from_dict([{('a',): 1}, {('a',): 2}]).columns
Out[3]: Index(['a'], dtype='object')

In [4]: pandas.DataFrame.from_dict([{('a',): 1, ('b',): 2}]).columns
Out[4]: Index([('a',), ('b',)], dtype='object')

In [5]: pandas.DataFrame.from_dict([{('a', 'b'): 1}]).columns
Out[5]: Index([('a', 'b')], dtype='object')

Problem description

When (1) dictionaries with a single identical key is given to pandas.DataFrame.from_dict and (2) the key is a singleton tuple, then it returns a dataframe whose column is the content of the tuple, instead of the tuple itself.

Note that this problem does not happen when (1) is not the case (see In [4]) or (2) is not the case (see In [5]). It makes the case (1) & (2) inconsistent with those other cases.

Expected Output

In [3]: pandas.DataFrame.from_dict([{('a',): 1}, {('a',): 2}]).columns
Out[3]: Index([('a',)], dtype='object')

Output of pd.show_versions()

INSTALLED VERSIONS ------------------ commit: None python: 3.6.0.final.0 python-bits: 64 OS: Linux OS-release: 4.4.47-1-lts machine: x86_64 processor: byteorder: little LC_ALL: None LANG: en_US.UTF-8 LOCALE: en_US.UTF-8

pandas: 0.20.2
pytest: 3.1.2
pip: 9.0.1
setuptools: 36.0.1
Cython: None
numpy: 1.13.0
scipy: None
xarray: None
IPython: 6.1.0
sphinx: None
patsy: None
dateutil: 2.6.0
pytz: 2017.2
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
pandas_gbq: None
pandas_datareader: None

It is also reproduced with the current master branch:

INSTALLED VERSIONS ------------------ commit: 1265c27 python: 3.6.0.final.0 python-bits: 64 OS: Linux OS-release: 4.4.47-1-lts machine: x86_64 processor: byteorder: little LC_ALL: None LANG: en_US.UTF-8 LOCALE: en_US.UTF-8

pandas: 0.21.0.dev+179.g1265c27f4
pytest: None
pip: 9.0.1
setuptools: 36.0.1
Cython: 0.25.2
numpy: 1.13.0
scipy: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.6.0
pytz: 2017.2
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions