Python Groupby计数值为isin-0

Python Groupby计数值为isin-0,python,pandas,group-by,Python,Pandas,Group By,我希望将一些groupby方法传递给函数。使用下面的代码,我有一个包含一组列表的函数。然后我希望将这些列表中的任何一个传递给一个单独的groupby函数。下面,我希望将上传到groupbycount函数 通过这种方式,我可以在第一个函数中拥有任意数量的列表,就像用一行执行groupby一样 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',

我希望将一些groupby方法传递给函数。使用下面的代码,我有一个包含一组列表的函数。然后我希望将这些列表中的任何一个传递给一个单独的groupby函数。下面,我希望将
上传到
groupby
count
函数

通过这种方式,我可以在第一个函数中拥有任意数量的列表,就像用一行执行groupby一样

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]))
预期产出:

Label  A  B
Num        
1      3  0
2      1  1
Label   A   B
Num         
1       3   0
2       1   1
而不是这样做:

Up = counts(df, lists([0]))
这样做:

Up = counts(df, lists()[0])
现在,如果您向上打印
Up
,您将获得所需的输出:

Label  A  B
Num        
1      3  0
2      1  1
Label   A   B
Num         
1       3   0
2       1   1
解释:

在您的代码中:
Up=counts(df,list([0]))

您正在将一个
列表([0])
作为参数传递给
lists()
函数(实际需要 (无参数) 如果调用
lists()
函数,您将得到
列表的
元组

lists()

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