分组并获取多列的计数

2024-10-03 13:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧

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

我知道如何进行groupby,但不知道如何计算多行并将行转换为列以获得计数


Tags: 数据noappletypecolumntvoneyes
1条回答
网友
1楼 · 发布于 2024-10-03 13:17:41

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

我通过apply()使用了一个定制的聚合函数sum_col_three(x),并通过to_frame()将结果转换为一个新的列。之后,我用新的DataFrametolist()将元组拆分为两个独立的列:

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

相关问题 更多 >