在Python中计数和分组

时间:2017-03-06 23:39:03

标签: python count group-by

我创建了以下代码,该代码计算一个人(通过他们的login_id)在一年内登录程序的次数。

def ytSearchLaunch(video_id, added_actions=[]):
  if len(added_actions)==0: # first time
      a1 = argparser.add_argument("--q", help="Search term", default=video_id)
      a2 = argparser.add_argument("--max-results", help="Max results", default=25)
      added_actions.append(a1)
      added_actions.append(a2)
  else:         # repeats
      # change defaults to the -q argument without adding a new one
      added_actions[0].default = video_id
  args = argparser.parse_args()
  youtube_search(args)

输出看起来像这样:

data1.query("'2015-12-01' <= login_date <= '2016-12-01'").groupby(['employer_key','account_id']).size().reset_index().groupby(['employer_key','account_id'])[[0]].count()

我想计算每个单独的employer_key的account_id数量,以便我可以确定每个雇主在一年内登录的帐户数量。

输出有望看起来像这样:

employer_key   account_id  # times logged in
 Apple            X1             1
 Google           Y5             2
 Facebook         X3             4
 Apple            X2             2
 Facebook         Y2             1

1 个答案:

答案 0 :(得分:1)

我想这应该有效:

data.groupby(['employer_key','account_id']).count().\
             unstack().sum(axis=1).astype(int)
#employer_key
#Apple       2
#Facebook    2
#Google      1
#dtype: int64