How to apply groupby on a sub-frame of a dataframe using the same groupby call that was used to create the sub-frame

Viewed 145

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")
1 Answers

You can just do:

def regroup(df):
    section("regroup")
    print(f"   input df={df}")
    gb = df.groupby('books')

    # differences lie here
    for book, group in gb:
        _df = pd.DataFrame(group)
        print(_df)
    endsection("regroup")

Output:

<BEGIN regroup>
   input df=  books  b  c
0   abc  2 -5
1   def  5  2
2   abc  3  1
3   xyz  2  8
4   def  6  2
  books  b  c
0   abc  2 -5
2   abc  3  1
  books  b  c
1   def  5  2
4   def  6  2
  books  b  c
3   xyz  2  8
<END regroup>
Related