Pandas:分块时计算每日统计数据
考虑一个 postgres 表,其中对于 2022 年 5 月 1 日的日期,我们有 200 个不同时间的值:
time value
2022-05-01 00:17:20+00:00 17175
2022-05-01 13:33:56+00:00 18000
...
我需要使用 chunk_size = 50 逐块读取数据。进行重采样和聚合来计算每日统计信息,会产生四个相同的索引其中每个包含聚合值的一部分。
with engine.connect().execution_options(stream_results=True) as conn:
for chunk_df in pd.read_sql(query, engine, chunksize=50):
chunk_df.index = pd.to_datetime(chunk_df.time, utc=pytz.utc)
chunk_df.sort_index(inplace=True)
result_df = chunk_df.resample('1D').agg('sum')
time value
2022-05-01 00:00:00+00:00 52175
time value
2022-05-01 00:00:00+00:00 12001
time value
2022-05-01 00:00:00+00:00 3506
time value
2022-05-01 00:00:00+00:00 45623
我想知道是否有任何解决方案可以直接计算正确的聚合值。换句话说,我们如何根据重采样过程的时间间隔来设置块大小。
time value
2022-05-01 00:00:00+00:00 113305
Consider a postgres table where for the date 2022-05-01 we have 200 values for various times:
time value
2022-05-01 00:17:20+00:00 17175
2022-05-01 13:33:56+00:00 18000
...
I need to read data chunk by chunk with a chunk_size = 50. Doing resampling and aggregation to compute daily statistics, results in the four same indexes where each one contains a portion of the aggregated value.
with engine.connect().execution_options(stream_results=True) as conn:
for chunk_df in pd.read_sql(query, engine, chunksize=50):
chunk_df.index = pd.to_datetime(chunk_df.time, utc=pytz.utc)
chunk_df.sort_index(inplace=True)
result_df = chunk_df.resample('1D').agg('sum')
time value
2022-05-01 00:00:00+00:00 52175
time value
2022-05-01 00:00:00+00:00 12001
time value
2022-05-01 00:00:00+00:00 3506
time value
2022-05-01 00:00:00+00:00 45623
I was wondering is there any solution that directly computes the correct aggregated value. In other words, how we can set the chunk size according to the time interval of the resampling process.
time value
2022-05-01 00:00:00+00:00 113305
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我得到了你想要的,这样的查询应该可以解决问题:
你还可以添加
If I got what you want right, a query like this should do the trick:
You can also add
order by 1 asc/desc
to sort itwhere date_trunc('day', time) = '2020-03-16 00:00:00'
to filter by date