如何将DataFrame中带B/MM的金额字符串转为百万单位数值?
处理带MM/B后缀的金融数据列转换
步骤1:修正解析函数
你的原始parse_currency函数未适配数据中的MM后缀和纯数字(如"0")场景,先调整函数匹配你的数据格式:
def parse_currency(value): # 处理纯数字(含负数)情况 if isinstance(value, int) or value.isdigit() or (value.startswith('-') and value[1:].isdigit()): return float(value) # 处理MM后缀(直接提取数值,单位已是百万) elif value.endswith('MM'): return float(value[:-2]) # 处理B后缀(十亿转百万,需乘1000) elif value.endswith('B'): return float(value[:-1]) * 1000 # 兜底处理其他格式 else: return float(value)
步骤2:应用到整个DataFrame
如果所有列都需要转换,直接用applymap方法对每个元素执行函数:
import pandas as pd # 构造你的原始DataFrame df = pd.DataFrame({ 'FCF (t)': ['0', '0', '-3MM', '261MM'], 'FCF (t-1)': ['0', '0', '-12MM', '265MM'], 'FCF (t-2)': ['0', '0', '-1MM', '603MM'], 'FCF (t-3)': ['0', '0', '-1MM', '118MM'], 'FCF (t-4)': ['0', '0', '0', '148MM'], 'FCF (t-5)': ['0', '0', '0', '199MM'], 'FCF (t-6)': ['0', '0', '0', '179MM'], 'Total Assets LTM': ['378MM', '2.60B', '17MM', '5.00B'] }, index=[1006, 1007, 1008, 1009]) # 批量转换所有列 processed_df = df.applymap(parse_currency) # 转成整数匹配目标结果格式 processed_df = processed_df.astype(int) print(processed_df)
运行后输出结果:
FCF (t) FCF (t-1) FCF (t-2) FCF (t-3) FCF (t-4) FCF (t-5) FCF (t-6) Total Assets LTM 1006 0 0 0 0 0 0 0 378 1007 0 0 0 0 0 0 0 2600 1008 -3 -12 -1 -1 0 0 0 17 1009 261 265 603 118 148 199 179 5000
步骤3:仅处理指定列
如果只需转换部分列,先指定目标列列表,再逐列应用函数:
target_cols = ['FCF (t)', 'FCF (t-1)', 'FCF (t-2)', 'FCF (t-3)', 'FCF (t-4)', 'FCF (t-5)', 'FCF (t-6)', 'Total Assets LTM'] df[target_cols] = df[target_cols].apply(lambda col: col.apply(parse_currency)).astype(int)
关键说明
applymap是DataFrame批量元素处理的高效方式,无需手动循环列- 修正后的函数覆盖了数据中所有格式场景:纯数字、MM后缀、B后缀
- 最终转
int是匹配你的目标结果格式,若需保留小数可省略此步骤
内容的提问来源于stack exchange,提问作者user20311840
相关产品推荐
相关产品推荐

