Pandas version checks
-
[X] I have checked that this issue has not already been reported.
-
[X] I have confirmed this bug exists on the latest version of pandas.
-
[X] 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
Comment From: rhshadrach
Thanks for the report! It seems to me treating tuples and lists differently is not desired here. This is due to:
https://github.com/pandas-dev/pandas/blob/4c3b968a0a4de483c00d15bd267bc776a218337e/pandas/core/indexes/multi.py#L591
and that code goes back to https://github.com/pandas-dev/pandas/commit/bc5a7451a5cfb049e3cc6c9cfc56d2c01656e327. 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!
Comment From: ShashwatAgrawal20
take
Comment From: ShashwatAgrawal20
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 Attribute "dtype" are different [left]: object [right]: float64">left = Index([], dtype='object'), right = Index([nan], dtype='float64'), obj = 'Series.index level [2]'
def _check_types(left, right, obj: str = "Index") -> None:
if not exact:
return
assert_class_equal(left, right, exact=exact, obj=obj)
> 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 = <pandas.tests.series.test_constructors.TestSeriesConstructors object at 0x72f8efd00b40>
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]])
)
> 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") -> 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
> 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>
Comment From: siber64
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 ?
Comment From: ShashwatAgrawal20
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
.
Comment From: VishalSindham
@VishalSindham are you doing similar ?
Yes @siber64. Did not start yet. You can contribute early if you have the solution.
Comment From: siber64
Thanks, I can look later today, doesn't sound like Python problem
Comment From: siber64
@VishalSindham As I suspected it is just the behavior of zip, zip_longest fixes it. I'll take and do a PR
Comment From: siber64
take
Comment From: JonKissil
Has this issue been completed? If not could I take it?
Comment From: siber64
Yes of course I've been swamped with life stuff. So the fix is just to swap zip for zip_longest , there is no performance hit. Some of the unit tests though fail as they expect the old behaviour. Now I could not get a clean unit test run and didn't have the time to go through all the failures to see which was due to this change.
Comment From: JonKissil
Alright appreciated 👍 I’ll get to work on this ASAP
Comment From: JonKissil
take
Comment From: mansoor17syed
Hi everyone,
I picked up this issue and have started working on it. I’d be happy to receive any guidance or feedback along the way. Apologies if this was already assigned to someone—please let me know if I should coordinate differently. Looking forward to contributing!
Comment From: JonKissil
Hello @mansoor17syed,
I was already working on this but I am happy to collaborate! Right now I’m looking at the failing unit tests because of the new behavior of zip_longest.
Comment From: mansoor17syed
Hi @JonKissil ,
Could you review the changes and let me know if there's anything I can help with? I just wanted to give it a shot, so I went ahead and pushed my changes.Appreciate your support
Comment From: JonKissil
@mansoor17syed you're more than welcome to continue working on it if you think you can come to a solution, I'm also a bit strapped for time.
Comment From: Anurag-Varma
take
Comment From: Anurag-Varma
Hi @ArneBinder @rhshadrach
I made some changes to the code and would like to confirm if the expected output I mentioned below is correct for the given code.
import pandas as pd
pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
# Expected output:
# l1 NaN v1
# l2 v2
# dtype: object
Comment From: siber64
No, here is the unit test I added to pandas/tests/indexes/multi/test_constructors.py
@pytest.mark.parametrize("keys, expected", ( ((("l1",), ("l1","l2")), (("l1", np.nan), ("l1","l2"))), ((("l1","l2",), ("l1",)), (("l1","l2"), ("l1", np.nan))), )) def test_from_tuples_with_various_tuple_lengths(keys, expected): # Issue 60695 idx = MultiIndex.from_tuples(keys) assert tuple(idx) == expected
From: Anurag Varma @.> Sent: 16 February 2025 09:43 To: pandas-dev/pandas @.> Cc: Simon @.>; Assign @.> Subject: Re: [pandas-dev/pandas] BUG: Series constructor from dictionary drops key (index) levels when not all keys have same number of entries (Issue #60695)
[Anurag-Varma]Anurag-Varma left a comment (pandas-dev/pandas#60695)https://github.com/pandas-dev/pandas/issues/60695#issuecomment-2661347323
Hi @ArneBinderhttps://github.com/ArneBinder @rhshadrachhttps://github.com/rhshadrach
Is the expected output which i mentioned below correct for the given code ?
import pandas as pd
pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
Expected output:
l1 NaN v1
l2 v2
dtype: object
— Reply to this email directly, view it on GitHubhttps://github.com/pandas-dev/pandas/issues/60695#issuecomment-2661347323, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AD3Z4PKNQHHHP67CZB7QOLT2QBMVDAVCNFSM6AAAAABVAHQGESVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRRGM2DOMZSGM. You are receiving this because you were assigned.
Comment From: Anurag-Varma
Hi @siber64
What you said is correct, but thats only of tuple of tuples given input to MultiIndex.from_tuples
My question is diffferent, i am using pd.Series with dictionary and tuple is keys in a dictionary.
So, I think pandas treats this as Multiindex and the first index of each tuple becomes the primary index and the second element becomes the sub-index.
Example of existing behaviour:
import pandas as pd
pd.Series({("l1","l3"):"v1", ("l1","l2"): "v2"})
# Existing Output:
# l1 l3 v1
# l2 v2
# dtype: object
Example of error behaviour:
import pandas as pd
pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
# Error Output:
# l1 v1
# l1 v2
# dtype: object
Example of expected behaviour:
import pandas as pd
pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
# Expected Output:
# l1 NaN v1
# l2 v2
# dtype: object
Comment From: siber64
Only problem I found was with tuples
Sent from Outlook for Androidhttps://aka.ms/AAb9ysg
From: Anurag Varma @.> Sent: Sunday, February 16, 2025 3:50:18 PM To: pandas-dev/pandas @.> Cc: Simon @.>; Mention @.> Subject: Re: [pandas-dev/pandas] BUG: Series constructor from dictionary drops key (index) levels when not all keys have same number of entries (Issue #60695)
Hi @siber64https://github.com/siber64
What you said is correct, but thats only of tuple of tuples given input to MultiIndex.from_tuples
My question is diffferent, i am using pd.Series with dictionary and tuple is keys in a dictionary.
So, I think pandas treats this as Multiindex and the first index of each tuple becomes the primary index and the second element becomes the sub-index.
Example of existing behaviour:
import pandas as pd pd.Series({("l1","l3"):"v1", ("l1","l2"): "v2"})
Existing Output:
l1 l3 v1
l2 v2
dtype: object
Example of error behaviour:
import pandas as pd pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
Error Output:
l1 v1
l1 v2
dtype: object
Example of expected behaviour:
import pandas as pd pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
Expected Output:
l1 NaN v1
l2 v2
dtype: object
— Reply to this email directly, view it on GitHubhttps://github.com/pandas-dev/pandas/issues/60695#issuecomment-2661494022, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AD3Z4PIYY4IUVULAJ2DAS4D2QCXTVAVCNFSM6AAAAABVAHQGESVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRRGQ4TIMBSGI. You are receiving this because you were mentioned.Message ID: @.***>
[Anurag-Varma]Anurag-Varma left a comment (pandas-dev/pandas#60695)https://github.com/pandas-dev/pandas/issues/60695#issuecomment-2661494022
Hi @siber64https://github.com/siber64
What you said is correct, but thats only of tuple of tuples given input to MultiIndex.from_tuples
My question is diffferent, i am using pd.Series with dictionary and tuple is keys in a dictionary.
So, I think pandas treats this as Multiindex and the first index of each tuple becomes the primary index and the second element becomes the sub-index.
Example of existing behaviour:
import pandas as pd pd.Series({("l1","l3"):"v1", ("l1","l2"): "v2"})
Existing Output:
l1 l3 v1
l2 v2
dtype: object
Example of error behaviour:
import pandas as pd pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
Error Output:
l1 v1
l1 v2
dtype: object
Example of expected behaviour:
import pandas as pd pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
Expected Output:
l1 NaN v1
l2 v2
dtype: object
— Reply to this email directly, view it on GitHubhttps://github.com/pandas-dev/pandas/issues/60695#issuecomment-2661494022, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AD3Z4PIYY4IUVULAJ2DAS4D2QCXTVAVCNFSM6AAAAABVAHQGESVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRRGQ4TIMBSGI. You are receiving this because you were mentioned.Message ID: @.***>
Comment From: ArneBinder
I made some changes to the code and would like to confirm if the expected output I mentioned below is correct for the given code.
import pandas as pd
pd.Series({("l1",):"v1", ("l1","l2"): "v2"})
Expected output:
l1 NaN v1
l2 v2
dtype: object
@Anurag-Varma Yes, exactly, that's what I had in mind.
Comment From: Anurag-Varma
Hi @rhshadrach
I was trying to fix the bug but below test case was failing:
pandas/tests/series/methods/test_map.py::test_map_dict_with_tuple_keys
When I further tried to fix it, found out that the Series.map()
is failing for multiple examples with tuples as keys in the dictionary.
So created a new issue for that: #60988
Comment From: Anurag-Varma
Hi @rhshadrach
I was trying to fix the bug but below test case was failing:
pandas/tests/series/methods/test_map.py::test_map_dict_with_tuple_keys
When I further tried to fix it, found out that the
Series.map()
is failing for multiple examples with tuples as keys in the dictionary.So created a new issue for that: #60988
I solved this current issue but the above test case is failing so unable to send a new commit in my PR #60944
Should i mark it as xfail and proceed forward ?
Comment From: rhshadrach
I solved this current issue but the above test case is failing so unable to send a new commit in my PR #60944
Is this related to this change: https://github.com/pandas-dev/pandas/pull/60944/files#r1966545298?
If not, I do not understand your comment. It is best to discuss these things on the PR, where the discussion can happen next to the code involved.