Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: MultiIndex.from_tuples() fails to infer dtype from nan-only values from an index #36375

Open
2 of 3 tasks
ssche opened this issue Sep 15, 2020 · 3 comments
Open
2 of 3 tasks
Labels
Bug Dtype Conversions Unexpected or buggy dtype conversions MultiIndex

Comments

@ssche
Copy link
Contributor

ssche commented Sep 15, 2020

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

In [23]: df2 = pd.DataFrame({'a': [np.nan, 1, 2, 1], 'b': [1, 1, 2, 1], 'd': [np.nan, np.nan, np.nan, np.nan], 'c': [1, 1, 1, 1]}) 

In [24]: df2.dtypes

Out[24]: 
a    float64
b      int64
d    float64
c      int64
dtype: object

In [29]: s2 = df2.groupby(['a', 'b', 'd'], dropna=False)['c'].sum()                                                                                                                                
In [30]: s2.index                                                                                                                                                                                  
Out[30]: 
MultiIndex([(1.0, 1, nan),
            (2.0, 2, nan),
            (nan, 1, nan)],
           names=['a', 'b', 'd'])

In [31]: s2.index.get_level_values(2).dtype                                                                                                                                                        
Out[31]: dtype('float64')

In [32]: pd.MultiIndex.from_tuples(s2.index)                                                                                                                                                       
Out[32]: 
MultiIndex([(1.0, 1, nan),
            (2.0, 2, nan),
            (nan, 1, nan)],
           )

In [34]: pd.MultiIndex.from_tuples(s2.index).get_level_values(2).dtype                                                                                                                             
Out[34]: dtype('O')

Problem description

When a MultiIndex is re-created from another MultiIndex which contains a nan-only column by using .from_tuples(), the dtype of the nan-only level is object when it should be float64.

As a workaround, the dtype can be inferred correctly when the original index is wrapped in a tuple:

In [35]: pd.MultiIndex.from_tuples(tuple(s2.index)).get_level_values(2).dtype                                                                                                                      
Out[35]: dtype('float64')

This problem also doesn't occur when there is at least one non-nan value in the index column:

In [36]: df3 = pd.DataFrame({'a': [np.nan, 1, 2, 1], 'b': [1, 1, 2, 1], 'd': [np.nan, np.nan, np.nan, 1], 'c': [1, 1, 1, 1]})
In [37]: pd.MultiIndex.from_tuples(df3.groupby(['a', 'b', 'd'], dropna=False)['c'].sum().index).get_level_values(2).dtype
Out[37]: dtype('float64')

Expected Output

The dtype is inferred correctly even without wrapping the source index into a tuple.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 2a7d332
python : 3.8.5.final.0
python-bits : 64
OS : Darwin
OS-release : 19.6.0
Version : Darwin Kernel Version 19.6.0: Thu Jun 18 20:49:00 PDT 2020; root:xnu-6153.141.1~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_AU.UTF-8
LOCALE : en_AU.UTF-8

pandas : 1.1.2
numpy : 1.19.2
pytz : 2020.1
dateutil : 2.8.1
pip : 20.1.1
setuptools : 46.4.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 7.18.1
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

@ssche ssche added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 15, 2020
@ssche ssche changed the title BUG: MultiIndex.from_tuples() fails to infer dtype from nan-only index column BUG: MultiIndex.from_tuples() fails to infer dtype from nan-only values from an index Sep 15, 2020
@arw2019
Copy link
Member

arw2019 commented Sep 15, 2020

Here is a condensed reproducer. I get this on 1.2 master

import numpy as np
import pandas as pd
import pandas._testing as tm

df = pd.DataFrame(
    {
        "a": [np.nan, 1, 2, 1],
        "b": [1, 1, 2, 1],
        "d": [np.nan, np.nan, np.nan, np.nan],
        "c": [1, 1, 1, 1],
    }
)

gb_sum = df.groupby(["a", "b", "d"], dropna=False)["c"].sum()

