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
df = pd.DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}).set_index("a")
df.columns = pd.MultiIndex.from_tuples([("b",)])
# Works
df.groupby("a")[("b",)].sum()
df.columns = pd.MultiIndex.from_tuples([("b", 1)])
# Fails
df.groupby("a")[("b", 1)].sum()
# "ValueError: Cannot subset columns with a tuple with more than one element. Use a list instead.".
Issue Description
Prior to 1.0.0, passing a multi-element tuple to DataFrameGroupBy
was treated as passing a list of the tuple elements (e.g., df_gb[("a", "b")] === df_gb[["a", "b"]] === df_gb["a", "b"]
). The ability to pass multi-element tuples was deprecated with a FutureWarning
in 1.0.0, and removed in 2.0.0 (see #30546).
A related behavior is that passing a tuple to a non-MultiIndexed DataFrame is allowed (see #36302)
Expected Behavior
There should be no difference between the two examples above. DataFrameGroupBy.__getitem__(tuple)
should match DataFrame.__getitem__(tuple)
:
- If
len(tuple) < df.columns.nlevels
, return aDataGrameGroupBy
selecting the columns that match the first n levels (and reduce the column level depth bylen(tuple)
- If
len(tuple) == df.columns.nlevels
, return aSeriesGroupBy
- If
len(tuple) > df.columns.nlevels
, raise an error.
Installed Versions
Comment From: rhshadrach
Thanks for opening this!
2. If
len(tuple) == df.columns.nlevels
, return aSeriesGroupBy
Small nit: if there are duplicates in the columns, then we wouldn't necessarily return a SeriesGroupBy
.
Matching DataFrame.__getitem__
makes a lot of sense to me, +1.
Comment From: fxjung
As I just ran into the exact same problem, I would volunteer to work on this.