在Julia中如何使用if else实现年龄分箱并生成对应字典?
基于if else的简洁实现
你原代码存在三个可优化的问题:循环内重复定义函数无意义、else分支不能直接加判断条件、单值场景下用zip构造字典的逻辑错误。可以直接把分箱逻辑抽为独立工具函数,用短路求值简化多层if else判断,代码更清爽:
using Dates # 提前定义公共工具,不用循环内重复创建 date_format = DateFormat("y-m-d") result = [] # 存储所有结果字典 # 分箱逻辑独立封装 function get_age_bin(age) age <= 25 && return "1-25" age <= 50 && return "26-50" age <= 75 && return "51-75" age <= 100 && return "76-100" return "100+" # 超过100岁的场景可自定义返回值 end open("../data/FILE.csv", "r") do input_file readline(input_file) # 直接跳过表头,无需额外flag变量 for line in eachline(input_file) line_array = split(line, ",") subject_id = line_array[2] date_birth = line_array[4][1:10] date_death = line_array[5][1:10] age_days = Date(date_death, date_format) - Date(date_birth, date_format) age_years = round(Int, Dates.value(age_days)/365.25) age_bin = get_age_bin(age_years) # 构造你需要的字段字典 push!(result, Dict( "subject_id" => subject_id, "age" => age_years, "age_bin" => age_bin )) # 要输出示例里的元组格式直接打印即可:println((subject_id, age_years, age_bin)) end end
DataFrames更优实现方案
数据量较大时用DataFrames的列级运算效率远高于逐行循环,也不需要手动处理拆分、跳表头这类重复逻辑,代码更简洁:
首先提前安装依赖包:import Pkg; Pkg.add(["CategoricalArrays"])
using CSV, DataFrames, Dates, CategoricalArrays # 直接读取CSV为结构化表,自动处理表头 df = CSV.read("../data/FILE.csv", DataFrame) date_format = DateFormat("y-m-d") # 批量计算年龄,列级广播运算比逐行循环快数倍 df.age_years = round.(Int, Dates.value.( Date.(chop.(df.date_of_death, tail=length(df.date_of_death[1])-10), date_format) - Date.(chop.(df.date_of_birth, tail=length(df.date_of_birth[1])-10), date_format) ) ./ 365.25) # 一行实现分箱,无需写判断逻辑 df.age_bin = cut(df.age_years, [0,25,50,75,100, Inf], labels=["1-25", "26-50", "51-75", "76-100", "100+"], extend=true) # 提取需要的三个字段转成结果字典列表 result = [Dict( "subject_id"=>row.subject_id, "age"=>row.age_years, "age_bin"=>row.age_bin ) for row in eachrow(df[!, [:subject_id, :age_years, :age_bin]])]
优势:
- 无需手动处理文件读取的边缘逻辑,CSV和DataFrames官方库已经做了大量容错处理
- 后续要做年龄分布统计、筛选、导出其他格式,直接调用DataFrames内置API即可,不用额外写逻辑
- 数据量超过1万行时,运算速度比逐行循环高一个数量级
注:如果你的CSV没有自定义列名,默认读取的列名是Column1/Column2,替换代码里的对应列名即可。
内容的提问来源于stack exchange,提问作者Mariah_5288
相关产品推荐
相关产品推荐

