I have a DataFrame that contains objects and items belonging to the objects. Items have additional data (not shown) and multiple items can belong to one object.
df = pd.DataFrame(
{
"object_id": [1, 1, 1, 1, 1, 2, 2, 2],
"item_id": [1, 2, 4, 4, 5, 1, 1, 2],
"item_count": [6, 6, 6, 6, 6, 3, 3, 3],
}
)
I now want to group by the object_id
and extract information from the associated items. While this works, it does not add items that are not already in the DataFrame (i.e. "0" values).
df_group = df.groupby(["object_id", "item_id"], as_index=False).size()
>>> df_group
object_id item_id size
0 1 1 1
1 1 2 1
# e.g. item 3 missing
2 1 4 2
3 1 5 1
4 2 1 2
5 2 2 1
I now wanted to find out if there is a way to expand the groupby given the item_counts
. My current naive approach is to create an dataframe list and merge the groupby afterwards:
all_items = [
dict(object_id=entity, item_id=obj + 1)
for entity in df["object_id"].unique()
for obj in range(df.loc[df["object_id"] == entity, "item_count"].iloc[0])
]
df_full = pd.DataFrame(all_items).merge(df_group, how="left").fillna(0).astype({"size": "int"})
>>> df_full
object_id item_id size
0 1 1 1
1 1 2 1
2 1 3 0
3 1 4 2
4 1 5 1
5 1 6 0
6 2 1 2
7 2 2 1
8 2 3 0