2024-06-17 16:15:01 发布
网友
假设我有以下数据
Orchard Tree 1 Apple 2 Peach 1 Peach 3 Apple
我怎样才能按orchard分组并显示每棵树在果园中出现的次数?结果看起来像
orchard
Tree Apple Peach Orchard 1 1 1 2 0 1 3 1 0
让我们不要忘记美好的时光value_counts 只需确保在groupby之后减少到Tree
value_counts
groupby
Tree
df.groupby('Orchard').Tree.value_counts().unstack(fill_value=0)
你想要什么?你知道吗
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()在引擎盖下的方式):
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
让我们不要忘记美好的时光
value_counts
只需确保在
groupby
之后减少到Tree
你想要什么?你知道吗
或者使用
groupby()
和unstack()
(这就是pivot_table()
在引擎盖下的方式):相关问题 更多 >
编程相关推荐