python - 分配唯一年月组合的计数
问题描述
我想计算每封受尊重的电子邮件的独特组合的年月数
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。
解决方案
您需要对“电子邮件”进行分组并使用transform
withnunique
来获取广播到原始 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
推荐阅读
- python - SQLAlchemy 可以将 grouped_by 查询作为字典返回吗?
- bash - 如何在 sed 命令中使用带有 \ 的变量
- java - 如何在具有匹配属性的列表中查找元素的索引
- excel - 向自动 Outlook 邮件添加签名
- elasticsearch - ElasticSearch 匹配多词关键字标记化字段
- css - flex align 在本地主机上工作,但不在 github 上
- javascript - 如何使用 php 和 javascript 进行身份验证
- python - 如何使用python脚本并行运行多个函数
- mysql - 是否可以使用 TypeORM 和 Angular 6
- javascript - tensorflow.js 多元回归 sgd 中的错误最小化