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屋!
查看全文