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

Python实现基于ID1、ID2的半年度/年度时间聚合求和

分号分隔TXT数据的半年度/年度聚合求和方案

问题背景

我有一个分号分隔的TXT数据文件,内容示例如下:

ID1;ID2;TIME;VALUE
1000;100;012021;12
1000;100;022021;4129
1000;100;032021;128
...(完整数据见原提问)

其中TIME字段格式为MMYYYY,需要按ID1+ID2分组,对VALUE执行半年度(每6个月)和年度的聚合求和操作。之前尝试的半年度处理代码存在问题,需要完整的Python实现方案。

原代码问题说明

你之前的代码仅按行号每6行截取子列表,既没有按ID1/ID2分组,也没有根据TIME字段判断所属半年度,完全不符合需求逻辑,因此无法得到正确结果。


方案一:纯Python实现(无第三方库依赖)

核心逻辑

  1. 解析TIME字段,拆分出月份和年份,判断所属半年度(1-6月为H1,7-12月为H2)
  2. 以(ID1, ID2)为键分组,存储每个分组的半年度、年度VALUE总和
  3. 按时间顺序输出聚合结果

完整代码

def parse_time(time_str):
    # 解析MMYYYY格式,返回(年份, 半年度标识)和年份
    month = int(time_str[:2])
    year = int(time_str[2:])
    half_year = "H1" if month <= 6 else "H2"
    return (year, half_year), year

# 初始化分组存储结构
group_data = {}

# 读取并处理数据
with open("file.txt", "r", encoding="utf-8") as f:
    # 跳过表头
    next(f)
    for line in f:
        line = line.strip()
        if not line:
            continue
        id1, id2, time_str, value = line.split(";")
        value = int(value)
        # 获取半年度和年度标识
        half_key, year_key = parse_time(time_str)
        group_key = (id1, id2)
        
        # 初始化分组数据
        if group_key not in group_data:
            group_data[group_key] = {
                "half_year": {},
                "year": {}
            }
        
        # 更新半年度求和
        if half_key not in group_data[group_key]["half_year"]:
            group_data[group_key]["half_year"][half_key] = 0
        group_data[group_key]["half_year"][half_key] += value
        
        # 更新年度求和
        if year_key not in group_data[group_key]["year"]:
            group_data[group_key]["year"][year_key] = 0
        group_data[group_key]["year"][year_key] += value

# 输出半年度结果
print("=== 半年度聚合结果 ===")
print("ID1;ID2;YEAR_HALF;TOTAL_VALUE")
for (id1, id2), aggregates in group_data.items():
    # 按年份和半年度排序
    for (year, half), total in sorted(aggregates["half_year"].items()):
        print(f"{id1};{id2};{year}{half};{total}")

# 输出年度结果
print("\n=== 年度聚合结果 ===")
print("ID1;ID2;YEAR;TOTAL_VALUE")
for (id1, id2), aggregates in group_data.items():
    # 按年份排序
    for year, total in sorted(aggregates["year"].items()):
        print(f"{id1};{id2};{year};{total}")

方案二:Pandas实现(高效简洁)

如果可以使用第三方库,Pandas能大幅简化代码,适合处理大规模数据:

完整代码

import pandas as pd

# 读取分号分隔的文件
df = pd.read_csv("file.txt", sep=";")

# 转换VALUE为数值类型
df["VALUE"] = pd.to_numeric(df["VALUE"], errors="coerce")

# 解析TIME字段,提取年份、月份和半年度
df["MONTH"] = df["TIME"].str[:2].astype(int)
df["YEAR"] = df["TIME"].str[2:].astype(int)
df["HALF_YEAR"] = df["MONTH"].apply(lambda x: "H1" if x <= 6 else "H2")
df["YEAR_HALF"] = df["YEAR"].astype(str) + df["HALF_YEAR"]

# 半年度聚合
half_year_result = df.groupby(["ID1", "ID2", "YEAR_HALF"])["VALUE"].sum().reset_index()
# 年度聚合
year_result = df.groupby(["ID1", "ID2", "YEAR"])["VALUE"].sum().reset_index()

# 输出结果
print("=== 半年度聚合结果 ===")
print(half_year_result.to_csv(sep=";", index=False))

print("\n=== 年度聚合结果 ===")
print(year_result.to_csv(sep=";", index=False))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:45:32