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
#!/usr/bin/env python
import argparse
import pandas as pd
def main(args):
df_data = {
"A": ["A1", "A2", "A3", "A1"],
"B": ["B1", "B2", "B3", "B1"],
"C": [1.1, 1.2, 1.3, 1.4]
}
df = pd.DataFrame(df_data)
as_index = args.as_index
print("df:")
print(df)
print('---------')
print(f"Non-Category: Groupby non-agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index)["C"].sum()
print(gdf)
print('---------')
print(f"Non-Category: Groupby agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index).agg({"C": "sum"})
print(gdf)
print('---------')
df["A"] = df["A"].astype("category")
df["B"] = df["B"].astype("category")
print(f"Category: Groupby non-agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index)["C"].sum()
print(gdf)
print('---------')
print(f"Category: Groupby agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index).agg({"C": "sum"})
print(gdf)
print('---------')
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Main script",
epilog="Example usage: python test_gb_with_cats.py filename",
)
parser.add_argument("--as-index", default=False, action="store_true")
args = parser.parse_args()
main(args)
Issue Description
When using cateogry types as gb columns with as_index=True
Both df.groupby
and df.groupby.agg
work but the result seems to have all permutations of the underyling categories.
See output of reproducible example below
df:
A B C
0 A1 B1 1.1
1 A2 B2 1.2
2 A3 B3 1.3
3 A1 B1 1.4
---------
Non-Category: Groupby non-agg, as_index=True
A B
A1 B1 2.5
A2 B2 1.2
A3 B3 1.3
Name: C, dtype: float64
---------
Non-Category: Groupby agg, as_index=True
C
A B
A1 B1 2.5
A2 B2 1.2
A3 B3 1.3
---------
Category: Groupby non-agg, as_index=True
A B
A1 B1 2.5
B2 0.0
B3 0.0
A2 B1 0.0
B2 1.2
B3 0.0
A3 B1 0.0
B2 0.0
B3 1.3
Name: C, dtype: float64
---------
Category: Groupby agg, as_index=True
C
A B
A1 B1 2.5
B2 0.0
B3 0.0
A2 B1 0.0
B2 1.2
B3 0.0
A3 B1 0.0
B2 0.0
B3 1.3
---------
When using cateogry types as gb columns with as_index=False
df.groupby
works but again the result seems to have all permutations of the underyling categories.
However, df.groupby.agg
fails with a crpytic error message like
ValueError: Length of values (3) does not match length of index (9)
Expected Behavior
Both groupby
and groupby.agg
should work with/without as_index
and shouldn't do a cross join on the underlying categories
Installed Versions
Comment From: samukweku
@RogerThomas if you pass observed=True
for categorical group by, is there any change?
Comment From: RogerThomas
Yes indeed @samukweku passing observed=True
for the categorical group bys does indeed fix the issue, i.e.:
#!/usr/bin/env python
import argparse
import pandas as pd
def main(args):
df_data = {
"A": ["A1", "A2", "A3", "A1"],
"B": ["B1", "B2", "B3", "B1"],
"C": [1.1, 1.2, 1.3, 1.4]
}
df = pd.DataFrame(df_data)
as_index = args.as_index
print("df:")
print(df)
print('---------')
print(f"Non-Category: Groupby non-agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index)["C"].sum()
print(gdf)
print('---------')
print(f"Non-Category: Groupby agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index).agg({"C": "sum"})
print(gdf)
print('---------')
df["A"] = df["A"].astype("category")
df["B"] = df["B"].astype("category")
print(f"Category: Groupby non-agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index, observed=True)["C"].sum()
print(gdf)
print('---------')
print(f"Category: Groupby agg, as_index={as_index}")
gdf = df.groupby(["A", "B"], as_index=as_index, observed=True).agg({"C": "sum"})
print(gdf)
print('---------')
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Main script",
epilog="Example usage: python test_gb_with_cats.py filename",
)
parser.add_argument("--as-index", default=False, action="store_true")
args = parser.parse_args()
main(args)
Comment From: rhshadrach
Thanks for the report! For observed=False
(the default), this is expected behavior. For agg
raising on categories with as_index=False
, this is a duplicate of #36698. Closing.