如何用最Pythonic的方法对Pandas中字符串格式的列求和?
解决带格式金额字符串的条件求和问题
示例数据表格
| current | new |
|---|---|
| ($100) | $1 |
| $5 | |
| $100 | ($2) |
核心思路
要实现new列有值取new,无值取current的求和,同时保留原字符串格式用于展示,关键是单独做「字符串转数值」的转换逻辑,不修改原数据列。
具体实现步骤
1. 定义金额字符串转数值的辅助函数
这个函数能处理带$符号、括号表示负数的格式:
def str_to_num(s): if not s: return 0 # 移除$和逗号(如果有千分位的话) num_str = s.replace('$', '').replace(',', '') # 括号包裹的是负数,提取内部数值后加负号 if num_str.startswith('(') and num_str.endswith(')'): return -float(num_str[1:-1]) return float(num_str)
2. 两种Pythonic的求和方式
假设你的DataFrame是df,可以用以下两种方式计算:
方式一:用np.where选择目标列后转换求和
import pandas as pd import numpy as np # 构造示例DataFrame(如果已有数据可跳过这步) df = pd.DataFrame({ 'current': ['($100)', '$5', '$100'], 'new': ['$1', '', '($2)'] }) # 选择new非空时用new,否则用current,得到待转换的字符串序列 target_values = np.where(df['new'] != '', df['new'], df['current']) # 转换为数值后求和 agg_sum = pd.Series(target_values).apply(str_to_num).sum() print(agg_sum) # 输出4.0
方式二:用df.apply逐行判断求和
agg_sum = df.apply( lambda row: str_to_num(row['new']) if row['new'] != '' else str_to_num(row['current']), axis=1 ).sum()
关键说明
- 原DataFrame的
current和new列始终保持字符串格式,完全不影响后续表格展示。 - 之前的代码报错是因为直接对字符串列调用
sum()会执行字符串拼接,而非数值求和,必须先完成格式转换。
内容的提问来源于stack exchange,提问作者mmvw
相关产品推荐
相关产品推荐

