如何用字典将Pandas多列转换为百分比并添加后缀列
基于字典映射计算DataFrame中各测试的百分比得分
问题背景
现有记录数百名参与者两次随访测试数据的DataFrame,示例包含AB、LC、MA三项测试,各测试对应满分分别为:AB=150、LC=12、MA=2000。原始数据如下:
import pandas as pd data = { "ID": [1, 1, 2, 2, 3, 3], "Visit": [1, 2, 1, 2, 1, 2], "AB": [30, 40, 50, 20, 10, 10], "LC": [1, 4, 5, 6, 8, 9], "MA": [300, 900, 400, 400, 450, 350] } df = pd.DataFrame(data) print(df)
输出结果:
ID Visit AB LC MA 0 1 1 30 1 300 1 1 2 40 4 900 2 2 1 50 5 400 3 2 2 20 6 400 4 3 1 10 8 450 5 3 2 10 9 350
需求:基于各测试的满分计算每行的百分比得分,新增带_percent后缀的列(如AB_percent),通过字典映射不同测试的满分实现。
解决方案
方法一:列批量运算(推荐,效率更高)
直接遍历满分字典,对每个测试列执行百分比计算并新增列,适合大数据量场景:
# 定义各测试的满分映射字典 max_scores = {"AB": 150, "LC": 12, "MA": 2000} # 遍历字典生成百分比列 for test_name, max_val in max_scores.items(): df[f"{test_name}_percent"] = (df[test_name] / max_val) * 100 # 查看结果 print(df)
方法二:行级apply处理
如果需要更灵活的行级逻辑,可使用apply方法:
max_scores = {"AB": 150, "LC": 12, "MA": 2000} def add_percent_cols(row): for test_name, max_val in max_scores.items(): row[f"{test_name}_percent"] = (row[test_name] / max_val) * 100 return row # 应用函数到每行 df = df.apply(add_percent_cols, axis=1) print(df)
最终输出
两种方法都会生成包含百分比列的DataFrame:
ID Visit AB LC MA AB_percent LC_percent MA_percent 0 1 1 30 1 300 20.0 8.333333 15.0 1 1 2 40 4 900 26.666667 33.333333 45.0 2 2 1 50 5 400 33.333333 41.666667 20.0 3 2 2 20 6 400 13.333333 50.000000 20.0 4 3 1 10 8 450 6.666667 66.666667 22.5 5 3 2 10 9 350 6.666667 75.000000 17.5
关键说明
- 优先选择方法一:直接列运算的效率远高于行级
apply,数据量越大优势越明显。 - 扩展性强:新增测试时,只需在
max_scores字典中添加对应的测试名称和满分,无需修改计算逻辑。
内容的提问来源于stack exchange,提问作者Sid0311
相关产品推荐
相关产品推荐

