在R中确定主要受伤侧及下半身受伤侧的技术求助
解决运动损伤侧别分类的列生成问题
针对你的运动损伤数据集需求,下面提供基于Python Pandas的可运行代码方案,直接适配你要生成的两个新列:
核心思路
- 先建立「受限损伤全称」与「缩写损伤列」的映射关系(必须根据你的真实数据调整)
- 编写通用函数,根据指定的损伤类别(全部/下半身)提取侧别,按照规则返回对应结果:
- 无受限损伤 →
None - 所有目标损伤侧别一致 → 返回该侧别
- 存在不同侧别或包含双侧 → 返回
Both
- 无受限损伤 →
完整代码实现
import pandas as pd # 替换成你的真实数据集 df = pd.read_csv("你的数据集路径.csv") # -------------------------- # 关键:根据你的数据调整以下映射和侧别提取规则 # -------------------------- # 受限损伤全称 → 缩写损伤列的映射 injury_full_to_abbr = { "左侧踝关节扭伤": "Lat_Ankle_Sprain", "右侧踝关节扭伤": "Lat_Ankle_Sprain", "双侧踝关节扭伤": "Lat_Ankle_Sprain", "左侧膝关节扭伤": "Knee_Sprain", "右侧膝关节扭伤": "Knee_Sprain", "双侧膝关节扭伤": "Knee_Sprain", "左侧肩关节扭伤": "Shoulder_Sprain", "右侧肩关节扭伤": "Shoulder_Sprain", "双侧肩关节扭伤": "Shoulder_Sprain" } # 从损伤全称提取侧别的函数(适配你的中文表述) def get_side_from_full(full_name): if "左侧" in full_name or "左" in full_name: return "Left" elif "右侧" in full_name or "右" in full_name: return "Right" elif "双侧" in full_name or "两边" in full_name: return "Both" return pd.NA # -------------------------- # 通用侧别计算函数 # -------------------------- def compute_injury_side(row, target_injuries=None): # 默认处理所有三类损伤 target_injuries = target_injuries or ["Lat_Ankle_Sprain", "Knee_Sprain", "Shoulder_Sprain"] restricted = row["Injury_RestrictedParticipation"] # 无受限损伤的情况 if pd.isna(restricted) or restricted.strip() == "" or restricted == "NA": return "None" collected_sides = [] # 拆分多个损伤 for injury in restricted.split(","): injury = injury.strip() abbr = injury_full_to_abbr.get(injury) # 跳过非目标损伤 if abbr not in target_injuries: continue # 提取侧别并收集 side = get_side_from_full(injury) if pd.notna(side): collected_sides.append(side) # 处理收集到的侧别集合 if not collected_sides: return "None" unique_sides = set(collected_sides) # 只要有双侧,直接返回Both if "Both" in unique_sides: return "Both" # 所有侧别一致 if len(unique_sides) == 1: return unique_sides.pop() # 存在左右不同侧 return "Both" # -------------------------- # 生成需求列 # -------------------------- # 需求1:所有受限损伤的主侧别 df["Primary_Injury_Side"] = df.apply(compute_injury_side, axis=1) # 需求2:仅下半身损伤(排除肩关节扭伤)的侧别 df["LowerBody_Injury_Side"] = df.apply( lambda r: compute_injury_side(r, target_injuries=["Lat_Ankle_Sprain", "Knee_Sprain"]), axis=1 ) # 保存结果 df.to_csv("处理后数据集.csv", index=False)
注意事项
- 必须调整映射规则:
injury_full_to_abbr字典要完全匹配你数据中Injury_RestrictedParticipation列的所有损伤全称,否则会遗漏数据 - 适配侧别表述:如果你的损伤全称用"左膝"、"右踝"这类简写,要修改
get_side_from_full里的判断条件,确保能正确提取侧别 - NA值处理:如果你的数据中无损伤是用字符串"NA"而不是pandas的空值,要在
compute_injury_side的判断逻辑里加上restricted == "NA"
内容的提问来源于stack exchange,提问作者zmcclean
相关产品推荐
相关产品推荐

