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

Python处理大型CSV文件:拆分数据实现分类排序需求

解决CSV数据拆分与后续处理方案

一、替换手动拆分,使用专业CSV解析库

你当前用line.split(",")手动拆分CSV的方式很容易出错——如果字段里包含逗号(比如带双引号的"Congo, Democratic Republic of"),拆分结果会完全混乱。直接用Python内置的csv模块更可靠:

import csv

# 读取带表头的CSV文件
with open("your_file.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)  # 自动识别表头,按字段名取值
    for row in reader:
        country = row["国家"]  # 替换成你CSV实际的表头名
        abv = row["缩写"]
        year = int(row["年份"])
        expectancy = float(row["预期寿命"])
        # 后续处理逻辑

如果你的CSV没有表头,用csv.reader按索引取值:

import csv

with open("your_file.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    next(reader)  # 跳过表头行(如果存在)
    for row in reader:
        country = row[0]
        abv = row[1]
        year = int(row[2])
        expectancy = float(row[3])

二、数据拆分与结构化存储(满足至少4部分分类)

为了后续分类排序和查询,建议把数据按以下4种维度拆分存储:

  • 按国家分组:键为国家名,值是该国家所有年份的预期寿命数据

    country_data = {}
    for row in reader:
        country = row["国家"]
        year = int(row["年份"])
        expectancy = float(row["预期寿命"])
        if country not in country_data:
            country_data[country] = []
        country_data[country].append({"year": year, "expectancy": expectancy})
    
  • 按年份分组:键为年份,值是该年份所有国家的预期寿命数据

    year_data = {}
    for row in reader:
        year = int(row["年份"])
        country = row["国家"]
        expectancy = float(row["预期寿命"])
        if year not in year_data:
            year_data[year] = []
        year_data[year].append({"country": country, "expectancy": expectancy})
    
  • 按缩写映射:键为国家缩写,值是对应的国家全称及所有数据

    abv_map = {}
    for row in reader:
        abv = row["缩写"]
        country = row["国家"]
        year = int(row["年份"])
        expectancy = float(row["预期寿命"])
        if abv not in abv_map:
            abv_map[abv] = {"country": country, "data": []}
        abv_map[abv]["data"].append({"year": year, "expectancy": expectancy})
    
  • 按预期寿命区间分组:分低(<60)、中(60-75)、高(>75)三个区间,存储对应国家和年份数据

    expectancy_ranges = {
        "low": [],
        "medium": [],
        "high": []
    }
    for row in reader:
        country = row["国家"]
        year = int(row["年份"])
        expectancy = float(row["预期寿命"])
        if expectancy < 60:
            expectancy_ranges["low"].append({"country": country, "year": year, "expectancy": expectancy})
        elif 60 <= expectancy <=75:
            expectancy_ranges["medium"].append({"country": country, "year": year, "expectancy": expectancy})
        else:
            expectancy_ranges["high"].append({"country": country, "year": year, "expectancy": expectancy})
    

三、实现分类排序与查询示例

1. 按国家查询所有年份数据并排序

# 查询中国的所有年份数据,按年份升序排列
china_data = sorted(country_data.get("中国", []), key=lambda x: x["year"])
for item in china_data:
    print(f"年份: {item['year']}, 预期寿命: {item['expectancy']}")

2. 按年份查询所有国家数据并按预期寿命降序排序

# 查询2020年的所有国家数据,按预期寿命从高到低排列
year_2020_data = sorted(year_data.get(2020, []), key=lambda x: x["expectancy"], reverse=True)
for item in year_2020_data:
    print(f"国家: {item['country']}, 预期寿命: {item['expectancy']}")

3. 通过缩写查询对应国家数据

# 通过缩写"CN"查询数据
cn_info = abv_map.get("CN")
if cn_info:
    print(f"国家全称: {cn_info['country']}")
    for item in cn_info["data"]:
        print(f"年份: {item['year']}, 预期寿命: {item['expectancy']}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:05:23