gpt4 book ai didi

python - 使用 'how=count' 重新采样导致问题

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

我有一个简单的 pandas 数据框,它在不同时间都有测量值:

                     volume
t
2013-10-13 02:45:00 17
2013-10-13 05:40:00 38
2013-10-13 09:30:00 29
2013-10-13 11:40:00 25
2013-10-13 12:50:00 11
2013-10-13 15:00:00 17
2013-10-13 17:10:00 15
2013-10-13 18:20:00 12
2013-10-13 20:30:00 20
2013-10-14 03:45:00 9
2013-10-14 06:40:00 30
2013-10-14 09:40:00 43
2013-10-14 11:05:00 10

我正在做一些基本的重采样和绘图,例如每日总体积,效果很好:

df.resample('D',how='sum').head()   

volume
t
2013-10-13 184
2013-10-14 209
2013-10-15 197
2013-10-16 309
2013-10-17 317

但出于某种原因,当我尝试计算每天的条目总数时,它返回一个多索引系列而不是数据框:

df.resample('D',how='count').head()

2013-10-13 volume 9
2013-10-14 volume 9
2013-10-15 volume 7
2013-10-16 volume 9
2013-10-17 volume 10

我可以修复数据,以便通过简单的 unstack 调用轻松绘制它,即 df.resample('D',how='count').unstack(),但为什么调用 resample使用 how='count' 的行为与使用 how='sum' 的行为不同?

最佳答案

resamplecount 确实在结果数据帧的结构方面导致了一些奇怪的行为(好吧,至少达到 0.13.1)。请参阅此处了解略有不同但相关的上下文:Count and Resampling with a mutli-ndex

您可以使用相同的策略 这里:

>>> df
volume
date
2013-10-13 02:45:00 17
2013-10-13 05:40:00 38
2013-10-13 09:30:00 29
2013-10-13 11:40:00 25
2013-10-13 12:50:00 11
2013-10-13 15:00:00 17
2013-10-13 17:10:00 15
2013-10-13 18:20:00 12
2013-10-13 20:30:00 20
2013-10-14 03:45:00 9
2013-10-14 06:40:00 30
2013-10-14 09:40:00 43
2013-10-14 11:05:00 10

所以这是你的问题:

>>> df.resample('D',how='count')

2013-10-13 volume 9
2013-10-14 volume 4

您可以通过在 resample 调用中使用字典指定 count 应用于 volume 列来解决此问题:

>>> df.resample('D',how={'volume':'count'})

volume
date
2013-10-13 9
2013-10-14 4

关于python - 使用 'how=count' 重新采样导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745656/

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