You can use the following methods to get a specific group after using the groupby() function on a pandas DataFrame:
Method 1: Get Group After Using groupby()
grouped_df.get_group('A')
Method 2: Get Specific Columns of Group After Using groupby()
grouped_df[['column1', 'column3']].get_group('A')
The following examples show how to use each method in practice with the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'store': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'sales': [12, 15, 24, 24, 14, 19, 12, 38], 'refunds': [4, 8, 7, 7, 10, 5, 4, 11]}) #view DataFrame print(df) store sales refunds 0 A 12 4 1 A 15 8 2 A 24 7 3 A 24 7 4 B 14 10 5 B 19 5 6 B 12 4 7 B 38 11
Example 1: Get Group After Using groupby()
The following code shows how to use the groupby() function to group the rows by store name, then use the get_group() function to retrieve all rows that belong to the group with the group name ‘A’:
#group rows of DataFrame based on value in 'store' column
grouped_stores = df.groupby(['store'])
#get all rows that belong to group name 'A'
grouped_stores.get_group('A')
store sales refunds
0 A 12 4
1 A 15 8
2 A 24 7
3 A 24 7
Notice that get_group() returns all rows that belong to the group with the group name ‘A’.
Example 2: Get Specific Columns of Group After Using groupby()
The following code shows how to use the groupby() function to group the rows by store name, then use the get_group() function to retrieve all rows that belong to the group with the group name ‘A’ only for the ‘sales’ and ‘refunds’ columns:
#group rows of DataFrame based on value in 'store' column
grouped_stores = df.groupby(['store'])
#get all rows that belong to group name 'A' for sales and refunds columns
grouped_stores[['store', 'refunds']].get_group('A')
store refunds
0 A 4
1 A 8
2 A 7
3 A 7
Notice that get_group() returns all rows that belong to the group with the group name ‘A’ for the ‘sales’ and ‘refunds’ columns only.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Perform a GroupBy Sum in Pandas
How to Use Groupby and Plot in Pandas
How to Count Unique Values Using GroupBy in Pandas