python - 零值的 Pandas groupby

标签 python pandas dataframe group-by

我在一个csv文件中有这样的数据

Symbol  Action  Year
  AAPL     Buy  2001
  AAPL     Buy  2001
   BAC    Sell  2002
   BAC    Sell  2002

我可以像这样阅读和分组

df.groupby(['Symbol','Year']).count()

我明白了

             Action
Symbol Year        
AAPL   2001       2
BAC    2002       2

我想要这个(顺序无关紧要)

             Action
Symbol Year        
AAPL   2001       2
AAPL   2002       0
BAC    2001       0
BAC    2002       2

我想知道是否可以计算零次出现

最佳答案

你可以使用这个:

df = df.groupby(['Symbol','Year']).count().unstack(fill_value=0).stack()
print (df)

输出:

             Action
Symbol Year        
AAPL   2001       2
       2002       0
BAC    2001       0
       2002       2

关于python - 零值的 Pandas groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003100/

相关文章:

python - 使用 python 获取所有 pytest 节点 ID 的列表

python - 如果在 python 中,需要减少多个 else

python - 插入mysql数据库,pymysql无法插入

python - 有没有一种方法可以以有吸引力的方式自动呈现 pandas Dataframes

python - Pandas : select row where column A does not begin with column B

Python - 列表中每个项目后的换行符

python - 使用最大日期字段和收入字段按类别进行新列计算

python - Pandas 数学运算,以列值为条件

python - pandas:如何从使用 iterrows() 提取的行创建 DataFrame?

python - 使用 loc 对 Pandas DataFrame 进行选择性操作,而不覆盖未选定的行