You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python通过12次循环实现月度数据聚合?(有周度代码参考)

Monthly Data Aggregation Implementation Guide

Overview

This guide adapts your existing weekly data aggregation code to generate monthly results via a 12-month loop.

Key Implementation Steps

  • Reuse your weekly aggregation logic within a loop over each month (1-12)
  • Filter weekly data to only include entries belonging to the current month
  • Validate each monthly result against raw data to catch discrepancies
  • Jump to Sample Code

Sample Monthly Aggregation Loop (Python)

# Your existing weekly aggregation function (example)
def aggregate_weekly_data(weekly_entries):
    return {
        'total_sales': sum(entry['sales'] for entry in weekly_entries),
        'avg_customers': sum(entry['customers'] for entry in weekly_entries) / len(weekly_entries)
    }

# Sample weekly data structure (replace with your actual data)
weekly_data = [
    {'month': 1, 'week': 1, 'sales': 1500, 'customers': 45},
    {'month': 1, 'week': 2, 'sales': 1800, 'customers': 52},
    # ... rest of weekly entries
]

# 12-month loop for monthly aggregation
monthly_aggregates = []
for month_num in range(1, 13):
    # Filter weeks for the current month
    month_weeks = [entry for entry in weekly_data if entry['month'] == month_num]
    if not month_weeks:
        # Handle months with no data
        monthly_aggregates.append({'month': month_num, 'total_sales': 0, 'avg_customers': 0})
        continue
    # Reuse weekly aggregation function
    monthly_stats = aggregate_weekly_data(month_weeks)
    monthly_stats['month'] = month_num
    monthly_aggregates.append(monthly_stats)

# Output results
for result in monthly_aggregates:
    print(f"Month {result['month']}: Sales = ${result['total_sales']}, Avg Customers = {result['avg_customers']:.1f}")

Critical Edge Cases to Consider

Months with no weekly data (e.g., a new business starting mid-year) should return default values instead of causing errors.

Visualization Reference

Here’s a placeholder for a monthly aggregation chart:
Monthly Sales Aggregation Chart

内容的提问来源于stack exchange,提问作者trizy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:35:28