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

如何在DataFrame中仅对含末尾R的单元格格式化移除该字符

处理DataFrame中以'R'结尾的单元格,移除末尾的'R'

针对你需求里的场景,我们可以用Pandas的字符串方法精准处理,只移除单元格末尾的'R',不影响其他位置的字符(比如"RGB LED"里的R不会被处理)。

方法1:定位目标单元格 + 切片移除末尾字符

先通过str.endswith()定位目标列中以'R'结尾的单元格,再用切片[:-1]去掉最后一个字符:

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    "Value": ["47", "47R", "220K", "RGB LED", "220R"],
    "Designator": ["R12", "R13", "R14", "LED1", "R15"]
})

# 仅修改Value列中以'R'结尾的单元格
df.loc[df['Value'].str.endswith('R'), 'Value'] = df['Value'].str[:-1]

print(df)

方法2:正则表达式替换

直接用正则匹配字符串末尾的'R',将其替换为空:

import pandas as pd

df = pd.DataFrame({
    "Value": ["47", "47R", "220K", "RGB LED", "220R"],
    "Designator": ["R12", "R13", "R14", "LED1", "R15"]
})

# 正则匹配末尾的R并替换,需开启regex模式
df['Value'] = df['Value'].str.replace(r'R$', '', regex=True)

print(df)

两种方法运行后都会得到你想要的结果:

Value Designator
0        47        R12
1        47        R13
2      220K        R14
3  RGB LED        LED1
4       220        R15

如果需要处理整个DataFrame的所有列,可改成遍历列的形式:

for col in df.columns:
    df[col] = df[col].str.replace(r'R$', '', regex=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:05:21