pandas如何将存储多科成绩的字符串列拆分为科目得分长表
pandas 实现Score列拆分转为长表的方案
核心思路
先清理Score列的换行/多余空格,再通过正则匹配提取所有科目-分数对,最后拆分爆炸为长格式即可。
完整实现代码
import pandas as pd # 构造示例DataFrame(实际使用时替换为你自己的df即可) data = [ ["A", 1, "Math: 80.0 Physical Education: 30.5 Biology: 50.0"], ["B", 2, "Math: 70.0 Physical Education: 60.5 Biology: 50.0 English \nLiterature: 100.0"], ["C", 3, "Math: 30.0 Physical Education: 10.5 Biology: 50.0"] ] df = pd.DataFrame(data, columns=["Name", "ID", "Score"]) # 1. 预处理Score列:去除换行、合并连续空格 df["Score"] = df["Score"].str.replace(r"\n", " ", regex=True)\ .str.replace(r"\s+", " ", regex=True)\ .str.strip() # 2. 正则提取所有(科目, 分数)对 # 如果科目包含中文,可将正则替换为 r"([\u4e00-\u9fa5a-zA-Z\s]+): (\d+\.?\d*)" df["score_pairs"] = df["Score"].str.findall(r"([a-zA-Z\s]+): (\d+\.?\d*)", regex=True) # 3. 把列表形式的科目分数对拆分为单独行 df = df.explode("score_pairs", ignore_index=True) # 4. 拆分得到独立的科目、分数字段 df[["Subject", "Score"]] = pd.DataFrame(df["score_pairs"].tolist(), index=df.index) # 5. 转换分数为浮点型、清理冗余列 df["Score"] = df["Score"].astype(float) df = df[["Name", "ID", "Subject", "Score"]] # 输出结果 print(df)
效果验证
运行后输出的df完全符合预期格式,换行拆分的English Literature条目也会被正确识别,不存在丢失或拆分错误的问题。
内容的提问来源于stack exchange,提问作者Tien Huynh
相关产品推荐
相关产品推荐

