如何在考虑其他列时使用.value_count()行?

时间:2016-12-16 13:45:44

标签: python python-3.x pandas dataframe jupyter-notebook

我有一个这样的数据框:

  date   post 
   da1     a 
   da1     b
   da2     a
   da3     c
   da1     d
   da1     a

我想做的是:

    date post total
     da1   a     2
     da1   b     1
     da2   a     1
     da3   c     1
     da1   d     1

我试过了:

    df.groupby(["date","post"]).count().sort_values(['index'], ascending=0)

然后按顺序对其进行排序,但我无法通过以下方式访问日期/帖子值: df.date df.post ,因为所有日期/帖子成为他们自己的"键"总计的价值。

我必须通过标题访问列中的值 - 我该怎么做呢?

1 个答案:

答案 0 :(得分:3)

我认为你需要:

print (df.groupby(["date","post"]).size().reset_index(name='total'))
  date post  total
0  da1    a      2
1  da1    b      1
2  da1    d      1
3  da2    a      1
4  da3    c      1

What is the difference between size and count in pandas?

相关问题