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: Series constructor from dictionary drops key (index) levels when not all keys have same number of entries #60695

Open
3 tasks done
ArneBinder opened this issue Jan 11, 2025 · 9 comments

Comments

@ArneBinder
Copy link

ArneBinder commented Jan 11, 2025

Pandas version checks

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

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

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
# Out[30]: 
# l1    v1
# l1    v2
# dtype: object

# the reason is that the Series constructor uses internally MultiIndex.from_tuples in the following way (note that the input is a tuple of tuples!):
pd.MultiIndex.from_tuples((("l1",), ("l1","l2")))
# Out[32]: 
# MultiIndex([('l1',),
#             ('l1',)],
#            )

# compare to the following which produces the expected result:
pd.MultiIndex.from_tuples([("l1",), ("l1","l2")])
# Out[33]: 
# MultiIndex([('l1',  nan),
#             ('l1', 'l2')],
#            )

# Note: this was tested with latest release and current master

Issue Description

When calling the Series constructor with a dict where the keys are tuples, a series with MulitIndex gets created. However, if the number of entries in the keys is not the same, key entries from keys with more than the minimum number get dropped. This is in several ways problematic, especially if this produces duplicated index values / keys which is not expected because it was called with a dict (which has per definition unique keys).

Expected Behavior

The MultiIndex of the new series has nan-padded values.

Installed Versions

INSTALLED VERSIONS

commit : 0691c5c
python : 3.10.16
python-bits : 64
OS : Linux
OS-release : 6.8.0-51-generic
Version : #52~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Mon Dec 9 15:00:52 UTC 2
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : de_DE.UTF-8
LOCALE : de_DE.UTF-8

pandas : 2.2.3
numpy : 2.2.1
pytz : 2024.2
dateutil : 2.9.0.post0
pip : 24.2
Cython : None
sphinx : None
IPython : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : None
lxml.etree : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : None
pyreadstat : None
pytest : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2024.2
qtpy : None
pyqt5 : None

@ArneBinder ArneBinder added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 11, 2025
@rhshadrach
Copy link
Member

rhshadrach commented Jan 22, 2025

Thanks for the report! It seems to me treating tuples and lists differently is not desired here. This is due to:

elif isinstance(tuples, list):

and that code goes back to bc5a745. It appears this was not intentional. I'd suggest looking into replacing the isinstance with is_list_like. Further investigations and PRs to fix are welcome!

@rhshadrach rhshadrach added MultiIndex good first issue and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 22, 2025
@ShashwatAgrawal20
Copy link
Contributor

take

@ShashwatAgrawal20
Copy link
Contributor

hey @rhshadrach,
I tried replacing the isinstance to use is_list_like, but that alone doesn't seem to fix the issue. The test case(test_constructor_dict_tuple_indexer) continues to fail, and I'm unsure if the problem lies with the test setup or if there's more to adjust?

Here's the test result for test_constructor_tuple_indexer

<?xml version="1.0" encoding="utf-8"?><testsuites><testsuite name="pytest" errors="0" failures="1" skipped="0" tests="1" time="0.594" timestamp="2025-01-23T21:11:54.485741+05:30" hostname="archlap"><testcase classname="pandas.tests.series.test_constructors.TestSeriesConstructors" name="test_constructor_dict_tuple_indexer" time="0.008"><failure message="AssertionError: Series.index level [2] are different&#10;&#10;Attribute &quot;dtype&quot; are different&#10;[left]:  object&#10;[right]: float64">left = Index([], dtype='object'), right = Index([nan], dtype='float64'), obj = 'Series.index level [2]'

    def _check_types(left, right, obj: str = "Index") -&gt; None:
        if not exact:
            return
    
        assert_class_equal(left, right, exact=exact, obj=obj)
&gt;       assert_attr_equal("inferred_type", left, right, obj=obj)
E       AssertionError: Series.index level [2] are different
E       
E       Attribute "inferred_type" are different
E       [left]:  empty
E       [right]: floating

pandas/_testing/asserters.py:246: AssertionError

During handling of the above exception, another exception occurred:

self = &lt;pandas.tests.series.test_constructors.TestSeriesConstructors object at 0x72f8efd00b40&gt;

    def test_constructor_dict_tuple_indexer(self):
        # GH 12948
        data = {(1, 1, None): -1.0}
        result = Series(data)
        expected = Series(
            -1.0, index=MultiIndex(levels=[[1], [1], [np.nan]], codes=[[0], [0], [-1]])
        )
&gt;       tm.assert_series_equal(result, expected)

pandas/tests/series/test_constructors.py:1417: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

left = Index([nan], dtype='object'), right = Index([nan], dtype='float64'), obj = 'Series.index level [2]'

    def _check_types(left, right, obj: str = "Index") -&gt; None:
        if not exact:
            return
    
        assert_class_equal(left, right, exact=exact, obj=obj)
        assert_attr_equal("inferred_type", left, right, obj=obj)
    
        # Skip exact dtype checking when `check_categorical` is False
        if isinstance(left.dtype, CategoricalDtype) and isinstance(
            right.dtype, CategoricalDtype
        ):
            if check_categorical:
                assert_attr_equal("dtype", left, right, obj=obj)
                assert_index_equal(left.categories, right.categories, exact=exact)
            return
    
&gt;       assert_attr_equal("dtype", left, right, obj=obj)
E       AssertionError: Series.index level [2] are different
E       
E       Attribute "dtype" are different
E       [left]:  object
E       [right]: float64

pandas/_testing/asserters.py:257: AssertionError</failure></testcase></testsuite></testsuites>

@siber64
Copy link

siber64 commented Jan 23, 2025

Hi I'm new and this is first I looked at. I know I didn't "take" it, but I think looking at it briefly try changing line 539 to
arrs = zip_longest(*tuples, fillvalue=np.nan)
also need to include
import from itertools zip_longest.

This will create an index with the number of dimensions of the longest iterable, even if it is not the first, for instance ((1,2), (3,), (3,4,5), (5,) ) gets us ((1, 3, 3, 5), (2, nan, 4, nan), (nan, nan, 5, nan)).

Or should I take it and do it ? Not sure of etiquette. @VishalSindham are you doing similar ?

@ShashwatAgrawal20
Copy link
Contributor

I've tried doing that, even when manually converting None values to np.nan doesn't resolve the issue with my test cases. ig it has something to do with how python's parsing these types.

The only solution I've found to make the tests pass is by adding check_index_type=False to the assertion statement in test_constructor_dict_tuple_indexer.

@VishalSindham
Copy link

@VishalSindham are you doing similar ?

Yes @siber64. Did not start yet. You can contribute early if you have the solution.

@siber64
Copy link

siber64 commented Jan 24, 2025

Thanks, I can look later today, doesn't sound like Python problem

@siber64
Copy link

siber64 commented Jan 24, 2025

@VishalSindham As I suspected it is just the behavior of zip, zip_longest fixes it. I'll take and do a PR

@siber64
Copy link

siber64 commented Jan 24, 2025

take

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants