The code below shows that regroup is passed a sub-frame of the original dataframe. This sub-frame has a column books yet when the function regroup attempts to call `df.groupby('books') an error is thrown even though the line right before the groupby printed the dataframe. So my question is:
How does one iterate over sub-frames of a groupby(expr) such that one can pass these sub-frames to another function and that function can also call groupby(expr) on that sub-frame and where expr is exactly the same for the initial and subsequent calls?
import pandas as pd
def divider():
print("-----------------------")
def section(label, start=True):
if not start:
label = f"<END {label}>"
else:
label = f"<BEGIN {label}>"
print(label)
def endsection(label):
section(label, start=False)
def regroup(df):
section("regroup")
print(f" input df={df}")
gb = df.groupby('books')
for group in gb:
_df = pd.DataFrame(group)
print(_df)
endsection("regroup")
df = pd.DataFrame({"books" : ["abc", "def", "abc", "xyz", "def"], #
"b" : [2, 5, 3, 2, 6],
"c" : [-5, 2, 1, 8, 2]})
print(df)
gb = df.groupby('books')
section("groups")
for group in gb:
_df = pd.DataFrame(group)
print(_df)
regroup(_df)
endsection("groups")