如何使用Python将CSV文件转为字典并按条件完成疫情与人口数据计算
美国新冠及人口数据处理实现方案
依赖说明
全程使用Python标准库实现,无需安装第三方包,依赖模块如下:
csv:用于CSV文件读取- 可选使用
collections.defaultdict,统计州累计数据时更便捷
一、新冠县域疫情数据处理
1. 生成(州名,县名)为键的结果字典
注:若数据为包含多日期的时间序列,可先过滤出各县最新日期的记录再执行以下逻辑,避免重复统计
import csv covid_dict = {} with open("替换为你的新冠数据文件路径.csv", "r", encoding="utf-8") as f: reader = csv.reader(f) # 读取表头匹配字段位置 header = next(reader) county_idx = header.index("county") state_idx = header.index("state") cases_idx = header.index("confirmed_cases") deaths_idx = header.index("confirmed_deaths") for row in reader: state = row[state_idx].strip() county = row[county_idx].strip() # 数值转整数,空值默认填0可根据需求调整 cases = int(row[cases_idx]) if row[cases_idx].strip().isdigit() else 0 deaths = int(row[deaths_idx]) if row[deaths_idx].strip().isdigit() else 0 covid_dict[(state, county)] = [cases, deaths]
2. 统计指定州累计确诊死亡总和
def count_state_deaths(target_state: str, covid_dict: dict) -> int: total = 0 for (state, _), (_, deaths) in covid_dict.items(): if state == target_state: total += deaths return total # 示例:统计阿拉巴马州的死亡总和 alabama_deaths = count_state_deaths("Alabama", covid_dict) print(alabama_deaths)
3. 统计确诊病例落在指定区间的县域数量
def count_counties_in_case_range(low: int, high: int, covid_dict: dict) -> int: count = 0 for cases, _ in covid_dict.values(): if low <= cases <= high: count += 1 return count # 示例:统计确诊在1000到10000之间的县数量 range_count = count_counties_in_case_range(1000, 10000, covid_dict) print(range_count)
二、各州人口数据及死亡密度计算
1. 生成州名到最新人口的字典
pop_dict = {} with open("替换为你的人口数据文件路径.csv", "r", encoding="utf-8") as f: reader = csv.reader(f) for row in reader: if not row: continue # 首个字段去除前导点得到州名 state = row[0].lstrip(".").strip() # 末尾字段转整数为最新人口,空值处理可按需调整 pop = int(row[-1]) if row[-1].strip().isdigit() else 0 pop_dict[state] = pop
2. 计算各州确诊死亡密度
注:密度默认单位为每10万人死亡数,可按需调整倍数;未匹配到人口的州会自动跳过
# 先预统计所有州的累计死亡数 state_total_deaths = {} for (state, _), (_, deaths) in covid_dict.items(): state_total_deaths[state] = state_total_deaths.get(state, 0) + deaths state_death_density = {} for state, deaths in state_total_deaths.items(): pop = pop_dict.get(state, 0) if pop > 0: state_death_density[state] = round(deaths / pop * 100000, 2)
3. 计算全美总确诊死亡密度
us_total_deaths = sum(state_total_deaths.values()) us_total_pop = sum(pop for pop in pop_dict.values() if pop > 0) us_total_density = round(us_total_deaths / us_total_pop * 100000, 2) if us_total_pop > 0 else 0 print(f"全美每10万人确诊死亡密度为:{us_total_density}")
内容的提问来源于stack exchange,提问作者Answersplease
相关产品推荐
相关产品推荐

