简体   繁体   中英

Groupby count values isin - pandas

I'm hoping to pass some groupby methods to a function. Using below, I have a function that contains a set of lists. I'm then hoping to pass any of those lists to a separate groupby function. Below, I'm hoping to pass Up to the groupby count function.

This way I can have any amount of lists within the first function as can perform a groupby with a single line.

df = pd.DataFrame({      
    'Num' : [1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2],
    'Label' : ['A','B','A','B','B','B','A','B','B','A','A','A','B','A','B','A'],   
    'Item' : ['Up1','Left2','Up2','Left3','Down1','Right2','Up2','Down4','Right2','Down1','Right2','Up1','Up3','Right4','Down2','Left2'],        
   })

def lists():

    Up = ['Up1', 'Up2', 'Up3', 'Up4']

    Down = ['Down1', 'Down1', 'Down1', 'Down1']

    Left = ['Up', 'Up', 'Up', 'Up']

    Right = ['Down1', 'Down1', 'Down1', 'Down1']

    return Up, Down, Left, Right


def counts(df, direction):

    df = (df[df['Item'].isin(direction)]
                  .groupby(['Num','Label'])['Item']
                  .count()
                  .unstack( 
                  fill_value = 0)
                  )

return df

 Up = counts(df, lists([0]))

intended output:

Label  A  B
Num        
1      3  0
2      1  1

Instead of doing this:

Up = counts(df, lists([0]))

Do this:

Up = counts(df, lists()[0])

Now if you print Up you will get your desired output:

Label   A   B
Num         
1       3   0
2       1   1

Explaination:

In your code: Up = counts(df, lists([0]))

You are passing a list([0]) as a parameter to lists() function (Which actually takes no parameter) and if you call lists() function you will get a tuple of lists

lists()

#output
(['Up1', 'Up2', 'Up3', 'Up4'],
 ['Down1', 'Down1', 'Down1', 'Down1'],
 ['Up', 'Up', 'Up', 'Up'],
 ['Down1', 'Down1', 'Down1', 'Down1'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM