如何在groupby中实现类似于`value_counts()`的东西?

时间:2016-10-12 18:36:58

标签: python pandas dataframe

假设我有以下数据

Orchard    Tree
1           Apple
2           Peach
1           Peach
3           Apple

我如何按orchard进行分组,并显示每棵树在果园中出现的次数?结果看起来像

Tree     Apple  Peach
Orchard
1          1     1
2          0     1
3          1     0

2 个答案:

答案 0 :(得分:3)

pivot_table()你想要的是什么吗?

In [48]: df
Out[48]:
   Orchard   Tree
0        1  Apple
1        2  Peach
2        1  Peach
3        3  Apple

In [49]: df.pivot_table(index='Orchard', columns='Tree', aggfunc='size', fill_value=0)
Out[49]:
Tree     Apple  Peach
Orchard
1            1      1
2            0      1
3            1      0

或使用groupby()unstack()pivot_table()如何做到这一点:

In [57]: df.groupby(['Orchard','Tree']).size().unstack('Tree', fill_value=0)
Out[57]:
Tree     Apple  Peach
Orchard
1            1      1
2            0      1
3            1      0

答案 1 :(得分:3)

让我们不要忘记好的' value_counts
只需确保在Tree

之后减少到groupby
df.groupby('Orchard').Tree.value_counts().unstack(fill_value=0)

enter image description here