用户在Python上对数据进行分组

时间:2017-03-05 21:55:14

标签: python pandas

我正在尝试按照另一列中的数据对一列中的数据进行分组,但我只想要来自特定时间范围的数据。所以让我们坐在2015-11-1到2016-4-30。我的数据库看起来像这样:

  account_id    employer_key    login_date
  1111111       google          2016-03-03 20:58:36.000000
  2222222       walmart         2015-11-18 11:52:56.000000
  2222222       walmart         2015-11-18 11:53:14.000000
  1111111       walmart         2016-04-06 23:29:04.000000
  3333333       walmart         2015-09-05 14:13:53.000000
  3333333       walmart         2016-01-28 03:20:58.000000
  2222222       walmart         2015-09-03 00:11:38.000000
  1111111       walmart         2015-09-03 00:12:25.000000
  1111111      dell_inc         2015-11-13 01:59:59.000000

我正在尝试获得类似这样的输出:

  account_id             login_date
  1111111                3
  2222222                2
  3333333                1

如何在特定时间窗口内获取account_id的唯一金额?

2 个答案:

答案 0 :(得分:2)

您可以先过滤DF,然后使用.groupby().count()

In [213]: df.query("'2015-11-01' <= login_date <= '2016-04-30'") \
            .groupby('account_id')['login_date'] \
            .count() \
            .reset_index()
Out[213]:
   account_id  login_date
0     1111111           3
1     2222222           2
2     3333333           1

或者您可以使用boolean indexingdf.loc[...])代替df.query(...),但它看起来有点笨......

答案 1 :(得分:1)

使用betweenvalue_counts

v = pd.value_counts(df.account_id[df.login_date.between('2015-11-01', '2016-04-30')])
v.rename_axis('account_id').reset_index(name='login_date')

   account_id  login_date
0     1111111           3
1     2222222           2
2     3333333           1