【问题标题】:How to .value_count() rows while taking into account other columns?如何在考虑其他列的同时 .value_count() 行?
【发布时间】:2017-05-02 08:02:11
【问题描述】:

我有一个这样的数据框:

  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.datedf.post 访问日期/发布值作为所有日期/帖子成为他们自己的“关键”,这些价值总计。

我必须通过它们的标题访问列中的值 - 我应该如何去做?

【问题讨论】:

  • 在结果上调用reset_index()df.groupby(["date","post"]).count().sort_values(['index'], ascending=0).result_index()

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


【解决方案1】:

我认为你需要:

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?

【讨论】:

  • 你还需要sort_index()吗?
猜你喜欢
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
相关资源
最近更新 更多