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

如何用Python将字符串列中的数字按另一列数值做除法并保留其余字符

解决方案

可以通过 正则表达式匹配数字 结合 pandas 的行级处理来实现需求,核心思路是提取code_input中的每个数字,除以对应行的days值后,再替换回原字符串位置。

实现代码

import pandas as pd
import re

# 示例数据集
data = {
    "code_input": ["15.5C + 72HT", "46C + 28HT +6T"],
    "days": [3, 2]
}
df = pd.DataFrame(data)

# 定义处理函数:对单个字符串中的数字做除法替换
def process_code(code_str, days):
    # 匹配所有数字(包括小数),替换为除以days后的结果
    def replace_num(match):
        num = float(match.group())
        # 保留两位小数(如示例中的5.16),整数则显示为整数格式
        result = num / days
        return f"{result:.2f}".rstrip('0').rstrip('.') if result % 1 != 0 else f"{int(result)}"
    
    return re.sub(r'\d+\.?\d*', replace_num, code_str)

# 生成code_output列
df["code_output"] = df.apply(lambda row: process_code(row["code_input"], row["days"]), axis=1)

print(df)

代码说明

  • re.sub(r'\d+\.?\d*', replace_num, code_str):用正则匹配所有整数或小数,调用replace_num函数处理每个匹配到的数字。
  • replace_num函数:将匹配到的数字转为浮点数,除以days后,根据结果是否为整数调整输出格式(避免整数显示为x.00)。
  • df.apply(..., axis=1):逐行调用处理函数,将结果存入code_output列。

输出结果

code_input  days         code_output
0    15.5C + 72HT      3    5.16C + 24HT
1  46C + 28HT +6T      2  23C + 14HT + 3T

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:37:45