Search code examples
python-3.xdataframegroup-by

Print a groupby object for a specific group/groups only


I need to print the result of groupby object in Python for a specific group/groups only.

Below is the dataframe:

import pandas as pd
df = pd.DataFrame({'ID'    : [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
                   'Entry' : [1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]})
print("\n df = \n",df)

In order to group the dataferame by ID and print the result I used these codes:

grouped_by_unit = df.groupby(by="ID")
print("\n", grouped_by_unit.apply(print)) 

Can somebody please let me know below two things:

  1. How can I print the data frame grouped by 'ID=1' only? I need to get the below output:

enter image description here

  1. Likewise, how can I print the data frame grouped by 'ID=1' and 'ID=4' together? I need to get the below output:

enter image description here


Solution

  • You can iterate over the groups for example with for-loop:

    grouped_by_unit = df.groupby(by="ID")
    
    for id_, g in grouped_by_unit:
        if id_ == 1 or id_ == 4:
            print(g)
            print()
    

    Prints:

       ID  Entry
    0   1      1
    1   1      2
    2   1      3
    3   1      4
    
        ID  Entry
    12   4      1
    13   4      2
    14   4      3
    15   4      4
    16   4      5
    17   4      6