-2

Say I have a simple dataframe with the names of people. I perform a groupby on name

import pandas as pd

df = pd.DataFrame({'col1' : [1,2,3,4,5,6,7], 'name': ['George', 'John', 'Tim', 'Joe', 'Issac', 'George', 'Tim'] })

df1 = df.groupby('name')

Question: How can I select specific names out during the groupby name given a list of those names?

e.g say I have the following list

list = ['John', 'Tim', 'George']

Attempted:

list
df1 = df[df['name'].isin(list)].groupby('name')

How could we group by name and output the entries which have names given in the list? Any alternative ways of doing this will be helpful. For example, can perform this in the group by of extract values in the list after the group by has been performed.

Curious
  • 325
  • 1
  • 10

1 Answers1

-1

If you have to do the filtering after the grouping -

for group, group_df in df1:
    if group in ['John', 'Tim', 'George']:
        print(group_df)
#       col1    name
#    0     1  George
#    5     6  George
#       col1  name
#    1     2  John
#       col1 name
#    2     3  Tim
#    6     7  Tim
Mortz
  • 4,654
  • 1
  • 19
  • 35