assert gb_sum.index.get_level_values(2).dtype is np.dtype("float64")

mi = gb_sum.index

# reconstruct mi using MultiIndex.from_tuples
mi_from_tuples = pd.MultiIndex.from_tuples(mi, name=["a", "b", "d"])

# roundtrip fails b/c dtype
tm.assert_index_equal(mi, mi_from_tuples)

                                                                                         
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-9-8a8a0fb1ba00> in <module>
     19 
     20 # roundtrip fails b/c dtype
---> 21 tm.assert_index_equal(mi, mi_reconstructed)

    [... skipping hidden 2 frame]

/workspaces/pandas-arw2019/pandas/_testing.py in _check_types(l, r, obj)
    711     def _check_types(l, r, obj="Index"):
    712         if exact:
--> 713             assert_class_equal(l, r, exact=exact, obj=obj)
    714 
    715             # Skip exact dtype checking when `check_categorical` is False

    [... skipping hidden 2 frame]

AssertionError: MultiIndex level [2] are different

MultiIndex level [2] classes are not equivalent
[left]:  Float64Index([nan, nan, nan], dtype='float64', name='d')
[right]: Index([nan, nan, nan], dtype='object', name='d')
Output of pd.show_versions()

INSTALLED VERSIONS

commit : a3f42df
python : 3.8.3.final.0
python-bits : 64
OS : Linux
OS-release : 5.4.0-47-generic
Version : #51-Ubuntu SMP Fri Sep 4 19:50:52 UTC 2020
machine : x86_64
processor :
byteorder : little
LC_ALL : C.UTF-8
LANG : C.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.2.0.dev0+428.ga3f42df79
numpy : 1.18.5
pytz : 2020.1
dateutil : 2.8.1
pip : 20.1.1
setuptools : 49.1.0.post20200704
Cython : 0.29.21
pytest : 5.4.3
hypothesis : 5.19.0
sphinx : 3.1.1
blosc : None
feather : None
xlsxwriter : 1.2.9
lxml.etree : 4.5.2
html5lib : 1.1
pymysql : None
psycopg2 : 2.8.5 (dt dec pq3 ext lo64)
jinja2 : 2.11.2
IPython : 7.16.1
pandas_datareader: None
bs4 : 4.9.1
bottleneck : 1.3.2
fsspec : 0.7.4
fastparquet : 0.4.0
gcsfs : 0.6.2
matplotlib : 3.2.2
numexpr : 2.7.1
odfpy : None
openpyxl : 3.0.4
pandas_gbq : None
pyarrow : 0.17.1
pytables : None
pyxlsb : None
s3fs : 0.4.2
scipy : 1.5.0
sqlalchemy : 1.3.18
tables : 3.6.1
tabulate : 0.8.7
xarray : 0.15.1
xlrd : 1.2.0
xlwt : 1.3.0
numba : 0.50.1

@dsaxton dsaxton added Dtype Conversions Unexpected or buggy dtype conversions MultiIndex and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 15, 2020
@phofl
Copy link
Member

phofl commented Nov 1, 2020

Index level is inferred via Categorical(values, ordered=False) where values are the index values. The behavior, that only nan values are transformed to object is intentional there. Don't know, if this should be the same for MultiIndex then...

@mzeitlin11
Copy link
Member

mzeitlin11 commented Jan 2, 2021

Inconsistency also shows up just in construction:

import pandas as pd
idx = pd.MultiIndex.from_tuples([("foo", np.nan)])
idx.levels[1]

gives

Index([], dtype='object')

But

idx = pd.MultiIndex.from_arrays((["foo"], [np.nan]))
idx.levels[1]

and

idx = pd.MultiIndex.from_product((["foo"], [np.nan]))
idx.levels[1]

give

Float64Index([], dtype='float64')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Dtype Conversions Unexpected or buggy dtype conversions MultiIndex
Projects
None yet
Development

No branches or pull requests

5 participants