gpt4 book ai didi

python - Pandas :重新采样后计算唯一值

转载 作者:太空狗 更新时间:2023-10-30 01:15:14 24 4
gpt4 key购买 nike

我刚刚开始使用 Pandas 并尝试组合:按日期对我的数据进行分组,并计算每组中的唯一值。

这是我的数据:

                  User, Type
Datetime
2014-04-15 11:00:00, A, New
2014-04-15 12:00:00, B, Returning
2014-04-15 13:00:00, C, New
2014-04-20 14:00:00, D, New
2014-04-20 15:00:00, B, Returning
2014-04-20 16:00:00, B, Returning
2014-04-20 17:00:00, D, Returning

这就是我想要做的:将日期时间索引重新采样到当天(我可以这样做),并且还计算每天的唯一用户数。我对“类型”列还不感兴趣。

Day, Unique Users
2014-04-15, 3
2014-04-20, 2

我正在尝试 df.user.resample('D', how='count').unique 但它似乎没有给我正确的答案。

最佳答案

您无需重新采样即可在问题中获得所需的输出。我认为您可以在日期上使用 groupby 来解决问题:

print df.groupby(df.index.date)['User'].nunique()

2014-04-15 3
2014-04-20 2
dtype: int64

然后,如果您愿意,可以在计算唯一用户数后重新采样以填补时间序列空白:

cnt = df.groupby(df.index.date)['User'].nunique()
cnt.index = cnt.index.to_datetime()
print cnt.resample('D')

2014-04-15 3
2014-04-16 NaN
2014-04-17 NaN
2014-04-18 NaN
2014-04-19 NaN
2014-04-20 2
Freq: D, dtype: float64

关于python - Pandas :重新采样后计算唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23208368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com