[英]Groupby count values isin - pandas
I'm hoping to pass some groupby methods to a function.我希望将一些 groupby 方法传递给 function。 Using below, I have a function that contains a set of lists.
使用下面,我有一个包含一组列表的 function。 I'm then hoping to pass any of those lists to a separate groupby function.
然后我希望通过 function 将这些列表中的任何一个传递给单独的组。 Below, I'm hoping to pass
Up
to the groupby
count
function.下面,我希望将
Up
传递给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.这样,我可以在第一个 function 中拥有任意数量的列表,就像可以用一行执行 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]))
intended output:预期 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:现在,如果您打印出来,您将获得所需的
Up
:
Label A B
Num
1 3 0
2 1 1
Explaination:解释:
In your code: Up = counts(df, lists([0]))
在您的代码中:
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
您将
list([0])
作为参数传递给lists()
function (实际上没有参数),如果您调用lists()
function 您将得到一个lists
tuple
lists()
#output
(['Up1', 'Up2', 'Up3', 'Up4'],
['Down1', 'Down1', 'Down1', 'Down1'],
['Up', 'Up', 'Up', 'Up'],
['Down1', 'Down1', 'Down1', 'Down1'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.