如何计算pandas Dataframe中分类数据的子组?

时间:2017-03-02 18:31:51

标签: python pandas dataframe

我有以下pandas数据帧:

import pandas as pd
import numpy as np
df = pd.DataFrame({"shops": ["shop1", "shop2", "shop3", "shop4", "shop5", "shop6"], "franchise" : ["franchise_A", "franchise_A", "franchise_A", "franchise_A", "franchise_B", "franchise_B"],"items" : ["dog", "cat", "dog", "dog", "bird", "fish"]})
df = df[["shops", "franchise", "items"]]
print(df)

   shops    franchise items
0  shop1  franchise_A   dog
1  shop2  franchise_A   cat
2  shop3  franchise_A   dog
3  shop4  franchise_A   dog
4  shop5  franchise_B  bird
5  shop6  franchise_B  fish

因此,每行都是一个独特的样本shop1shop2等,其中每个样本属于一个子群franchise_Afranchise_Bfranchise_C,等等 在items列中,可能只有四个分类值:dogcatfishbird。我的动机是为每个“特许经营权”创建一个dogcatfishbird数量的条形图。

我希望输出为

franchise        dogs    cats    birds    fish
franchise_A      3       1       0        0
franchise_B      0       0       1        1

我相信我首先必须使用groupby(),例如

df.groupby("franchise").count()
             shops  items
franchise                
franchise_A      4      4
franchise_B      2      2

但我不确定我如何计算每个特许经营项目的数量。

2 个答案:

答案 0 :(得分:4)

您可以value_counts使用unstack,感谢Nickil Maveli

from collections import Counter

print (df.groupby("franchise")['items'].value_counts().unstack(fill_value=0))
items        bird  cat  dog  fish
franchise                        
franchise_A     0    1    3     0
franchise_B     1    0    0     1

crosstabpivot_table的其他解决方案:

print (pd.crosstab(df["franchise"], df['items']))
items        bird  cat  dog  fish
franchise                        
franchise_A     0    1    3     0
franchise_B     1    0    0     1
print (df.pivot_table(index="franchise", columns='items', aggfunc='size', fill_value=0))
items        bird  cat  dog  fish
franchise                        
franchise_A     0    1    3     0
franchise_B     1    0    0     1

答案 1 :(得分:3)

您可以在groupby中添加items列,然后使用size

>>> df.groupby(['franchise', 'items']).size().unstack(fill_value=0)

items        bird  cat  dog  fish
franchise                        
franchise_A     0    1    3     0
franchise_B     1    0    0     1

粗略)基准

%timeit df.groupby(['franchise', 'items']).size().unstack(fill_value=0)
100 loops, best of 3: 2.73 ms per loop

%timeit (df.groupby("franchise")['items'].apply(Counter).unstack(fill_value=0).astype(int))
100 loops, best of 3: 4.18 ms per loop

%timeit df.groupby('franchise')['items'].value_counts().unstack(fill_value=0)
100 loops, best of 3: 2.71 ms per loop