Python 分组并获取多个列的计数

Python 分组并获取多个列的计数,python,group-by,grouping,Python,Group By,Grouping,我有一个像 column_one columnn_two type column_three apple headphones one yes apple headphones two yes apple tv one no apple iPhones two yes apple iPad

我有一个像

column_one  columnn_two     type    column_three    
apple       headphones      one         yes
apple       headphones      two         yes
apple       tv              one         no
apple       iPhones         two         yes
apple       iPad            one         no
apple       iPad            two         no

我想把他们分成多行,让他们的数量

column_one  columnn_two     yes         no  
apple       headphones      2           0
apple       tv              0           1
apple       iPhones         1           0
apple       iPad            0           2

我知道如何进行分组,但不确定如何计算多行并将行转换为列以获得计数。

可能不是最有效的方法,但可能仍然有帮助:-)

我通过
apply()
使用了一个自定义聚合函数
sum\u col\u three(x)
,并通过
to\u frame()
将结果转换为一个新列。之后,我使用一个新的
DataFrame
tolist()
将元组拆分为两列:


可能不是最有效的方法,但可能仍然有帮助:-)

我通过
apply()
使用了一个自定义聚合函数
sum\u col\u three(x)
,并通过
to\u frame()
将结果转换为一个新列。之后,我使用一个新的
DataFrame
tolist()
将元组拆分为两列:

def sum_col_three(x):
    return sum(x['column_three']=='yes'), sum(x['column_three']=='no')

df = df.groupby(['column_one', 'column_two']).apply(sum_col_three).to_frame('yes')
df[['yes', 'no']] = pd.DataFrame(df['yes'].tolist(), index=df.index) 

df

>>                           yes    no
>>column_one    column_two      
>>apple         headphones   2      0
>>              iPad         0      2
>>              iPhones      1      0
>>              tv           0      1