首页 > 解决方案 > 分配唯一年月组合的计数

问题描述

我想计算每封受尊重的电子邮件的独特组合的年月数

test_df = pd.DataFrame(
    data={'email': ['a', 'a', 'b', 'b', 'c', 'c', 'c'], 
          'purchases': ['2016-08-25 01:09:42',
                        '2016-08-23 13:30:20',
                        '2018-10-23 05:33:15',
                        '2016-09-20 17:41:04',
                        '2017-04-09 17:59:00',
                        '2018-02-25 15:14:53',
                        '2016-02-25 15:14:53']})
test_df['purchases'] = pd.to_datetime(test_df['purchases'], yearfirst=True)

在此之后,我有这个带有purchases时间戳的 DF

   email    purchases
0   a   2016-08-25 01:09:42
1   a   2016-08-23 13:30:20
2   b   2018-10-23 05:33:15
3   b   2016-09-20 17:41:04
4   c   2017-04-09 17:59:00
5   c   2018-02-25 15:14:53
6   c   2016-02-25 15:14:53

在此之后,我计算月数并将值分配给新列months_of_active

test_df['months_of_active'] = 
pd.DatetimeIndex(test_df.purchases).to_period("M").nunique()

这将创建下一个输出:

   email    purchases       months_of_active
0   a   2016-08-25 01:09:42   6
1   a   2016-08-23 13:30:20   6
2   b   2018-10-23 05:33:15   6
3   b   2016-09-20 17:41:04   6
4   c   2017-04-09 17:59:00   6
5   c   2018-02-25 15:14:53   6
6   c   2016-02-25 15:14:53   6

所需的输出是:

   email    purchases      months_of_active
0   a   2016-08-25 01:09:42   1
1   a   2016-08-23 13:30:20   1
2   b   2018-10-23 05:33:15   2
3   b   2016-09-20 17:41:04   2
4   c   2017-04-09 17:59:00   3
5   c   2018-02-25 15:14:53   3
6   c   2016-02-25 15:14:53   3

a= 1 因为有两个相似的月份 b= 2 因为有两个不同的月份 c= 2 因为有两个不同的月份(2 个相同,1 个另一个)

无法理解,在上面的函数中添加什么来对过滤后的系列执行 to_period()。

更新:我确实需要考虑年数,2017-1并将2018-1计为 2。

标签: pythonpandasdatetimedataframe

解决方案


您需要对“电子邮件”进行分组并使用transformwithnunique来获取广播到原始 DataFrame 行的唯一计数:

s = pd.Series(pd.DatetimeIndex(df.purchases).to_period('M'), index=df.index)
df['months_of_active'] = s.groupby(df.email).transform('nunique')


df
  email           purchases  months_of_active
0     a 2016-08-25 01:09:42                 1
1     a 2016-08-23 13:30:20                 1
2     b 2018-10-23 05:33:15                 2
3     b 2016-09-20 17:41:04                 2
4     c 2017-04-09 17:59:00                 3
5     c 2018-02-25 15:14:53                 3
6     c 2016-02-25 15:14:53                 3

或者,使用dt.strftime获取年月组合:

df['months_of_active'] = (
   df.purchases.dt.strftime('%Y-%m').groupby(df.email).transform('nunique'))

df
  email           purchases  months_of_active
0     a 2016-08-25 01:09:42                 1
1     a 2016-08-23 13:30:20                 1
2     b 2018-10-23 05:33:15                 2
3     b 2016-09-20 17:41:04                 2
4     c 2017-04-09 17:59:00                 3
5     c 2018-02-25 15:14:53                 3
6     c 2016-02-25 15:14:53                 3

推荐阅读