You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码将力板数据集的左右侧字段替换为伤侧/健侧?

解决方案(基于Pandas实现)

假设你的数据集是Pandas DataFrame格式,且包含injured_side字段(记录每个样本的伤侧为left或right),以下是简洁规范的实现方案:

1. 定义映射规则

先创建表头替换的映射字典,覆盖全称和缩写场景:

# 左右标识到伤侧/健侧的映射
side_mapping = {
    'left': 'injured',
    'right': 'uninjured',
    'L': 'injured',
    'R': 'uninjured'
}

2. 批量替换表头字段

用正则表达式批量处理所有表头,统一替换左右标识:

import re

# 替换表头中的左右标识(不区分大小写)
df.columns = [
    re.sub(r'(left|L)', 'injured', col, flags=re.IGNORECASE)
    for col in df.columns
]
df.columns = [
    re.sub(r'(right|R)', 'uninjured', col, flags=re.IGNORECASE)
    for col in df.columns
]
# 处理合并类字段(如"L/R average")
df.columns = [
    re.sub(r'L/R', 'injured/uninjured', col, flags=re.IGNORECASE)
    for col in df.columns
]

3. 根据伤侧调整对应数据

如果样本伤侧为右侧,需要调换原右脚(现在映射为uninjured)和左脚(现在映射为injured)的数据,确保伤侧数据对应正确字段:

# 筛选出伤侧为右侧的样本
right_injured_mask = df['injured_side'].str.lower() == 'right'

# 匹配伤侧和健侧的对应字段(假设命名规则一致)
injured_cols = sorted([col for col in df.columns if 'injured' in col.lower()])
uninjured_cols = sorted([col for col in df.columns if 'uninjured' in col.lower()])

# 向量化调换数据(比循环高效)
df.loc[right_injured_mask, injured_cols + uninjured_cols] = \
    df.loc[right_injured_mask, uninjured_cols + injured_cols].values

关键注意事项

  • 必须保证数据集包含injured_side字段,否则无法判断伤侧;
  • 如果有无关字段包含left/right,需要调整正则规则避免误替换;
  • 向量化操作相比iterrows()循环效率更高,适合大数据集。

内容的提问来源于stack exchange,提问作者Christopher Duffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 14:33:10