零值的 Pandas groupby [英] Pandas groupby for zero values
本文介绍了零值的 Pandas groupby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 csv 文件中有这样的数据
I have data like this in a csv file
Symbol Action Year
AAPL Buy 2001
AAPL Buy 2001
BAC Sell 2002
BAC Sell 2002
我可以像这样阅读它和分组
I am able to read it and groupby like this
df.groupby(['Symbol','Year']).count()
我明白了
Action
Symbol Year
AAPL 2001 2
BAC 2002 2
我想要这个(顺序无关紧要)
I desire this (order does not matter)
Action
Symbol Year
AAPL 2001 2
AAPL 2002 0
BAC 2001 0
BAC 2002 2
我想知道是否可以计算零次出现
I want to know if its possible to count for zero occurances
推荐答案
您可以使用 pivot_table
与 unstack
:
You can use pivot_table
with unstack
:
print df.pivot_table(index='Symbol',
columns='Year',
values='Action',
fill_value=0,
aggfunc='count').unstack()
Year Symbol
2001 AAPL 2
BAC 0
2002 AAPL 0
BAC 2
dtype: int64
如果您需要输出为 DataFrame
使用 to_frame
:
If you need output as DataFrame
use to_frame
:
print df.pivot_table(index='Symbol',
columns='Year',
values='Action',
fill_value=0,
aggfunc='count').unstack()
.to_frame()
.rename(columns={0:'Action'})
Action
Year Symbol
2001 AAPL 2
BAC 0
2002 AAPL 0
BAC 2
这篇关于零值的 Pandas groupby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文