我有一个像这样的数据帧
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,但不确定如何对多行进行计数,并将行转换为列以获得计数。
发布于 2019-05-10 07:24:56
可能不是最有效的方法,但也许它仍然有帮助:-)
我通过apply()使用了一个自定义聚合函数sum_col_three(x),并通过to_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 1https://stackoverflow.com/questions/56068296
复制相似问题