-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
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
Comments
Thanks for the report! It seems to me treating tuples and lists differently is not desired here. This is due to: pandas/pandas/core/indexes/multi.py Line 591 in 4c3b968
and that code goes back to bc5a745. It appears this was not intentional. I'd suggest looking into replacing the |
take |
hey @rhshadrach, Here's the test result for <?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> |
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 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 ? |
I've tried doing that, even when manually converting The only solution I've found to make the tests pass is by adding |
Yes @siber64. Did not start yet. You can contribute early if you have the solution. |
Thanks, I can look later today, doesn't sound like Python problem |
@VishalSindham As I suspected it is just the behavior of zip, zip_longest fixes it. I'll take and do a PR |
take |
Has this issue been completed? If not could I take it? |
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. |
Alright appreciated 👍 I’ll get to work on this ASAP |
take |
…hen keys have varying entry counts
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! |
…hen keys have varying entry counts
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. |
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 |
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
…hen keys have varying entry counts
@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. |
take |
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 |
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)<#60695 (comment)>
Hi @ArneBinder<https://github.com/ArneBinder> @rhshadrach<https://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 GitHub<#60695 (comment)>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/AD3Z4PKNQHHHP67CZB7QOLT2QBMVDAVCNFSM6AAAAABVAHQGESVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRRGM2DOMZSGM>.
You are receiving this because you were assigned.
|
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 |
Only problem I found was with tuples
Sent from Outlook for Android<https://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 @siber64<https://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 GitHub<#60695 (comment)>, or unsubscribe<https://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)<#60695 (comment)>
Hi @siber64<https://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 GitHub<#60695 (comment)>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/AD3Z4PIYY4IUVULAJ2DAS4D2QCXTVAVCNFSM6AAAAABVAHQGESVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRRGQ4TIMBSGI>.
You are receiving this because you were mentioned.Message ID: ***@***.***>
|
@Anurag-Varma Yes, exactly, that's what I had in mind. |
Hi @rhshadrach I was trying to fix the bug but below test case was failing:
When I further tried to fix it, found out that the 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 ? |
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. |
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
Issue Description
When calling the
Series
constructor with a dict where the keys are tuples, a series withMulitIndex
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
The text was updated successfully, but these errors were encountered: