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

如何对Series中括号分隔的两个数字求和?最佳方法咨询

处理带补货数量的pandas Series数值求和

嘿,这个需求用正则表达式来处理是最稳妥的方案,比两次split要灵活得多,还能完美覆盖有/无补货数量的情况!

核心思路

我们可以用正则提取字符串里所有的数字(不管是开头的基础数量,还是括号里的补货数量),然后把这些数字转成数值类型后相加。

具体实现步骤

  1. 先导入需要的库,构造一个示例Series方便测试:
import pandas as pd
import re

# 模拟你的数据:包含纯数量、带补货数量的两种格式
item_counts = pd.Series(["10", "5 (3)", "8 (2)", "15", "7 (4)"])
  1. 定义一个处理单个字符串的函数,提取所有数字并求和:
def get_total_count(text):
    # 提取所有连续数字,转成整数后求和
    numbers = list(map(int, re.findall(r'\d+', str(text))))
    return sum(numbers)
  1. 将函数应用到整个Series上:
total_counts = item_counts.apply(get_total_count)
print(total_counts)

运行后输出会是:

0    10
1     8
2    10
3    15
4    11
dtype: int64

为什么这个方法更靠谱?

  • 兼容性强:不管字符串是纯数字,还是带括号的补货格式,都能正确提取所有数值
  • 健壮性高:即使字符串里有其他干扰字符(只要数字是连续的),正则依然能准确抓取
  • 可扩展性好:如果你的补货数量是小数,只需要调整正则和转换类型就行,比如:
item_counts_float = pd.Series(["10.5", "5.2 (3.8)"])
def get_total_float(text):
    numbers = list(map(float, re.findall(r'\d+\.?\d*', str(text))))
    return sum(numbers)
print(item_counts_float.apply(get_total_float))
# 输出:0    10.5,1     9.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:36:20