如何在groupby中实现类似于“value\u counts()”的功能?

2024-06-17 16:15:01 发布

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

假设我有以下数据

Orchard    Tree
1           Apple
2           Peach
1           Peach
3           Apple

我怎样才能按orchard分组并显示每棵树在果园中出现的次数?结果看起来像

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

Tags: 数据treeapple次数peachorchard果园
2条回答

让我们不要忘记美好的时光value_counts
只需确保在groupby之后减少到Tree

df.groupby('Orchard').Tree.value_counts().unstack(fill_value=0)

enter image description here

你想要什么?你知道吗

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

相关问题 更多 >